From bscrivener42 at gmail.com Wed May 30 17:04:12 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: 30 May 2007 14:04:12 -0700 Subject: paste text with newlines into raw_input? Message-ID: <1180559052.806975.154890@h2g2000hsg.googlegroups.com> Using Python on Debian Etch. What is the best way to paste a block of text in at the command prompt. I'm trying something like: Quote = raw_input("Paste quote here: ") Which works great for one line of text with a single newline. It gets stripped. Okay. Is there a way to paste in a block of text that has multiple lines and newlines? I don't care if they all get stripped in the process, in fact I'd prefer it. I've used strip before, but that doesn't seem to work until you get the text into the program. Thanks for any help. Rick From jorgen.maillist at gmail.com Tue May 22 07:12:00 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Tue, 22 May 2007 13:12:00 +0200 Subject: [Fwd: Re: managed lists?] In-Reply-To: References: <4651fe96$0$24671$426a34cc@news.free.fr> <11e49df10705220013q11c35e6axba72cc4227401ac2@mail.gmail.com> Message-ID: <11e49df10705220412x9ae8b3fy4881043f91ccbe8b@mail.gmail.com> Hi Gabriel, Yep that basically covered my implementation as well. It was rather trivial to make it, and even for a python newbie it was simple which says enough about the language itself. ;-) Although I understand the opinions that you should not care about types, I do believe putting a constraint on the list by either class type or interface spec, is no bad thing. The interface specification is hard to realise as this list now functions as some kind of template class (hence the parameter that specifies which type is allowed). I also added callback arguments that are called opon when there are items added to the list, deleted or when it is cleared so that the main object gets notified when another object changes it. Here is my implementation (I bet it can be done better, but I am only playing with python since about 3 months now): -------------------------- class ObjListException(Exception): pass class ObjListIterator(object): def __init__(self, objlist): self.__objlist = objlist self.__idx = 0 #--------------------------------------------------------------------------- def __iter__(self): return self #--------------------------------------------------------------------------- def next(self): result = None if self.__idx >= len(self.__objlist): raise StopIteration() else: result = self.__objlist[self.__idx] self.__idx += 1 return result #=============================================================================== """ ObjList - A managed somewhat strong typed list for Python. Expects {object}._id to be a property """ class ObjList(object): def __init__(self, class_name, add_callback = None, remove_callback = None, clear_callback = None): self.__list = [] self.__cname = class_name self.__add_cb = add_callback self.__remove_cb = remove_callback self.__clear_cb = clear_callback #--------------------------------------------------------------------------- def __iter__(self): return ObjListIterator(self.unmanaged_list()) #--------------------------------------------------------------------------- def __getitem__( self, key): if key < len(self.__list) and key >= 0: return self.__list[key] return None #--------------------------------------------------------------------------- def clear(self): self.__list = [] #--------------------------------------------------------------------------- def append(self, obj): if isinstance(obj, self.__cname): if obj not in self.__list: self.__list.append(obj) if self.__add_cb: self.__add_cb(self, obj) else: raise ObjListException() #--------------------------------------------------------------------------- def remove(self, obj): if obj in self.__list: self.__list.remove(obj) if self.__remove_cb: self.__remove_cb(self, obj) #--------------------------------------------------------------------------- def count(self): return len(self.__list) #--------------------------------------------------------------------------- def unmanaged_list(self): return self.__list[:] #--------------------------------------------------------------------------- def find_id(self, id): for i in self.__list: if i._id == id: return i return None #--------------------------------------------------------------------------- def has_item(self, obj): if obj in self.__list: return True return False #--------------------------------------------------------------------------- def append_many(self, lst): for l in lst: self.append(l) Regards, - Jorgen From learned at gmail.com Thu May 24 01:59:58 2007 From: learned at gmail.com (Denrael) Date: 23 May 2007 22:59:58 -0700 Subject: Accessing iTunes with Python via the Windows SDK In-Reply-To: <1179983821.769700.45870@d30g2000prg.googlegroups.com> References: <1179980636.045976.145070@q75g2000hsh.googlegroups.com> <1179983821.769700.45870@d30g2000prg.googlegroups.com> Message-ID: <1179986398.203388.244090@q66g2000hsg.googlegroups.com> On May 24, 12:17 am, Tony Meyer wrote: > On May 24, 4:23 pm, Denrael wrote:> I've been playing with the iTunes sdk on windows, and have come across > > a strange problem. With the following code: > > The object you get back from iTunes.CurrentTrack (the traceback shows > this) is an IITTrack. If you check the iTunes SDK, you'll see that > IITTrack objects don't have a "SkippedCount" attribute - > IITFileOrCDTrack objects do (from memory, this excludes things like > radio links). You need to conver the IITrack object to a > IITFileOrCDTrack object (assuming that it is one); you can do this > with win32com.client.CastTo, as follows: > > Cheers, > Tony Thanks Tony! I had a suspicion it had to do with casting it, but I was missing some synapses to figure out exactly how to do that. Things have changed from my Assembly Language PL/1 and REXX days. :) I figure if I'm gonna learn a new language, Python's a lot more usable than VBS, and it has an elegance to it that I already appreciate. I'm working my way thru Learning Python ... I suppose I better find some doc on the Win32 COM stuff too. From efrat_regev at yahoo.com Tue May 22 06:53:46 2007 From: efrat_regev at yahoo.com (Efrat Regev) Date: Tue, 22 May 2007 13:53:46 +0300 Subject: Fastest Way To Iterate Over A Probability Simplex In-Reply-To: <1179829743.120449.148390@r3g2000prh.googlegroups.com> References: <4652b323$1@news.bezeqint.net> <1179829743.120449.148390@r3g2000prh.googlegroups.com> Message-ID: <4652CBBA.6020905@yahoo.com> bearophileHUGS at lycos.com wrote: > On May 22, 11:19 am, Efrat Regev: >> I want to iterate over all >> such vectors under the constraint that the granularity of >> each component is at most some delta. > > You can think of this like your sum is an integer>=1 and the single > "probabilities" are integers>=1 So given the sum, like 6, you can find > all the parts of it, and then find all the permutations of such parts. > Eppstein has given code for the parts of an integer, and you can can > find the iterable permutations code on the cookbook. But the number of > such possible vectors grows very quickly... > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/218332 > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/474124 > > Bye, > bearophile > Many thanks. I modified the recipes you attached some, and it works much better. Nice and informative answer! From slava.maslov at gmail.com Sun May 6 21:19:51 2007 From: slava.maslov at gmail.com (Vyacheslav Maslov) Date: Mon, 7 May 2007 08:19:51 +0700 Subject: unable to construct tuple with one item In-Reply-To: References: <271115400705060523t2f1c23e4ndc87e612384d4951@mail.gmail.com> <1178486806.743481.24580@y5g2000hsa.googlegroups.com> Message-ID: <271115400705061819y40af1a9dx12462b17fad3d8fb@mail.gmail.com> Guys, thanks a lot for you answers -------------- next part -------------- An HTML attachment was scrubbed... URL: From rrr at ronadam.com Fri May 25 16:31:17 2007 From: rrr at ronadam.com (Ron Adam) Date: Fri, 25 May 2007 15:31:17 -0500 Subject: webbrowser module bug? In-Reply-To: References: <1180118146.617722.300670@g4g2000hsf.googlegroups.com> Message-ID: Ron Adam wrote: > Got it. > > It looks like the problem started when I told firefox to make itself > the default browser. That changed the way webbrowser.py figured out the > browser to use. So instead of trying them in order, it asked the gnome > configure tool for it. > > def register_X_browsers(): > # The default Gnome browser > if _iscommand("gconftool-2"): > # get the web browser string from gconftool > gc = 'gconftool-2 -g /desktop/gnome/url-handlers/http/command > 2>/dev/null' > out = os.popen(gc) > commd = out.read().strip() > retncode = out.close() > > > After this commd is: > > '/usr/lib/firefox/firefox "%s"' > > It's then split, but the quotes aren't removed. I'm not sure why this > doesn't show up in 2.6. Maybe it's been fixed there already. A bit more follow up... so others can find this and avoid a lot of debugging, head scratching, computer smashing or worse. Reseting the default browser with the gnome default application window confirmed this. The browser selection can either have the quotes around the args "%s" paremteter, or not depending on how and what sets it. Seems to me it should be quoted unless spaces in path names are never a problem in Linux. So this could be both a python bug and a Gnome desktop bug. Firefox probably does the right thing by putting the quotes around it, but that causes problems for webbrowser.py, which doesn't expect them. Since the python trunk (2.6) has been changed to get the browser name in a different way, it won't be a problem for python 2.6. To check the args parameter or reset the default browser in the gnome desktop, use the gnome default application panel. $ gnome-default-applications-properties You can then either remove the extra quotes from the "%s" or reset the browser. Cheers, Ron From noagbodjivictor at gmail.com Sat May 5 15:13:30 2007 From: noagbodjivictor at gmail.com (noagbodjivictor at gmail.com) Date: 5 May 2007 12:13:30 -0700 Subject: How do I use the config parser? Message-ID: <1178392410.866037.179950@e65g2000hsc.googlegroups.com> Hi, I need a specific example. I have seen the docs, but I don't all the stuffs there. So basically, I need my config file to be created and read by my script. Here is a snippet # read old actions from ConfigParser import ConfigParser fp = open(makepath('App\qt_actions.conf')) configdict = ConfigParser() configdict.readfp(fp) Now I want to know how to read a section, a section attribute's value, and to write thoses back after reading. Thanks From kyosohma at gmail.com Wed May 23 08:57:35 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 23 May 2007 05:57:35 -0700 Subject: Create an XML document In-Reply-To: <46538B3D.2060307@web.de> References: <1179846012.972391.160800@z28g2000prd.googlegroups.com> <46538B3D.2060307@web.de> Message-ID: <1179925055.509111.63360@h2g2000hsg.googlegroups.com> On May 22, 7:30 pm, Stefan Behnel wrote: > kyoso... at gmail.com wrote: > > I am attempting to create an XML document dynamically with Python. It > > needs the following format: > > > > > > > 1179775800 > > 1800 > > > > > > Try lxml.objectify. > > http://codespeak.net/lxml/dev/objectify.html > > >>> from lxml import etree, objectify > >>> zAppointments = objectify.Element("zAppointments") > >>> zAppointments.set("reminder", "15") > >>> zAppointments.appointment = objectify.Element("appointment") > >>> zAppointments.appointment.begin = 1179775800 > >>> zAppointments.appointment.duration = 1800 > > >>> print etree.tostring(zAppointments, pretty_print=True) > > > 1179775800 > 1800 > > > > Pretty much what one would expect. > > Stefan Stefan, This looks really cool. I'll try implementing it sometime today and see if it affects my execution time any. It's definitely clearer code...at least in my opinion. Mike From inkey56 at yahoo.co.uk Wed May 30 13:33:27 2007 From: inkey56 at yahoo.co.uk (Andrew P) Date: 30 May 2007 10:33:27 -0700 Subject: Python 2.5 and WXPython demo's In-Reply-To: References: <1180523448.993195.59180@q69g2000hsb.googlegroups.com> Message-ID: <1180546407.948650.181560@q66g2000hsg.googlegroups.com> On May 30, 12:24 pm, Steve Holden wrote: > Andrew P wrote: > > Hello, > > > I am new (very) to Python and have just down loaded the latest version > > of Python (2.5) and WXPython (2.8). > > > For some reason I cannot get the WXPython demo to run at all. I run > > windows XP and it can't find a program to run the demo. Any advice? > > (apologies if this has been posted before). > > The demo is a separate download nowadays. Do you mean you just can't > find it, or are you running it and does it give you some error message > that you feel we shouldn't be told about? > > A little more information, 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 > ------------------ Asciimercial --------------------- > Get on the web: Blog, lens and tag your way to fame!! > holdenweb.blogspot.com squidoo.com/pythonology > tagged items: del.icio.us/steve.holden/python > All these services currently offer free registration! > -------------- Thank You for Reading ---------------- Thanks for your reply, this is what I get when I click on the WXPthon Icon: Python Traceback Shell Stating: ImportError: No module named pywin.framework.startup The Icon is the older python snake icon not the new coloured icon. Thanks Andrew. From tijs_news at artsoftonline.com Wed May 30 09:25:29 2007 From: tijs_news at artsoftonline.com (Tijs) Date: Wed, 30 May 2007 15:25:29 +0200 Subject: Scope - import and globals References: <1180455769.891470.116360@p47g2000hsd.googlegroups.com> Message-ID: <465d7b49$0$325$e4fe514c@news.xs4all.nl> HMS Surprise wrote: > > In the file snippet below the value for the global hostName is > determined at runtime. Functions imported from the parent baseClass > file such as logon also need access to this variable but cannot see it > the with the implementation I have attempted here. Use a class variable: class baseClass: hostName = None # undefined yet def someFunc(self): assert self.hostName is not None, "hostname not set yet" ... # use hostName here class temp(baseClass): def runTest(self): baseClass.hostName = getHostName() ... or a global variable: baseClass.py: hostName = None class baseClass: def someFunc(self): assert hostName is not None .... testme.py: import baseClass class temp(baseClass.baseClass): .... baseClass.hostName = getHostName() although neither solution strikes me as very elegant. I would normally pass the hostname to the constructor of baseClass or use a separate 'settings' module. Global variables are per-module. Use the "global" keyword when assigning a global variable in the 'current' module. Global variables of other modules are properties of the module, use .. > > Also, functions in this file and in the imported parent class need > PyHttpTestCase. Does there need to be an import statement in both > files? Yes. Don't worry, the work is done only once. Regards, Tijs From bill.scherer at verizonwireless.com Thu May 24 09:01:53 2007 From: bill.scherer at verizonwireless.com (Bill Scherer) Date: Thu, 24 May 2007 09:01:53 -0400 Subject: installing cx_Oracle. In-Reply-To: References: Message-ID: <46558CC1.5010100@verizonwireless.com> Carl K wrote: > I am trying to use this: > http://python.net/crew/atuining/cx_Oracle/html/cx_Oracle.html > it is a real module, right? > It is indeed. > sudo easy_install cx_Oracle did not easy_install cx_Oracle. > > http://www.python.org/pypi/cx_Oracle/4.3.1 doesn't give me any clue. > > I got the source from > http://prdownloads.sourceforge.net/cx-oracle/cx_Oracle-4.3.1.tar.gz?download > > carl at dell17:~/a/cx_Oracle-4.3.1$ python setup.py build > Traceback (most recent call last): > File "setup.py", line 36, in ? > oracleHome = os.environ["ORACLE_HOME"] > File "/usr/lib/python2.4/UserDict.py", line 17, in __getitem__ > def __getitem__(self, key): return self.data[key] > KeyError: 'ORACLE_HOME' > You have an oracle client installed, right? If not, go get an Instant Client: http://www.*oracle*.com/technology/software/tech/oci/*instant**client*/index.html Then you need to set an environment variable, ORACLE_HOME, to point to the root of the oracle client installation so that the cx_Oracle installer can find the oracle libraries to build with. > > Now I don't really know whos problem this is. > > Carl K > From marijuanated at gmail.com Sun May 27 22:52:58 2007 From: marijuanated at gmail.com (marijuanated at gmail.com) Date: 27 May 2007 19:52:58 -0700 Subject: Unsubscribing from the mailing list Message-ID: <1180320778.316540.296470@q19g2000prn.googlegroups.com> Hi All, I do not know if this is the correct group to ask this question. But since mailman is python-based I thought i would ask here. I had subscribed to a mailing list called gtk-app-devel-list at gnome.org adventitiously. I then wanted to reverse my decision and so tried to unsubscribe from the mailing list. The web interface told that I had to enter my username and then click unsubscribe. I did so. I was responded with the message that "A confirmation mail has been sent". However I did not get any mail of that sort. Due to this I am not able to unsubscribe and I get loads of emails from that mailing list every day. Can somebody help me get out of this mess?? Thanks, Sundar From jianbing.chen at gmail.com Sat May 5 16:05:46 2007 From: jianbing.chen at gmail.com (jianbing.chen at gmail.com) Date: 5 May 2007 13:05:46 -0700 Subject: behavior difference for mutable and immutable variable in function definition In-Reply-To: References: <1178314206.701824.291560@n59g2000hsh.googlegroups.com> Message-ID: <1178395546.598229.276340@e65g2000hsc.googlegroups.com> On May 4, 5:14 pm, Carsten Haese wrote: > On Fri, 2007-05-04 at 14:30 -0700, jianbing.c... at gmail.com wrote: > > Hi, > > > Can anyone explain the following: > > > Python 2.5 (r25:51908, Apr 9 2007, 11:27:23) > > [GCC 4.1.1 20060525 (Red Hat 4.1.1-1)] on linux2 > > Type "help", "copyright", "credits" or "license" for more information. > > >>> def foo(): > > ... x = 2 > > ... > > >>> foo() > > >>> def bar(): > > ... x[2] = 2 > > ... > > > >>> bar() > > Traceback (most recent call last): > > File "", line 1, in > > File "", line 2, in bar > > NameError: global name 'x' is not defined > > "x = 2" binds the name 'x' in foo's local namespace to the object '2'. > For this, it doesn't matter whether the name 'x' was previously bound to > anything. > > "x[2] = 2" is a shorthand notation for the method call > "x.__setitem__(2,2)". This requires the name 'x' to be bound to some > object that has a __setitem__ method. > > -Carsten This makes sense. Thank you. From half.italian at gmail.com Wed May 30 23:15:22 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 30 May 2007 20:15:22 -0700 Subject: paste text with newlines into raw_input? In-Reply-To: <1180559052.806975.154890@h2g2000hsg.googlegroups.com> References: <1180559052.806975.154890@h2g2000hsg.googlegroups.com> Message-ID: <1180581322.594132.259100@a26g2000pre.googlegroups.com> On May 30, 2:04 pm, BartlebyScrivener wrote: > Using Python on Debian Etch. > > What is the best way to paste a block of text in at the command > prompt. > > I'm trying something like: > > Quote = raw_input("Paste quote here: ") > > Which works great for one line of text with a single newline. It gets > stripped. Okay. > > Is there a way to paste in a block of text that has multiple lines and > newlines? I don't care if they all get stripped in the process, in > fact I'd prefer it. I've used strip before, but that doesn't seem to > work until you get the text into the program. > > Thanks for any help. > > Rick import sys s =sys.stdin.read() print s which will read until ctrl-d ~Sean From aleax at mac.com Wed May 16 00:09:39 2007 From: aleax at mac.com (Alex Martelli) Date: Tue, 15 May 2007 21:09:39 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <1hy2qg3.iqfvwnrvr9kjN%aleax@mac.com> Message-ID: <1hy69gm.eh6m866urk03N%aleax@mac.com> Aldo Cortesi wrote: > Thus spake Steven D'Aprano (steven at REMOVE.THIS.cybersource.com.au): > > > Perhaps you aren't aware that doing something "by eye" is idiomatic > > English for doing it quickly, roughly, imprecisely. It is the opposite of > > taking the time and effort to do the job carefully and accurately. If you > > measure something "by eye", you just look at it and take a guess. > > Well, Steve, speaking as someone not entirely unfamiliar with idiomatic > English, I can say with some confidence that that's complete and utter > bollocks (idomatic usage for "nonsense", by the way). To do something "by > eye" means nothing more nor less than doing it visually. Unless you can > provide a citation to the contrary, please move on from this petty little > point of yours, and try to make a substantial technical argument instead. I can't find any reference for Steven's alleged idiomatic use of "by eye", either -- _however_, my wife Anna (an American from Minnesota) came up with exactly the same meaning when I asked her if "by eye" had any idiomatic connotations, so I suspect it is indeed there, at least in the Midwest. Funniest, of course, is that the literal translation into Italian, "a occhio", has a similiar idiomatic meaning to _any_ native speaker of Italian -- and THAT one is even in the Italian wikipedia!-) I'll be the first to admit that this issue has nothing to do with the substance of the argument (on which my wife, also my co-author of the 2nd ed of the Python Cookbook and a fellow PSF member, deeply agrees with you, Aldo, and me), but natural language nuances and curios are my third-from-the-top most consuming interest (after programming and... Anna herself!-). [[_Visual inspection_ plays a crucial role in many areas of engineering, of course; for example, visual inspection of welds is a very reliable, although costly, quality assurance process, particularly if you ensure that the inspectors hold the top professional degrees from the American Welding Society (if you're operating in the USA:-)]]. Alex From nyamatongwe+thunder at gmail.com Mon May 14 19:39:03 2007 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Mon, 14 May 2007 23:39:03 GMT Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <4648EC26.8020907@v.loewis.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <7x4pmg716p.fsf@ruckus.brouhaha.com> <4648EC26.8020907@v.loewis.de> Message-ID: Martin v. L?wis: > Specification-wise, C99 and C++98 also support Unicode identifiers, > although many compilers still don't. Ada 2005 allows Unicode identifiers and even includes the constant '?' in Ada.Numerics. Neil From enleverlesX.XmcX at XmclaveauX.com Mon May 14 16:17:30 2007 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Mon, 14 May 2007 22:17:30 +0200 Subject: Bug? import cp1252 References: <46462b1a$0$25919$ba4acef3@news.orange.fr> <1179011549.196725.300860@y80g2000hsf.googlegroups.com> Message-ID: <4648ca2a$0$27391$ba4acef3@news.orange.fr> Hi! >>> I suspect that's there's some invisible character in the file No ; because I reproduce the problem, on another CPU, with typing from scratch. >>> I can't reproduce this -- Python 2.5.1, Windows XP Pro SP2 I'm sorry. Perhaps my "french" windows is a co-factor? Perhaps my locale has Or my local influence? I had try on four computer, with the same problem. Fortunately, write in UTF-8 delete the problem... -- Michel Claveau From jstroud at mbi.ucla.edu Wed May 9 18:44:31 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 09 May 2007 15:44:31 -0700 Subject: Suggestions for how to approach this problem? In-Reply-To: <4641ea34$0$6823$c3e8da3@news.astraweb.com> References: <4640ca5b$0$23392$c3e8da3@news.astraweb.com> <4641ea34$0$6823$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: > John Salerno wrote: > >> So I need to remove the line breaks too, but of course not *all* of >> them because each reference still needs a line break between it. > > > After doing a bit of search and replace for tabs with my text editor, I > think I've narrowed down the problem to just this: > > I need to remove all newline characters that are not at the end of a > citation (and replace them with a single space). That is, those that are > not followed by the start of a new numbered citation. This seems to > involve a look-ahead RE, but I'm not sure how to write those. This is > what I came up with: > > > \n(?=(\d)+) > > (I can never remember if I need parentheses around '\d' or if the + > should be inside it or not! I included code in my previous post that will parse the entire bib, making use of the numbering and eliminating the most probable, but still fairly rare, potential ambiguity. You might want to check out that code, as my testing it showed that it worked with your example. James From robert.kern at gmail.com Sun May 6 16:08:24 2007 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 06 May 2007 15:08:24 -0500 Subject: howto make Python list from numpy.array? In-Reply-To: References: <1178480447.245977.293010@n59g2000hsh.googlegroups.com> Message-ID: Amaury Forgeot d'Arc wrote: > Hello, > > John Nagle a ?crit : >> dmitrey wrote: >>> howto make Python list from numpy.array? >>> Thx, D. >>> >> lst = map(None, arr) // for 1D arrays. > > Which can be expressed more simply as: > lst = list(arr) For N-D arrays, that will give you a list of arrays. If you want a list of lists (of lists of lists ... etc N times), use the .tolist() method of arrays. -- 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 half.italian at gmail.com Wed May 9 17:35:25 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 9 May 2007 14:35:25 -0700 Subject: File I/O In-Reply-To: <1178745198.392518.56840@q75g2000hsh.googlegroups.com> References: <1178745198.392518.56840@q75g2000hsh.googlegroups.com> Message-ID: <1178746525.499358.179550@w5g2000hsg.googlegroups.com> On May 9, 2:13 pm, HMS Surprise wrote: > If one has a list of lists such as > > lst = [['a','1'],['b','2']] > > is there a standard python idiom for writing and reading the pairs to/ > from a file? > > Thanks, > > jh These work. Assuming you can choose the format. Or you could pickle the list. write ~~~~ lst = [['a','1'],['b','2']] file = open("file", 'w') [file.write(item[0] + "\t" + item[1] + "\n") for item in lst] file.close() read ~~~~ lst = [] file = open("file", 'r') [lst.append(list(line.split())) for line in file] file.close() print lst ~Sean From mensanator at aol.com Wed May 16 02:16:59 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 15 May 2007 23:16:59 -0700 Subject: Interesting list Validity (True/False) In-Reply-To: References: <1178915791.584216.293130@l77g2000hsb.googlegroups.com> <1178918808.091358.233740@o5g2000hsb.googlegroups.com> <1179017740.656323.209590@e51g2000hsg.googlegroups.com> <1179020634.130689.171960@o5g2000hsb.googlegroups.com> <1179031812.090768.248750@l77g2000hsb.googlegroups.com> <1179168081.603409.39970@e51g2000hsg.googlegroups.com> <1179203827.881205.287910@l77g2000hsb.googlegroups.com> <1179248480.350553.4430@n59g2000hsh.googlegroups.com> Message-ID: <1179296218.969564.240220@k79g2000hse.googlegroups.com> On May 15, 7:07 pm, "Gabriel Genellina" wrote: > En Tue, 15 May 2007 14:01:20 -0300, mensana... at aol.com > escribi?: > > > On May 15, 12:30 am, "Gabriel Genellina" > > wrote: > >> And said section 5.9 should be updated too: "The objects need not have > >> the > >> same type. If both are numbers or strings, they are converted to a > >> common > >> type. > > > Except when they aren't. > > I think you don't get the difference between a builtin object, fully under > the Python developers' control, and a user defined class that can behave > arbitrarily at wish of its writer and for which the Python documentation > barely can say a word. > The docs say how will the Python interpreter try to compare objects > (invoke the rich comparison methods, invoke __cmp__, etc) and how the > *builtin* objects behave. For other objects, it's up to the object > *writer* to provide such methods, and he can do whatever he wishes: > > py> class Reversed(int): > ... def __lt__(self, other): return cmp(int(self),other)>0 > ... def __gt__(self, other): return cmp(int(self),other)<0 > ... def __le__(self, other): return cmp(int(self),other)>=0 > ... def __ge__(self, other): return cmp(int(self),other)<=0 > ... > py> > py> j=Reversed(6) > py> j==6 > True > py> j>5 > False > py> j>10 > True > py> j<=5 > True > > You can't blame Python for this. > > >>>> import gmpy > >>>> a = 2**177149-1 > >>>> b = gmpy.mpz(2**177149-1) > >>>> a==b > > True > >>>> print '%d' % (b) > > > Traceback (most recent call last): > > File "", line 1, in > > print '%d' % (b) > > TypeError: int argument required > > > So although the comparison operator is smart enough to realize > > the equivalency of numeric types and do the type conversion, > > the print statement isn't so smart. > > This is up to the gmpy designers/writers/maintainers. Anyone writing a > class chooses which features to implement, which ones to omit, how to > implement them, etc. The code may contain bugs, may not be efficient, may > not behave exactly as the users expect, may not have anticipated all usage > scenarios, a long etc. In this case, probably the gmpy writers have chosen > not to allow to convert to int, and they may have good reasons to not do > that (I don't know what platform are you working in, but I feel that your > b object is somewhat larger than sys.maxint...). Then how does this work? >>> print '%d' % (long(gmpy.mpz(2**177149-1))) 1454...<53320 digits snipped>...3311 I honestly don't understand why there's a problem here. If print can handle arbitrary precision longs without a problem, why does it fail on mpzs > sys.maxint? If the gmpy writers are not allowing the conversion, then why do small mpz values work? Something smells inconsistent here. How is it that >>> print '%d' % (1.0) 1 doesn't make a type mismatch? Obviously, the float got changed to an int and this had nothing to do with gmpy. Is it the print process responsible for doing the conversion? Maybe I should say invoking the conversion? Maybe the gmpy call tries to literally convert to an integer rather than sneakily substitute a long? How else can this phenomena be explained? > >> Otherwise, objects of different builtin types always compare > >> unequal, and are ordered consistently but arbitrarily. You can control > >> comparison behavior of objects of non-builtin types by defining a > >> __cmp__ > >> method or rich comparison methods like __gt__, described in section > >> 3.4." > > >> I hope this helps a bit. Your performance issues don't have to do with > >> the > >> *definition* of equal or not equal, > > > I didn't say that, I said the performance issues were related > > to type conversion. Can you explain how the "definition" of > > equal does not involve type conversion? > > There is no type conversion involved for user defined classes, *unless* > the class writer chooses to do so. > Let's invent some new class Number; they can be added and have basic > str/repr support > > py> class Number(object): > ... def __init__(self, value): self.value=value > ... def __add__(self, other): return Number(self.value+other.value) > ... def __str__(self): return str(self.value) > ... def __repr__(self): return 'Number(%s)' % self.value > ... > py> x = Number(2) > py> y = Number(3) > py> z = x+y > py> z > Number(5) > py> z == 5 > False > py> 5 == z > False > py> z == Number(5) > False > py> int(z) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: int() argument must be a string or a number > py> "%d" % z > Traceback (most recent call last): > File "", line 1, in ? > TypeError: int argument required > > You can't compare them to anything, convert to integer, still nothing. > Let's add "int conversion" first: > > py> Number.__int__ = lambda self: int(self.value) > py> int(z) > 5 > py> "%d" % z > '5' > py> z == 5 > False > py> 5 == z > False > > Ok, a Number knows how to convert itself to integer, but still can't be > compared successfully to anything. (Perhaps another language would try to > convert automagically z to int, to compare against 5, but not Python). > Let's add basic comparison support: > > py> Number.__cmp__ = lambda self, other: cmp(self.value, other.value) > py> z == Number(5) > True > py> z > Number(7) > False > py> z == z > True > py> z == 5 > Traceback (most recent call last): > File "", line 1, in ? > File "", line 1, in > AttributeError: 'int' object has no attribute 'value' > > Now, a Number can be compared to another Number, but still not compared to > integers. Let's make the comparison a bit smarter (uhm, I'll write it as a > regular function because it's getting long...) > > py> def NumberCmp(self, other): > ... if isinstance(other, Number): return cmp(self.value, other.value) > ... else: return cmp(self.value, other) > ... > py> Number.__cmp__ = NumberCmp > py> z == 5 > True > py> z == 6 > False > py> 5 == z > True > > As you can see, until I wrote some code explicitely to do the comparison, > and allow other types of comparands, Python will not "convert" anything. > If you find that some class appears to do a type conversion when comparing > instances, it's because the class writer has explicitely coded it that > way, not because Python does the conversion automagically. Ok, ok. But how does the subroutine that the class writer created to do the actual conversion get invoked? > > >> only with how someone decided to write the mpz class. > > I'm beginning to think there's a problem there. > > Yes: you don't recognize that gmpy is not a builtin package, it's an > external package, and its designers/writers/implementors/coders/whatever > decide how it will behave, not Python itself nor the Python developers. > > -- > Gabriel Genellina From stefan.sonnenberg at pythonmeister.com Wed May 9 05:40:13 2007 From: stefan.sonnenberg at pythonmeister.com (Stefan Sonnenberg-Carstens) Date: Wed, 9 May 2007 11:40:13 +0200 (CEST) Subject: Using the CSV module In-Reply-To: <676224240705090140k2525224ch541a5740a19a6f3f@mail.gmail.com> References: <676224240705090140k2525224ch541a5740a19a6f3f@mail.gmail.com> Message-ID: <1068189.36314.BlRUCl8VTQA=.1178703613.squirrel@webmailer.hosteurope.de> Most of the time I found the CSV module not as useful as it might be - due to the restrictions you describe. Why not write a simple parser class ? On Mi, 9.05.2007, 10:40, Nathan Harmston wrote: > Hi, > > I ve been playing with the CSV module for parsing a few files. A row > in a file looks like this: > > some_id\t|\tsome_data\t|t\some_more_data\t|\tlast_data\t\n > > so the lineterminator is \t\n and the delimiter is \t|\t, however when > I subclass Dialect and try to set delimiter is "\t|\t" it says > delimiter can only be a character. > > I know its an easy fix to just do .strip("\t") on the output I get, > but I was wondering > a) if theres a better way of doing this when the file is actually > being parsed by the csv module > b) Why are delimiters only allowed to be one character in length. > > Many Thanks in advance > Nathan > -- > http://mail.python.org/mailman/listinfo/python-list > > From thinkogram at hotmail.com Sun May 20 04:35:33 2007 From: thinkogram at hotmail.com (thinkogram at hotmail.com) Date: 20 May 2007 01:35:33 -0700 Subject: docs patch: dicts and sets In-Reply-To: <_5-dnU7aIN73j9LbnZ2dnUVZ_uCinZ2d@comcast.com> References: <_5-dnU7aIN73j9LbnZ2dnUVZ_uCinZ2d@comcast.com> Message-ID: <1179650133.407140.257190@e65g2000hsc.googlegroups.com> On May 19, 8:06 am, Steven Bethard wrote: > Seems to me that you're focusing on the wrong part of the docs. The > source of this "bug" is not sets or dicts, Seems to me, this thread has lost touch with reality. There is no bug, just a quest to make some random change to docs just to make the OP feel better about not being able to grasp the concept of an unordered collection. Seems to me, he missed something so basic that docs won't help him. When you care about order, then don't use an unordered collection. Case closed. No need to add useless, distracting garbage to the docs. Seems to me, some people would rather think themselves into knots than to accept the obvious. Richard T From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon May 7 14:05:28 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 07 May 2007 20:05:28 +0200 Subject: Simulating simple electric circuits Message-ID: <5a9838F2nlbanU1@mid.individual.net> Hello all, I'm trying to simulate simple electric logic (asynchronous) circuits. By "simple" I mean that I only want to know if I have "current" or "no current" (it's quite digital) and the only elements need to be (with some level of abstraction to my specific problem) - sources (here begin currents) - ground (here end currents) - joints - switches (which are able to let current pass or not, depending on outside influence) - loads (which can signal change in current flow to the outside -- just like a light bulb) Is there any library for this? I couldn't find one. I tried to implement this using objects that are two-way linked; every object has "ports". For every port, there is - an input function (that is called by the neighbour if "current" comes in) - a reference to the neighbour's input function, to be able to let current flow the other way There is a master "current controller" object which tells the "source" object to start a "current" by calling its neighbour. The calls traverse the network until they reach a "ground" object. Specifically, the source passes a "telegram" instance with these calls, and everyone it passes through "registers" himself with it (telegrams are duplicated at joints). Then, the ground object calls back to the controller with all received telegrams. Like this I'm already able to get all possible ways through the network. But that's where my ideas go out. Let's assume there is a load in the middle of such a current, e. g. a light bulb. So if the current flows through it it gets notice of this because there is a telegram passing through it. But what if a contact before it now "cuts" the current, how could I notify all objects behind the cut? I tried several ways the past few days, but all lead to confusing (and non-working) code. (I'm sorry I can't provide any working code yet) Often it boils down to the need to check all possible ways in the entire network with every change. This shouldn't, in perfomance terms, be a big problem for me here, but it feels very dirty, and I smell inconsistencies. Another way I thought of is - to let load objects have a timer that resets their state to "no flow" after ~ 200 ms - "pulse" the network every ~ 100 ms from all sources to ground - and reset all load timers on the way. This feels even more dirty. There are several professional-grade simulation tools that track many other parameters, how do they work in general, is there a different strategy? I wonder if I'm making it too complicated or if I'm seeing problems where there really aren't any. I also looked at NetworkX, but I can't see how it might be of use yet. I appreciate all suggestions. Thanks for you consideration. Regards, Bj?rn P.S.: This is no homework, it's pure hobby ;) -- BOFH excuse #70: nesting roaches shorted out the ether cable From sjmachin at lexicon.net Mon May 7 20:59:51 2007 From: sjmachin at lexicon.net (John Machin) Date: 7 May 2007 17:59:51 -0700 Subject: getmtime differs between Py2.5 and Py2.4 In-Reply-To: <463fb305$0$326$e4fe514c@news.xs4all.nl> References: <463FA51D.1060600@v.loewis.de> <463fb305$0$326$e4fe514c@news.xs4all.nl> Message-ID: <1178585991.924458.154570@l77g2000hsb.googlegroups.com> On May 8, 9:15 am, Irmen de Jong wrote: > Martin v. L?wis wrote: > >> Is this a bug? > > > Why don't you read the responses posted earlier? John Machin > > replied (in <1178232636.415630.106... at l77g2000hsb.googlegroups.com>) > > that you are mistaken: There is NO difference between the outcome > > of os.path.getmtime between Py2.5 and Py2.4. It always did return > > UTC, and always will. > > > Regards, > > Martin > > Err.....: > > [E:\Projects]dir *.py > > Volume in drive E is Data Serial number is 2C4F:9C2D > Directory of E:\Projects\*.py > > 31-03-2007 20:46 511 log.py > 25-11-2006 16:59 390 p64.py > 7-03-2007 23:07 207 sock.py > 3-02-2007 16:15 436 threads.py > 1.544 bytes in 4 files and 0 dirs 16.384 bytes allocated > 287.555.584 bytes free > > [E:\Projects]c:\Python24\python.exe -c "import os; print os.path.getmtime('p64.py')" > 1164470381 > > [E:\Projects]c:\Python25\python.exe -c "import os; print os.path.getmtime('p64.py')" > 1164466781.28 > > This is python 2.4.4 and Python 2.5.1 on windows XP. > The reported time clearly differs. > > --Irmen Well nitpicked, but irrelevant to the OP's perceptual problem. The reported time clearly differs due to the result being (as documented) now a float instead of an int. The OP is complaining about an alleged difference of time-zone magnitude (i.e. at least 30 minutes, not 0.28 seconds). Somehow he has got the idea that Python 2.4 & earlier returned local time, not UTC. HTH, John From maxerickson at gmail.com Sun May 6 10:48:01 2007 From: maxerickson at gmail.com (Max Erickson) Date: Sun, 6 May 2007 14:48:01 +0000 (UTC) Subject: Installation of eyeD3 on Windows (newbie) References: <1178456159.115779.274630@l77g2000hsb.googlegroups.com> Message-ID: phishboh at gmail.com wrote: > I would highly appreciate if someone could help me with how to > proceed (step-by-step) to get started and use the eyeD3 library > in Windows? > > Many thanks in advance! > It appears that you need to do as follows: Extract the tar.gz to a temporary directory. rename 'eyeD3-6.13\src\eyeD3\__init__.py.in' to 'eyeD3-6.13\src\eyeD3\__init__.py' run 'python setup.py.in install' from the eyeD3-6.13 directory. (It appears you may have extracted the files into the site-packages directory; if so, move them somewhere else before running the commands.) I have just done this and from eyeD3.tag import * completes successfully. There is some reference to a C library in the build files, but no importing of it in the source code, so this might just make it appear to install but not actually work, I don't know. The steps I outlined only install the library, the eyeD3 utility is not installed. If you want to use it, you need to drop it somewhere in your path and give windows some way to find it, by wrapping it in a batch file or renaming it to eyeD3.py and making .py files executable or whatever. You might also give mutagen a look, I settled on it last time I went looking for an id3 library: http://www.sacredchao.net/quodlibet/wiki/Development/Mutagen (I was not using if for writing though) max From mensanator at aol.com Sun May 13 22:45:22 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 13 May 2007 19:45:22 -0700 Subject: Interesting list Validity (True/False) In-Reply-To: References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> <1178914190.166662.285410@p77g2000hsh.googlegroups.com> <1178915791.584216.293130@l77g2000hsb.googlegroups.com> <1178918808.091358.233740@o5g2000hsb.googlegroups.com> <1179017740.656323.209590@e51g2000hsg.googlegroups.com> <1179020634.130689.171960@o5g2000hsb.googlegroups.com> <1179073565.933957.174250@o5g2000hsb.googlegroups.com> Message-ID: <1179110721.982567.89610@p77g2000hsh.googlegroups.com> On May 13, 2:09?pm, Carsten Haese wrote: > On Sun, 2007-05-13 at 09:26 -0700, mensana... at aol.com wrote: > There are no exceptions. "...and when I say none, I mean there is a certain amount." From devicerandom at gmail.com Sat May 26 08:57:50 2007 From: devicerandom at gmail.com (massimo s.) Date: 26 May 2007 05:57:50 -0700 Subject: of destructors, open files and garbage collection In-Reply-To: References: <1180021256.619953.80500@q66g2000hsg.googlegroups.com> Message-ID: <1180184270.264255.27900@k79g2000hse.googlegroups.com> > No, it removes the association between the name 'item' and the object it is > currently bound to. In CPython, removing the last such reference will > cause the object to be gc'ed. In other implementations, actual deletion > may occur later. You probably should close the files directly and arrange > code so that you can do so before too many are open. Thanks a lot, I'll follow that way. m. From miki.tebeka at gmail.com Tue May 22 16:39:54 2007 From: miki.tebeka at gmail.com (Miki) Date: 22 May 2007 13:39:54 -0700 Subject: OSError[Error 5] In-Reply-To: <1179831143.709611.61580@b40g2000prd.googlegroups.com> References: <1179831143.709611.61580@b40g2000prd.googlegroups.com> Message-ID: <1179866393.429055.18680@r3g2000prh.googlegroups.com> Hello SamG, > I do this on PowerPC.. > > >>> import os > >>> os.listdir('/usr/bin') > > And endup getting this ... > > OSError: [Error 5] Input/output error:/usr/bin What happens when you run "ls /usr/bin" in the terminal? HTH, -- Miki http://pythonwise.blogspot.com From mcl.office at googlemail.com Sat May 26 05:54:12 2007 From: mcl.office at googlemail.com (mosscliffe) Date: 26 May 2007 02:54:12 -0700 Subject: Newbie: Struggling again 'map' Message-ID: <1180173252.906992.262570@q75g2000hsh.googlegroups.com> I thought I had the difference between 'zip' and 'map' sorted but when I try to fill missing entries with something other than 'None'. I do not seem to be able to get it to work - any pointers appreciated. Richard lista = ['a1', 'a2'] listb = ['b10', 'b11','b12' ,'b13'] for x,y in zip(lista, listb): # Fine Truncates as expected print "ZIP:", x, "<>", y for x,y in map(None, lista, listb): # Also fine - extends as expected print "MAP:", x, "<>", y for x,y in map("N/A", lista, listb): ########## Fails - Can not call a 'str' print "MAP:", x, "<>", y def fillwith(fillchars): return fillchars for x,y in map(fillwith("N/A"), lista, listb): ########## Fails also - Can not call a 'str' print "MAP:", x, "<>", y From http Mon May 28 18:58:22 2007 From: http (Paul Rubin) Date: 28 May 2007 15:58:22 -0700 Subject: itertools.groupby References: <1180373388.112182.225700@i13g2000prf.googlegroups.com> <1180382532.846606.265100@q19g2000prn.googlegroups.com> <7xzm3o36o0.fsf@ruckus.brouhaha.com> Message-ID: <7xd50kv9m9.fsf@ruckus.brouhaha.com> Paul Rubin writes: > > See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/259173 > But that recipe generates the groups in a random order depending on > the dict hashing, Correction, it generates the right order in this case, although it builds up an in-memory copy of the entire input, which could be problematic if the input is large (e.g. the input sequence is coming from a file or socket stream). From stefan.behnel-n05pAM at web.de Sun May 13 16:04:59 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sun, 13 May 2007 22:04:59 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476081.7080609@web.de> Message-ID: <46476F6B.2000501@web.de> Josiah Carlson wrote: > It's also about being able to type names to use them in your own code > (generally very difficult if not impossible for many non-Latin > characters), or even be able to display them. And no number of > guidelines, suggestions, etc., against distributing libraries with > non-Latin identifiers will stop it from happening, and *will* fragment > the community as Anton (and others) have stated. Ever noticed how the community is already fragmented into people working on project A and people not working on project A? Why shouldn't the people working on project A agree what language they write and spell their identifiers in? And don't forget about project B, C, and all the others. I agree that code posted to comp.lang.python should use english identifiers and that it is worth considering to use english identifiers in open source code that is posted to a public OS project site. Note that I didn't say "ASCII identifiers" but plain english identifiers. All other code should use the language and encoding that fits its environment best. Stefan From __peter__ at web.de Mon May 21 17:42:33 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 21 May 2007 23:42:33 +0200 Subject: Moving class used in pickle References: Message-ID: Jeffrey Barish wrote: > I have a class derived from string that is used in a pickle. In the new > version of my program, I moved the module containing the definition of the > class. Now the unpickle fails because it doesn't find the module. I was > thinking that I could make the unpickle work by putting a copy of the > module in the original location and then redefine the class by sticking a > __setstate__ in the class thusly: > > def __setstate__(self, state): > self.__dict__.update(state) > self.__class__ = NewClassName > > My plan was to specify the new location of the module in NewClassName. > However, when I do this I get the message "'class' object layout differs > from 'class'". I don't think that they do as the new module is a copy of > the old one. I suspect that I am not allowed to make the class assignment > because my class is derived from string. What is the best way to update > the pickle? The only thought I have is to read all the data with the old > class module, store the data in some nonpickle format, and then, with > another program, read the nonpickle-format file and rewrite the pickle > with the class module in the new location. You could overwrite Unpickler.find_class(): import pickle from cStringIO import StringIO class AliasUnpickler(pickle.Unpickler): def __init__(self, aliases, *args, **kw): pickle.Unpickler.__init__(self, *args, **kw) self.aliases = aliases def find_class(self, module, name): module, name = self.aliases.get((module, name), (module, name)) return pickle.Unpickler.find_class(self, module, name) def loads(aliases, str): file = StringIO(str) return AliasUnpickler(aliases, file).load() if __name__ == "__main__": import before, after data = before.A() print data.__class__, data dump = pickle.dumps(data) data = loads({("before", "A"): ("after", "B")}, dump) print data.__class__, data In the example the aliases dictionary maps (module, classname) pairs to (module, classname) pairs. Of course this only works when the class layout wasn't changed. Peter From jstroud at mbi.ucla.edu Fri May 4 23:19:33 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 04 May 2007 20:19:33 -0700 Subject: Firefighters at the site of WTC7 "Move away the building is going to blow up, get back the building is going to blow up." In-Reply-To: <1178329932.455122.161530@u30g2000hsc.googlegroups.com> References: <1178161820.731367.264500@y80g2000hsf.googlegroups.com> <1hlj33p6aq838o2urk1dv6h75b5is4i2vd@4ax.com> <3TD_h.219$mR2.195@newssvr22.news.prodigy.net> <1178329932.455122.161530@u30g2000hsc.googlegroups.com> Message-ID: MooseFET wrote: > On May 4, 12:32 pm, James Stroud wrote: > [....] > >>The Marxist contribution to western thought is that it put everything in >>terms of labor and thus allowed us to quantify the human component of >>economies. > > > No the great insight by Marx was in the selling of ducks. "Anybody > want to buy a duct" has done more to advance economic thinking than > the works of most economists. > > Economists have a vested interest in preventing people from > understanding economics. They are well paid and know that they > wouldn't be for long if people really understood what was going on. > You must be an economist because you provide absolutely no interpretation of what the hell you were saying in ghe first paragraph (as if you actually know what you were trying to say). Duct or duck, first of all. Second of all--make a point. James From fsckedagain at gmail.com Fri May 11 12:25:55 2007 From: fsckedagain at gmail.com (fscked) Date: 11 May 2007 09:25:55 -0700 Subject: path stuff In-Reply-To: References: <1178734266.858048.311740@y5g2000hsa.googlegroups.com> <1178818879.239014.152210@e65g2000hsc.googlegroups.com> <1178826330.282268.132350@p77g2000hsh.googlegroups.com> <1178829783.996168.48250@u30g2000hsc.googlegroups.com> <1178834670.518728.102920@e65g2000hsc.googlegroups.com> Message-ID: <1178900755.209201.94000@n59g2000hsh.googlegroups.com> On May 10, 6:08 pm, "Gabriel Genellina" wrote: > En Thu, 10 May 2007 19:04:30 -0300, fscked > escribi?: > > > > > > > ok, I lied, it is still doing the archived folders. Here is the code: > > > import os, sys > > from path import path > > > myfile = open("boxids.txt", "r", 0) > > for line in myfile: > > d = 'D:\\Dir\\' + path(line.strip()) > > for f in d.walkfiles('*Config*.xml'): > > for dirpath, dirnames, filenames in os.walk(d): > > if "Archived" in dirnames: > > dirnames.remove("Archived") #skip this directory > > print f > > print 'Done' > > > when it does the print f it still shows me the dirs i don't want to > > see. > > You are walking the directory structure *twice*, using two different > methods at the same time. Also, there is no standard `path` module, and > several implementations around, so it would be a good idea to tell us > which one you use. > If you want to omit a directory, and include just filenames matching a > pattern: > > import os, sys, os.path, fnmatch > > def findinterestingfiles(root_dir): > for dirpath, dirnames, filenames in os.walk(root_dir): > if "Archived" in dirnames: > dirnames.remove("Archived") > for filename in fnmatch.filter(filenames, '*Config*.xml'): > fullfn = os.path.join(dirpath, filename) > print fullfn > > myfile = open("boxids.txt", "r") > for line in myfile: > dirname = os.path.join('D:\\Dir\\', line.strip()) > findinterestingfiles(dirname): > myfile.close() > > -- > Gabriel Genellina- Hide quoted text - > > - Show quoted text - Should this code work? I get a syntax error and cannot figure out why. From Dave.Baum at motorola.com Thu May 24 14:45:53 2007 From: Dave.Baum at motorola.com (Dave Baum) Date: Thu, 24 May 2007 13:45:53 -0500 Subject: What is an instance and what isn't? References: Message-ID: In article , "Gre7g Luterman" wrote: > I suppose I was lulled into complacency by how Python makes so many things > look like classes, but I'm starting to realize that they're not, are they? > > I'm writing a C program which handles Python objects in different ways based > on their type. I do a PyInstance_Check(PyObj) to determine if the PyObj is > an instance, but it is returning 0 on a lot of stuff that I thought would be > an instance. So I did the following simple test on three things that look > like instances: > > 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. > >>> class a: pass > ... > >>> type(a()) > > >>> type(Exception()) > > >>> class b(dict): pass > ... > >>> type(b()) > > > I was relieved that a() returns an instance, but I was surprised that > Exceptions aren't really instances at all. And what's the deal with derving > a class from a standard type like a dictionary? I thought for sure, that > would be an instance, but this shows it is a class?!? > There are actually two kinds of classes in Python (as of 2.2): new-style classes and classic classes. What you are calling an instance is an instance of a classic class. Here is how a new-style class would look: >>> class c(object): pass ... >>> type(c()) Actually the new-style classes are a lot more consistent with the built-in types, and the type hierarchy makes more sense with them, so I would suggest in general migrating towards new-style classes for all of your own code. More information about new-style classes can be found here: http://docs.python.org/ref/node33.html http://www.python.org/doc/newstyle.html > Can anyone explain the last one and/or give me a simple test I can do in C > to determine whether a Python object is "instance-like"? With new-style classes, the type of an instance of that class is the class itself (type(x) == x.__class__). In your above example, class b is a subclass of dict, which itself is a new-style class, making b a new-style class as well. Thus type(b()) is b. As for a check, it really depends on what you mean by "instance-like". Are dictionaries "instance-like"? What about strings? Integers? Dave From devicerandom at gmail.com Thu May 24 11:40:56 2007 From: devicerandom at gmail.com (massimo s.) Date: 24 May 2007 08:40:56 -0700 Subject: of destructors, open files and garbage collection Message-ID: <1180021256.619953.80500@q66g2000hsg.googlegroups.com> Hi, Python 2.4, Kubuntu 6.06. I'm no professional programmer (I am a ph.d. student in biophysics) but I have a fair knowledge of Python. I have a for loop that looks like the following : for item in long_list: foo(item) def foo(item): item.create_blah() #<--this creates item.blah; by doing that it opens a file and leaves it open until blah.__del__() is called Now, what I thought is that if I call del(item) it will delete item and also all objects created inside item. So I thought that item.blah.__del__() would have been called and files closed. Question 1: This is not the case. I have to call del(item.blah), otherwise files are kept open and the for loops end with a "Too many open files" error. Why isn't __del__() called on objects belonging to a parent object? Is it OK? So I thought: oh, ok, let's put del(self.blah) in item.__del__() Question 2: This doesn't work either. Why? Thanks a lot, M. From sjdevnull at yahoo.com Thu May 17 19:03:44 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 17 May 2007 16:03:44 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179355081.828574.241690@h2g2000hsg.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179289167.723990.223890@u30g2000hsc.googlegroups.com> <464abd12$0$23364$426a34cc@news.free.fr> <1179307776.953405.207680@l77g2000hsb.googlegroups.com> <464ad388$0$28786$426a34cc@news.free.fr> <1179337277.347833.237450@n59g2000hsh.googlegroups.com> <1179355081.828574.241690@h2g2000hsg.googlegroups.com> Message-ID: <1179443024.632355.110680@e65g2000hsc.googlegroups.com> On May 16, 6:38 pm, r... at yahoo.com wrote: > On May 16, 11:41 am, "sjdevn... at yahoo.com" > wrote: > > > Christophe wrote: > ....snip... > > > Who displays stack frames? Your code. Whose code includes unicode > > > identifiers? Your code. Whose fault is it to create a stack trace > > > display procedure that cannot handle unicode? You. > > > Thanks but no--I work with a _lot_ of code I didn't write, and looking > > through stack traces from 3rd party packages is not uncommon. > > Are you worried that some 3rd-party package you have > included in your software will have some non-ascii identifiers > buried in it somewhere? Surely that is easy to check for? > Far easier that checking that it doesn't have some trojan > code it it, it seems to me. What do you mean, "check for"? If, say, numeric starts using math characters (as has been suggested), I'm not exactly going to stop using numeric. It'll still be a lot better than nothing, just slightly less better than it used to be. > > And I'm often not creating a stack trace procedure, I'm using the > > built-in python procedure. > > > And I'm often dealing with mailing lists, Usenet, etc where I don't > > know ahead of time what the other end's display capabilities are, how > > to fix them if they don't display what I'm trying to send, whether > > intervening systems will mangle things, etc. > > I think we all are in this position. I always send plain > text mail to mailing lists, people I don't know etc. But > that doesn't mean that email software should be contrainted > to only 7-bit plain text, no attachements! I frequently use > such capabilities when they are appropriate. Sure. But when you're talking about maintaining code, there's a very high value to having all the existing tools work with it whether they're wide-character aware or not. > If your response is, "yes, but look at the problems html > email, virus infected, attachements etc cause", the situation > is not the same. You have little control over what kind of > email people send you but you do have control over what > code, libraries, patches, you choose to use in your > software. > > If you want to use ascii-only, do it! Nobody is making > you deal with non-ascii code if you don't want to. Yes. But it's not like this makes things so horribly awful that it's worth my time to reimplement large external libraries. I remain at -0 on the proposal; it'll cause some headaches for the majority of current Python programmers, but it may have some benefits to a sizeable minority and may help bring in new coders. And it's not going to cause flaming catastrophic death or anything. From kelvin.you at gmail.com Wed May 30 11:01:03 2007 From: kelvin.you at gmail.com (=?gb2312?B?yMvR1MLkyNXKx8zs0cSjrM37vKvM7NHEsru8+7zS?=) Date: 30 May 2007 08:01:03 -0700 Subject: How to print this character u'\u20ac' to DOS terminal In-Reply-To: <465d760d$0$338$e4fe514c@news.xs4all.nl> References: <1180501468.957322.106650@z28g2000prd.googlegroups.com> <465D0A6B.1000203@v.loewis.de> <1180508736.598924.26170@r19g2000prf.googlegroups.com> <465d760d$0$338$e4fe514c@news.xs4all.nl> Message-ID: <1180537263.762432.37770@n15g2000prd.googlegroups.com> On 5?30?, ??9?03?, Tijs wrote: > ??????????????? wrote: > > But the string contained the u'\u20ac' is get from remote host. Is > > there any method to decode it to the local 'mbcs'? > > remote_string = u'\u20ac' > try: > local_string = remote_string.encode('mbcs') > except: > # no mbcs equivalent available > print "encoding error" > else: > # local_string is now an 8-bit string > print "result:", local_string > # if console is not mbcs, you should see incorrect result > assert result == '\x80' > > Mbcs is windows-only so I couldn't test this. > > If your application handles text, it may be easier to just leave everything > in Unicode and encode to utf-8 for storage? > > Regards, > Tijs Yes, it works, thank you. But I doubt this way may not work on linux. Maybe I should write some additional code for supporting both windows and linux OS. From john at datavoiceint.com Fri May 11 16:43:36 2007 From: john at datavoiceint.com (HMS Surprise) Date: 11 May 2007 13:43:36 -0700 Subject: Time Message-ID: <1178916216.893542.257320@y80g2000hsf.googlegroups.com> I need to convert the string below into epoch seconds so that I can perform substractions and additions. I assume I will need to break it up into a time_t struct and use mktime. Two questions if you will please: Is there a way to use multiple separator characters for split similar to awk's [|] style? Could you point to an example of a python time_t struct? 05/11/2007 15:30 Thanks, jvh From alextabone at gmail.com Tue May 15 06:29:28 2007 From: alextabone at gmail.com (Alchemist) Date: 15 May 2007 03:29:28 -0700 Subject: time format Message-ID: <1179224967.959750.21490@l77g2000hsb.googlegroups.com> I have a ctime() object that when I convert to string returns this string: "Tue May 15 12:27:11 2007" Now I need to convert it in the following (string) format: "Tue, 15 May 2007 10:25:40 GMT" How can I format a ctime() object? Can anyone give me (or lead me to) an example of a solution to my problem? Thanks From tjreedy at udel.edu Tue May 22 20:03:41 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 22 May 2007 20:03:41 -0400 Subject: Slightly OT: Why all the spam? References: <3bb44c6e0705220008y10f5deb7v86ed82d3f8241761@mail.gmail.com> <1179848997.22230.4.camel@contra.chem.byu.edu> Message-ID: "Michael L Torrie" wrote in message news:1179848997.22230.4.camel at contra.chem.byu.edu... | On Tue, 2007-05-22 at 09:08 +0200, bryan rasmussen wrote: | > Well two things I would suppose: | > | > 1. relative popularity and volume of the group leads spammers to put | > more resources towards spamming the group. | > | > 2. I seem to remember that python-list is also a usenet group? | > non-moderated, meaning it is tough to ban people? | > | > Actually, it would be nice to know if anybody has any good filters | > worked up that will work in Gmail for reading python-list. | | It appears that people using nntp to read this list aren't seeing the | spam because the moderators expire the messages as they find them. | However, by then the messages have already hit the mailman gateway. | Thus you may want to consider reading c.l.p via nntp when at work. | | Lately all the spams contain a url to a certain site, so you can | probably procmail filter based on that. The spam does not appear to be | random-bot generated, but targeted spam by a single person or entity. | Which makes it easier to filter out. I am getting lots of it reading via gmane. It is not clear to me from the headers for some whether the spam is being injected via gmane or is being passed thru the mailing lists, which is supposed to block such (I thought). Anyone clear for this one? Path: news.gmane.org!not-for-mail From: Dicky.Links5 at gmail.com Newsgroups: gmane.comp.python.general Subject: ^? Ron Jeremeys Dick Gets Longer! Date: 21 May 2007 22:17:04 -0700 Organization: http://groups.google.com Lines: 6 Approved: news at gmane.org Message-ID: <1179811024.413786.177400 at b40g2000prd.googlegroups.com> NNTP-Posting-Host: lo.gmane.org Mime-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 7bit X-Trace: sea.gmane.org 1179811282 28713 80.91.229.12 (22 May 2007 05:21:22 GMT) X-Complaints-To: usenet at sea.gmane.org NNTP-Posting-Date: Tue, 22 May 2007 05:21:22 +0000 (UTC) To: python-list at python.org Original-X-From: python-list-bounces+python-python-list=m.gmane.org at python.org Tue May 22 07:21:20 2007 Return-path: Envelope-to: python-python-list at gmane.org Original-Received: from smtp-vbr8.xs4all.nl ([194.109.24.28]) by lo.gmane.org with esmtp (Exim 4.50) id 1HqMoC-00046j-8v for python-python-list at gmane.org; Tue, 22 May 2007 07:21:20 +0200 Original-Received: from bag.python.org (bag.python.org [194.109.207.14]) by smtp-vbr8.xs4all.nl (8.13.8/8.13.8) with ESMTP id l4M5LK8b075024 for ; Tue, 22 May 2007 07:21:20 +0200 (CEST) (envelope-from python-list-bounces+python-python-list=m.gmane.org at python.org) Original-Received: from bag.python.org (bag [127.0.0.1]) by bag.python.org (Postfix) with ESMTP id C3F051E4003 for ; Tue, 22 May 2007 07:21:19 +0200 (CEST) Original-Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!news2.euro.net!newsgate.cistron.nl!xs4all!news.glorb.com!postnews.google.com!b40g2000prd.googlegroups.com!not-for-mail Original-Newsgroups: comp.lang.python, misc.writing, alt.consumers.uk-discounts.and.bargains, alt.guitar.amps, comp.unix.solaris Original-Lines: 3 Original-NNTP-Posting-Host: 66.183.79.3 Original-X-Trace: posting.google.com 1179811048 22970 127.0.0.1 (22 May 2007 05:17:28 GMT) Original-X-Complaints-To: groups-abuse at google.com Original-NNTP-Posting-Date: Tue, 22 May 2007 05:17:28 +0000 (UTC) User-Agent: G2/1.0 X-HTTP-UserAgent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.0.10) Gecko/20061220 Mandriva/1.5.0.10-2mdv2007.0 (2007.0) Firefox/1.5.0.10,gzip(gfe),gzip(gfe) Complaints-To: groups-abuse at google.com Injection-Info: b40g2000prd.googlegroups.com; posting-host=66.183.79.3; posting-account=0f6UMg0AAAC5bxvnyv-Tuh1EvQXxN9Ru Original-Xref: news.xs4all.nl comp.lang.python:496115 misc.writing:997260 alt.consumers.uk-discounts.and.bargains:213090 alt.guitar.amps:815089 comp.unix.solaris:552028 X-BeenThere: python-list at python.org X-Mailman-Version: 2.1.9 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Original-Sender: python-list-bounces+python-python-list=m.gmane.org at python.org Errors-To: python-list-bounces+python-python-list=m.gmane.org at python.org X-Virus-Scanned: by XS4ALL Virus Scanner Xref: news.gmane.org gmane.comp.python.general:523407 Archived-At: I have sent notices to groups_abuse at google.com and get no response and spam continues from same account. I am wondering if google thinks it is too big to be punished for being a spam source. tjr From roger at computer-surgery.co.uk Sat May 12 13:09:06 2007 From: roger at computer-surgery.co.uk (Roger Gammans) Date: 12 May 2007 17:09:06 GMT Subject: Finally started on python.. Message-ID: Hi, Having known about python since around the turn of the century , I finally found a (actually two) reason to learn it. Python seems to have moved on a little since the 1.5.2 release covered in the reference book (Essential Python) I bought way back when so I could learn it when the time came but it seems to be mainly backward compatible - is there anything that likely to catch me out - I use linux, so heavy use of an upto date pydoc has filled the gaps so far. I do however have a couple of questions:- 1) A nice simple language query : I found myself using this sort of code a bit in one of my recent scripts class Something: def Entries(self): sort=self._data.keys() sort.sort() for i in sort: yield i IS this preferable to just returning the sort array from the function or not? Which is more runtime efficent. Does it change if the last line was yield self._data[i] instead as that would require a map() in the function ? 2) I've ended up coding a new wrapper for reading in data structures from XML files (it wraps xml.sax) so that ctor are call on each end tag with the XML Objects contents. Does the python communitity have something like Perl's CPAN and is there already something there taht does this or would it be something that I could give back? Is there a naming convention for such modules in python - I couldn't easly detect one looking at the library which whip with python in Debian. Sorry, for asking so much in a first post but I thought both queries were link with by relative newby status. TTFN -- Roger. Home| http://www.sandman.uklinux.net/ Master of Peng Shui. (Ancient oriental art of Penguin Arranging) Work|Independent Sys Consultant | http://www.computer-surgery.co.uk/ So what are the eigenvalues and eigenvectors of 'The Matrix'? --anon From kyosohma at gmail.com Thu May 10 16:46:22 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 10 May 2007 13:46:22 -0700 Subject: Comparing dates problem In-Reply-To: <1178826321.961336.66070@q75g2000hsh.googlegroups.com> References: <1178746479.776908.319930@p77g2000hsh.googlegroups.com> <1178748764.663230.186570@y80g2000hsf.googlegroups.com> <1178823142.101246.220660@l77g2000hsb.googlegroups.com> <1178826321.961336.66070@q75g2000hsh.googlegroups.com> Message-ID: <1178829981.943508.238320@h2g2000hsg.googlegroups.com> On May 10, 2:45 pm, John Machin wrote: > On May 11, 4:52 am, kyoso... at gmail.com wrote: > > > > > On May 9, 5:12 pm, John Machin wrote: > > > > On May 10, 7:34 am, kyoso... at gmail.com wrote: > > > > > Hi, > > > > > I am writing a reminder program for our Zimbra email client. One of > > > > the requirements I was given was to automatically increment or > > > > decrement the display to show something like the following: > > > > > 5 minutes until appointment > > > > > or > > > > > 10 minutes past your appointment > > > > > Either way, as each minute goes by, I need to increment it or > > > > decrement it. I am having trouble finding a coherent way to take the > > > > same date and compare just the number of minutes between them to find > > > > the difference. Like if I have an appointment at 9:30 a.m. and the app > > > > is loaded at 8 a.m., I need to know the number of minutes or hours and > > > > minutes until the appointment. > > > > > I have looked at the dateutils module and it has many comparison > > > > methods, but they seem to only return the number of days or seconds. > > > > Ermmm ... what's wrong with > > > > minutes = seconds / 60.0 > > > hours = minutes / 60.0 > > > > ? > > > I'm sure there is a hack for doing something like what you suggest, > > but it would be messy. The problem is that I get a datetime object > > returned and division really isn't something you can do to one of > > those objects. Besides, if I had seconds returned, I would want to > > multiply by 60, not divide. > > > Maybe I misunderstand you. > > Maybe it's mutual -- hack? messy? multiply? Where I come from, 180 > seconds is (180 / 60 = 3) minutes. 180 seconds * 60 is 10800 sixtieths- > of-a-second, which appears to be travelling away from a solution to > your problem. > > You have *TWO* datetime objects, (say) appt_dt and now_dt. > > delta =appt_dt - now_dt # delta is a timedelta object. > # calculate difference in minutes > mins = delta.days * 24 * 60 + delta.seconds // 60 > > Have you not read Tim Golden's response? Yeah. I said I felt stupid. I'm sorry. I was looking at the problem from the wrong direction. Mike From tartifola at gmail.com Fri May 18 04:39:26 2007 From: tartifola at gmail.com (Tartifola) Date: Fri, 18 May 2007 10:39:26 +0200 Subject: Random selection Message-ID: <20070518103926.65bb8ea7.tartifola@gmail.com> Hi, I have a list with probabilities as elements [p1,p2,p3] with of course p1+p2+p3=1. I'd like to draw a random element from this list, based on the probabilities contained in the list itself, and return its index. Any help on the best way to do that? Thanks From aisaac at american.edu Thu May 10 09:28:30 2007 From: aisaac at american.edu (Alan Isaac) Date: Thu, 10 May 2007 13:28:30 GMT Subject: change of random state when pyc created?? References: Message-ID: <26F0i.5709$wy2.454@trnddc03> >> Alan Isaac requested: >> http://docs.python.org/lib/typesmapping.html: to footnote (3), add phrase >> http://docs.python.org/lib/types-set.html: append a new sentence to 2nd paragraph "Hamilton, William " wrote in message news:mailman.7519.1178802108.32031.python-list at python.org... > "Keys and values are listed in an arbitrary order. This order is > non-random, varies across Python implementations, and depends on the > dictionary's history of insertions and deletions as well as factors outside > the scope of the containing program." > "Iteration over a set returns elements in an arbitrary order, which may > depend on factors outside the scope of the containing program." I think this is good and might have clued me in. At least I'd have had a fighting chance this way. Alan Isaac From aisaac at american.edu Tue May 1 20:23:01 2007 From: aisaac at american.edu (Alan Isaac) Date: Wed, 02 May 2007 00:23:01 GMT Subject: relative import broken? References: <1hxa9x3.c0unyd1jw7vu9N%aleax@mac.com> <1hxcdkq.47p2r6beuctcN%aleax@mac.com> <1hxeg2v.1ct59rv3oyq87N%aleax@mac.com> <7nNZh.4420$st3.1414@trnddc06> Message-ID: > "Alex Martelli" wrote in message > news:1hxeg2v.1ct59rv3oyq87N%aleax at mac.com... > > I don't know of any "pretty" way -- I'd do it by path manipulation > > (finding mypackage from os.path.abspath(__file__) and inserting its > > _parent_ directory in sys.path). > "Alan Isaac" wrote in message news:7nNZh.4420$st3.1414 at trnddc06... > Yes, that seems to be the standard solution. > I find it ugly. Just to confirm that I am right to find it ugly: does this not clearly introduce the possibility of name clashes? Or am I overlooking some trick? Alan Isaac From bjourne at gmail.com Tue May 29 04:16:38 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Tue, 29 May 2007 10:16:38 +0200 Subject: Is PEP-8 a Code or More of a Guideline? In-Reply-To: References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <1180254338.292249.29520@h2g2000hsg.googlegroups.com> Message-ID: <740c3aec0705290116m47c9a136xe10bf110ecaeaddb@mail.gmail.com> On 5/29/07, Eric S. Johansson wrote: > A huge reason why this is important because the vast majority of software > developers who are injured fall off the economic ladder. They leave the > profession and had very few options for work that doesn't involve significant > handy is. The last time I looked at the numbers, in the US somewhere north of > 60,000 developers per year are injured. Some recover (kind of). Others, like I I'm curious, where did you get that statistic? Assuming the US hosts no more than 6M developers, then 60,000 is >=1% which is an alarming amount. -- mvh Bj?rn From mail at timgolden.me.uk Wed May 2 03:49:47 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 02 May 2007 08:49:47 +0100 Subject: Killing Threads In-Reply-To: <000d01c78c60$8c0056d0$a4010470$@rawlins@thinkbluemedia.co.uk> References: <000d01c78c60$8c0056d0$a4010470$@rawlins@thinkbluemedia.co.uk> Message-ID: <4638429B.3000200@timgolden.me.uk> Robert Rawlins - Think Blue wrote: > I've got an application which I've fearfully placed a couple of threads into > however when these threads are running it seems as if I try and quite the > application from the bash prompt it just seems to freeze the SSH client. > I've also seen that if I have my app running in the background on the system > then my 'reboot' no longer works, it just hangs after saying it's going to > shut down. You really need to post code fragments: it makes it much easier to see what you've actually done, rather than the guess which I'm making :) You probably need to setDaemon (True) on your threads after you've created them and before they run. That tells the OS: don't bother waiting for these ones to finish if the program exits. (At least I think that's what it does; I don't use threads all that much) TJG From bob at greschke.com Tue May 1 02:18:12 2007 From: bob at greschke.com (Bob Greschke) Date: Tue, 1 May 2007 00:18:12 -0600 Subject: Want to build a binary header block Message-ID: This is the idea Block = pack("240s", "") Block[0:4] = pack(">H", W) Block[4:8] = pack(">H", X) Block[8:12] = pack(">B", Y) Block[12:16] = pack(">H", Z)) but, of course, Block, a str, can't be sliced. The real use of this is a bit more complicated such that I can't just fill in all of the "fields" within Block in one giant pack(). I need to build it on the fly. For example the pack(">H", X) may be completely skipped some times through the function. There are many more fields in Block than in this example and they are all kinds of types not just H's and B's. What I really want is a C struct union. :) How would I do this? Thanks! Bob From paul at boddie.org.uk Wed May 9 18:02:45 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 9 May 2007 15:02:45 -0700 Subject: String parsing In-Reply-To: References: <1178672992.522463.228620@l77g2000hsb.googlegroups.com> <1178725312.394037.201820@q75g2000hsh.googlegroups.com> Message-ID: <1178748165.367623.97360@l77g2000hsb.googlegroups.com> Dennis Lee Bieber wrote: > > I was trying to stay with a solution the should have been available > in the version of Python equivalent to the Jython being used by the > original poster. HTMLParser, according to the documents, was 2.2 level. I guess I should read the whole thread before posting. ;-) I'll have to look into libxml2 availability for Java, though, as it appears (from various accounts) that some Java platform users struggle with HTML parsing or have a really limited selection of decent and performant parsers in that area. Another thing for the "to do" list... Paul From steve at holdenweb.com Sat May 19 21:42:27 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 19 May 2007 21:42:27 -0400 Subject: python shell In-Reply-To: References: <1179337107.842668.112690@k79g2000hse.googlegroups.com> <1179552984.466321.137550@u30g2000hsc.googlegroups.com> Message-ID: Cameron Laird wrote: > In article <1179552984.466321.137550 at u30g2000hsc.googlegroups.com>, > Paddy wrote: >> On May 16, 6:38 pm, Krypto wrote: >>> I have been using python shell to test small parts of the big program. >>> What other ways can I use the shell effectively. My mentor told me >>> that you can virtually do anything from testing your program to >>> anything in the shell. Any incite would be useful. >> Doctest! >> http://en.wikipedia.org/wiki/Doctest > . > . > . > will probably prove more fruitful. > > While I don't like follow-ups which consist of trivial corrections, I *very* > much want to encourage readers to explore Doctest more deeply; it deserves the > attention, even at the cost of appearing pedantic. Is there some mistake in this post? I find that there *is* an article at http://en.wikipedia.org/wiki/Doctest but that http://en.wikipedia.org/wiki/DocTest doesn't refer to an extant article. Since you claim to be exercising your pedantry, I wonder why I get the results I do. Since we *are* being pedantic, by the way, surely the name is actually "doctest", not "Doctest". 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From duncan.booth at invalid.invalid Tue May 22 15:11:12 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 22 May 2007 19:11:12 GMT Subject: Inheritance References: <1179859216.425460.252130@w5g2000hsg.googlegroups.com> Message-ID: HMS Surprise wrote: > I am trying to understand the 'if' statement and the exec statement in > the code below. > > from PyHttpTestCase import PyHttpTestCase > from com.bitmechanic.maxq import Config > global validatorPkg > if __name__ == 'main': > validatorPkg = Config.getValidatorPkgName() > # Determine the validator for this testcase. > exec 'from '+validatorPkg+' import Validator' 'global' inside a function makes a name have global scope in the function where it would otherwise have been local. 'global' at file scope is completely pointless. > In particular what is the purpose of the > surrounding plus signs? The plus sign are simply concatenating strings. exec should generally be avoided for several reasons. Here it is being used simply to import from a module whose name has been determined at runtime: a call to the __import__ builtin could be used for the same thing. > May I assume the if statement overrides an > imported assignment statement. There isn't anything in the code you pasted which could be assigning to the name validatorPkg. If the code is run as the main script then validatorPkg is set to some value. If the code is imported as a module then validatorPkg will (unless there is some very convoluted code) be unset when the exec is executed. It would appear that the 'if' statement serves purely to make the code fail if it is imported as a module. From cam.ac.uk at mh391.invalid Sun May 20 20:06:48 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 21 May 2007 01:06:48 +0100 Subject: Inverse of id()? In-Reply-To: References: <1179618173.280286.284120@n59g2000hsh.googlegroups.com> Message-ID: Gabriel Genellina wrote: > En Sat, 19 May 2007 20:42:53 -0300, Paul McGuire > escribi?: > >>>>> z = id(results) >>>>> for x in globals().values(): >> ... if id(x)==z: break >> ... >> >> This gives me a variable x that is indeed another ref to the results >> variable: >>>>> x is results >> True >>>>> x.x >> 123 >> >> Now is there anything better than this search technique to get back a >> variable, given its id? > > py> class A:pass > ... > py> class B:pass > ... > py> a=A() > py> id(a) > 10781400 > py> del a > py> b=B() > py> id(b) > 10781400 > > Now if you look for id=10781400 you'll find b, which is another, > absolutely unrelated, object. That's not what I get: Python 2.5 (r25:51908, Mar 13 2007, 08:13:14) [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> class A: pass ... >>> class B: pass ... >>> a = A() >>> id(a) 2146651820 >>> b = B() >>> id(b) 2146651948 -- Michael Hoffman From luismgz at gmail.com Fri May 4 17:54:01 2007 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M=2E_Gonz=E1lez?=) Date: 4 May 2007 14:54:01 -0700 Subject: Microsoft's Dynamic Languages Runtime (DLR) In-Reply-To: <1178313159.059210.97560@y80g2000hsf.googlegroups.com> References: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> <1178151313.421106.43130@o5g2000hsb.googlegroups.com> <1178151574.302703.205560@l77g2000hsb.googlegroups.com> <1178296035.993859.183720@n59g2000hsh.googlegroups.com> <1178313159.059210.97560@y80g2000hsf.googlegroups.com> Message-ID: <1178315641.763473.168290@h2g2000hsg.googlegroups.com> On May 4, 6:12 pm, Fuzzyman wrote: > On May 4, 5:27 pm, Kaz Kylheku wrote: > > > > > On May 2, 5:19 pm, sturlamolden wrote: > > > > On May 3, 2:15 am, Kaz Kylheku wrote: > > > > > Kindly refrain from creating any more off-topic, cross-posted threads. > > > > Thanks. > > > > The only off-topic posting in this thread is your own (and now this > > > one). > > > You are making a very clumsy entrance into these newsgroups. So far > > you have started two cross-posted threads. The first is only topical > > in comp.lang.python (how to emulate macros in Python). This one is > > topical in neither one, since it is about Microsoft DLR. > > > It's quite possible that some Lisp and Python programmers have a > > strong interest in Microsoft DLR. Those people who have such an > > interest (regardless of whether they are Lisp and Python user also) > > and who like to read Usenet will almost certainly find a Microsoft DLR > > newsgroup for reading about and discussing Microsoft DLR. Do you not > > agree? > > Given that the DLR is a dynamic language framework, abstracted out of > the IronPython 1.0 release, and that it also runs on top of the core > CLR shipped with SilverLight meaning that for the first time sandboxed > Python scripts can run in the browser... > > It would seem entirely on topic for a Python newsgroup.... very on- > topic... > > Fuzzymanhttp://www.voidspace.org.uk/ironpython/index.shtml > > > Also note that there is very rarely, if ever, any good reason for > > starting a thread which is crossposted among comp.lang.* newsgroups, > > even if the subject contains elements that are topical in all of them > > (yours does not). > > > > Begone. > > > You are childishly beckoning Usenet etiquette to be gone so that you > > may do whatever you wish. But I trust that you will not, out of spite > > for being rebuked, turn a few small mistakes into a persistent style. Indeed, the subject is absolutely on-topic. If can't talk about a so called "Dynamic Languages Runtime" in a pyhton mailing list, I wonder what it takes to be considered on-topic. Frankly, this on-topic/off-topic fascism I see in this list is pissing me off a little bit. I suggest reading this paragraph right from http://www.python.org/community/lists/: "Pretty much anything Python-related is fair game for discussion, and the group is even fairly tolerant of off-topic digressions; there have been entertaining discussions of topics such as floating point, good software design, and other programming languages such as Lisp and Forth." Luis From mikeminer53 at hotmail.com Tue May 22 14:49:39 2007 From: mikeminer53 at hotmail.com (mkPyVS) Date: 22 May 2007 11:49:39 -0700 Subject: Resizing listbook's listview pane Message-ID: <1179859779.588679.9220@h2g2000hsg.googlegroups.com> I'm having an issue I need help with. I want to resize the listview control in a listbook but have been unsuccessfull through setting the columnWidth of the 0'th column and trying to retrieve the listbooks sizer return's None.... Ideas? Thanks, From haraldarminmassa at gmail.com Mon May 21 01:54:13 2007 From: haraldarminmassa at gmail.com (GHUM) Date: 20 May 2007 22:54:13 -0700 Subject: EUROPYTHON: Talk submission deadline extended up to Friday, 25th of May Message-ID: <1179726853.011402.112610@x35g2000prf.googlegroups.com> We took longer then planned to open the registration. Some potential speakers came in late. To make it even, we extended talk submission deadline for ONE WEEK. New deadline is Friday, 25th of May 2007. So, if you made a fortune with Python: tell others about it at EuroPython. If you have a great distributed revision control system, which has been stable on 9.3 for months, submit a talk to EuroPython and announce 1.0 there! If you have a fantastic new keyword, graphic library or web framework for Python: submit your talk to EuroPython. If you are doing something interesting with Python - grab the chance to visit Lithuania and tell Europe about it. And if you do not wanna give a talk: block 9-11 July 2007 in your calendar, adjust your budget, tell your customers that you will be in Vilnius. Again: Talk submission deadline of EuroPython 2007 extended to Friday, 25th of May 2007 Submit your talk @ www.europython.org For the EuroPython 2007 organizers Harald Armin Massa From gh at gregor-horvath.com Wed May 16 05:08:39 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Wed, 16 May 2007 11:08:39 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464ab811$0$10185$9b4e6d93@newsspool4.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <46478694$0$1412$426a34cc@news.free.fr> <1hy252p.1anf7sr1p4yp12N%aleax@mac.com> <464988a4$0$20289$9b4e6d93@newsspool3.arcor-online.net> <464aaee8$0$10188$9b4e6d93@newsspool4.arcor-online.net> <464ab811$0$10185$9b4e6d93@newsspool4.arcor-online.net> Message-ID: Ren? Fleschenberg schrieb: >> I love Python because it does not dictate how to do things. >> I do not need a ASCII-Dictator, I can judge myself when to use this >> feature and when to avoid it, like any other feature. > > *That* logic can be used to justify the introduction of *any* feature. > No. That logic can only be used to justify the introduction of a feature that brings freedom. Who are we to dictate the whole python world how to spell an identifier? Gregor From tjreedy at udel.edu Mon May 7 20:37:57 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 7 May 2007 20:37:57 -0400 Subject: is for reliable? References: Message-ID: Yes. wrote in message news:BmL%h.781$%k.3759 at twister2.libero.it... | Hi to all I have a question about the for statement of python. I have the | following piece of code where cachefilesSet is a set that contains the | names of 1398 html files cached on my hard disk [snip]| | this code stops at the 473th file instead of reaching 1398 In what way does it stop? Exception and traceback? | however I changed the for and substituted it with a while in this way | | while cachefilesSet: | fn = cachefilesSet.pop() | ....... | ....... | | the while loop reaches the 1398th file and is some 3-4 times faster than | the for loop Perhaps you have a broken installation. What version,system,compiler? tjr From pydecker at gmail.com Mon May 21 17:30:10 2007 From: pydecker at gmail.com (Peter Decker) Date: Mon, 21 May 2007 17:30:10 -0400 Subject: Python and GUI In-Reply-To: <4651CDBC.1070508@ulmcnett.com> References: <1179761984.704369.116310@b40g2000prd.googlegroups.com> <4651CDBC.1070508@ulmcnett.com> Message-ID: On 5/21/07, Paul McNett

wrote: > Shameless plug: consider using Dabo on top of wxPython - we feel it > makes wxPython even easier and more pythonic, but admittedly there's a > bit of a learning curve there too. Even though Dabo is a full > application framework originally meant for desktop database > applications, it is modular and you can choose to only use the UI > bits... http://dabodev.com I second this. I used (and struggled!) with wxPython for over a year. The results were great, but I hated coding it. I switched to the Dabo UI wrapper, and stuff that used to take me a day to create is now done in an hour or two. -- # p.d. From JarodEvans at gmail.com Wed May 30 05:20:35 2007 From: JarodEvans at gmail.com (JarodEvans at gmail.com) Date: 30 May 2007 02:20:35 -0700 Subject: Speex bindings for python 2.5 In-Reply-To: <1180485052.149837.105080@a26g2000pre.googlegroups.com> References: <1180466922.114571.46410@d30g2000prg.googlegroups.com> <1180467121.238065.111720@r19g2000prf.googlegroups.com> <1180485052.149837.105080@a26g2000pre.googlegroups.com> Message-ID: <1180516835.493969.24840@q66g2000hsg.googlegroups.com> On 30 mai, 02:30, momobear wrote: > > I forgot to give the url http://www.freenet.org.nz/python/pySpeex/ > > I Couldn't Open the website. Maybe it was a temporary shutdown, I have no problem here. From robin at reportlab.com Wed May 30 12:10:35 2007 From: robin at reportlab.com (Robin Becker) Date: Wed, 30 May 2007 17:10:35 +0100 Subject: Call for Ruby Champion !! In-Reply-To: <1180539296.378055.194680@m36g2000hse.googlegroups.com> References: <1180539296.378055.194680@m36g2000hse.googlegroups.com> Message-ID: <465DA1FB.7080800@chamonix.reportlab.co.uk> IT Recruiter wrote: > Hello friends! > > I am looking for a Ruby Champion to lead the race in Website > development within Java environment... > > Who loves programming, with new techniques as well as old..... > Who also enjoys hand coding open source technologies with in-depth > knowledge of statistical methods > Has a practical approach when it comes to problem solving > And aspires a team spirit to be agile... > > It's very useful to have other programming languages and paradigms > > About Client: Young Company, fastest growing in the web market > > This is a permanent role in central London, paying as per market rate > for the excellent candidate > > > About Me: I am a Resourcing Consultant specialist in recruiting for > Open Source Technologies. > > please do not hesitate to speak to me or write me back ! > > Really appreciable for a word of mouth with our friends !!! > > Cheers, > Srini > Boy have you got the wrong vampire ;) -- Robin Becker From stugots at qwest.net Thu May 10 10:39:46 2007 From: stugots at qwest.net (John DeRosa) Date: Thu, 10 May 2007 07:39:46 -0700 Subject: preferred windows text editor? References: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> Message-ID: <6gb64356ef7bprc01casahl4p15heicv59@4ax.com> On Wed, 9 May 2007 13:06:52 -0500, "T. Crane" wrote: >Right now I'm using Notepad++. What are other people using? SPE, out of the trunk. http://sourceforge.net/projects/spe/ John From arunmail at gmail.com Thu May 10 17:43:17 2007 From: arunmail at gmail.com (lazy) Date: 10 May 2007 14:43:17 -0700 Subject: Newbie question about string(passing by ref) Message-ID: <1178833397.076720.279940@l77g2000hsb.googlegroups.com> Hi, I want to pass a string by reference. I understand that strings are immutable, but Im not going to change the string in the function, just to aviod the overhead of copying(when pass-by-value) because the strings are long and this function will be called over and over again. I initially thought of breaking the strings into list and passing the list instead, but I think there should be an efficient way. So is there a way to pass a const reference to a string? Thanks From grante at visi.com Mon May 14 15:14:49 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 14 May 2007 19:14:49 -0000 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <4648B002.3050508@web.de> Message-ID: <134hd99dujkhh45@corp.supernews.com> On 2007-05-14, Stefan Behnel wrote: > Marc 'BlackJack' Rintsch schrieb: >> In , Michel Claveau >> wrote: >> >>> And Il1 O0 ? >> >> Hm, we should ban digits from identifier names. :-) > > Ah, good idea - and capital letters also. After all, they are > rare enough in English to just plain ignore their existance. And I don't really see any need for using more than two characters. With just two letters (ignoring case, of course), you can create 676 identifiers in any namespace. That's certainly got to be enough. If not, adding a special caracter suffix (e.g. $,%,#) to denote the data type should sufficient expand the namespace. So, let's just silently ignore anything past the first two. That way we'd be compatible with Commodor PET Basic. [You don't want to know how long it took me to find all of the name-collision bugs after porting a basic program from a CP/M system which had a fairly sophisticated Basic compiler (no line numbers, all the normal structured programming flow control constructs) to a Commodore PET which had a really crappy BASIC interpreter.] -- Grant Edwards grante Yow! Am I having fun yet? at visi.com From bumtool at gmail.com Wed May 30 07:53:25 2007 From: bumtool at gmail.com (kilnhead) Date: 30 May 2007 04:53:25 -0700 Subject: pyAntTasks In-Reply-To: <1180353401.548751.110330@p77g2000hsh.googlegroups.com> References: <1180353401.548751.110330@p77g2000hsh.googlegroups.com> Message-ID: <1180526005.514740.101580@o5g2000hsb.googlegroups.com> On May 28, 7:56 am, kilnhead wrote: > I am trying to use pyAntTasks in Eclipse. I have followed the example > in the ibm doc, but I get the following error: > > [taskdef] Could not load definitions from resource > pyAntTasks.properties. It could not be found. > > I have added pyAntTasks to my classpath and AntHome directory. > > Anybody have any ideas? I found my major problem. It was spaces in my directory names. From sickcodemonkey at gmail.com Wed May 9 21:49:59 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Wed, 9 May 2007 21:49:59 -0400 Subject: file uploader Message-ID: <2adc542f0705091849t6c092ba0mf1cedd080da36960@mail.gmail.com> Hey guys. I wanted to write a little desktop application that would upload files to an external server, to a specific directory. The desktop application is running on Mac OS X and I built a .psp script that is running on a Red Hat server. NOTE: This application is written for Python 2.5 (both py and psp) My code is giving me problems, in that it is overwriting files. I was wondering if anyone knew of a module or a method that would overcome this dilemma. I can adapt my program to search to see if the file existed already in the directory and append a random string sequence to keep this from occurring, but I do not want to reinvent the wheel (if such a thing exists) and that would clutter up my program. :) Here is what I am currently using: fname = os.path.basename(uploadFile.filename) dir_path = "/u01" open(os.path.join(dir_path, fname), 'wb').write(uploadFile.file.read()) As always, any help is greatly appreciated. .dave -------------- next part -------------- An HTML attachment was scrubbed... URL: From olsongt at verizon.net Thu May 10 14:23:35 2007 From: olsongt at verizon.net (olsongt at verizon.net) Date: 10 May 2007 11:23:35 -0700 Subject: Towards faster Python implementations - theory In-Reply-To: References: <1210i.7468$2v1.2505@newssvr14.news.prodigy.net> <1178705421.711371.182770@e65g2000hsc.googlegroups.com> Message-ID: <1178821414.998672.247260@w5g2000hsg.googlegroups.com> On May 9, 5:02 pm, John Nagle wrote: > Paul Boddie wrote: > > Python has that capability mostly because it's free in an > "everything is a dictionary" implementation. ("When all you have > is a hash, everything looks like a dictionary".) But that limits > implementation performance. Most of the time, nobody is using > "setattr" to mess with the internals of a function, class, or > module from far, far away. But the cost for that flexibility is > being paid, unnecessarily. > I've had this idea in the back of my head for a year or so now, but have been too lazy or busy or both to give the implementation a try. The idea is to create a special dictionary for python internals that contains a pointer-to-a-pointer for the value side of the dictionary, instead of just the standard PyObject*. Then when you start to eval a code block, you could do a one-time lookup of the pointer-to-the- pointer for each method, attribute, etc; and store them in pre- allocated slots. The calls in the block to various GET_ and SET_ functions can then just deal with pointer derefencing instead of a dictionary lookup, and the dictionary can still get changed while this is going on without things blowing up. I think you'd get a big speed up by changing all those dictionary function calls to inlined pointer deref code. Anyone else buy this approach? Or see any fatal flaws? From mail at gedankenkonstrukt.de Sat May 12 05:34:16 2007 From: mail at gedankenkonstrukt.de (Thomas Wittek) Date: Sat, 12 May 2007 11:34:16 +0200 Subject: stealth screen scraping with python? In-Reply-To: <1178911975.308104.297380@n59g2000hsh.googlegroups.com> References: <1178911975.308104.297380@n59g2000hsh.googlegroups.com> Message-ID: different.engine at gmail.com schrieb: > I am screen scraping a large volume of data from Yahoo Finance each > evening, and parsing with Beautiful Soup. > > I was wondering if anyone could give me some pointers on how to make > it less obvious to Yahoo that this is what I am doing, as I fear that > they probably monitor for this type of activity, and will soon ban my > IP. Use anonymizing proxies: http://www.google.com/search?q=proxies+OR+proxy+anonymous+OR+anonymizing -- Thomas Wittek http://gedankenkonstrukt.de/ Jabber: streawkceur at jabber.i-pobox.net From ccormie at aussiemail.com.au Tue May 8 02:28:04 2007 From: ccormie at aussiemail.com.au (Christopher Cormie) Date: Tue, 08 May 2007 16:28:04 +1000 Subject: interesting exercise In-Reply-To: <1178595952.641173.76540@y80g2000hsf.googlegroups.com> References: <1178595952.641173.76540@y80g2000hsf.googlegroups.com> Message-ID: <134061ls64blmff@corp.supernews.com> Michael Tobis wrote: > I want a list of all ordered permutations of a given length of a set > of tokens. Each token is a single character, and for convenience, they > are passed as a string in ascending ASCII order. > > For example > > permute("abc",2) > > should return ["aa","ab","ac","ba","bb","bc","ca","cb","cc"] If N is constant and small (e.g hard-coded N of 2), list comprehensions provide a concise solution: a = "abc" b = [(x,y) for x in a for y in a] c = ["".join(z) for z in b] print b print c Gives: [('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', ' a'), ('c', 'b'), ('c', 'c')] ['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc'] Cheers, Chris From aahz at pythoncraft.com Thu May 24 15:58:53 2007 From: aahz at pythoncraft.com (Aahz) Date: 24 May 2007 12:58:53 -0700 Subject: Newsgroups and mailing lists (was Re: Slightly OT: Why all the spam?) References: <3bb44c6e0705220008y10f5deb7v86ed82d3f8241761@mail.gmail.com> Message-ID: In article , Michael L Torrie wrote: > >It appears that people using nntp to read this list aren't seeing the >spam because the moderators expire the messages as they find them. Allow this creaky and cranky old-timer to correct what you're trying to write: First of all, if you're accessing python-list as comp.lang.python, you're accessing a newsgroup, *not* a mailing list. Secondly, c.l.py is an unmoderated group; there is no moderator and no control over who posts. However, netnews (Usenet) has a mechanism for cancelling articles, and cancelbots send out cancel messages for spam articles. (Expiring is a completely different mechanism from cancelling; you may be thinking of superceding -- yes, that's how the header is spelled, deal with it -- which uses the cancel mechanism to replace one article with a supposedly-better version.) These days, because of the cancelbot wars, many news servers do not honor cancels, so the extent to which you see spam in c.l.py depends partly on whether your server does honor cancels. Also, because of the nature of netnews distribution, you may still see spam even if your server does honor cancels because the cancel message takes too long to arrive. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Look, it's your affair if you want to play with five people, but don't go calling it doubles." --John Cleese anticipates Usenet From Aether.Singularity at gmail.com Wed May 16 03:53:49 2007 From: Aether.Singularity at gmail.com (Aether.Singularity at gmail.com) Date: 16 May 2007 00:53:49 -0700 Subject: Sorting troubles In-Reply-To: References: <1179158708.433792.127150@h2g2000hsg.googlegroups.com> <1179161396.220858.86150@q75g2000hsh.googlegroups.com> <1179204326.945346.38590@q75g2000hsh.googlegroups.com> Message-ID: <1179302029.409469.218550@n59g2000hsh.googlegroups.com> On May 15, 11:54 am, Steven D'Aprano wrote: > On Mon, 14 May 2007 21:45:26 -0700, seyensubs wrote: > > Ah, I see, just slicing it like that.. nice! But after doing some timing > > tests, the version that's in place and using partitions is about twice > > faster than the non hybrid qSort. The hybrid one, with insertionsSort > > used for smaller lists works faster, but in a weird way. When given > > lists of 2000, the best bet to is to set the threshold to 14, but when > > given a list of 40000, 14 is slow, but a threshold of 200(less or more > > is slower, again) makes it about 8 times faster than a normal qSort, and > > 4 times faster than an in-place qSort, using a self -defined > > partitioning alg. > > > Making a hybrid out of the in-place partitioned qSort makes it a bit > > faster, but not by much compared to the other hybrid which uses list > > comprehensions. > > > Teach said that the optimal threshold in hybrids is 14-16, but guess he > > wasn't so right after all =\\ The overhead of using insertion sort on a > > longer list turns out to be faster than just piling on recursions, when > > confronted with bigger lists. > > Teach may have been thinking of languages where comparing items is fast > and moving data is slow; Python is the opposite, comparisons invoke a > whole bucket-full of object-oriented mechanism, while moving data just > means moving pointers. > > It needs to be said, just in case... this is a good learning exercise, > but don't use this in real code. You aren't going to get within a bull's > roar of the performance of the built-in sort method. Tim Peter's > "timsort" is amazingly powerful; you can read about it here: > > http://pythonowns.blogspot.com/2002_07_28_pythonowns_archive.html#797... > > http://svn.python.org/projects/python/trunk/Objects/listsort.txt > > -- > Steven. Yeah, I know any stuff your average CS student will crank out is way below anything in-built in the core language and libraries. After all, smart, experienced people worked on those a lot more than me on these :) The blog post is dead, but the .txt is alive(it's the svn of python.org, after all). Gonna read it but looks a bit beyond my level of comprehension, for now anyway. Thanks for all the answers! ..oh, got a 10(out of 10) points in class for the program. Writing stuff in a language no one else learns at the university and doing 5 versions of quickSort to test performance must've paid off. Thanks again :) From sidewinder.asu at gmail.com Thu May 24 13:21:41 2007 From: sidewinder.asu at gmail.com (Christopher Anderson) Date: Thu, 24 May 2007 10:21:41 -0700 Subject: modifying values of List or Dictionary when iterating on them In-Reply-To: <1180026141.723991.303810@p47g2000hsd.googlegroups.com> References: <1180026141.723991.303810@p47g2000hsd.googlegroups.com> Message-ID: <5a12a1120705241021l37da9a08oc7ac5b17c3052329@mail.gmail.com> > d=dict(a=1, b=2, c=3) > for k, v in d.iteritems(): > d[k]=d[k]+1 You might as well do: d[k] = v + 1, like for the list. From hq4ever at gmail.com Fri May 4 06:04:41 2007 From: hq4ever at gmail.com (Maxim Veksler) Date: Fri, 4 May 2007 13:04:41 +0300 Subject: Non blocking sockets with select.poll() ? Message-ID: Hi, I'm trying to write a non blocking socket port listener based on poll() because select is limited to 1024 fd. Here is the code, it never gets to "I did not block" until I do a telnet connection to port 10000. """ #!/usr/bin/env python import socket import select s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setblocking(0) s.bind(('0.0.0.0', 10000)) s.listen(5) __poll = select.poll() __poll.register(s) __poll.poll() print "I did not block" """ -- Cheers, Maxim Veksler "Free as in Freedom" - Do u GNU ? From half.italian at gmail.com Tue May 15 04:25:54 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 15 May 2007 01:25:54 -0700 Subject: Trying to choose between python and java In-Reply-To: References: Message-ID: <1179217554.912067.176440@o5g2000hsb.googlegroups.com> >> #3 Is there any equivalent to jfreechart and jfreereport >> (http://www.jfree.org for details) in python. ChartDirector http://www.advsofteng.com/download.html Again, not free for commercial use, but very versatile. ~Sean From duncan.booth at invalid.invalid Fri May 11 04:59:05 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 May 2007 08:59:05 GMT Subject: Newbie question about string(passing by ref) References: <1178833397.076720.279940@l77g2000hsb.googlegroups.com> Message-ID: lazy wrote: > I want to pass a string by reference. I understand that strings are > immutable, but Im not > going to change the string in the function, just to aviod the overhead > of copying(when pass-by-value) because the > strings are long and this function will be called over and over > again. You'll find it is pretty hard to get Python to copy a string even if you wanted it to. About the only way is to break it apart and then construct a new string with the same value from it. >>> s = "some long string" >>> id(s) 12944352 >>> copyofs = s[:] >>> id(copyofs) 12944352 >>> copyofs = s[:-1]+s[-1:] >>> id(copyofs) 12944992 >>> def fn(foo): print id(foo) return foo >>> fn(s) 12944352 'some long string' >>> id(fn(s)) 12944352 12944352 And sometimes two strings created separately magically become the same string (not that should you assume this will happen, just that it might, and the behaviour will vary according to a lot of factors): >>> s1 = "abc" >>> id(s1) 12956256 >>> s2 = "abc" >>> id(s2) 12956256 >>> s1 = "pqr stu" >>> id(s1) 12956288 >>> s2 = "pqr stu" >>> id(s2) 12956192 From fsckedagain at gmail.com Thu May 3 12:57:38 2007 From: fsckedagain at gmail.com (fscked) Date: 3 May 2007 09:57:38 -0700 Subject: _csv.Error: string with NUL bytes In-Reply-To: References: <1178204593.280648.208040@c35g2000hsg.googlegroups.com> <1178209090.674787.202970@o5g2000hsb.googlegroups.com> Message-ID: <1178211458.634214.306500@o5g2000hsb.googlegroups.com> On May 3, 9:29 am, Marc 'BlackJack' Rintsch wrote: > In <1178209090.674787.202... at o5g2000hsb.googlegroups.com>, fscked wrote: > > The traceback is as follows: > > > Traceback (most recent call last): > > File "createXMLPackage.py", line 35, in ? > > for boxid, mac, activated, hw_ver, sw_ver, heartbeat, name, > > address, phone, country, city, in csvreader: > > _csv.Error: string with NUL bytes > > Exit code: 1 , 0001h > > As Larry said, this most likely means there are null bytes in the CSV file. > > Ciao, > Marc 'BlackJack' Rintsch How would I go about identifying where it is? From steve at holdenweb.com Tue May 29 19:31:24 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 29 May 2007 19:31:24 -0400 Subject: Why isn't this query working in python? In-Reply-To: <1180476987.550394.237260@q66g2000hsg.googlegroups.com> References: <1180103946.552760.239200@p47g2000hsd.googlegroups.com> <6e42ec490705250751i89d3cf3v3a3062690d0284aa@mail.gmail.com> <1180207521.072958.322770@p47g2000hsd.googlegroups.com> <1180225290.235515.274000@q19g2000prn.googlegroups.com> <1180279833.131269.136770@w5g2000hsg.googlegroups.com> <1180476987.550394.237260@q66g2000hsg.googlegroups.com> Message-ID: erikcw wrote: > On May 28, 2:47 pm, "Gabriel Genellina" > wrote: >> En Mon, 28 May 2007 14:53:57 -0300, Dennis Lee Bieber >> escribi?: >> >>> On Sun, 27 May 2007 20:35:28 -0400, Carsten Haese >>> declaimed the following in comp.lang.python: >>>> On Sun, 2007-05-27 at 16:39 -0400, davel... at mac.com wrote: >>>>>> sql = """SELECT payment_id FROM amember_payments WHERE >>>>>> member_id=%s AND expire_date > NOW() AND completed=1 AND (product_id >>>>>>>> 11 AND product_id <21)""", (self.uid) >>> It's confusing, as the example shown is not the common form for >>> parameter passing on the .execute() call -- without the .execute() it is >>> unclear. I presume the .execute() is using *sql to unpack the tuple... >> Yes, the original message said self.amember_cursor.execute(*sql) >> It IS confusing... >> >> -- >> Gabriel Genellina > > This is how I've always writing my queries. I learned it from some > tutorial I found on Google when I started - what is the preferred/ > pythonic way to write this query? > Use separate names for the SQL statement and the argument tuple, then pass them as two separate arguments to cursor.execute(). Apart from anything else this makes it somewhat easier to use the same statement with different arguments. But it is no different in principle than what you are doing now, so the change won't remove your bug, I'm afraid. Could you show us a query (with actual results, if you can publish them) that works manually but doesn't work in Python? There has to be something pretty simple wrong here. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From tijs_news at artsoftonline.com Wed May 30 12:22:04 2007 From: tijs_news at artsoftonline.com (Tijs) Date: Wed, 30 May 2007 18:22:04 +0200 Subject: How can an Exception pass over an "except" clause ? References: <1180540010.548057.220270@m36g2000hse.googlegroups.com> Message-ID: <465da4ac$0$329$e4fe514c@news.xs4all.nl> Nebur wrote: > I'm using the contract.py library, running Python 2.4.4. > > Now I'm confronted with the following exception backtrace: > (...) > File "/usr/lib/python2.4/site-packages/contract.py", line 1265, in > _check_preconditions > p = f.__assert_pre > AttributeError: 'function' object has no attribute '__assert_pre' > > For my surprise, I found that the code of contract.py around line 1265 > looks like: > > 1264: try: > 1265: p = f.__assert_pre > 1266: except AttributeError: > 1267: pass > > I'd expect line 1267 to "swallow" the AttributeError siliently. But > the application stops with the above backtrace. > Someone familiar enough with the Python innards ? How can one manage > that an "except" seems to be ignored ? > > Ruben The 'raise' in line 1271 re-raises the last error instead of the exception in whose block it is called. This: try: raise KeyError except: try: raise IndexError except: pass raise raises IndexError, not KeyError. -- Regards, Tijs From gagsl-py2 at yahoo.com.ar Sun May 27 02:18:15 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 27 May 2007 03:18:15 -0300 Subject: a bug in python windows service? References: <1180231245.444827.171390@g37g2000prf.googlegroups.com> Message-ID: En Sat, 26 May 2007 23:00:45 -0300, momobear escribi?: > I feel really puzzled about fellowing code, please help me finger out > what problem here. > > import threading > > class workingthread(threading.Thread): > def __init__(self): > self.quitEvent = threading.Event() > self.waitTime = 10 > threading.Thread.__init__(self) > > def run(self): > while not self.quitEvent.isSet(): > self.quitEvent.wait(self.waitTime) > > def join(self, timeout = None): > self.quitEvent.set() > threading.Thread.join(self, timeout) > > import win32serviceutil > import win32event > > class testTime(win32serviceutil.ServiceFramework): > _svc_name_ = "testTime" > _svc_display_name_ = "testTime" > _svc_deps_ = ["EventLog"] > > def __init__(self, args): > win32serviceutil.ServiceFramework.__init__(self, args) > self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) > self.thread = workingthread() > > def SvcStop(self): > win32event.SetEvent(self.hWaitStop) > > def SvcDoRun(self): > self.thread.run() > win32event.WaitForSingleObject(self.hWaitStop, > win32event.INFINITE) > self.thread.join() No, this is not a bug. You must not call Thread.run(), use Thread.start() instead - else your code won't run in a different thread of execution. See http://docs.python.org/lib/thread-objects.html on how to use Thread objects - and note that you should *only* override __init__ and run, if any. Instead of extending join(), write a specific method to signal the quitEvent or just let the caller signal it. And I don't see in this example why do you need two different events (one on the thread, another on the service controller), a single event would suffice. -- Gabriel Genellina From electronixtar at gmail.com Mon May 7 03:13:46 2007 From: electronixtar at gmail.com (est) Date: 7 May 2007 00:13:46 -0700 Subject: Newbie prob: How to write a file with 3 threads? In-Reply-To: <1178485944.755068.321740@y5g2000hsa.googlegroups.com> References: <1178440537.257526.40980@y5g2000hsa.googlegroups.com> <1178485944.755068.321740@y5g2000hsa.googlegroups.com> Message-ID: <1178522026.763041.319940@e65g2000hsc.googlegroups.com> On May 7, 5:12 am, MRAB wrote: > On May 6, 9:51 am, Marc 'BlackJack' Rintsch wrote:> In <1178440537.257526.40... at y5g2000hsa.googlegroups.com>, est wrote: > > > I need to write a file using 3 threads simutaniously, e.g. Thread 1 > > > write the first byte of test.bin with an "a", second thread write the > > > second byte "b", third thread write the third byte "c". Anyone could > > > give a little example on how to do that? > > > Simplest solution is: don't do that. Write from one thread and send the > > date from the other threads via a `Queue.Queue` to the writing thread. > > Send the number of the thread with the data so the writer thread knows in > > which order the data has to be written. > > [snip] > Or have a `Queue.Queue` for each source thread and make the writer > thread read from each in turn. I'll try Queue.Queue, thank you. I didn't expect that multithread write a file is so troublesome From sickcodemonkey at gmail.com Thu May 31 21:08:05 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Thu, 31 May 2007 21:08:05 -0400 Subject: ImageMagick Issue In-Reply-To: References: <2adc542f0705302100g3135fd0fn1e6c3decd210bd5f@mail.gmail.com> Message-ID: <2adc542f0705311808g61b1ababob62ad7c7f58b2bbb@mail.gmail.com> I ran into another slight problem. And I attempted to fix it, but have not been able to do so yet. If a filename does not contain a space, then this method works like a charm. But if there is a space then the code throws a nasty error. import os import subprocess from os import * imagefile = "/somedir/images/david.huggins/Photo 1.jpg" cmdw = "identify -format %w '"+imagefile+"'" cmdh = "identify -format %h '"+imagefile+"'" pw = subprocess.Popen(cmdw.split(), stdout=subprocess.PIPE, stderr= subprocess.STDOUT) ph = subprocess.Popen(cmdh.split(), stdout=subprocess.PIPE, stderr= subprocess.STDOUT) w = pw.stdout.read().strip() h = ph.stdout.read().strip() ------------ identify: Unable to open file ('/somedir/images/david.huggins/Photo) [No such file or directory]. identify: Unable to open file (1.jpg') [No such file or directory]. identify: Missing an image file name [No such file or directory]. identify: Unable to open file ('/somedir/images/david.huggins/Photo) [No such file or directory]. identify: Unable to open file (1.jpg') [No such file or directory]. identify: Missing an image file name [No such file or directory]. Traceback (most recent call last): On 5/31/07, Facundo Batista wrote: > > Sick Monkey wrote: > > > When I run the following command: > > ozdon at SickCodeMonkey david.huggins]# identify -format %w > > '/someDIR/images/david.huggins/100_0264.JPG' > > >From Python interpreter: > > >>> cmd = "identify -format %w test.jpg" > >>> p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr= > subprocess.STDOUT) > >>> t = p.stdout.read() > >>> p.stdout.close() > >>> t > '50\n' > >>> > > >From command line: > > facundo at expiron:~$ identify -format %w test.jpg > 50 > facundo at expiron:~$ > > Regards, > > -- > . Facundo > . > Blog: http://www.taniquetil.com.ar/plog/ > PyAr: http://www.python.org/ar/ > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From Mattia.Gentilini_REMOVE_ at _REMOVE_CNAF.INFN.IT Wed May 23 04:26:38 2007 From: Mattia.Gentilini_REMOVE_ at _REMOVE_CNAF.INFN.IT (Mattia Gentilini) Date: Wed, 23 May 2007 10:26:38 +0200 Subject: Python on Vista installation issues In-Reply-To: <1179868315.458709.114000@p47g2000hsd.googlegroups.com> References: <1179868315.458709.114000@p47g2000hsd.googlegroups.com> Message-ID: will ha scritto: > Vista is a 64 bit OS and there is no port of pywin32 for either Vista > or 64-bit XP Vista exists in BOTH 32 bit and 64 bit versions. -- |\/|55: Mattia Gentilini e 55 curve di seguito con gli sci |/_| ETICS project at CNAF, INFN, Bologna, Italy |\/| www.getfirefox.com www.getthunderbird.com * Using Mac OS X 10.4.9 powered by Cerebros (Core 2 Duo) * From bbxx789_05ss at yahoo.com Fri May 25 17:54:57 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 25 May 2007 14:54:57 -0700 Subject: problem with eval while using PythonCard In-Reply-To: References: Message-ID: <1180130097.439585.308510@g4g2000hsf.googlegroups.com> On May 25, 3:33 pm, "Michal Lipinski" wrote: > Hi > > its my first post. I have a problem, I want to user eval() function in > a for loop to set labels to staticText so i done something like this: > > dzien=self.components.Calendar.GetDate().GetDay() > for i in range(1,8): > act=dzien+i -1 > eval( 'self.components.d' + str(i) + '.text = "'+ str(act) + '"') > > but there is a problem, the program returned error: > > File "/home/lipton/Projekty/kami-organizer/grafik.py", line 27, in __init__ > eval( 'self.components.d' + str(i) + '.text = "'+ str(act) + '"') > File "", line 1 > self.components.d1.text = "25" > > SyntaxError: invalid syntax > > dont know what is wrong, becouse when i copy and paste in to code : > self.components.d1.text = "25" > > it work great, but when Im trying to do it using eval() it give me a SyntaxError > > Please help. > > ps. sorry for my english ;) How about something like this: ############ #make object: class S(object):pass class X(object):pass class Y(object):pass s = S() s.components = X() s.components.d1 = Y() s.components.d1.text = "hello world" ########### obj = getattr(s.components, "d" + str(1)) obj.text = "goodybe" print s.components.d1.text From gregcorradini at gmail.com Wed May 9 08:37:01 2007 From: gregcorradini at gmail.com (Greg Corradini) Date: Wed, 9 May 2007 05:37:01 -0700 (PDT) Subject: Boolean confusion Message-ID: <10393362.post@talk.nabble.com> Hello all, I'm having trouble understanding why the following code evaluates as it does: >>> string.find('0200000914A','.') and len('0200000914A') > 10 True >>> len('0200000914A') > 10 and string.find('0200000914A','.') -1 In the 2.4 Python Reference Manual, I get the following explanation for the 'and' operator in 5.10 Boolean operations: " The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned." Based on what is said above, shouldn't my first expression ( string.find('0200000914A','.') and len('0200000914A') > 10) evaluate to false b/c my 'x' is false? And shouldn't the second expression evaluate to True? Thanks for your help Greg -- View this message in context: http://www.nabble.com/Boolean-confusion-tf3715438.html#a10393362 Sent from the Python - python-list mailing list archive at Nabble.com. From stefan.sonnenberg at pythonmeister.com Sun May 27 02:14:27 2007 From: stefan.sonnenberg at pythonmeister.com (Stefan Sonnenberg-Carstens) Date: Sun, 27 May 2007 08:14:27 +0200 Subject: Is PEP-8 a Code or More of a Guideline? In-Reply-To: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> Message-ID: <465921C3.50708@pythonmeister.com> Paul McGuire schrieb: > I'm starting a new thread for this topic, so as not to hijack the one > started by Steve Howell's excellent post titled "ten small Python > programs". > > In that thread, there was a suggestion that these examples should > conform to PEP-8's style recommendations, including use of > lower_case_with_underscores style for function names. I raised some > questions about this suggestion, since I liked the names the way they > were, but as a result, part of the discussion has drifted into a > separate track about PEP-8, and naming styles. > > I was under the impression that lower_case_with_underscores was a > dated recommendation, and that recent practice is more inclusive of > mixedCase style identifiers. On the contrary, Steven Bethard > straightened me out, saying that PEP-8 used to accept either style, > but has been amended to accept only lower_case_with_underscores. > > My latest thought on the topic relates back to the Martin v. L?wis > thread-that-would-not-die requesting feedback about PEP 3131, on > adding support for non-ASCII identifiers in Py3K. I posted an out-of- > curiosity comment asking about how underscore separators mix with > Unicode identifiers, including the mechanics of actually typing an > underscore on a non-US keyboard. At this point, I realized that I was > taking things too far off-topic, so I decided to start a new thread. > > Steve, sorry for taking your thread down a rathole. I hope we can > move any further PEP-8-related discussion (if the point merits any) to > this thread. > > -- Paul > > I prefer mixedCaseStyle, and I think that should be "standard", as this style is commonly used in all "major" languages , for example Java,C++,C#. It shortens the identifiers but leaves the meaning intact. From f.braennstroem at gmx.de Mon May 28 14:53:23 2007 From: f.braennstroem at gmx.de (Fabian Braennstroem) Date: Mon, 28 May 2007 18:53:23 +0000 Subject: vte examples and installation Message-ID: Hi, I am looking for simple vte examples mainly for pygtk. Can anyone point me in the right direction or is there a better terminal emulation for pygtk? It would be nice, if there exist a good howto for installing vte up for the use of python; esp. for an old redhat/scientific linux machine... I am a little bit confused!? Greetings! Fabian From pillsbury at gmail.com Wed May 2 23:02:53 2007 From: pillsbury at gmail.com (Pillsy) Date: 2 May 2007 20:02:53 -0700 Subject: ignorance and intolerance in computing communties In-Reply-To: <1178120019.271716.299590@e65g2000hsc.googlegroups.com> References: <1178120019.271716.299590@e65g2000hsc.googlegroups.com> Message-ID: <1178161373.347033.200680@c35g2000hsg.googlegroups.com> On May 2, 11:33 am, Xah Lee wrote: [...] > In a person's computing career, concrete and specialized questions > like these abound, and the answers or knowledge about them are scarce. > Due to the general ignorance of technical knowledge, and the power- > struggling nature of males, and the habit of intolerance and "troll- > crying" in computing communities, made it difficult to have any > sensible discussion of original questions that doesn't fit into some > elementary level of FAQs and concepts. I'm sort of wondering why you'd expect to have a conversation about one concrete and specialized topic in a venue devoted to an entirely different concrete and specialized topic. Cheers, Pillsy From stefan.behnel-n05pAM at web.de Tue May 8 07:30:59 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 08 May 2007 13:30:59 +0200 Subject: replacing string in xml file In-Reply-To: <1178623414.092046.91120@y5g2000hsa.googlegroups.com> References: <1178623414.092046.91120@y5g2000hsa.googlegroups.com> Message-ID: <46405F73.3080501@web.de> saif.shakeel at gmail.com schrieb: > Hi, > I need to replace a string in xml file with something else.Ex > > - > rate > rate > > > > - > > Here i have opened an xml > file(small part is pasted here).I want to replace the word 'localId' > with 'dataPackageID' wherever it comes in xml file.I tried this but > didnt work: > > import sys > > file_input = raw_input("Enter The ODX File Path:") > input_xml = open(file_input,'r') This should say input_xml = open(file_input,'r').read() > input_xml.replace('localId','dataPackageId') > This gives error ---> AttributeError: 'file' > object has no attribute 'replace' > Can someone help me . > Thanks > Stefan From fidtz at clara.co.uk Thu May 3 08:45:26 2007 From: fidtz at clara.co.uk (fidtz at clara.co.uk) Date: 3 May 2007 05:45:26 -0700 Subject: ascii to unicode line endings In-Reply-To: References: <1178191837.424765.51090@o5g2000hsb.googlegroups.com> Message-ID: <1178196326.926359.187930@p77g2000hsh.googlegroups.com> On 3 May, 13:00, Jean-Paul Calderone wrote: > On 3 May 2007 04:30:37 -0700, f... at clara.co.uk wrote: > > > > >On 2 May, 17:29, Jean-Paul Calderone wrote: > >> On 2 May 2007 09:19:25 -0700, f... at clara.co.uk wrote: > > >> >The code: > > >> >import codecs > > >> >udlASCII = file("c:\\temp\\CSVDB.udl",'r') > >> >udlUNI = codecs.open("c:\\temp\\CSVDB2.udl",'w',"utf_16") > > >> >udlUNI.write(udlASCII.read()) > > >> >udlUNI.close() > >> >udlASCII.close() > > >> >This doesn't seem to generate the correct line endings. Instead of > >> >converting 0x0D/0x0A to 0x0D/0x00/0x0A/0x00, it leaves it as 0x0D/ > >> >0x0A > > >> >I have tried various 2 byte unicode encoding but it doesn't seem to > >> >make a difference. I have also tried modifying the code to read and > >> >convert a line at a time, but that didn't make any difference either. > > >> >I have tried to understand the unicode docs but nothing seems to > >> >indicate why an seemingly incorrect conversion is being done. > >> >Obviously I am missing something blindingly obvious here, any help > >> >much appreciated. > > >> Consider this simple example: > > >> >>> import codecs > >> >>> f = codecs.open('test-newlines-file', 'w', 'utf16') > >> >>> f.write('\r\n') > >> >>> f.close() > >> >>> f = file('test-newlines-file') > >> >>> f.read() > >> '\xff\xfe\r\x00\n\x00' > > >> And how it differs from your example. Are you sure you're examining > >> the resulting output properly? > > >> By the way, "\r\0\n\0" isn't a "unicode line ending", it's just the UTF-16 > >> encoding of "\r\n". > > >> Jean-Paul > > >I am not sure what you are driving at here, since I started with an > >ascii file, whereas you just write a unicode file to start with. I > >guess the direct question is "is there a simple way to convert my > >ascii file to a utf16 file?". I thought either string.encode() or > >writing to a utf16 file would do the trick but it probably isn't that > >simple! > > There's no such thing as a unicode file. The only difference between > the code you posted and the code I posted is that mine is self-contained > and demonstrates that the functionality works as you expected it to work, > whereas the code you posted is requires external resources which are not > available to run and produces external results which are not available to > be checked regarding their correctness. > > So what I'm driving at is that both your example and mine are doing it > correctly (because they are doing the same thing), and mine demonstrates > that it is correct, but we have to take your word on the fact that yours > doesn't work. ;) > > Jean-Paul Thanks for the advice. I cannot prove what is going on. The following code seems to work fine as far as console output goes, but the actual bit patterns of the files on disk are not what I am expecting (or expected as input by the ultimate user of the converted file). Which I can't prove of course. >>> import codecs >>> testASCII = file("c:\\temp\\test1.txt",'w') >>> testASCII.write("\n") >>> testASCII.close() >>> testASCII = file("c:\\temp\\test1.txt",'r') >>> testASCII.read() '\n' Bit pattern on disk : \0x0D\0x0A >>> testASCII.seek(0) >>> testUNI = codecs.open("c:\\temp\\test2.txt",'w','utf16') >>> testUNI.write(testASCII.read()) >>> testUNI.close() >>> testUNI = file("c:\\temp\\test2.txt",'r') >>> testUNI.read() '\xff\xfe\n\x00' Bit pattern on disk:\0xff\0xfe\0x0a\0x00 Bit pattern I was expecting:\0xff\0xfe\0x0d\0x00\0x0a\0x00 >>> testUNI.close() Dom From jstroud at mbi.ucla.edu Sun May 20 06:43:46 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 20 May 2007 10:43:46 GMT Subject: converting strings to most their efficient types '1' --> 1, 'A' ---> 'A', '1.2'---> 1.2 In-Reply-To: <465017A0.1030901@lexicon.net> References: <1179529661.555196.13070@k79g2000hse.googlegroups.com> <464E6F32.7070200@lexicon.net> <61B3i.6880$H_.138@newssvr21.news.prodigy.net> <464F93C1.8030305@lexicon.net> <42T3i.29504$Um6.11611@newssvr12.news.prodigy.net> <465017A0.1030901@lexicon.net> Message-ID: John Machin wrote: > So, all in all, Bayesian inference doesn't seem much use in this scenario. This is equivalent to saying that any statistical analysis doesn't seem much use in this scenario--but you go ahead and use statistics anyway? From andy.terrel at gmail.com Thu May 3 21:31:10 2007 From: andy.terrel at gmail.com (Andy Terrel) Date: 3 May 2007 18:31:10 -0700 Subject: Decorating class member functions In-Reply-To: <1178241696.641350.292210@n59g2000hsh.googlegroups.com> References: <1178241696.641350.292210@n59g2000hsh.googlegroups.com> Message-ID: <1178242270.465032.159550@p77g2000hsh.googlegroups.com> Oh I should mention the decorator needs to have some notion of state (such as with the above class) From python at rcn.com Fri May 4 02:41:48 2007 From: python at rcn.com (Raymond Hettinger) Date: 3 May 2007 23:41:48 -0700 Subject: Getting some element from sets.Set In-Reply-To: <1178258913.095438.173020@h2g2000hsg.googlegroups.com> References: <1178258913.095438.173020@h2g2000hsg.googlegroups.com> Message-ID: <1178260908.240628.204210@c35g2000hsg.googlegroups.com> > I do not want to remove the element, but get some element > from the Set. . . . > Is there a way to do this. I am doing it like this: > > for x in s: break > > Now x is /some_element/ from s. That is one way to do it. Another is to write: x = iter(s).next() One more approach: x = s.pop() s.add(x) Raymond Hettinger From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed May 30 07:49:33 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 30 May 2007 13:49:33 +0200 Subject: Key Listeners In-Reply-To: References: <1180491273.446164.281990@q75g2000hsh.googlegroups.com> <1180510259.914953.225420@h2g2000hsg.googlegroups.com> Message-ID: <465d64c4$0$7452$426a74cc@news.free.fr> Benedict Verheyen a ?crit : > bruno.desthuilliers at gmail.com schreef: >> On 30 mai, 04:14, Mike wrote: >>> Are there key listeners for Python? Either built in or third party? >> >> What is a "key listener" ? >> (snip) > In google, the first link is a link to the java sun home page. > The first sentence on that page: "Key events indicate when the user is > typing at the keyboard." I do know what's a "key listener" in Java, thanks !-) My question was supposed to have side effects - like the OP asking himself if he was really asking the right question. Regards too. From sickcodemonkey at gmail.com Thu May 31 00:00:39 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Thu, 31 May 2007 00:00:39 -0400 Subject: ImageMagick Issue Message-ID: <2adc542f0705302100g3135fd0fn1e6c3decd210bd5f@mail.gmail.com> I have the following: OS = RedHat ImagMagick installed. Python v2.5 --------------------- When I run the following command: ozdon at SickCodeMonkey david.huggins]# identify -format %w '/someDIR/images/david.huggins/100_0264.JPG' I get the following result 2304 -------------------- However, when I try to set this value to a variable, ie w= os.system("identify -format %w '/someDIR/images/david.huggins/100_0264.JPG'") print w I get TypeError: argument 1 must be string or read-only buffer, not int NOTE: This is coming from a Python Servlet Page. As always, any input is GREATLY appreciated. Thanks Dave -------------- next part -------------- An HTML attachment was scrubbed... URL: From Roka100 at gmail.com Sat May 19 12:33:34 2007 From: Roka100 at gmail.com (Jia Lu) Date: 19 May 2007 09:33:34 -0700 Subject: Many-to-many pattern possiable? Message-ID: <1179592414.652507.4110@p77g2000hsh.googlegroups.com> Hi all I see dict type can do 1-to-1 pattern, But is there any method to do 1-to-many, many-to-1 and many-to-many pattern ? What about using some Serialized objects? Thanks. From __peter__ at web.de Thu May 10 15:08:39 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 10 May 2007 21:08:39 +0200 Subject: which is more pythonic/faster append or +=[] References: <1hxtelz.7f6rvnw4cyxmN%aleax@mac.com> <1178723595.516379.18180@u30g2000hsc.googlegroups.com> <1hxuz03.husyup2cjk81N%aleax@mac.com> Message-ID: Stargaming wrote: > Alex Martelli schrieb: >> 7stud wrote: >> ... >> >>>>.append - easy to measure, too: >>>> >>>>brain:~ alex$ python -mtimeit 'L=range(3); n=23' 'x=L[:]; x.append(n)' >>>>1000000 loops, best of 3: 1.31 usec per loop >>>> >>>>brain:~ alex$ python -mtimeit 'L=range(3); n=23' 'x=L[:]; x+=[n]' >>>>1000000 loops, best of 3: 1.52 usec per loop >>>> >>>>Alex >>> >>>Why is it necessary to copy L? >> >> >> If you don't, then L gets longer and longer -- to over a million >> elements by the end of the loop -- so we're measuring something that's >> potentially very different from the problem under study, "what's the >> best way to append one item to a 3-items list". >> >> That's important to consider for any microbenchmark of code that changes >> some existing state: make sure you're measuring a piece of code that >> _overall_ does NOT change said existing state in a cumulative way, >> otherwise you may be measuring something very different from the issue >> of interest. It's maybe the only important caveat about using "python >> -mtimeit". >> >> >> Alex >> > > Cannot reproduce that. Consider the following: > > $ python -mtimeit "L=range(3)" "L.append(1); print len(L)" That should be $ python2.5 -m timeit -s "L = range(3)" "L.append(1); print len(L)" | tail 999995 999996 999997 999998 999999 1000000 1000001 1000002 1000003 1000000 loops, best of 3: 1.98 usec per loop Note the -s before the initialization statement that Alex meant to add but didn't. If that is missing L = range(3) is executed on every iteration. Peter From showell30 at yahoo.com Sun May 27 15:00:16 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 27 May 2007 12:00:16 -0700 (PDT) Subject: ten small Python programs In-Reply-To: Message-ID: <856383.68356.qm@web33513.mail.mud.yahoo.com> --- Steven Bethard wrote: > Steve Howell wrote: > > --- Steven Bethard > wrote: > >> I think I would rewrite the current unit-testing > >> example to use the > >> standard library unittest module:: > >> > >> # Let's write reusable code, and unit test > it. > >> def add_money(amounts): > >> # do arithmetic in pennies so as not to > >> accumulate float errors > >> pennies = sum([round(int(amount * 100)) > for > >> amount in amounts]) > >> return float(pennies / 100.0) > >> import unittest > >> class TestAddMoney(unittest.TestCase): > >> def test_float_errors(self): > >> > self.failUnlessEqual(add_money([0.13, > >> 0.02]), 0.15) > >> > self.failUnlessEqual(add_money([100.01, > >> 99.99]), 200) > >> self.failUnlessEqual(add_money([0, > >> -13.00, 13.00]), 0) > >> if __name__ == '__main__': > >> unittest.main() > >> > > > > Just a minor quibble, but wouldn't you want the > import > > and test class to only get executed in the > ___main__ > > context? > > That would be fine too. In the real world, I'd put > the tests in a > different module. > Maybe this is the first good example that motivates a hyperlink to alternatives. Would you accept the idea that we keep my original example on the SimplePrograms page, but we link to a UnitTestingPhilosophies page, and we show your alternative there? Or vice versa, show your example on the first page, but then show mine on the hyperlinked page? I am in 100% agreement with you that most unit tests would be completely outside the module, although I often follow the practice that my modules have a little "if __main__" section that runs a few simple unit tests, as sort of a bit of self-documentation. ____________________________________________________________________________________Building a website is a piece of cake. Yahoo! Small Business gives you all the tools to get online. http://smallbusiness.yahoo.com/webhosting From rridge at caffeine.csclub.uwaterloo.ca Tue May 15 12:59:32 2007 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Tue, 15 May 2007 12:59:32 -0400 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: Marc 'BlackJack' Rintsch wrote: >I think you have to search examples of ASCII sources with transliterated >identifiers too, because the authors may have skipped the transliteration >if they could have written the non-ASCII characters in the first place. The point of my search was to look for code that actually used non-ASCII characters in languages that actually supported it (mainly Java at the time). The point wasn't to create more speculation about what programmers might or might not do, but to find out what they were actually doing. >And then I dare to guess that much of that code is not open source. Lots of non-open source code makes it on to the Internet in the form of code snippets. You don't have to guess what closed-source are actually doing either. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From steven.klass at gmail.com Wed May 2 10:22:07 2007 From: steven.klass at gmail.com (rh0dium) Date: 2 May 2007 07:22:07 -0700 Subject: Is it possible to determine what a function needs for parameters - Message-ID: <1178115727.932794.100390@h2g2000hsg.googlegroups.com> Hi all, Below is a basic threading program. The basic I idea is that I have a function which needs to be run using a queue of data. Early on I specified my function needed to only accept basic parameters ( no postional *args or *kwargs ) but now I am re-writing it and I want to accept these. Is there anyway to determine what parameters are needed by a given function and format the arguments given appropriately. My problem is that I feel my "Kludge"section is just that - a kludge. While it works for most cases it won't work for all (Try running this on function4 for example...). I guess I have a problem with multiple if statements and I think it should just look to see what parameters are accepted and format them appropriately. Thoughts? If I am really screwing this up - please help me get back on the right track. I appreciate all of the help I get and it's great to learn from the experts. import random import threading import Queue class WorkerB(threading.Thread): def __init__(self, *args, **kwargs): self.id = kwargs.get('id', 0) self.requestQ = kwargs.get('requestQ', None) self.function = kwargs.get('function', None) threading.Thread.__init__(self, name=self.__class__.__name__ +"."+str(self.id)) def run(self): while 1: input = self.requestQ.get() if input is None: break # How do I look at the function and determine what it requires then apply that as an input? # -------- Start Kludge ---------- tu=dic=False if isinstance(input, tuple): try: if isinstance(input[0], tuple): tu = True elif isinstance(input[0], list): tu=True except: pass try: if isinstance(input[1], dict):dic = True except: pass if tu and dic: print " -Tuple and list found" result = self.function(*input[0], **input[1]) elif tu and not dic: print " -Tuple found" result = self.function(*input[0]) elif isinstance(input, list): print " -list only found" result = self.function(*input) else: print " -Unknown" result = self.function(input) # -------- End Kludge ---------- def function1(arg1): print arg1 def function2(*a ): print "args", a def function3(*a, **kw): print "args", a print "kwargs", kw def function4(arg1, *a, **kw): print arg1 print "args", a print "kwargs", kw def main(): lod = 2 myQ=Queue.Queue() # A basic example print "\n== Example 1" for x in range(lod):myQ.put( random.random() ) myQ.put(None) a=WorkerB(requestQ=myQ, function=function1).start() # Throw at is some args print "\n== Example 2" for x in range(lod):myQ.put(["a","b","c"]) myQ.put(None) a=WorkerB(requestQ=myQ, function=function2).start() # Throw at it both args and kwargs print "\n== Example 3" for x in range(lod):myQ.put(((1,2,3), {"input":random.random(),"loglevel":10})) myQ.put(None) a=WorkerB(requestQ=myQ, function=function3).start() # Throw at it both args and kwargs print "\n== Example 4 Does nothing!!" for x in range(lod):myQ.put(("alpha",(1,2,3), {"input":random.random(),"loglevel":10})) myQ.put(None) a=WorkerB(requestQ=myQ, function=function4).start() if __name__ == '__main__': main() From gagsl-py2 at yahoo.com.ar Fri May 18 02:14:05 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 18 May 2007 03:14:05 -0300 Subject: Interesting list Validity (True/False) References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> <1178915791.584216.293130@l77g2000hsb.googlegroups.com> <1178918808.091358.233740@o5g2000hsb.googlegroups.com> <1179017740.656323.209590@e51g2000hsg.googlegroups.com> <1179020634.130689.171960@o5g2000hsb.googlegroups.com> <1179031812.090768.248750@l77g2000hsb.googlegroups.com> <1179168081.603409.39970@e51g2000hsg.googlegroups.com> <1179203827.881205.287910@l77g2000hsb.googlegroups.com> <1179248480.350553.4430@n59g2000hsh.googlegroups.com> <1hya1ot.nv08e511bp1wiN%aleax@mac.com> Message-ID: En Fri, 18 May 2007 01:48:29 -0300, Alex Martelli escribi?: > The gmpy designer, writer and maintainer (all in the singular -- that's > me) has NOT chosen anything of the sort. gmpy.mpz does implement > __int__ and __long__ -- but '%d'%somempzinstance chooses not to call > either of them. sys.maxint has nothing to do with the case: > '%d'%somelonginstance DOES work just fine -- hey, even a *float* > instance formats just fine here (it gets truncated). I personally > consider this a bug in %d-formatting, definitely NOT in gmpy. Yes, sorry, at first I thought it was gmpz which refused to convert itself to long. But the fault is in the string formatting code, and it was pointed out later on this same thread. Floats have the same problem: "%d" % 5.2 does work, but "%d" % 1e30 does not. After digging a bit in the implementation of PyString_Format, for a "%d" format it does: - test if the value to be printed is actually a long integer (using PyLong_Check). Yes? Format as a long integer. - else, convert the value into a plain integer (using PyInt_AsLong), and format that. No attempt is made to *convert* the value to a long integer. I understand that this could be a slow operation, so the various tests should be carefully ordered, but anyway the __long__ conversion should be done. -- Gabriel Genellina From aleax at mac.com Mon May 14 01:05:47 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 13 May 2007 22:05:47 -0700 Subject: Basic question References: <1178986686.510137.195490@p77g2000hsh.googlegroups.com> <1178991933.421386.58500@u30g2000hsc.googlegroups.com> <1178992910.318929.77790@e51g2000hsg.googlegroups.com> <1178995630.925969.207740@w5g2000hsg.googlegroups.com> <1hy0cy8.eg6p1p135hbo3N%aleax@mac.com> Message-ID: <1hy2nwq.be9xtykcg7rkN%aleax@mac.com> Gabriel Genellina wrote: > En Sat, 12 May 2007 20:13:48 -0300, Alex Martelli escribi?: > > > Cesar G. Miguel wrote: > >> ------------------- > >> L = [] > >> file = ['5,1378,1,9', '2,1,4,5'] > >> str='' > >> for item in file: > >> L.append([float(n) for n in item.split(',')]) > > > > The assignment to str is useless (in fact potentially damaging because > > you're hiding a built-in name). > > > > L = [float(n) for item in file for n in item.split(',')] > > > > is what I'd call Pythonic, personally (yes, the two for clauses need to > > be in this order, that of their nesting). > > But that's not the same as requested - you get a plain list, and the > original was a list of lists: > > L = [[float(n) for n in item.split(',')] for item in file] Are we talking about the same code?! What I saw at the root of this subthread was, and I quote: > L = [] > file = ['5,1378,1,9', '2,1,4,5'] > str='' > for item in file: > j=0 > while(j while(item[j] != ','): > str+=item[j] > j=j+1 > if(j>= len(item)): break > > if(str != ''): > L.append(float(str)) > str = '' > > j=j+1 > > print L This makes L a list of floats, DEFINITELY NOT a list of lists. > And thanks for my "new English word of the day": supererogatory :) You're welcome! Perhaps it's because I'm not a native speaker of English, but I definitely do like to widen my vocabulary (and others'). Alex From tleeuwenburg at gmail.com Tue May 22 05:44:06 2007 From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com) Date: 22 May 2007 02:44:06 -0700 Subject: Volume 2, Issue 2 of The Python Papers is now available! Download it from www.pythonpapers.org. Message-ID: Volume 2, Issue 2 of The Python Papers is now available! Download it from www.pythonpapers.org. This issue marks a major landmark in our publication. We present a number of industry articles. These include "Python in Education" and "MPD WebAMP", as well as a great insight into Python in Germany, a wrap-up of PyCon 2007, a preview of EuroPython 2007 and a look at some great videos prepared by primary school students. Our peer-reviewed section reproduces two selected papers which were originally presented at the Open Source Developer's Conference 2006 (Melbourne, Australia). Check it out and let us know what you think. All the best, The Python Papers Team From steve at holdenweb.com Tue May 29 16:45:27 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 29 May 2007 16:45:27 -0400 Subject: How to set a class inheritance at instance creation? In-Reply-To: <1180453971.556244.91370@q69g2000hsb.googlegroups.com> References: <1180453971.556244.91370@q69g2000hsb.googlegroups.com> Message-ID: <465C90E7.2080108@holdenweb.com> glomde wrote: > Hi I wonder if you can set what subclass a class should > have at instance creation. > > The problem is that I have something like: > > class CoreLang(): > def AssignVar(self, var, value): > pass > > class Lang1(CoreLang): > def AssignVar(self, var, value): > return var, "=", value > > class Lang2(CoreLang): > def AssignVar(self, var, value): > return var, "<=", value > > class WriteStruct(): > def Generate(self, vars): > for var in vars: > print self.AssignVar() > > The problem is that I want WriteStruct to sometimes be a subclass of > Lang1 and sometimes > of Lang2. > In the above example I could but the Generate Method in CoreLang. But > in my real > example I also want to able to subclass WriteStruct to be able to easy > customize WriteStruct. > Which I wouldnt be able to do if it was a method in CoreLang. > > So in code I would like to write something like: > > WriteStruct(Lang1).Generate(vars) > > Even better would be that if I in the Lang1 class could > just do WriteStruct().Generate(vars) and Lang1 class would > magically make WriteStruct a subclass of itself. > > You should rethink your program design. It seems that when you create a WriteStruct you should really be passing its __init__() method the class that you want it to be a "subclass" of, creating an instance of that class, and then using generic delegation to that subclass (using a modified __getattr__()) to handle methods that aren't found in the WriteStruct. I can see there are circumstances in which this might not work, but I believe your current ugly intentions reveal a design smell that you really need to get rid of if you want a clean program. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From silverburgh.meryl at gmail.com Thu May 24 14:22:09 2007 From: silverburgh.meryl at gmail.com (silverburgh.meryl at gmail.com) Date: 24 May 2007 11:22:09 -0700 Subject: How can I time a method of a class in python using Timeit In-Reply-To: <1180028476.396282.316330@q69g2000hsb.googlegroups.com> References: <1180020970.039576.319230@m36g2000hse.googlegroups.com> <1180027843.322955.57280@q75g2000hsh.googlegroups.com> <1180028334.650900.283930@m36g2000hse.googlegroups.com> <1180028476.396282.316330@q69g2000hsb.googlegroups.com> Message-ID: <1180030929.813680.257140@h2g2000hsg.googlegroups.com> On May 24, 12:41 pm, 7stud wrote: > Actually, you can do this: > > class Dog(object): > def aFunction(self): > result = 20 + 2 > def run(self): > #do stuff > aFunction() > #do other stuff > import timeit > > t = timeit.Timer("d.aFunction()", "from __main__ import Dog; d = > Dog()") > print t.timeit() > > Since you only want to time aFunction(), you can call it directly. Thanks for all the idea. From gagsl-py2 at yahoo.com.ar Wed May 2 02:07:13 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 02 May 2007 03:07:13 -0300 Subject: os.path.join References: <1178072869.844914.59010@u30g2000hsc.googlegroups.com> Message-ID: En Wed, 02 May 2007 01:23:45 -0300, Elliot Peele escribi?: > On Tue, 2007-05-01 at 19:27 -0700, 7stud wrote: >> On May 1, 7:36 pm, Elliot Peele wrote: >> > Why does os.path.join('/foo', '/bar') return '/bar' rather than >> > '/foo/bar'? That just seems rather counter intuitive. >> > >> > Elliot >> >> join( path1[, path2[, ...]]) >> Join one or more path components intelligently. If any component is an >> absolute path, all previous components (on Windows, including the >> previous drive letter, if there was one) are thrown away... > > Yes, but that still doesn't answer my question as to why os.path.join > works that way. I understand that that is how it is written, but why? It's not *how* it is written, but the current documentation for os.path.join: http://docs.python.org/lib/module-os.path.html#l2h-2176 It appears that the function docstring (used by the help system) is too terse here. -- Gabriel Genellina From johnjsal at NOSPAMgmail.com Thu May 3 11:37:52 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 03 May 2007 11:37:52 -0400 Subject: Any way to refactor this? In-Reply-To: References: <461fe75c$0$11278$c3e8da3@news.astraweb.com> <461ff01c$0$29118$426a74cc@news.free.fr> <4638af08$0$448$c3e8da3@news.astraweb.com> Message-ID: <4639ffc9$0$30537$c3e8da3@news.astraweb.com> Steven D'Aprano wrote: > Bruno's code has two micro-optimizations. The first is to avoid > looking up visual.cylinder each time (six times the number of loops) and > instead only look it up once. Oh I see. I was thinking the optimization had something to do with *calling* the function less often, but that's different from the actual lookup I suppose. :) From bradallen137 at gmail.com Wed May 2 02:13:36 2007 From: bradallen137 at gmail.com (bradallen) Date: 1 May 2007 23:13:36 -0700 Subject: Python user group in Portland, OR? In-Reply-To: <1178057364.942127.203200@n76g2000hsh.googlegroups.com> References: <1178054753.732189.137230@h2g2000hsg.googlegroups.com> <1178057364.942127.203200@n76g2000hsh.googlegroups.com> Message-ID: <1178086416.627917.263780@h2g2000hsg.googlegroups.com> It looks like there are a lot of folks in the Portland area at meetup.com who have expressed an interest in a meetup group. In hopes of attracting those, I went ahead and shelled out the bucks to start a meetup site for a Portland Python user group: http://python.meetup.com/183/ From roy at panix.com Sun May 27 16:25:22 2007 From: roy at panix.com (Roy Smith) Date: Sun, 27 May 2007 16:25:22 -0400 Subject: Is PEP-8 a Code or More of a Guideline? References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <87abvqpl6v.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Is C no longer a "major" language? The long-standing convention there > is for lower_case_with_underscores. Which dates back to the days of ASR-33's which only had one case (upper case, as a matter of fact). Does nobody else remember C compilers which accepted \( and \) for { and }? From castironpi at gmail.com Tue May 8 00:34:36 2007 From: castironpi at gmail.com (castironpi at gmail.com) Date: 7 May 2007 21:34:36 -0700 Subject: interesting exercise In-Reply-To: <1178595952.641173.76540@y80g2000hsf.googlegroups.com> References: <1178595952.641173.76540@y80g2000hsf.googlegroups.com> Message-ID: <1178598876.913274.184850@p77g2000hsh.googlegroups.com> On May 7, 10:45 pm, Michael Tobis wrote: > I want a list of all ordered permutations of a given length of a set > of tokens. Each token is a single character, and for convenience, they > are passed as a string in ascending ASCII order. > > For example > > permute("abc",2) > > should return ["aa","ab","ac","ba","bb","bc","ca","cb","cc"] > > and permute("13579",3) should return a list of 125 elements > ["111","113", ... ,"997","999"] > > permute("axc",N) or permute("2446",N) should raise ValueError as the > alphabet is not strictly sorted. > > I have a reasonably elegant solution but it's a bit verbose (a couple > dozen lines which I'll post later if there is interest). Is there some > clever Pythonism I didn't spot? > > thanks > mt Post yours. From collver at peak.org Fri May 4 10:22:34 2007 From: collver at peak.org (Ben Collver) Date: Fri, 04 May 2007 07:22:34 -0700 Subject: My Python annoyances In-Reply-To: References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> <1178202431.147195.249790@u30g2000hsc.googlegroups.com> Message-ID: Ben Collver wrote: > Chris Mellon wrote: >> Code like this is working directly against Python philosophy. You >> probably got told this on #python, too. There's hardly any >> circumstance where you should need to validate the exact class of an >> object, and as long as they have the same interface theres no harm >> whatsoever in tempfile changing it's return value between Python >> versions. > > I am unqualified to comment on the Python philosophy, but I would like > for my function to do some basic error checking on its arguments. By "basic error checking" I mean "verify that the file argument actually is a file-like object". By same interface, do you mean that I should check for the methods that I depend on? That sounds easy enough. Thanks for the hint, Ben From esj at harvee.org Tue May 29 15:22:11 2007 From: esj at harvee.org (Eric S. Johansson) Date: Tue, 29 May 2007 15:22:11 -0400 Subject: Is PEP-8 a Code or More of a Guideline? In-Reply-To: <007001c7a204$a5a45e10$240110ac@Muse> References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <1180254338.292249.29520@h2g2000hsg.googlegroups.com> <007001c7a204$a5a45e10$240110ac@Muse> Message-ID: Warren Stringer wrote: > Hi Eric, > > You make a compelling argument for underscores. I sometimes help a visually > impaired friend with setting up his computers. > > I'm wondering about the aural output to you second example: > > link.set_parse_action(emit_link_HTML) > > Does it sound like this: unfortunately, I do not have text to speech set up on this machine as I'm saving the storage for more MP3s. :-) > link dot set under parse under action space between parens emit under link > under HTML jump out it would probably say underscore instead of under and left ( and right ) (too much work is make it spell out the symbol). > > Also, does how HTML read? Is it "H T M L" or "cap H cap T cap M cap L" ? probably HTML. Remember case is not apparent in an aural interface. > How many python programmers can reconfigure their speech-to-text and > text-to-speech converter? It's really difficult. I'm getting by right now with some minimal macros to start classes and methods as well as things like putting a: on the end of the line. But it is really primitive. When I had voice coder working, it was pretty good and the only problem was command surface area. Isn't there a Python based accessibility project? You might be thinking of voice coder and VR-mode for Emacs. Both projects need help, via-mode probably the most useful to the beginning user but combining the two would make a very nice voice driven Python IDE. Of course if somebody wanted to adapt it to another IDE that was nice and not too expensive, I think people would not say no to that either. > Perhaps a few lines of script to add CamelBack support, using an amplitude > increase for initial caps and maybe lingering on the initial phoneme for an > extra 100 milliseconds. So then, the above example would read: I can tell you've never used speech recognition. :-) if you do that for a few weeks, you'll find yourself being reluctant to talk and considering using Morse code sent by big toe as your primary computer interface. QLF OM? Seriously, amplitude and timing information is gone by the time we get recognition events. This is a good thing because it eliminates problems caused by individual habits and physiological traits. As I've said before, I think the ultimate programming by voice environment is one in which the environment is aware of what symbols can be spoken and uses that information to improve accuracy. This will also allow for significant shortcuts in what you say in order to get the right code. The problem with this being that it needs to work when the code is broken. And I don't mean a little broken, I mean the kind of broken it gets when you are ripping out the implementation of one concept and putting in a new one. Yes, it's a hard problem. ---eric From gagsl-py2 at yahoo.com.ar Tue May 1 04:32:52 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 01 May 2007 05:32:52 -0300 Subject: Log-in to forums (using cookielib)? References: <4636f011$0$329$e4fe514c@news.xs4all.nl> Message-ID: En Tue, 01 May 2007 04:44:57 -0300, Olivier Oost escribi?: > I need to login to a online forum, like a phpbb forum, and leave a > message there. I figured I need to use cookielib, but the documentation > of cookielib is not very clear to me. > Can someone please tell me how I should log-in and leave a message on > the board? Sure. But considering that this smells like an Automatic Spamming Machine, I hope nobody will. -- Gabriel Genellina From hafeliel at yahoo.com Sat May 19 10:19:56 2007 From: hafeliel at yahoo.com (Gre7g Luterman) Date: Sat, 19 May 2007 08:19:56 -0600 Subject: Creating a sub folder in the pythons LIB Directory References: <1179582729.526366.13130@p77g2000hsh.googlegroups.com> Message-ID: wrote in message news:1179582729.526366.13130 at p77g2000hsh.googlegroups.com... > Hi, > > I am creating a library of functions. I would like to have them saved > in a sub folder of pythons LIB folder, but I cannot get it to work. > > I have a script called test.py > I stored it in LIB folder and typed > Import test, work fine. > I store the script in lib/ted > Then type > Import lib\ted Try "import ted.test" or "from ted import test". I also recommend reading http://www.python.org/doc/essays/packages.html as it explains how to use __init__.py files. From stefan.sonnenberg at pythonmeister.com Sun May 6 02:52:43 2007 From: stefan.sonnenberg at pythonmeister.com (Stefan Sonnenberg-Carstens) Date: Sun, 06 May 2007 08:52:43 +0200 Subject: Python Binding In-Reply-To: <463D6FFD.2050005@web.de> References: <463D6FFD.2050005@web.de> Message-ID: <463D7B3B.6040704@pythonmeister.com> Stefan Behnel schrieb: > Georg Grabler wrote: > >> There's a C library which i'd like to have python bindings for. I havn't >> known anything before about how to write python bindings for a C library. >> >> I succeeded now by using distutils to write the first bindings for functions >> and similar. >> >> Now, it seems as something is blocking my brain. For the library, i >> need "custom" types, so types defined in this library (structures), >> including pointers and similar. >> >> I've been thinking about what i will need to represent this lists in python. >> I thought about creating an external python object, providing "information" >> i get from the list in C structures which can be converted. >> >> Basically, it are list of packages, which have several attributes (next, >> prev, etc). But i don't know how to supply a proper list from the binding / >> object written in C. >> >> Any suggestions or hints about this? >> > > Use Pyrex. It's a Python-like language that was designed to write extension > modules in C and it's great for writing wrappers. > > http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/ > > An example wrapper is described here: > > http://ldots.org/pyrex-guide/ > > Hope it helps, > Stefan > Hi, use SWIG. It is a no-brainer for simple libs. wxPython relies heavily on it. I worked with some times and it is really straightforward. See this: http://www.swig.org/Doc1.1/HTML/Python.html Cheers, Stefan From gagsl-py2 at yahoo.com.ar Mon May 21 03:24:50 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 21 May 2007 04:24:50 -0300 Subject: trouble with pyvtk References: <1179462146.957576.193110@o5g2000hsb.googlegroups.com> <1179466886.812669.95170@w5g2000hsg.googlegroups.com> <1179724306.614416.166960@z24g2000prd.googlegroups.com> Message-ID: En Mon, 21 May 2007 02:11:46 -0300, LokiDawg escribi?: > Thanks for the tip, Ondrej. Unfortunately, this didn't do it, as pytvk > still ends up at the same place: > > File "/usr/lib/python2.4/site-packages/pyvtk/common.py", line 149, > in get_datatype > r = self.get_datatype(o) > File "/usr/lib/python2.4/site-packages/pyvtk/common.py", line 140, > in get_datatype > if is_int(obj): return self.default_int > > RuntimeError: maximum recursion depth exceeded This looks like either a bug on pyvtk or maybe you making a circular reference to something - either way I think you'll get more help from the package developers. -- Gabriel Genellina From _karlo_ at _mosor.net Sat May 12 14:09:46 2007 From: _karlo_ at _mosor.net (Karlo Lozovina) Date: Sat, 12 May 2007 20:09:46 +0200 Subject: Basic question In-Reply-To: <1178992910.318929.77790@e51g2000hsg.googlegroups.com> References: <1178986686.510137.195490@p77g2000hsh.googlegroups.com> <1178991933.421386.58500@u30g2000hsc.googlegroups.com> <1178992910.318929.77790@e51g2000hsg.googlegroups.com> Message-ID: Cesar G. Miguel wrote: > ------------------------------------- > L = [] > file = ['5,1378,1,9', '2,1,4,5'] > str='' > for item in file: > j=0 > while(j while(item[j] != ','): > str+=item[j] > j=j+1 > if(j>= len(item)): break > > if(str != ''): > L.append(float(str)) > str = '' > > j=j+1 > > print L > But I'm not sure this is an elegant pythonic way of coding :-) Example: In [21]: '5,1378,1,9'.split(',') Out[21]: ['5', '1378', '1', '9'] So, instead of doing that while-based traversal and parsing of `item`, just split it like above, and use a for loop on it. It's much more elegant and pythonic. HTH, Karlo. From maciej.blizinski at gmail.com Thu May 31 14:30:10 2007 From: maciej.blizinski at gmail.com (=?utf-8?B?TWFjaWVqIEJsaXppxYRza2k=?=) Date: 31 May 2007 11:30:10 -0700 Subject: Adding tuples to a dictionary Message-ID: <1180636210.328300.298850@p77g2000hsh.googlegroups.com> Hi Pythonistas! I've got a question about storing tuples in a dictionary. First, a small test case which creates a list of dictionaries: import time list_of_dicts = [] keys = [str(x) for x in range(200000)] prev_clk = time.clock() for i in range(20): my_dict = {} for key in keys: my_dict[key] = key list_of_dicts.append(my_dict) new_clk = time.clock() print i, new_clk - prev_clk prev_clk = new_clk It creates dictionaries and stores them in a list, printing out execution times. The size of each dictionary is constant, so is the execution time for each iteration. 0 0.1 1 0.1 2 0.1 3 0.08 4 0.09 ...and so on. Then, just one line is changed: my_dict[key] = key into: my_dict[key] = (key, key) Full code: list_of_dicts = [] keys = [str(x) for x in range(200000)] prev_clk = time.clock() for i in range(20): my_dict = {} for key in keys: my_dict[key] = (key, key) list_of_dicts.append(my_dict) new_clk = time.clock() print i, new_clk - prev_clk prev_clk = new_clk The difference is that instead of single values, tuples are added to the dictionary instead. When the program is run again: 0 0.27 1 0.37 2 0.49 3 0.6 ... 16 2.32 17 2.45 18 2.54 19 2.68 The execution time is rising linearly with every new dictionary created. Next experiment: dictionaries are not stored in a list, they are just left out when an iteration has finished. It's done by removing two lines: list_of_dicts = [] and list_of_dicts.append(my_dict) Full code: keys = [str(x) for x in range(200000)] prev_clk = time.clock() for i in range(20): my_dict = {} for key in keys: my_dict[key] = (key, key) new_clk = time.clock() print i, new_clk - prev_clk prev_clk = new_clk The time is constant again: 0 0.28 1 0.28 2 0.28 3 0.26 4 0.26 I see no reason for this kind of performance problem, really. It happens when both things are true: dictionaries are kept in a list (or more generally, in memory) and they store tuples. As this goes beyond my understanding of Python internals, I would like to kindly ask, if anyone has an idea about how to create this data structure (list of dictionaries of tuples, assuming that size of all dictionaries is the same), in constant time? Regards, Maciej From __peter__ at web.de Thu May 31 01:45:26 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 31 May 2007 07:45:26 +0200 Subject: Usage of the __and__ method References: <1180588305.004419.127680@d30g2000prg.googlegroups.com> Message-ID: theju wrote: > I've two objects (both instances of a class called Person) and I want > to use the __and__ method and print the combined attributes of the two > instances. > r = p and q > print r.print_name() > The above output in both cases is giving me a doubt if __and__ method > is over-ridable or not? You cannot customize the logical 'and'. The __and__() method is used to implement the binary and '&'. Change your code to r = p & q print r.print_name() Peter From winston.yang at netrics.com Thu May 10 13:42:56 2007 From: winston.yang at netrics.com (winston.yang at netrics.com) Date: 10 May 2007 10:42:56 -0700 Subject: reading argv argument of unittest.main() Message-ID: <1178818976.822327.145380@w5g2000hsg.googlegroups.com> I've read that unittest.main() can take an optional argv argument, and that if it is None, it will be assigned sys.argv. Is there a way to pass command line arguments through unittest.main() to the setUp method of a class derived from unittest.TestCase? Thank you in advance. Winston From rene at korteklippe.de Wed May 16 03:30:02 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Wed, 16 May 2007 09:30:02 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <464ab2f9$0$23146$9b4e6d93@newsspool1.arcor-online.net> Gregor Horvath schrieb: > If comments are allowed to be none English, then why are identifier not? I don't need to be able to type in the exact characters of a comment in order to properly change the code, and if a comment does not display on my screen correctly, I am not as fscked as badly as when an identifier does not display (e.g. in a traceback). -- Ren? From laurent.pointal at wanadoo.fr Tue May 1 10:25:18 2007 From: laurent.pointal at wanadoo.fr (Laurent Pointal) Date: Tue, 01 May 2007 16:25:18 +0200 Subject: Why are functions atomic? References: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> <46374c50$0$5112$ba4acef3@news.orange.fr> Message-ID: <46374c7f$0$5112$ba4acef3@news.orange.fr> Laurent Pointal wrote: > http://docs.python.org/lib/partial-objects.html OOps http://docs.python.org/lib/module-functools.html From daniele.varrazzo at gmail.com Mon May 7 05:32:43 2007 From: daniele.varrazzo at gmail.com (Daniele Varrazzo) Date: 7 May 2007 02:32:43 -0700 Subject: problem with quoted strings while inserting into varchar field of database. In-Reply-To: References: <1178475772.423687.118800@e65g2000hsc.googlegroups.com> <1178526655.933789.294700@h2g2000hsg.googlegroups.com> Message-ID: <1178530363.516882.228380@l77g2000hsb.googlegroups.com> On 7 Mag, 10:46, "Stefan Sonnenberg-Carstens" wrote: > On Mo, 7.05.2007, 10:30, Daniele Varrazzo wrote: > > > On 7 Mag, 08:55, "krishnakant Mane" wrote: > >> On 6 May 2007 11:22:52 -0700, Daniele Varrazzo > >> >> Every serious database driver has a > >> complete and solid SQL escaping > >> > mechanism. This mechanism tipically involves putting placeholders in > >> > your SQL strings and passing python data in a separate tuple or > >> > dictionary. Kinda > > >> > cur.execute("INSERT INTO datatable (data) VALUES (%s);", > >> > (pickled_data,)) > > >> I will try doing that once I get back to the lab. > >> mean while I forgot to mention in my previous email that I use MySQLdb > >> for python-mysql connection. > > Why not use qmark parameter passing (PEP 249) ? > > cur.execute("INSERT INTO datatable (data) VALUES (?);" , (pickled_data,)) > > Then the DB driver will take care for you. >>> import MySQLdb >>> print MySQLdb.paramstyle format MySQLdb (as many other drivers) use format parameter passing. Not much difference w.r.t. qmark, at least when passing positional parameters: the placeholder is "%s" instead of "?". A difference is that "format" also allows named parameters (actually it should have been "pyformat", but IIRC MySQLdb can also use named placeholders, even if they advertise "format"). Anyway it is only a matter of placeholder style: they both allow the driver to take care of data escaping, the concept the OT didn't know about. -- Daniele From hpj at urpla.net Thu May 10 14:09:06 2007 From: hpj at urpla.net (Hans-Peter Jansen) Date: Thu, 10 May 2007 20:09:06 +0200 Subject: trouble with generators References: Message-ID: Marc 'BlackJack' Rintsch wrote: > In , Hans-Peter Jansen wrote: > >> class Gen(object): >> def records(self, cls): >> for i in range(3): >> setattr(cls, "id", "%s%s" % (cls.__doc__, i)) >> yield cls >> >> [?] >> >> class GenA(Gen): >> def __init__(self): >> self.genB = GenB() >> >> def records(self): >> for a in Gen.records(self, A()): > > Here you create an instance of `A` and pass that *instance* and not the > *class*. If you would pass the class here, you must create objects in > `Gen.records()`. Yes, that was my fault, as you both found. > Ciao, > Marc 'BlackJack' Rintsch Thanks, Marc. Cheers, Pete From grante at visi.com Thu May 3 11:05:49 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 03 May 2007 15:05:49 -0000 Subject: How to replace the last (and only last) character in a string? References: <1178202464.201578.211150@c35g2000hsg.googlegroups.com> Message-ID: <133juidfpal3jf2@corp.supernews.com> On 2007-05-03, Johny wrote: > Let's suppose > s='12345 4343 454' > How can I replace the last '4' character? >>> s = '12345 4343 454' >>> s = s[:-1] + 'X' >>> s '12345 4343 45X' -- Grant Edwards grante Yow! Where's th' DAFFY at DUCK EXHIBIT?? visi.com From bdesth.quelquechose at free.quelquepart.fr Tue May 22 16:37:40 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 22 May 2007 22:37:40 +0200 Subject: [Fwd: Re: managed lists?] In-Reply-To: References: <4651fe96$0$24671$426a34cc@news.free.fr> Message-ID: <46534a27$0$17169$426a74cc@news.free.fr> Jorgen Bodde a ?crit : > Hi Bruno, > > Thanks for your answer. > > Well what I am after is a list of relations to some class type. And in > that list I do not wish to have accidentally put ints, strings, So don't do it !-) > only > one type of object, or interface. Now I can make the list interface > safe, but it is only meant for relational purposes only. So to > illustrate: > > Song <>---->> Tab > Song <>--->> Tuning > > I want a "tabs" collection only consisting of Tab objects. They are > very specific so "mimicing" a tab interface is not something that will > be done anytime soon. Yes, probably. As usual, there's the general rule and the reality. But still, while I understand both your use case and your fears, I think you're not solving the problem the right way - at least the pythonic way !-) > I'm a traditional C++ programmer, and maybe I go through some > transitional phase s/maybe/certainly/ > I don't know but exposing my list as read / > (over)write property to the "outside world" being the rest of my > object model, is just asking for problems. Not necessarily. I came to Python from a C/Java (and bits of C++ FWIW) background, with the firm belief that coding with no static typing and no access restriction was "just asking for problems". It turned out that it usually just works - even if it sometimes requires to think about the problem in a different way. > So this "strong" typed list > will ensure me at "add" time the exception occurs, rather then > somewhere in my applciation who knows much later that something blows > up because the "object" from that list is retrieved and something > unpredictable goes wrong. Is that so weird to do? Nope, not at all. The goal is perfectly legitimate : ease debugging. It's the solution that is wrong IMHO - even in your particular case. Let's restate your problem : you want to simplify debugging by knowing ASAP when some incompatible object is added to a Song's tunes or tabs list. The right solution IMHO is to *not* expose these lists as part of the interface - after all, the fact that tabs and tunes are stored in lists is an implementation detail -, and to add the necessary API to the Song object - ie : Song.add_tune, Song.add_tab, Song.iter_tunes, Song.iter_tabs, etc. Then you just have to add some assert statements in the add_XXX methods so you'll be warned at the right time when some part of the client code pass something wrong. Then it's just a matter of re-compiling this code with the -o flag to turn off assertion when deploying the finished product - by this time, you should be confident enough in the fact that the client code is doing right. As an added bonus, you gain clean encapsulation and respect the law of Demeter. > As I said earlier I > am a python newbie, I love the language, but the fact it can blow up > at unpredictable times, gives me shivers. Any program in any language can crash at unpredictable time. Better learn to live with it. At least Python saves you from a lot of common C/C++ problems related to memory management... >> Everything in Python is an object. Including integers. And there's no >> 'char' type in Python. > > > The array type by the way says in the API that it can be constructed > with a simple type like a char as in a "c" type, an int as in a "i" > type etc.. Yes, I know. As you noticed, this is a somewhat peculiar module - not intended to be use as a replacement of C++ template containers. I just wanted to emphasis the fact that in Python itself everything is an object (at least anything you can bind to a name). > As I said, I might be going through a transitional phase, but exposing > my relation list as simply a list class where all kinds of objects can > be dumped in, seems too much for me at this point ;-) As I said, the problem is (IMHO) more about exposing the list *as part of the interface* than about the fact that a list can contain any kind of object. Oh, yes, while we're at it, and in case you don't know yet: the Python idiom for implementation attributes (including methods - remember, everything is an object) is to prefix them with a single underscore. HTH From mad.vijay at gmail.com Fri May 4 03:05:52 2007 From: mad.vijay at gmail.com (SamG) Date: 4 May 2007 00:05:52 -0700 Subject: How to find the present working directory using python. In-Reply-To: <1178262224.269446.69410@c35g2000hsg.googlegroups.com> References: <1178262224.269446.69410@c35g2000hsg.googlegroups.com> Message-ID: <1178262352.837860.59880@e65g2000hsc.googlegroups.com> On May 4, 12:03 pm, pradeep nair wrote: > how to find out the present working directory using python. > > os.system('pwd') works good. But i need some specific one in > python rather than embedding shell command into python. os.path.getcwd() From bborcic at gmail.com Tue May 15 14:33:29 2007 From: bborcic at gmail.com (Boris Borcic) Date: Tue, 15 May 2007 20:33:29 +0200 Subject: File record separators. In-Reply-To: <1179249866.369812.167590@u30g2000hsc.googlegroups.com> References: <1179241525.667682.112220@y80g2000hsf.googlegroups.com> <1179249866.369812.167590@u30g2000hsc.googlegroups.com> Message-ID: HMS Surprise wrote: > Thanks folks. Was unaware of enumerate , still have a lot to learn > about python. > > Sorry for the poorly phrased request, but you gathered the gist of it. > My wonderment is how to write the following 2 lines and make sure they > are saved as separate records or lines so that I pull in only one at a > time with readline(?). > > ['a', 'b'], ['c','d']] > [['a', 'b'], ['c','d'], ['e','f']] > > Would like to use pickle but it is apparently unavailable in the > package I am using, Jython 2.2. I am pretty sure some version of pickle or cPickle is available in Jython 2.1, though. I'd take a second look, to be sure. From shuimuliang at gmail.com Sun May 27 00:29:27 2007 From: shuimuliang at gmail.com (shuimuliang at gmail.com) Date: 26 May 2007 21:29:27 -0700 Subject: How to get a dot's or pixel's RGB with PIL Message-ID: <1180240167.582601.247050@q19g2000prn.googlegroups.com> e.g. From NikitaTheSpider at gmail.com Sat May 12 18:07:32 2007 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Sat, 12 May 2007 18:07:32 -0400 Subject: mmap thoughts References: <1178924977.507496@smirk> Message-ID: In article <1178924977.507496 at smirk>, "James T. Dennis" wrote: > * There don't seem to be any currently maintained SysV IPC > (shm, message, and semaphore) modules for Python. I guess some > people have managed to hack something together using ctypes; > but I haven't actually read, much less tested, any of that code. http://NikitaTheSpider.com/python/shm/ Enjoy =) -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From bdesth.quelquechose at free.quelquepart.fr Tue May 15 17:16:50 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 15 May 2007 23:16:50 +0200 Subject: Trying to choose between python and java In-Reply-To: <1179250163.596672.321480@o5g2000hsb.googlegroups.com> References: <1179250163.596672.321480@o5g2000hsb.googlegroups.com> Message-ID: <464a190c$0$19570$426a34cc@news.free.fr> Beliavsky a ?crit : > On May 15, 1:30 am, Anthony Irwin wrote: > > > >>#5 someone said that they used to use python but stopped because the >>language changed or made stuff depreciated (I can fully remember >>which) and old code stopped working. Is code written today likely to >>still work in 5+ years or do they depreciate stuff and you have to update? > > > Because Python 3 will change the syntax of print to disallow > > print "Hello, world." > > a substantial fraction of Python programs in existence, including all > of my programs, will be broken. Draw your own conclusions. The fact that Py3K will be a "big cleanup" release is not new - it has been clear for some years now that this would be the first release that would break compatibility. Still GvR and the team seem to be making their best to not avoid as much breakage as possible, clearly document what will break, and if possible provide tools to ease migration. I've been using Python since 1.5.2 and had no problem yet with upgrades. I couldn't say so of some proprietary languages I've used, where each minor release could potentially break something - not talking about major ones that were certified to imply a full rewrite (and I'm not talking of something as easily scriptable as replacing print statements with a function or method call). From gagsl-py2 at yahoo.com.ar Sun May 27 11:25:15 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 27 May 2007 12:25:15 -0300 Subject: a bug in python windows service? References: <1180231245.444827.171390@g37g2000prf.googlegroups.com> <1180267656.857094.260980@d30g2000prg.googlegroups.com> Message-ID: En Sun, 27 May 2007 09:07:36 -0300, momobear escribi?: >> Instead of extending join(), write a specific method to signal the >> quitEvent or just let the caller signal it. And I don't see in this >> example why do you need two different events (one on the thread, another >> on the service controller), a single event would suffice. > > I don't think a single event is enought, since I think the event > python created and windows event are not same kind of event. They are not the same object, of course (altough the threading.Event object relies eventually on a mutex implemented using CreateEvent). But in this case both can be successfully used; of course, having the Python object a more "pythonic" interfase (not a surprise!), it's easier to use. The same example modified using only a threading.Event object (and a few messages to verify how it runs): import threading from win32api import OutputDebugString as ODS class workingthread(threading.Thread): def __init__(self, quitEvent): self.quitEvent = quitEvent self.waitTime = 1 threading.Thread.__init__(self) def run(self): while not self.quitEvent.isSet(): ODS("Running...\n") self.quitEvent.wait(self.waitTime) ODS("Exit run.\n") import win32serviceutil import win32event class testTime(win32serviceutil.ServiceFramework): _svc_name_ = "testTime" _svc_display_name_ = "testTime" _svc_deps_ = ["EventLog"] def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = threading.Event() self.thread = workingthread(self.hWaitStop) def SvcStop(self): self.hWaitStop.set() def SvcDoRun(self): self.thread.start() self.hWaitStop.wait() self.thread.join() if __name__ == '__main__': win32serviceutil.HandleCommandLine(testTime) -- Gabriel Genellina From yaogzhan at gmail.com Sat May 12 14:30:41 2007 From: yaogzhan at gmail.com (=?utf-8?B?6Km55YWJ6ICA?=) Date: 12 May 2007 11:30:41 -0700 Subject: Read from Windows Address Book (.wab file format) ? Message-ID: <1178994641.809507.127690@l77g2000hsb.googlegroups.com> Hi all! I wonder if there's any Python module that could read from .wab file. I googled but found nothing useful. Any idea? Thanks :) Rio From google at mrabarnett.plus.com Thu May 17 16:56:55 2007 From: google at mrabarnett.plus.com (MRAB) Date: 17 May 2007 13:56:55 -0700 Subject: remove all elements in a list with a particular value In-Reply-To: <1179328873.105705.95580@l77g2000hsb.googlegroups.com> References: <1179328873.105705.95580@l77g2000hsb.googlegroups.com> Message-ID: <1179435415.258096.167900@y80g2000hsf.googlegroups.com> On May 16, 4:21 pm, Lisa wrote: > I am reading in data from a text file. I want to enter each value on > the line into a list and retain the order of the elements. The number > of elements and spacing between them varies, but a typical line looks > like: > > ' SRCPARAM 1 6.35e-07 15.00 340.00 1.10 3.0 ' > > Why does the following not work: > > line = ' SRCPARAM 1 6.35e-07 15.00 340.00 1.10 3.0 ' > li = line.split(' ') > for j,i in enumerate(li): > if i == '': > li.remove(i) > [snip] What you're forgetting is that when you remove an item from a list all the following items move down. If you try this: li = list('abc') for i, j in enumerate(li): print ", ".join("li[%d] is '%s'" % (p, q) for p, q in enumerate(li)) print "Testing li[%d], which is '%s'" % (i, j) if j == 'a': print "Removing '%s' from li" % j li.remove(j) then you'll get: li[0] is 'a', li[1] is 'b', li[2] is 'c' Testing li[0], which is 'a' Removing 'a' from li li[0] is 'b', li[1] is 'c' Testing li[1], which is 'c' You can see that when 'enumerate' yielded li[0] 'b' was in li[1] and when it yielded li[1] 'b' was in li[1]; it never saw 'b' because 'b' moved! Oops! Been there, done that... :-) From efrat_regev at yahoo.com Tue May 22 05:19:31 2007 From: efrat_regev at yahoo.com (Efrat Regev) Date: Tue, 22 May 2007 12:19:31 +0300 Subject: Fastest Way To Iterate Over A Probability Simplex Message-ID: <4652b323$1@news.bezeqint.net> Hello, Let's say a probability vector of dimension d is x_1, ..., x_d, where each one is a non-negative term, and they all sum up to 1. Now I'd like to iterate over all probability vectors, but this is impossible, since they're uncountable. So instead, let's say I want to iterate over all such vectors under the constraint that the granularity of each component is at most some delta. To make things pythonesque, here's the interface: class simplex: def __init__(self, dim, delta): ... def __iter__(self): ... def next(self): ... The problem is, what's a fast implementation? I tried something simple, and it is slooooooooooooow. If anyone can think of something clever, I'd love to hear it. Many Thanks, Efrat From cam.ac.uk at mh391.invalid Sun May 20 06:55:03 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 20 May 2007 11:55:03 +0100 Subject: Can't embed python in C++(Mingw[3.*] compiler) In-Reply-To: <1179637269.471339.307050@w5g2000hsg.googlegroups.com> References: <1179591280.469302.289010@p77g2000hsh.googlegroups.com> <1179637269.471339.307050@w5g2000hsg.googlegroups.com> Message-ID: Arjun Narayanan wrote: > That AND I didn't use the american spelling Py_Initiali >>> Z <<< e(); Like many words ending in -ize/-ise, initialize is listed with what you call the "American" spelling in the Oxford English Dictionary. -- Michael Hoffman From memracom at yahoo.com Thu May 17 14:37:25 2007 From: memracom at yahoo.com (memracom at yahoo.com) Date: 17 May 2007 11:37:25 -0700 Subject: (Modular-)Application Framework / Rich-Client-Platform in Python In-Reply-To: References: Message-ID: <1179427045.561519.234620@w5g2000hsg.googlegroups.com> > There seem to loads of python frameworks for Web-Apps, but I have a hard > time finding one for desktop-apps. > I imagine it wouldn't be too hard (if still time consuming) whipping up > something simple myself, but I thought, I'd ask here before diving into it. Sounds like you should look at DABO http://dabodev.com/ But remember, that by combining something like YUI with any WSGI framework and a Python web server (PASTE, FAPWS) you can use a web browser as the client for an application that runs on the same computer. From gagsl-py2 at yahoo.com.ar Mon May 14 04:03:55 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 14 May 2007 05:03:55 -0300 Subject: Basic question References: <1178986686.510137.195490@p77g2000hsh.googlegroups.com> <1178991933.421386.58500@u30g2000hsc.googlegroups.com> <1178992910.318929.77790@e51g2000hsg.googlegroups.com> <1178995630.925969.207740@w5g2000hsg.googlegroups.com> <1hy0cy8.eg6p1p135hbo3N%aleax@mac.com> <1hy2nwq.be9xtykcg7rkN%aleax@mac.com> Message-ID: En Mon, 14 May 2007 02:05:47 -0300, Alex Martelli escribi?: > Gabriel Genellina wrote: >> But that's not the same as requested - you get a plain list, and the >> original was a list of lists: > Are we talking about the same code?! What I saw at the root of this > subthread was, and I quote: [...code painfully building a plain list...] Oh, sorry, I got confused with another reply then. >> And thanks for my "new English word of the day": supererogatory :) > You're welcome! Perhaps it's because I'm not a native speaker of > English, but I definitely do like to widen my vocabulary (and others'). Me too! -- Gabriel Genellina From irmen.NOSPAM at xs4all.nl Tue May 8 16:38:16 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Tue, 08 May 2007 22:38:16 +0200 Subject: getmtime differs between Py2.5 and Py2.4 In-Reply-To: <1178599214.484104.171330@o5g2000hsb.googlegroups.com> References: <463FA51D.1060600@v.loewis.de> <463fb305$0$326$e4fe514c@news.xs4all.nl> <1178599214.484104.171330@o5g2000hsb.googlegroups.com> Message-ID: <4640dfb8$0$326$e4fe514c@news.xs4all.nl> Leo Kislov wrote: > > Let me guess: your E drive uses FAT filesystem? > > -- Leo > Nope, its all NTFS on my system. Anyway this doesn't matter, as the true cause is explained in another reply in this thread (bug in c runtime library of Python 2.4). --Irmen From steve at REMOVE.THIS.cybersource.com.au Sat May 5 13:06:35 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 06 May 2007 03:06:35 +1000 Subject: File names and file objects [was Re: My Python annoyances] References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> <1178202431.147195.249790@u30g2000hsc.googlegroups.com> <1hxkwj0.12jtj1v3b522bN%aleax@mac.com> Message-ID: On Fri, 04 May 2007 07:55:25 -0700, Alex Martelli wrote: >> What about the case where I have an array of objects that represent some >> particular binary file format. If the object is a file, then I want to >> copy its contents. If the object is a string, then I want to write the >> string. And so forth. > > "Type-switching" in this way is a rather dubious practice in any > language (it can't respect the "open-closed" principle). What do people think about functions that accept either a file name or a file object? def handle_file(obj): if type(obj) == str: need_to_close = True obj = file(obj, 'r') else: need_to_close = False do_something_with(obj.read()) if need_to_close: data.close() Good idea? Bad idea? Just a matter of personal preference? -- Steven. From fuzzyman at gmail.com Fri May 4 17:12:39 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 4 May 2007 14:12:39 -0700 Subject: Microsoft's Dynamic Languages Runtime (DLR) In-Reply-To: <1178296035.993859.183720@n59g2000hsh.googlegroups.com> References: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> <1178151313.421106.43130@o5g2000hsb.googlegroups.com> <1178151574.302703.205560@l77g2000hsb.googlegroups.com> <1178296035.993859.183720@n59g2000hsh.googlegroups.com> Message-ID: <1178313159.059210.97560@y80g2000hsf.googlegroups.com> On May 4, 5:27 pm, Kaz Kylheku wrote: > On May 2, 5:19 pm, sturlamolden wrote: > > > On May 3, 2:15 am, Kaz Kylheku wrote: > > > > Kindly refrain from creating any more off-topic, cross-posted threads. > > > Thanks. > > > The only off-topic posting in this thread is your own (and now this > > one). > > You are making a very clumsy entrance into these newsgroups. So far > you have started two cross-posted threads. The first is only topical > in comp.lang.python (how to emulate macros in Python). This one is > topical in neither one, since it is about Microsoft DLR. > > It's quite possible that some Lisp and Python programmers have a > strong interest in Microsoft DLR. Those people who have such an > interest (regardless of whether they are Lisp and Python user also) > and who like to read Usenet will almost certainly find a Microsoft DLR > newsgroup for reading about and discussing Microsoft DLR. Do you not > agree? > Given that the DLR is a dynamic language framework, abstracted out of the IronPython 1.0 release, and that it also runs on top of the core CLR shipped with SilverLight meaning that for the first time sandboxed Python scripts can run in the browser... It would seem entirely on topic for a Python newsgroup.... very on- topic... Fuzzyman http://www.voidspace.org.uk/ironpython/index.shtml > Also note that there is very rarely, if ever, any good reason for > starting a thread which is crossposted among comp.lang.* newsgroups, > even if the subject contains elements that are topical in all of them > (yours does not). > > > Begone. > > You are childishly beckoning Usenet etiquette to be gone so that you > may do whatever you wish. But I trust that you will not, out of spite > for being rebuked, turn a few small mistakes into a persistent style. From mwilson at the-wire.com Sun May 6 11:04:11 2007 From: mwilson at the-wire.com (Mel Wilson) Date: Sun, 06 May 2007 11:04:11 -0400 Subject: [python 2.4] unable to construct tuple with one item In-Reply-To: <271115400705060523t2f1c23e4ndc87e612384d4951@mail.gmail.com> References: <271115400705060523t2f1c23e4ndc87e612384d4951@mail.gmail.com> Message-ID: Vyacheslav Maslov wrote: > So, the main question is why using syntax like [X] python constuct list > with > one item, but when i try to construct tuple with one item using similar > syntax (X) python do nothing? Because `(` and `)` are used in expressions to bracket sub-expressions. a = (4 + 3) * 2 means: add 4 to 3, multiply the sum by 2. It can't mean: make a tuple containing 7 and extend it to 7,7 . The real constructor for tuples is `,`. When you see parens around tuple creation they're there to bracket the sub-expression that creates the tuple. You see new tuples without parens all the time: for i, thing in enumerate (things): ... starter, main_course, dessert, beverage = order_meal (*hunger) etc. Mel. From stargaming at gmail.com Mon May 21 15:11:38 2007 From: stargaming at gmail.com (Stargaming) Date: Mon, 21 May 2007 21:11:38 +0200 Subject: Installing Python in a path that contains a blank In-Reply-To: References: Message-ID: Konrad Hinsen schrieb: > I am trying to install Python from sources in my home directory on a > Mac cluster (running MacOS X 10.4.8). The path to my home directory > contains a blank, and since the installation procedure insists on > getting an absolute path for the prefix, I cannot avoid installing to a > path whose name contains a blank. Python does not seem to be prepared > for this, as it uses only the part before the blank, resulting in > numerous error messages. > > Does anyone know a workaround? > > Thanks, > Konrad. > You could give /foo/bar\ baz/ham or "/foo/bar baz/ham" (either escaping the blanks or wrapping the path in quotation marks) a try. I can't verify it either, just guess from other terminals' behaviour. HTH, Stargaming From Eric_Dexter at msn.com Fri May 18 19:26:29 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 18 May 2007 16:26:29 -0700 Subject: Anti-Aliasing in wxPython? In-Reply-To: <0brr43to59ltspg1g7cu32jpgqrbonandj@4ax.com> References: <0brr43to59ltspg1g7cu32jpgqrbonandj@4ax.com> Message-ID: <1179530789.595604.46810@k79g2000hse.googlegroups.com> On May 18, 1:20 pm, Alexander D?nisch wrote: > Hi everybody > > i'm wondering if there's a way to enable > Anti-Aliasing for the Graphics Object in wxPython. > > in Java i do this: > > ((Graphics2D)g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, > RenderingHints.VALUE_ANTIALIAS_ON); > > i haven't found anything like this in wxPython yet. > Thanks > > Alex http://www.wxpython.org/maillist.php this may be more helpfull http://www.stormpages.com/edexter/csound.html From steve at holdenweb.com Sat May 19 09:23:01 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 19 May 2007 09:23:01 -0400 Subject: Python compared to other language In-Reply-To: <1179555855.410877.51390@k79g2000hse.googlegroups.com> References: <1179540061.598417.13870@y80g2000hsf.googlegroups.com> <1179555855.410877.51390@k79g2000hse.googlegroups.com> Message-ID: walterbyrd wrote: > On May 18, 8:28 pm, Steve Holden wrote: > >> Surely the fact that Python is available on so many platforms implies >> that C is a fairly portable language. > > Unless it's the same C code, I don't see how that means anything. If I > write an app on Windows with C, and I rewrite the same app on UNIX > with C - that doesn't mean the C code has been ported. > > My guess is that some of the C code used to develop Python is the same > between the different Python distros, but much of the code is unique > to the particular platform. If that is the case, then the C code may > not be very portable. > > But, I can often take the same python code, and run it on MacOS, > Linux, FreeBSD, and Windows. Often I can do this even if the app has a > gui interface. > Perhaps you could try a more constructive approach in future. The reason you can do this with Python is precisely because the developers have ironed out the wrinkles between platforms by putting the requisite conditionals in the C source. Which, by the way, is open in case you ever feel like answering your own questions. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From martin at v.loewis.de Tue May 1 14:25:13 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 01 May 2007 20:25:13 +0200 Subject: Why are functions atomic? In-Reply-To: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> References: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> Message-ID: <46378609.403@v.loewis.de> > I know I could use a 'functor' defining __call__ and using member > variables, but this is more complicated and quite a bit slower. (I > also know that I can use new.function to create a new copy, but I > would like to know the rational behind the decision to make functions > atomic before I shoot myself in the foot;-) Function objects were not copyable because they were immutable. For an immutable object, a copy cannot reasonably be distinguished from the original object. See copy.py, around line 105. Regards, Martin From claird at lairds.us Mon May 21 12:18:23 2007 From: claird at lairds.us (Cameron Laird) Date: Mon, 21 May 2007 16:18:23 +0000 Subject: Python and GUI References: <1179761984.704369.116310@b40g2000prd.googlegroups.com> Message-ID: In article <1179761984.704369.116310 at b40g2000prd.googlegroups.com>, wrote: > >Just wondering on what peoples opinions are of the GUIs avaiable for >Python? > >All I am doing is prompting users for some data (listbox, radio >buttons, text box, ect...). Then I will have some text output, maybe >a scrolling text message as things are happening. > >I have some minor things I need to do, for example, if Checkbutton X >is clicked, I need to disable TextBox Y, and I would like to display >the scrolling text (output) > >Ultimately, is it worth downloading and learning some of the packages >avaiable for Python, or should I just stick to the Tkinter stuff that >is included. > >More specifically, has anyone used the Qt stuff for python, easy to >use? > While PyQt is plenty wonderful, Tkinter's more than adequate, given the requirements you've described. From erco at 3dsite.com Fri May 11 23:46:16 2007 From: erco at 3dsite.com (Greg Ercolano) Date: Fri, 11 May 2007 20:46:16 -0700 Subject: os.popen on windows: loosing stdout of child process Message-ID: When I use os.popen(cmd,'w'), I find that under windows, the stdout of the child process disappears, instead of appearing in the DOS window the script is invoked from. eg: C:\> type foo.py import os import sys file = os.popen("nslookup", 'w') file.write("google.com\n") file.close() C:\> python foo.py <-- nothing is printed C:\> This just seems wrong. The following DOS equivalent works fine: C:\> echo google.com | nslookup Default Server: dns.erco.x Address: 192.168.1.14 [..expected output..] When I run the same python program on a unix box, the output from 'nslookup' appears in the terminal, as I'd expect. Shouldn't popen() be consistent in its handling of the child's stdout and stderr across platforms? Maybe I'm missing something, being somewhat new to python, but an old hand at unix and win32 and functions like popen(). Didn't see anything in the docs for popen(), and I googled around quite a bit on the web and groups for eg. 'python windows popen stdout lost' and found nothing useful. FWIW, I'm using the windows version of python 2.5 from activestate. From sjmachin at lexicon.net Thu May 10 08:18:39 2007 From: sjmachin at lexicon.net (John Machin) Date: 10 May 2007 05:18:39 -0700 Subject: msbin to ieee In-Reply-To: <1178794090.436098.322540@p77g2000hsh.googlegroups.com> References: <1178487847.671199.108140@h2g2000hsg.googlegroups.com> <1178794090.436098.322540@p77g2000hsh.googlegroups.com> Message-ID: <1178799519.762159.236090@p77g2000hsh.googlegroups.com> On May 10, 8:48 pm, imageguy wrote: > On May 6, 6:44 pm, revuesbio wrote: > > > Hi > > Does anyone have the python version of the conversion from msbin to > > ieee? > > Thank u > > Not sure if this helps, but I think this thread has the answer;http://groups.google.com/group/comp.lang.python/browse_thread/thread/... > > Check out the response from Bengt Richter. His function did the right > thing. Yes, Bengt's function did the right thing on the input for that particular problem, which involved IEEE 64-bit floating point numbers stored in little-endian format. The current problem involves 32-bit MBF (Microsoft Binary/Basic Floating-point/Format) numbers. Different problem. From aahz at pythoncraft.com Fri May 11 08:14:30 2007 From: aahz at pythoncraft.com (Aahz) Date: 11 May 2007 05:14:30 -0700 Subject: Jython 2.2 Beta2 is available References: Message-ID: In article , Charlie Groves wrote: > >I'm happy to announce that Jython 2.2-beta2 is available for download: >http://sourceforge.net/project/showfiles.php?group_id=12867&package_id=12218&release_id=507592 >See http://jython.org/Project/installation.html for installation instructions. > >This is the second and final beta release towards the 2.2 version of >Jython. It includes fixes for more than 30 bugs found since the first >beta and the completion of Jython's support for new-style classes. COngrats! Whoo-hoo! Excellent news! -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Look, it's your affair if you want to play with five people, but don't go calling it doubles." --John Cleese anticipates Usenet From bearophileHUGS at lycos.com Mon May 21 10:02:44 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 21 May 2007 07:02:44 -0700 Subject: NEWBIE: Extending a For Statement. In-Reply-To: <1179749446.179064.222990@z28g2000prd.googlegroups.com> References: <1179749446.179064.222990@z28g2000prd.googlegroups.com> Message-ID: <1179756164.506426.116210@x18g2000prd.googlegroups.com> mosscliffe: > if key in xrange (60,69) or key == 3: I keep seeing again and again code like this, mostly from people not much expert of Python, but the PEP 260 shows the fast in was removed, so it's O(n). Maybe removing the fast __contains__ was bad for necomers (or just the casual Python users, that I belive is really large). Bye, bearophile From laurstorage at yahoo.com Tue May 29 03:08:28 2007 From: laurstorage at yahoo.com (Laurentiu) Date: Tue, 29 May 2007 08:08:28 +0100 (BST) Subject: Python tutorials In-Reply-To: Message-ID: <68039.4793.qm@web36710.mail.mud.yahoo.com> Hello! i was searching the net for some python video tutorials (free and payed). i found some interesting stuff at www.showmedo.com but i want something more complex. can someone give me some address for python video tutorials or companies how made this tutorials, free or payed. i search at Lynda.com and vtc but i didn't find any python references. thanks for all answers. Laurentiu ___________________________________________________________ Yahoo! Answers - Got a question? Someone out there knows the answer. Try it now. http://uk.answers.yahoo.com/ From gh at gregor-horvath.com Thu May 17 09:20:57 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Thu, 17 May 2007 15:20:57 +0200 Subject: Declaring variables In-Reply-To: <1179406970.776873.144470@o5g2000hsb.googlegroups.com> References: <1179334649.990688.73320@o5g2000hsb.googlegroups.com> <1179359317.494376.259990@n59g2000hsh.googlegroups.com> <1179406970.776873.144470@o5g2000hsb.googlegroups.com> Message-ID: HMS Surprise schrieb: > > #~~~~~~~~~~~~~~~~~~~~~~ > createdIncidentId = 0 > . > . > . > #attempt to change varialbe > createdIncidentID = 1 > . > . > . > if createdIncidentId == 1: > ... > test.py is your code above $ pychecker -v test.py Processing test... Warnings... test.py:7: Variable (createdIncidentID) not used Gregor From eric.brunel at pragmadev.com Tue May 15 08:49:55 2007 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Tue, 15 May 2007 14:49:55 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476081.7080609@web.de> <46498514$0$6402$9b4e6d93@newsspool2.arcor-online.net> <4649882E.3060005@web.de> <46499940$0$10199$9b4e6d93@newsspool4.arcor-online.net> <46499BF9.30209@web.de> <4649a2c1$0$10193$9b4e6d93@newsspool4.arcor-online.net> <4649A429.3010406@web.de> Message-ID: On Tue, 15 May 2007 14:14:33 +0200, Stefan Behnel wrote: > Ren? Fleschenberg wrote: >> Please try to understand that the fact that certain bad practices are >> possible today is no valid argument for introducing support for more of >> them! > > You're not trying to suggest that writing code in a closed area project > is a > bad habit, are you? In the world we live in today, a "closed area project" is something that tends to disappear. One never knows if the code can be made public someday, or be outsourced to a country with a different language and default encoding. (Now that I think of it, this *is* a valid reason to accept this PEP: "Sorry, boss, but we can't possibly fire all our development team and outsource the project to Russia: all the identifiers are in French and they won't be able to make any sense of it" ;-) ) -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From C.delete_this.Sanders at BoM.GOv.AU Wed May 9 20:49:44 2007 From: C.delete_this.Sanders at BoM.GOv.AU (Charles Sanders) Date: Thu, 10 May 2007 10:49:44 +1000 Subject: interesting exercise In-Reply-To: <1178739676.565009.35590@u30g2000hsc.googlegroups.com> References: <1178595952.641173.76540@y80g2000hsf.googlegroups.com> <1178601624.812907.23550@u30g2000hsc.googlegroups.com> <1178661305.063868.130730@e65g2000hsc.googlegroups.com> <1178661851.606885.104330@p77g2000hsh.googlegroups.com> <1178670691.209680.119330@o5g2000hsb.googlegroups.com> <46416674$0$83110$c30e37c6@lon-reader.news.telstra.net> <1178739676.565009.35590@u30g2000hsc.googlegroups.com> Message-ID: <46426c28$0$83121$c30e37c6@lon-reader.news.telstra.net> castironpi at gmail.com wrote: > On May 9, 1:13 am, Charles Sanders > wrote: [snip] >> or even this monstrosity ... >> >> def permute2( s, n ): >> return [ ''.join([ s[int(i/len(s)**j)%len(s)] >> for j in range(n-1,-1,-1)]) >> for i in range(len(s)**n) ] >> >> print "permute2('abc',2) =", permute2('abc',2) >> print "len(permute2('13579',3)) =", len(permute2('13579',3)) >> >> permute2('abc',2) = ['aa', 'ab', 'ac', 'ba', 'bb', 'bc', >> 'ca', 'cb', 'cc'] >> len(permute2('13579',3)) = 125 >> >> Charles > > Could you explain, this one, actually? Don't forget StopIteration. > As Michael said, simple counting in base n with the string as the digits. No attempt at clarity or efficiency (I did say it was a "monstrosity"). Also, as a python beginner I didn't know about divmod, and have no idea what you (castironpi) mean by "Don't forget StopIteration." Charles From btnkumar at gmail.com Fri May 18 03:00:57 2007 From: btnkumar at gmail.com (Nagendra Kumar) Date: 18 May 2007 00:00:57 -0700 Subject: How to stop a scheduler stated using Message-ID: <1179471657.392581.251320@w5g2000hsg.googlegroups.com> Hello ALL, I am trying to schdule some of my class methods using sched module of python import sched, time s=sched.scheduler(time.time, time.sleep) event1=s.enter(60, 1, obj.scheduleAbuseAssignment1, ()) event2=s.enter(60, 1, obj.scheduleAbuseAssignment2, ()) event3=s.enter(60, obj.scheduleAbuseAssignment3, ()) Is there any way to stop these scheduled events?If so, can we do it through a UI Thanks in advance. Regards, - Nagendra Kumar From harry.g.george at boeing.com Tue May 29 10:18:46 2007 From: harry.g.george at boeing.com (George, Harry G) Date: Tue, 29 May 2007 07:18:46 -0700 Subject: Using python for a CAD program In-Reply-To: <000301c79fe7$b1e22c80$6501a8c0@corp.aviominc.com> References: <000301c79fe7$b1e22c80$6501a8c0@corp.aviominc.com> Message-ID: <8CCB8060D46A7A40BC6AB3DC1DCAFABC0359A08A@XCH-NW-8V2.nw.nos.boeing.com> I haven't followed up. When I last looked, I found the problem space is too large for one person (or project) to do it all. So the job is to glue together lots of good OSS tools -- which is a very pythonic task. The absolute requirement for Knowledge-Based-Engineering is an API which allows a script to do anything a human can do. E.g.: 1. For 3D mechanical CAD, there is OpenCascade, with the pythonic freecad frontend. http://www.opencascade.org/ http://juergen-riegel.net/FreeCAD/Docu/index.php?title=Main_Page OpenCascade requires registration and is big download. 2. For 2D mechanical CAD, there is PythonCAD http://www.pythoncad.org/ The explicit intent to provide full scriptability (anything a human can do via the GUI, a script can do via the API). 3. For EE schematics and simulation, there is OpenCollector and specifically gEDA suite. http://opencollector.org/ http://www.geda.seul.org/ Not pythonic, but people have written glueware scripts in python to tie the pieces together. 4. For fancy 3D objects and animations, Blender has the power and is scriptable in python. It comes from the world of animations, but the math doesn't care if you do EE 3D models instead. http://www.blender.org/ 5. We should all be concerned over SGI selling the OpenGL patents to Microsoft, so at least look to Mesa, and perhaps to alternative 3D libraries. 6. I don't do GUIs much, but I understand form others that PyQT's slot-and-signal architecture is well-respected, that *many* OSS projects use PyGTK, and that folks who use wxPython are looking at "wax" as a more pythonic layer. I finesse the whole issue by claimintg "GUIs are for humans to do the work. I write code so computers can do the work." :-). > -----Original Message----- > From: Dan Fabrizio [mailto:dfabrizio at aviom.com] > Sent: Saturday, May 26, 2007 3:46 PM > To: python-list at python.org; George, Harry G > Subject: Using python for a CAD program > > Hello, > > I saw your post from last year about using python for a EE > CAD program. What were your conclusions? I'm thinking about > converting a Java CAD program I developed to Python with > wxPython and C. I want to use C for the database storage and > manipulation and wxPython for the GUI and user scriptable interface. > > I have also done something like with Tcl/Tk and C but think > Python is much more modern and wxPython widgets look very > professional and OO programming is very important to me. > > What did you decide to do? What language and what GUI > libraries did you > pick? > > I would appreciate any suggestions or advice. > Regards, > > > Dan Fabrizio > ASIC Engineer > Aviom Inc. 1157 Pheonixville Pike. > West Chester, Pa. 19380 > Phone 610 738 9005 ext. 292 > Fax 610 738 9950 > > > > From apatheticagnostic at gmail.com Sat May 5 04:15:32 2007 From: apatheticagnostic at gmail.com (kaens) Date: Sat, 5 May 2007 04:15:32 -0400 Subject: Looping over lists In-Reply-To: References: <1hxlsky.tgi88sj7tfrN%aleax@mac.com> Message-ID: <163f0ce20705050115q4d37a992if50342f80745e87b@mail.gmail.com> I think the for i in range() is more readable (Maybe because I'm coming from a c-style syntax language background) - but what would the benefits of using enumerate be (other that being more . . . pythonesque?) On 5/5/07, Dennis Lee Bieber wrote: > On Fri, 4 May 2007 19:26:17 -0700, aleax at mac.com (Alex Martelli) > declaimed the following in comp.lang.python: > > > for i in range(n): > > for j in range(i+1, n): > > print a[i], a[j] > > > Ah, but wouldn't the cleaner Python be something like > > > >>> a = [1, 2, 3, 4, 5, 3, 6] #just to confuse matters > >>> for pos, val in enumerate(a): > ... for v2 in a[pos+1:]: > ... print val, v2 > ... > 1 2 > 1 3 > 1 4 > 1 5 > 1 3 > 1 6 > 2 3 > 2 4 > 2 5 > 2 3 > 2 6 > 3 4 > 3 5 > 3 3 > 3 6 > 4 5 > 4 3 > 4 6 > 5 3 > 5 6 > 3 6 > >>> > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com wulfraed at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-asst at bestiaria.com) > HTTP://www.bestiaria.com/ > -- > http://mail.python.org/mailman/listinfo/python-list > From joshua at eeinternet.com Fri May 18 15:08:22 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Fri, 18 May 2007 11:08:22 -0800 Subject: pyhdf References: <1179336974.691021.106680@k79g2000hse.googlegroups.com> Message-ID: <464ded53$0$16322$88260bb3@free.teranews.com> On Wednesday 16 May 2007 09:36, jsaacmk at gmail.com wrote: > Has anyone had success installing the pyhdf library with python 2.4 > under linux 2.6.18 (debian)? I have installed the HDF library and > development package from apt and have downloaded the pyhdf > installation files. I've had success with PyTables, which is a wrapper for HDF5. Or are we not talking about the same HDF? :) j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE -- Posted via a free Usenet account from http://www.teranews.com From igouy2 at yahoo.com Sat May 5 17:33:27 2007 From: igouy2 at yahoo.com (igouy2 at yahoo.com) Date: 5 May 2007 14:33:27 -0700 Subject: My newbie annoyances so far In-Reply-To: <_9pYh.1787$uJ6.894@newssvr17.news.prodigy.net> References: <1177688082.758043.133920@r30g2000prh.googlegroups.com> <_9pYh.1787$uJ6.894@newssvr17.news.prodigy.net> Message-ID: <1178400807.051103.95690@q75g2000hsh.googlegroups.com> On Apr 27, 9:07 am, John Nagle wrote: > The CPython implementation is unreasonably slow compared > to good implementations of other dynamic languages such > as LISP and JavaScript. Why do you say CPython is slower than JavaScript? Please provide examples. From nick at craig-wood.com Fri May 18 06:30:04 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Fri, 18 May 2007 05:30:04 -0500 Subject: zipfile stupidly broken References: Message-ID: Martin Maney wrote: > To quote from zipfile.py (2.4 library): > > # Search the last END_BLOCK bytes of the file for the record signature. > # The comment is appended to the ZIP file and has a 16 bit length. > # So the comment may be up to 64K long. We limit the search for the > # signature to a few Kbytes at the end of the file for efficiency. > # also, the signature must not appear in the comment. > END_BLOCK = min(filesize, 1024 * 4) > > So the author knows that there's a hard limit of 64K on the comment > size, but feels it's more important to fail a little more quickly when > fed something that's not a zipfile - or a perfectly legitimate zipfile > that doesn't observe his ad-hoc 4K limitation. I don't have time to > find a gentler way to say it because I have to find a work around for > this arbitrary limit (1): this is stupid. To search 64k for all zip files would slow down the opening of all zip files whereas most zipfiles don't have comments. The code in _EndRecData should probably read 1k first, and then retry with 64k. > (1) the leading candidate is to copy and paste the whole frigging > zipfile module so I can patch it, but that's even uglier than it is > stupid. "This battery is pining for the fjords!" You don't need to do that, you can just "monkey patch" the _EndRecData function. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From danb_83 at yahoo.com Sat May 26 06:21:16 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: 26 May 2007 03:21:16 -0700 Subject: Newbie: Struggling again 'map' In-Reply-To: <1180173252.906992.262570@q75g2000hsh.googlegroups.com> References: <1180173252.906992.262570@q75g2000hsh.googlegroups.com> Message-ID: <1180174876.941308.37200@p77g2000hsh.googlegroups.com> On May 26, 4:54 am, mosscliffe wrote: > I thought I had the difference between 'zip' and 'map' sorted but when > I try to fill missing entries with something other than 'None'. I do > not seem to be able to get it to work - any pointers appreciated. > > Richard > > lista = ['a1', 'a2'] > listb = ['b10', 'b11','b12' ,'b13'] > > for x,y in zip(lista, listb): # Fine Truncates as expected > print "ZIP:", x, "<>", y > > for x,y in map(None, lista, listb): # Also fine - extends as > expected > print "MAP:", x, "<>", y > > for x,y in map("N/A", lista, listb): ########## Fails - Can not call a > 'str' > print "MAP:", x, "<>", y > > def fillwith(fillchars): > return fillchars > > for x,y in map(fillwith("N/A"), lista, listb): ########## Fails also - > Can not call a 'str' > print "MAP:", x, "<>", y zip(lista + ['N/A'] * 2, listb) From half.italian at gmail.com Wed May 16 04:54:22 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 16 May 2007 01:54:22 -0700 Subject: iteration doesn't seem to work ?? In-Reply-To: References: Message-ID: <1179305662.928436.215140@q75g2000hsh.googlegroups.com> On May 16, 1:41 am, stef wrote: > hello, > > can someone tell me why the following iteration doesn't work, > and > how I should replace empty strings in a list with a default value. > > >>> v > ['123', '345', '', '0.3'] > >>> for items in v: > ... if items=='': > ... items='3' > ... > >>> > >>> v > ['123', '345', '', '0.3'] > >>> > > thanks, > Stef Mientki Inside the loop, 'items' is no longer referencing the list...its a string. >>> v = ['123', '4', '567', ''] >>> for i in v: ... print type(i) ... ... This works >>> for j,i in enumerate(v): ... if i=='': ... v[j] = '3' ... >>> v ['123', '4', '567', '3'] >>> ~Sean From istvan.albert at gmail.com Wed May 16 12:43:17 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: 16 May 2007 09:43:17 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46473267$0$31532$9b622d9e@news.freenet.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <1179333797.634234.245830@k79g2000hse.googlegroups.com> As a non-native English speaker, On May 13, 11:44 am, "Martin v. L?wis" wrote: > - should non-ASCII identifiers be supported? why? No. I don't think it adds much, I think it will be a little used feature (as it should be), every python instructor will start their class by saying here is a feature that you should stay away from because you never know where your code ends up. > - would you use them if it was possible to do so? in what cases? No. The only possible uses I can think of are intentionally obfuscating code. Here is something that just happened and relates to this subject: I had to help a student run some python code on her laptop, she had Windows XP that hid the extensions. I wanted to set it up such that the extension is shown. I don't have XP in front of me but when I do it takes me 15 seconds to do it. Now her Windows was set up with some asian fonts (Chinese, Korean not sure), looked extremely unfamiliar and I had no idea what the menu systems were. We have spent quite a bit of time figuring out how to accomplish the task. I had her read me back the options, but something like "hide extensions" comes out quite a bit different. Surprisingly tedious and frustrating experience. Anyway, something to keep in mind. In the end features like this may end up hurting those it was meant to help. i. From kbk at shore.net Sun May 13 20:40:38 2007 From: kbk at shore.net (Kurt B. Kaiser) Date: Sun, 13 May 2007 20:40:38 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200705140040.l4E0ect2013867@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 362 open ( +2) / 3766 closed ( +6) / 4128 total ( +8) Bugs : 968 open ( -3) / 6692 closed ( +9) / 7660 total ( +6) RFE : 256 open ( -1) / 286 closed ( +4) / 542 total ( +3) New / Reopened Patches ______________________ Fix off-by-one error in Modules/socketmodule.c (2007-05-06) CLOSED http://python.org/sf/1713797 opened by Bryan ?stergaard Patch for PEP 3109 (2007-05-06) http://python.org/sf/1713889 opened by wpy os.linesep needs clarification (2007-05-07) CLOSED http://python.org/sf/1714700 opened by Gabriel Genellina x64 clean compile patch for _ctypes (2007-05-09) http://python.org/sf/1715718 opened by Kristj?n Valur "Really print?" Dialog (2007-05-11) http://python.org/sf/1717170 opened by Tal Einat textView code cleanup (2007-05-13) http://python.org/sf/1718043 opened by Tal Einat PEP 3123 implementation (2007-05-13) http://python.org/sf/1718153 opened by Martin v. L?wis Patches Closed ______________ Fix off-by-one error in Modules/socketmodule.c (2007-05-06) http://python.org/sf/1713797 closed by gbrandl make range be xrange (2006-04-18) http://python.org/sf/1472639 closed by nnorwitz xrange that supports longs, etc (2006-08-24) http://python.org/sf/1546078 closed by nnorwitz os.linesep needs clarification (2007-05-08) http://python.org/sf/1714700 closed by gbrandl PEP 3132: extended unpacking (2007-05-02) http://python.org/sf/1711529 closed by gbrandl Bastion and rexec message out-of-date (2007-04-12) http://python.org/sf/1698951 closed by gbrandl New / Reopened Bugs ___________________ smtplib starttls() didn't do TLS Close Notify when quit() (2007-05-07) CLOSED http://python.org/sf/1713993 opened by AndCycle Multiple re.compile flags cause error (2007-05-06) CLOSED http://python.org/sf/1713999 opened by Saul Spatz character set in Japanese on Ubuntu distribution (2007-05-04) http://python.org/sf/1713252 reopened by cgrell Universal line ending mode duplicates all line endings (2007-05-07) CLOSED http://python.org/sf/1714381 opened by Geoffrey Bache subprocess.py problems errors when calling cmd.exe (2007-05-07) http://python.org/sf/1714451 opened by tzellman python throws an error when unpacking bz2 file (2007-05-08) http://python.org/sf/1714773 opened by runnig datetime.date won't accept 08 or 09 as valid days. (2007-05-08) CLOSED http://python.org/sf/1715302 opened by Erik Wickstrom Const(None) in compiler.ast.Return.value (2007-05-09) http://python.org/sf/1715581 opened by Ali Gholami Rudi Destructor behavior faulty (2007-05-12) http://python.org/sf/1717900 opened by Wolf Rogner posixpath and friends have uses that should be documented (2007-05-13) http://python.org/sf/1718017 opened by Gabriel de Perthuis Bugs Closed ___________ smtplib starttls() didn't do TLS Close Notify when quit() (2007-05-07) http://python.org/sf/1713993 deleted by andcycle Multiple re.compile flags cause error (2007-05-07) http://python.org/sf/1713999 closed by gbrandl Universal line ending mode duplicates all line endings (2007-05-07) http://python.org/sf/1714381 closed by gbrandl datetime.date won't accept 08 or 09 as valid days. (2007-05-08) http://python.org/sf/1715302 closed by fdrake Segfaults on memory error (2007-04-10) http://python.org/sf/1697916 closed by gbrandl types.InstanceType is missing but used by pydoc (2007-04-10) http://python.org/sf/1697782 closed by gbrandl improving distutils swig support - documentation (2004-10-14) http://python.org/sf/1046945 closed by gbrandl New / Reopened RFE __________________ Expose callback API in readline module (2007-05-06) http://python.org/sf/1713877 opened by strank if something as x: (2007-05-07) http://python.org/sf/1714448 opened by k0wax RFE Closed __________ commands module (2007-05-06) http://python.org/sf/1713624 closed by gbrandl additions to commands lib (2003-11-11) http://python.org/sf/840034 closed by gbrandl A large block of commands after an "if" cannot be (2003-03-28) http://python.org/sf/711268 closed by gbrandl Please add .bz2 in encodings_map (in the module mimetypes) (2007-04-25) http://python.org/sf/1707693 closed by gbrandl From clodoaldo.pinto at gmail.com Tue May 29 11:52:01 2007 From: clodoaldo.pinto at gmail.com (Clodoaldo) Date: 29 May 2007 08:52:01 -0700 Subject: Unicode to HTML entities Message-ID: <1180453921.357081.89500@n15g2000prd.googlegroups.com> I was looking for a function to transform a unicode string into htmlentities. Not only the usual html escaping thing but all characters. As I didn't find I wrote my own: # -*- coding: utf-8 -*- from htmlentitydefs import codepoint2name def unicode2htmlentities(u): htmlentities = list() for c in u: if ord(c) < 128: htmlentities.append(c) else: htmlentities.append('&%s;' % codepoint2name[ord(c)]) return ''.join(htmlentities) print unicode2htmlentities(u'S?o Paulo') Is there a function like that in one of python builtin modules? If not is there a better way to do it? Regards, Clodoaldo Pinto Neto From saif.shakeel at gmail.com Fri May 18 04:58:26 2007 From: saif.shakeel at gmail.com (saif.shakeel at gmail.com) Date: 18 May 2007 01:58:26 -0700 Subject: i/o prob revisited In-Reply-To: <1179478218.518917.309490@u30g2000hsc.googlegroups.com> References: <1179471963.303052.136690@q23g2000hsg.googlegroups.com> <1179478218.518917.309490@u30g2000hsc.googlegroups.com> Message-ID: <1179478706.505015.176490@w5g2000hsg.googlegroups.com> On May 18, 1:50 pm, half.ital... at gmail.com wrote: > On May 18, 12:06 am, saif.shak... at gmail.com wrote: > > > > > > > Hi, > > I am parsing an xml file ,before that i have replaced a string in > > the original xml file with another and made a new xml file which will > > now be parsed.I am also opening some more files for output.The > > following code shows some i/o commands. > > file_input = raw_input("Enter The ODX File Path:") > > input_xml = open(file_input,'r') > > > (shortname,ext)=os.path.splitext(file_input) > > f_open_out=shortname+".ini" > > log=shortname+".xls" > > test_file=shortname+"testxml.xml" > > > saveout = sys.stdout > > > xmlcont=input_xml.read() > > input_xml.close() > > > xmlcont=xmlcont.replace('localId','dataPackageId') > > > output_file = open(test_file,"w") > > output_file.write(xmlcont) > > output_file.close() > > > f_open=open(f_open_out, 'w') > > logfile=open(log,"w") > > sys.stdout = f_open > > > After this i have to parse the new xml file which is in > > output_file .hence > > > input_xml_sec = open(output_file,'r') > > xmldoc = minidom.parse(input_xml_sec) > > > But i am getting an error on this line > > (input_xml_sec = open(output_file,'r')).I have tried to figure out > > but > > not able to debug.Can someone throw some light or anything they feel > > could be going wrong somewhere. > > How do i capture the error as it vanishes very > > qucikly when i run through command prompt,(the idle envir gives > > indentation errors for no reason(which runs perfectly from cmd > > prompt),hence i dont run using conventional F5. > > http://docs.python.org/tut/ > > Read carefully.- Hide quoted text - > > - Show quoted text - ok i am able to trace the error ...It says: Traceback (most recent call last): File "C:\Projects\ODX Import\code_ini\odxparse_mod.py", line 294, in input_xml_sec = open(output_file,'r') TypeError: coercing to Unicode: need string or buffer, file found Any solutions. Thanks From frederic.pica at gmail.com Thu May 31 07:40:04 2007 From: frederic.pica at gmail.com (frederic.pica at gmail.com) Date: 31 May 2007 04:40:04 -0700 Subject: Python memory handling Message-ID: <1180611604.247696.149060@h2g2000hsg.googlegroups.com> Greets, I've some troubles getting my memory freed by python, how can I force it to release the memory ? I've tried del and gc.collect() with no success. Here is a code sample, parsing an XML file under linux python 2.4 (same problem with windows 2.5, tried with the first example) : #Python interpreter memory usage : 1.1 Mb private, 1.4 Mb shared #Using http://www.pixelbeat.org/scripts/ps_mem.py to get memory information import cElementTree as ElementTree #meminfo: 2.3 Mb private, 1.6 Mb shared import gc #no memory change et=ElementTree.parse('primary.xml') #meminfo: 34.6 Mb private, 1.6 Mb shared del et #no memory change gc.collect() #no memory change So how can I free the 32.3 Mb taken by ElementTree ?? The same problem here with a simple file.readlines() #Python interpreter memory usage : 1.1 Mb private, 1.4 Mb shared import gc #no memory change f=open('primary.xml') #no memory change data=f.readlines() #meminfo: 12 Mb private, 1.4 Mb shared del data #meminfo: 11.5 Mb private, 1.4 Mb shared gc.collect() # no memory change But works great with file.read() : #Python interpreter memory usage : 1.1 Mb private, 1.4 Mb shared import gc #no memory change f=open('primary.xml') #no memory change data=f.read() #meminfo: 7.3Mb private, 1.4 Mb shared del data #meminfo: 1.1 Mb private, 1.4 Mb shared gc.collect() # no memory change So as I can see, python maintain a memory pool for lists. In my first example, if I reparse the xml file, the memory doesn't grow very much (0.1 Mb precisely) So I think I'm right with the memory pool. But is there a way to force python to release this memory ?! Regards, FP From kyosohma at gmail.com Tue May 15 09:10:53 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 15 May 2007 06:10:53 -0700 Subject: Python Power Point Slides In-Reply-To: References: <1179183962.824333.31730@q75g2000hsh.googlegroups.com> <46490372$0$334$e4fe514c@news.xs4all.nl> Message-ID: <1179234653.483748.168500@u30g2000hsc.googlegroups.com> On May 15, 12:19 am, Steven D'Aprano wrote: > On Tue, 15 May 2007 02:48:47 +0200, Irmen de Jong wrote: > > Krypto wrote: > >> Hi, > > >> I want to give a short presentation in my group about benefits of > >> python, why should one use python and some basic starting information > >> about python, about its data type, etc. > > >> Can somebody point me to the right references on the web. I have > >> searched a lot and I do get quite a few but I thought to check on > >> newsgroup for a better presentation, or if you have prepared any, can > >> you please share it. > > >> Thanks > > > Ahem, if you can't create one yourself, how could you ever give a > > convincing presentation about these subjects? You'll have to tell your > > own story... You know the benefits of Python etc. yourself, don't you? > > Doesn't mean (s)he is articulate enough to explain them in his own words > without help, AND familiar enough with Powerpoint or OpenOffice to drive > them effectively, AND has an artistic flair to make the slides not suck, > AND has the time to do all these things. > > Asking for a good presentation is no worse than asking for a good code > library. Maybe Krypto is like some actors or professional Masters of > Ceremonies: excellent at giving the speech, lousy at writing it. > > -- > Steven. Examples of Python presentations: http://www.python.org/doc/essays/ppt/ http://www.cs.wfu.edu/~pauca/csc231/python/Python.pdf Be sure to cite your sources! Mike From slobodan.blazeski at gmail.com Thu May 3 06:29:12 2007 From: slobodan.blazeski at gmail.com (fireblade) Date: 3 May 2007 03:29:12 -0700 Subject: ignorance and intolerance in computing communties In-Reply-To: <1178120019.271716.299590@e65g2000hsc.googlegroups.com> References: <1178120019.271716.299590@e65g2000hsc.googlegroups.com> Message-ID: <1178188152.238480.153390@y80g2000hsf.googlegroups.com> > As i have indicated in my post, it is non-trivial to implement a > function that returns the positive angle of a vector. For example, it > can be done with sign checking of the coordinate components (in total > 4 cases, which can be done as 2 levels of nesting if, or simply 4 > if.), and or the evaluation of Min[Abs[ArcCos[x],Abs[ArcSin[x]]], or > use clever ways with dot product, or ArcTan. It is not a trivial to > know which algorithm is in general more efficient. (this is important, > since finding the angle of a vector is a basic function, that may > needs to be called millions times directly or indirectly) Further, > consider the inverse trig function, it is likely 99.99% of people with > a PH D in math wouldn't know how these are actually implemented. So, > the question of whether calling one of the inverse trig function is > more robust or efficient than another is a open question. And, besides > the algorithmic level, the question also entails how the language > actually implement the inverse trig functions. > > Besides efficiency concerns, there's also robustness concerns. For > example, if the 2 vectors are {1,0} and {0,1}, a simplistic > implementation will result in division by 0 or similar errors. > Checking whether one of them lies on the x or y axis means more if > statements, as well the non-trivial problem of determining if two > numbers are equal. (e.g. is 0.000001 considered equal to 0.0001 ) > > > ? Xah > ? x... at xahlee.org > ?http://xahlee.org/ Xah could you please post staff related to lisp programming like above in separate thread from your personal things like someone banning you from the IRC. thanks bobi From tjansson60 at gmail.com Fri May 11 17:06:39 2007 From: tjansson60 at gmail.com (Thomas Jansson) Date: 11 May 2007 14:06:39 -0700 Subject: Problems with grid() layout under tkinter Message-ID: <1178917599.072765.311830@u30g2000hsc.googlegroups.com> Dear all I am trying to make a small wrapper program for textbased program and it is going well but I have one problem. Namely that I simply do not understand how this grid thing work. I have assigned every widget a specific placement in a grid but when I am running the program it looks very strange. I hope you can help me. A example of the program http://tjansson.dyndns.dk/apache2-default/strange-grid.jpg and the code http://tjansson.dyndns.dk/tjansson/gui.py Kind regards Thomas Jansson From istvan.albert at gmail.com Thu May 17 10:10:25 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: 17 May 2007 07:10:25 -0700 Subject: Python Web Programming - looking for examples of solid high-traffic sites In-Reply-To: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> Message-ID: <1179411025.269221.72210@k79g2000hse.googlegroups.com> On May 16, 5:04 pm, Victor Kryukov wrote: > Our main requirement for tools we're going to use is rock-solid > stability. As one of our team-members puts it, "We want to use tools > that are stable, has many developer-years and thousands of user-years > behind them, and that we shouldn't worry about their _versions_." The > main reason for that is that we want to debug our own bugs, but not > the bugs in our tools. I think this is a requirement that is pretty much impossible to satisfy. Only dead frameworks stay the same. I have yet to see a framework that did not have incompatible versions. Django has a very large user base, great documentation and is deployed for several online new and media sites. It is fast, it's efficient and is simple to use. Few modern frameworks (in any language) are comparable, and I have yet to see one that is better, http://code.djangoproject.com/wiki/DjangoPoweredSites i. From ruiligc at earthlink.net Tue May 1 18:55:32 2007 From: ruiligc at earthlink.net (Ray) Date: Tue, 01 May 2007 22:55:32 GMT Subject: python win32com excel problem Message-ID: Hi, I'm working on something with mysql and excel. I'm using python and win32com. All major function works, But I have two problems: 1. the output need to do "auto fit" to make it readable. I tried to call "xlApp.Columns.AutoFit=1" the whole program will crash, but without xlApp.Columns.AutoFit=1, everything just fine. 2. How do I set a rows format? I need to set row "F" to "Text", "o","p" to general, and "Q", "R", to currency. the data in mysql is stored as text. and it's looks like: 551423 107300.00 22415.90 22124.17 In excel, It will display: 107300 #it should be 107300.00 22415.9 #it should be 22415.90 Error Message when I use Columns.AutoFit=1: Traceback (most recent call last): File "C:\Documents and Settings\Desktop\python\5.1.07\vpi.py", line 317, in root.mainloop() File "C:\Python25\lib\lib-tk\Tkinter.py", line 1023, in mainloop self.tk.mainloop(n) File "C:\Python25\lib\Pmw\Pmw_1_2\lib\PmwBase.py", line 1751, in __call__ _reporterror(self.func, args) File "C:\Python25\lib\Pmw\Pmw_1_2\lib\PmwBase.py", line 1777, in _reporterror msg = exc_type + ' Exception in Tk callback\n' TypeError: unsupported operand type(s) for +: 'type' and 'str' Python code : (this function is called by clicked on "Excel" button from main program) #Begin Function Generate_Excel# def generate_excel(desc): xlApp=Dispatch("Excel.Application") xlApp.Workbooks.Add() xlApp.Worksheets[0] header=['Company', 'Factory', 'PO Number', 'PO Date', 'Required Date', 'Item Number',\ 'Production Date', 'Actual ShipDate', 'Shipping Method', 'Cost', 'Quote', 'Order QTY', \ 'Item Cost', 'Item Quote', 'Pcs Shipped', 'Pcs UnShipped', 'UnShipped Cost', \ 'UnShipped Quote'] if desc==1: header.append('Description') column=1 for each in header: xlApp.ActiveSheet.Cells(1, column).Value=each column=column+1 conn=MySQLdb.connect(host='sql_server', user='t5sll9', passwd='5514dh6', db='app') curs=conn.cursor() curs.execute('call rr_shipping()') data=curs.fetchall() curs.close() conn.close() data_len=len(data)+1 if desc==0: range="A2:R"+str(data_len) if desc==1: range="A2:S"+str(data_len) xlApp.ActiveSheet.Range(range).Value=data #problem here, if I call Columns.AutoFit or ActiveSheet.Columns.AutoFit #the program will crush! #xlApp.Columns.AutoFit=1 #xlApp.ActiveSheet.Columns.AutoFit=1 xlApp.Visible=1 #End Function Generate_Excel# From inq1ltd at verizon.net Sat May 5 07:15:31 2007 From: inq1ltd at verizon.net (jim-on-linux) Date: Sat, 05 May 2007 07:15:31 -0400 Subject: What happened to webmaster@python.org? In-Reply-To: <1178331589.3212.24.camel@localhost.localdomain> References: <1178331589.3212.24.camel@localhost.localdomain> Message-ID: <200705050715.32041.inq1ltd@verizon.net> On Friday 04 May 2007 22:19, Carsten Haese wrote: > Hiya, > > I just tried sending an email to > webmaster at python.org to request a website > change, and the email bounced back with this > excerpt from the delivery failure report: > > """ > Reporting-MTA: dns; bag.python.org > [...] > Final-Recipient: rfc822; > webmaster at bag.python.org Original-Recipient: > rfc822; webmaster at python.org Action: failed > Status: 5.0.0 > Diagnostic-Code: X-Postfix; unknown user: > "webmaster" """ > > Who should I contact to request the website > change? > > Thanks, > > Carsten. I'm not sure but you can try; mailman-owner at python.org or http://mail.python.org/ jim-on-lnux http://www.inqvista.com From eugene.vandenbulke at gmail.com Wed May 30 16:22:13 2007 From: eugene.vandenbulke at gmail.com (EuGeNe Van den Bulke) Date: Wed, 30 May 2007 22:22:13 +0200 Subject: file / module / package - import problem Message-ID: Hi there, I have a "problem" which could be a bad design on my behalf but I am not sure so ... I have a package WMI which contains a module hauteur.py which, when imported, load data from a file located in WMI/data/. In hauteur.py I call open('data/hauteur.yaml'). test.py WMI/ hauteur.py data/ hauteur.yaml lot.py It works well when hauteur is imported in lot.py but if I try import WMI.hauteur in test.py it doesn't work because it looks for the hauteur.yaml file in the "wrong" place. Is there a way to tell a module in a package to look for a file in a specific place i.e. a within package location? Thanks, EuGeNe -- http://www.3kwa.com From bob.NGs at somewhere.com Tue May 1 07:35:53 2007 From: bob.NGs at somewhere.com (Bob Phillips) Date: Tue, 1 May 2007 12:35:53 +0100 Subject: SEO - Search Engine Optimization - Seo Consulting References: <1177808356.681710.42980@n76g2000hsh.googlegroups.com> Message-ID: You bottom posters really are a bunch of supercilious, self-righteous bigots. Personally, I find bottom-posting like reading a book backwards ... it doesn't work for me. And regardless of his response, Mr Bruney IS an MVP, he is clearly knowledgeable in his subject, and his book is well enough thought of to make me consider buying it. "Sherm Pendley" wrote in message news:m2slaik3yf.fsf at local.wv-www.com... > "Juan T. Llibre" writes: > >> Top or bottom posting is a user choice. > > Yes, one can choose to be polite and follow established usenet > conventions, or one can choose to be rude and self-centered. > > Those who choose rudeness over courtesy can expect to be called down > for it - which is arguably rude in itself, but on usenet one reaps what > one sows. Someone who can't deal with that, shouldn't be on usenet. > > sherm-- > > -- > Web Hosting by West Virginians, for West Virginians: http://wv-www.net > Cocoa programming in Perl: http://camelbones.sourceforge.net From carsten at uniqsys.com Fri May 11 17:19:32 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 11 May 2007 17:19:32 -0400 Subject: Interesting list Validity (True/False) In-Reply-To: <1178917940.363627.216580@y5g2000hsa.googlegroups.com> References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> <1178917940.363627.216580@y5g2000hsa.googlegroups.com> Message-ID: <1178918372.1820.37.camel@dot.uniqsys.com> On Fri, 2007-05-11 at 14:12 -0700, nufuhsus at gmail.com wrote: > However, how would you test for the falsness of the object arg? if not arg: # stuff -- Carsten Haese http://informixdb.sourceforge.net From warren at muse.com Thu May 31 23:17:07 2007 From: warren at muse.com (Warren Stringer) Date: Thu, 31 May 2007 20:17:07 -0700 Subject: c[:]() In-Reply-To: References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> <135tobve86qj808@corp.supernews.com> <135tru124pie2b3@corp.supernews.com> <135tv1bjqgbmsc9@corp.supernews.com> Message-ID: <002801c7a3fb$56cc8030$240110ac@Muse> As mentioned a while back, I'm now predisposed towards using `do(c)()` because square brackets are hard with cell phones. The one mitigating factor for more general use, outside of cell phones, is speed. If a PEP enables a much faster solution with c[selector()]() then it may be worthwhile. But, I feel a bit circumspect about suggesting a change as I haven't looked at Python source, nor have I looked at the BNF, lately. I think Martelli's recent post on implantation may be relevant: > Tuples are implemented as compact arrays of pointer-to-PyObject (so are > lists, BTW). So, for example, a 10-items tuple takes 40 bytes (plus a > small overhead for the header) on a 32-bit build, not 80 as it would if > implemented as a linked list of (pointer-to-object, pointer-to-next) > pairs; addressing sometuple[N] is O(1), NOT O(N); etc, etc. The questions about implementing a working c[:]() are: 1) Does it break anything? 2) Does it slow anything down? 3) Could it speed anything up? 4) Does it make code easier to read? 5) What question(s) did I forget to ask? 1) No? The fact that c() currently fails on a container implies that enabling it would not break existing client code. Would this break the language definition? A couple years ago, I hand transcribed the BNF of version 2.2 to an alternative to BNF. I would love to know if c[:]() would break the BNF in a fundamental way. 2) I don't know. I've always assumed that Python objects are hash table entries. How would this change? Would it change? Does the message "TypeError: 'list' object is not callable" guarantee a short path between bytecode and hash table? Is there some other mitigating factor? 3) Maybe? Does overriding __call__ create any extra indirection? If yes, then I presume that `do(c)()` would be slower the `c[:]()`. I am writing rather amorphous code. This may speed it up. 4) I posit yes. Am I missing something? What idiom does would c[:]() break? This correlates with whether `c[:]()` breaks the language definition, in question 1) Erik Max Francis wrote: > Warren Stringer wrote: > > > I'm still a bit new at this, was wondering why c[:]() doesn't work, and > > implicitly wondering why it *shouldn't* work. > > It does work. It means "make a sliced copy of `c`, and then call it > with no arguments." Functionally that is _no different_ from `c()`, > which means "take `c` and call it with no arguments," because presuming > `c` is a list, `c[:]` makes a shallow copy. > > So if you think `c()` and `c[:]()` should do something different in this > case, you are profoundly confused about Python's semantics of what > objects are, what it means to shallow copy a list, and what it means to > make a function call. That you keep including the slice suggests that > there's something about its meaning that's not yet clicking. I use `c[:]()` because it is unambiguous about using a container > If you really want syntax where a function call on a container calls all > of its elements, then that is trivially easy to do by creating such an > object and overriding its `__call__` method. > > If you're not willing to do that, but still insisting that `c[:]()` > makes sense, then perhaps it would be more advisable to learn more about > Python rather than try to suggest profound changes to the language and > its conventions. You're right. At the same time, version 3 is coming up soon. There is a short window of opportunity for profound changes. Also, my audacious suggestion has spawned illuminating replies. For this instance, I have read about shallow copy, before, but haven't been told where it is used, before now. Other posts led to insights about closures, and yielding a real solution. This is incredibly useful. I've learned a lot. Thanks, \~/ From showell30 at yahoo.com Sun May 27 14:31:31 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 27 May 2007 11:31:31 -0700 (PDT) Subject: itertools.groupby In-Reply-To: <474296.49047.qm@web33508.mail.mud.yahoo.com> Message-ID: <611756.61628.qm@web33507.mail.mud.yahoo.com> --- Steve Howell wrote: > > --- 7stud wrote: > > > Bejeezus. The description of groupby in the docs > is > > a poster child > > for why the docs need user comments. > Regarding the pitfalls of groupby in general (even assuming we had better documentation), I invite people to view the following posting that I made on python-ideas, entitled "SQL-like way to manipulate Python data structures": http://mail.python.org/pipermail/python-ideas/2007-May/000807.html In the thread, I don't really make a proposal, so much as a problem statement, but my radical idea is that lists of dictionaries fit the relational model perfectly, so why not allow some kind of native SQL syntax in Python that allows you to manipulate those data structures more naturally? ____________________________________________________________________________________Luggage? GPS? Comic books? Check out fitting gifts for grads at Yahoo! Search http://search.yahoo.com/search?fr=oni_on_mail&p=graduation+gifts&cs=bz From gur.tom at gmail.com Thu May 17 07:27:13 2007 From: gur.tom at gmail.com (Tom Gur) Date: 17 May 2007 04:27:13 -0700 Subject: Get a control over a window In-Reply-To: References: <1179234413.915336.263660@n59g2000hsh.googlegroups.com> Message-ID: <1179401233.915903.292010@k79g2000hse.googlegroups.com> Thanks guys, especially Duncan ! That's what I'm using now: import sys from win32gui import GetWindowText, EnumWindows, ShowWindow from win32con import SW_MINIMIZE def listWindowsHandles(): res = [] def callback(hwnd, arg): res.append(hwnd) EnumWindows(callback, 0) return res def listWindowsNames(): return (map(GetWindowText, listWindowsHandles())) def minimizeWindow(): a_hwnd = listWindowsHandles() [listWindowsNames().index(sys.argv[1])] ShowWindow(a_hwnd, SW_MINIMIZE) minimizeWindow() From penis.Mosely9 at gmail.com Fri May 18 15:45:24 2007 From: penis.Mosely9 at gmail.com (penis.Mosely9 at gmail.com) Date: 18 May 2007 12:45:24 -0700 Subject: NUDE PICS! FREE DOWNLOAD*! Message-ID: <1179517524.700946.96460@h2g2000hsg.googlegroups.com> http://nudepicks.blogspot.com/2007/05/us-education-official-testifies-before.html - Download all these hot nude pics!!! From kyosohma at gmail.com Wed May 9 16:55:45 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 9 May 2007 13:55:45 -0700 Subject: Unzip then Zip help In-Reply-To: <1178739362.137264.251600@e65g2000hsc.googlegroups.com> References: <1178739362.137264.251600@e65g2000hsc.googlegroups.com> Message-ID: <1178744145.148397.214670@u30g2000hsc.googlegroups.com> On May 9, 2:36 pm, sdoty... at gmail.com wrote: > I am a true n00b... and I just using Python to complete some very > small uneventful task, but need help with one last thing. > > Basically, this I what I am trying to do. > > make a temp directory (this part I can do) > > Need help with: > ***unzip a JAR file with the complete list of subdirectories w/ > files**** > > modify the a set of XML files (this part I can do) > > Need help with: > ***then zip the entire contents of the temp directory with sub > directories*** > > The only thing I am having trouble with is the whole directory stuff, > if this was just straight files, no problem. > > Any help would be appreciated I would use the subprocess module and command line flags for whatever zip client software you use to get the job done. For example, I have Filzip and IZArc, both of which support command line unzipping and zipping. One of my co-workers came up with a way to unzip a zipped file: def unzip(path, zipFile): """ Unzips file specified in above dictionary """ isdir = os.path.isdir join = os.path.join norm = os.path.normpath split = os.path.split for each in zipFile.namelist(): if not each.endswith('/'): root, name = split(each) directory = norm(join(path, root)) if not isdir(directory): os.makedirs(directory) file(join(directory, name), 'wb').write(zipFile.read(each)) # where path is the location you want to extract to and "zipFile" is the file.zip Good luck! Mike From __peter__ at web.de Mon May 28 17:57:46 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 28 May 2007 23:57:46 +0200 Subject: Tkinter error References: <1180388107.105473.203510@h2g2000hsg.googlegroups.com> Message-ID: BartlebyScrivener wrote: > Finally started trying to build a simple gui form for inserting text > data into a mysql db of quotations. > > I found this nice Tkinter tutorial, > > http://www.ibiblio.org/obp/py4fun/gui/tkPhone.html > > but midway I'm getting an error. > > from Tkinter import * > > >>> win = Tk() >>>> f = Frame(win) >>>> b1 = Button(f, "One") > > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 1936, in __init__ > Widget.__init__(self, master, 'button', cnf, kw) > File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 1859, in __init__ > BaseWidget._setup(self, master, cnf) > File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 1839, in _setup > if cnf.has_key('name'): > AttributeError: 'str' object has no attribute 'has_key' Hmm, there must have been an update to that tutorial after you read it: """ >>> b1 = Button(win,text="One") >>> b2 = Button(win,text="Two") The class Button takes the parent window as the first argument. As we will see later other objects, such as frames, may also act as parents. The rest of the arguments are passed by keyword and are all optional. """ Peter From mblume at socha.net Sat May 19 07:38:29 2007 From: mblume at socha.net (Martin Blume) Date: Sat, 19 May 2007 13:38:29 +0200 Subject: Execute commands from file References: <1179320782.594398.67980@u30g2000hsc.googlegroups.com> <464b370c$0$3808$5402220f@news.sunrise.ch> <1179387023.005808.60670@o5g2000hsb.googlegroups.com> <464c7e99$0$3814$5402220f@news.sunrise.ch> Message-ID: <464ee1b6$0$3812$5402220f@news.sunrise.ch> "Steve Holden" schrieb > > > > [ difference between exec open(fname).read() > > and for line in open(fname): exec line ] > > > > So it seems to depend on the way the file is read. > > > It depends on the way the lines of the file are executed, > not how they are read. > Could you elaborate a little bit more on the difference? I assumed that because read() reads the whole file, the body of my function sowhat() is present, so that it can be parsed while the invocation of exec is still running. If it is read and exec'd line by line, the definition of the function is still left open at the moment exec() ends, causing the "EOF" error. Hence my statement, "it depends on the way the file is read". > And you may remember the original poster was > proposing this: > > inp = open(cmd_file) > for line in inp: > exec line > > As for your first example, why not just use execfile() ? > I assume that execfile(fname) is equivalent to exec open(fname).read() ? Regards Martin From torriem at chem.byu.edu Mon May 21 11:22:01 2007 From: torriem at chem.byu.edu (Michael L Torrie) Date: Mon, 21 May 2007 09:22:01 -0600 Subject: Python compared to other language In-Reply-To: References: <1179753682.661307.186540@y18g2000prd.googlegroups.com> Message-ID: <1179760921.28714.14.camel@contra.chem.byu.edu> On Mon, 2007-05-21 at 16:00 +0200, Marc 'BlackJack' Rintsch wrote: > In <1179753682.661307.186540 at y18g2000prd.googlegroups.com>, > user2048 at yahoo.com wrote: > > >> Python is a strongly typed but dynamic language ... > > > > In the "A few questions" thread, John Nagle's summary of Python begins > > "Python is a byte-code interpreted untyped procedural dynamic > > language with implicit declaration. " > > > > Is Python strongly typed or untyped? > > Strongly typed. Most people think of statically typed, like Java, when they think of "Strongly typed." Python is strongly, dynamically typed. Some people refer to Python as "duck typed" meaning that python cares more about what the object appears to be, rather than it's actual type. If it looks like a duck, quacks like a duck, it must be a duck. Thus python is more concerned with the protocol of an object than the actual type. This is a powerful concept. I've also found, though, that duck-typing can be a real weakness when you're working with a complicated third-party library with weak documentation. You can't always infer what the method call is expecting, even if you have the source code in front of you. Figuring out the python twisted I/O library, is fraught with such challenges, despite the documentation. > > Ciao, > Marc 'BlackJack' Rintsch > From mwilliams at mgreg.com Sun May 13 12:17:24 2007 From: mwilliams at mgreg.com (Michael Williams) Date: Sun, 13 May 2007 12:17:24 -0400 Subject: Using "subprocess" without lists. . .? In-Reply-To: References: Message-ID: Hi All, I've recently seen the "subprocess" module and am rather confused by it's requirements. Is it not possible to execute an entire string without having to break them up into a list of arguments? For instance, I'd much rather do the following: subprocess.call("ls -al | grep -i test") . . .than to have to: list = ["ls", "-a", "-l" ] . . . . . . and so on and so forth. subprocess.call(list. . .) What is the best way to go about executing a massively complex single line command? Thanks, Michael From steve at holdenweb.com Sat May 26 21:13:46 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 26 May 2007 21:13:46 -0400 Subject: binary search trees using classes In-Reply-To: <738900580705261802w4c2883d7tad86a9c6ec74edb8@mail.gmail.com> References: <738900580705261802w4c2883d7tad86a9c6ec74edb8@mail.gmail.com> Message-ID: Arma?an ?elik wrote: >>/ Have a nice day. Have a nice day. > />/ Have a nice day. > />/ Have a nice day. > />/ > />/ the output is > />/ > />/ a 4 > />/ day 4 > / >>/ have 4 > />/ nice 4 > can you send c++ code of this output .This my homework/ > If it's your homework, shouldn't *you* be doing it? In case you hadn't noticed, this isn't even a C++ list. Perhaps you should visit the clue shop and make a purchase or two? 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From martin at v.loewis.de Thu May 17 08:58:45 2007 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Thu, 17 May 2007 14:58:45 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464abecb$0$6403$9b4e6d93@newsspool2.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <464ab2f9$0$23146$9b4e6d93@newsspool1.arcor-online.net> <464ABA99.8080208@web.de> <464abecb$0$6403$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <464C5185.4060302@v.loewis.de> Ren? Fleschenberg schrieb: > Stefan Behnel schrieb: >> Then get tools that match your working environment. > > Integration with existing tools *is* something that a PEP should > consider. This one does not do that sufficiently, IMO. What specific tools should be discussed, and what specific problems do you expect? Regards, Martin From fekadumamo at yahoo.com Sun May 6 19:17:11 2007 From: fekadumamo at yahoo.com (pickylee123) Date: 6 May 2007 16:17:11 -0700 Subject: New Skype 4.1 Alpha released for linux. Message-ID: <1178493431.155093.296530@l77g2000hsb.googlegroups.com> Skype 4.1 Alpha has been released for linux users. It has all the usual features but some has unresolved bugs. http://www.speedateauction.com/blog/blog_detail?blog_id=74315&user_id=1356 From george.sakkis at gmail.com Wed May 23 14:00:56 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 23 May 2007 11:00:56 -0700 Subject: Parallel/distributed generator Message-ID: <1179943256.575473.62610@q66g2000hsg.googlegroups.com> I'm looking for any existing packages or ideas on how to implement the equivalent of a generator (in the Python sense, i.e. http://www.python.org/dev/peps/pep-0255/) in a parallel/distributed way. As a use case, imagine a function that generates a range of primes. I'd like to be able to do something along the following lines: def iterprimes(start=1, end=None): # ... yield prime # rpc-related initialization ... rpc_proxy = some_rpc_lib(iterprimes, start=1e6, end=1e12) for prime in proxy: print prime Is there any module out there that does anything close to this ? George From robin at alldunn.com Tue May 15 15:36:38 2007 From: robin at alldunn.com (Robin Dunn) Date: Tue, 15 May 2007 12:36:38 -0700 Subject: ANN: wxPython 2.8.4.0 Message-ID: <464A0BC6.9020109@alldunn.com> Announcing ---------- The 2.8.4.0 release of wxPython is now available for download at http://wxpython.org/download.php. This release includes a number of bug fixes, updates to some contribs and other improvements. Source code is available, as well as binaries for both Python 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.4.0 ------------------ wxGTK: Make wx.NO_BORDER style work with wx.RadioBox (patch 1525406) Update to 1.0 of TreeMixin. wx.lib.customtreectrl: Patch from Andrea that fixes the following problems/issues: * ZeroDivisionError when using the Vista selection style and calling SelectItem; for some strange reason, sometimes the item rect is not initialized and that generates the ZeroDivisionError when painting the selection rectangle; * Added a DeleteWindow method to GenericTreeItem class, for items that hold a widget next to them; * Renamed CustomTreeCtrl method IsEnabled to IsItemEnabled, otherwise it conflicts with wx.Window.IsEnabled; * Now CustomTreeCtrl behaves correctly when the widget attached to an item is narrower (in height) than the item text; wx.lib.flatnotebook: Patch from Andrea that implements the following: * A new style FNB_FF2: my intentions were to make it like Firefox 2, however it turned out to be an hybrid between wxAUI notebook glose style & FF2 ...I still think it looks OK. The main purpose for making it more like wxAUI is to allow applications that uses both to have same look and feel (or as close as it can get...); * Changed the behavior of the left/right rotation arrows to rotate single tab at a time and not bulk of tabs; * Updated the demo module. XRCed now uses a wx.FileHistory object for managing the recent files menu. wx.DateSpan and wx.TimeSpan now use lower case property names in order to not conflict with the same named static methods that already existed. wx.aui.PyAuiDocArt and wx.aui.PyAuiTabArt can now be derived from in wxPython and plugged in to wx.AUI. XRCed has a new experimental feature to add controls by draging icons from the tool palette to the test window. Mouse position is tracked to highlight the future parent of the new item. Updates to MaskedEdit controls from Will Sadkin: maskededit.py: Added parameter option stopFieldChangeIfInvalid, which can be used to relax the validation rules for a control, but make best efforts to stop navigation out of that field should its current value be invalid. Note: this does not prevent the value from remaining invalid if focus for the control is lost, via mousing etc. numctrl.py, demo / MaskedNumCtrl.py: In response to user request, added limitOnFieldChange feature, so that out-of-bounds values can be temporarily added to the control, but should navigation be attempted out of an invalid field, it will not navigate, and if focus is lost on a control so limited with an invalid value, it will change the value to the nearest bound. combobox.py: Added handler for EVT_COMBOBOX to address apparently inconsistent behavior of control when the dropdown control is used to do a selection. textctrl.py Added support for ChangeValue() function, similar to that of the base control, added in wxPython 2.7.1.1. Update to latest FloatCanvas from Chris Barker. The pywxrc tool now properly supports generating classes for menus and menubars, and also creating attributes for menus, menubars and menu items. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From Green.Horn.000 at gmail.com Thu May 17 17:29:35 2007 From: Green.Horn.000 at gmail.com (GreenH) Date: 17 May 2007 14:29:35 -0700 Subject: An expression that rebinds a variable? In-Reply-To: References: <1179411429.536764.5620@q75g2000hsh.googlegroups.com> Message-ID: <1179437375.505844.306510@e65g2000hsc.googlegroups.com> On May 17, 9:15 am, Maric Michaud wrote: > GreenH a ?crit : > > > Can I know what kind of expressions rebind variables, of course unlike > > in C, assignments are not expressions (for a good reason) > > So, eval(expr) should bring about a change in either my global or > > local namespace, where 'expr' is the expression > > For global scope you could use globals().__setitem__('x', 5) but it's > not possible in local scope because the dict returned by locals() in > function is not where the local variables are really stored. > > So the preferred way is to use : > > In [39]: exec "x=5" > > which the same as : > > In [40]: eval(compile('x=5', '', 'exec')) > > -- > _____________ > > Maric Michaud > _____________ > > Aristote -www.aristote.info > 3 place des tapis > 69004 Lyon > Tel: +33 4 26 88 00 97 > Mobile: +33 6 32 77 00 21 Thanks, But, my interest is actually in finding the cases in which eval(expr) would throw surprises at me by bringing changes in namespace(s), just because I haven't given a namespace for that eval() i.e., where would we see the perils of not passing namespace to the 'eval'. -Green From turbana at gmail.com Tue May 1 19:28:00 2007 From: turbana at gmail.com (Ian Clark) Date: Tue, 1 May 2007 16:28:00 -0700 Subject: Read and Write the same file In-Reply-To: <1178060601.700099.263240@y5g2000hsa.googlegroups.com> References: <1178060601.700099.263240@y5g2000hsa.googlegroups.com> Message-ID: On 1 May 2007 16:03:28 -0700, JonathanB wrote: > Ok, so this is the scenario. I need to create a simple, no-frills XML > editor for non-technical users. It doesn't have to do anything fancy, > what I want is a series of text boxes with the text contents of the > elements pre-printed. Then the users can type their changes into the > text boxes and click submit and it will load the changes in. So here > is the problem, this means I need to open the same file as both read > and write. How do I do this? I'm slowly learning the DOM stuff that I > need to know to do this, but this file thing I haven't been able to > find anywhere. > > JonathanB Well the most straight forward approach is to read data from the file into memory. Let the user make any changes. Then save the data back to the file, overwriting the oringinal copy. Now, this only really works if you're dealing with small files. Regardless though, you never really need to have a file open for both reading and writing. Since they occur (so it sounds) at distinct times during your program flow, just open it twice: the first to read, the second to write. Ian From straton at lampsacos.demon.co.uk Tue May 1 15:31:59 2007 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Tue, 01 May 2007 20:31:59 +0100 Subject: Generate report containing pdf or ps figures? In-Reply-To: References: <132pnp6r4qg0lc2@corp.supernews.com> Message-ID: Cameron Laird wrote: > In article <132pnp6r4qg0lc2 at corp.supernews.com>, > Grant Edwards wrote: >> I need to be able to generate a PDF report which consists >> mostly of vector images (which I can generate as encapsulated >> Postscript, PDF, or SVG). What I need is a way to combine >> these figures into a single PDF document. Right now the >> reports consist entire of these figures, so I just write the >> figures out to temp files and then use os.system() to run >> ghostscript with appropriate options to combine them into a >> single PDF file. >> >> I'd like to be able to add some text and/or place the figures >> in a manner other than one per page in the output document. >> >> I've looked at ReportLab's documentation, but although it >> appears to be able to use bitmap images (e.g jpeg) it doesn't >> appear to be able to use vector images (EPS/PDF/SVG). >> >> Is there a PDF generation library that can place EPS or >> PDF figures on a page? > . > . > . > You're stuck. > I have also done quite a bit of work in this area, and keep coming back to LaTeX (pdfLaTeX). For automatic document production--if you have a good quantity of very similar documents--you can produce the LaTeX from XML, hence many other input formats. The graphics need to be converted into pdf format, and you need to be careful that the vector nature of the file is preserved during this conversion, as well as transparency. Unfortunately this is still uncommon for SVG. Also Adobe seem to have lost their one-time enthusiasm for SVG, since they acquired Flash and Friends. A rather new entry into the arena is 'Altsoft Xml2PDF Workstation' which is free for command-line use, but not for server use. Seems to produce PDF of reasonable quality and to use vector format, transparency and gradient fills. Another possibility is to wrap things up as SMIL. The latest versions of Acrobat reader can use them, using RealPlayer (for example) as the actual multimedia engine. There is at least one LaTeX package that can produce PDF that incorporates such multi-media. I've rather given up on ReportLab. Trying to extend it (the free part) to use graduated fills completely did my head in! From mail at timgolden.me.uk Wed May 16 02:32:43 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 16 May 2007 07:32:43 +0100 Subject: removing common elemets in a list In-Reply-To: <1179296224.885877.187200@q23g2000hsg.googlegroups.com> References: <1179296224.885877.187200@q23g2000hsg.googlegroups.com> Message-ID: <464AA58B.1010505@timgolden.me.uk> saif.shakeel at gmail.com wrote: > Hi, > Suppose i have a list v which collects some numbers,how do i > remove the common elements from it ,without using the set() opeartor. Is this a test? Why don't you want to use the set operator? Anyway, you can just move things from one list into another excluding those which are already moved: numbers = [1, 2, 3, 3, 4, 4, 5] unique_numbers = [] for n in numbers: if n not in unique_numbers: unique_numbers.append (n) print unique_numbers It won't be the fastest thing you could do, but it does work. Using a dictionary would speed things up, but then you're basically implementing a set using a dictionary. TJG From abbas4u at gmail.com Wed May 2 06:48:19 2007 From: abbas4u at gmail.com (M Abbas) Date: 2 May 2007 03:48:19 -0700 Subject: Calling Exe from Python Message-ID: <1178102899.910368.114140@n76g2000hsh.googlegroups.com> Hello Folks, This is what i am required to do. Call an executable from my python script, and when the executable is fininshed running, i should continue with my python script. I have tried "os.exec()" but it calls the executable and never returns to the calling python script. I tried "os.fork" it will start an independent process, since logic of my program depends on the results of executable. I am unable to figure, how to do it. Hope you folks would help me. ~JinBaba From mcepl at redhat.com Sat May 26 03:54:33 2007 From: mcepl at redhat.com (Matej Cepl) Date: Sat, 26 May 2007 09:54:33 +0200 Subject: email modul with writing to mboxes (and locking) for python 2.4.*? References: <87veeg4v0q.fsf@pobox.com> Message-ID: On 2007-05-25, 18:28 GMT, John J. Lee wrote: > Not sure whether you know this already, but module mailbox in > Python 2.5 supports writing mbox folders. If it's not 2.4 > compatible, it's fairly likely to be an easy backport. Cool! Thanks a lot. One more reason why to upgrade to Fedora Core 7 as soon as it is available, I suppose. Thanks again, Matej From kyosohma at gmail.com Thu May 31 09:53:12 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 31 May 2007 06:53:12 -0700 Subject: WEATHER PROGRAMMING IN PYTHON In-Reply-To: References: <1180618635.925002.282080@n15g2000prd.googlegroups.com> Message-ID: <1180619592.295456.196970@p47g2000hsd.googlegroups.com> On May 31, 8:44 am, Marc 'BlackJack' Rintsch wrote: > In <1180618635.925002.282... at n15g2000prd.googlegroups.com>, sandeep patil > wrote: > > > how to diplay the weather condiction on my webpage > > suppose i want to read weather fromwww.bbc.co.uk/weather.html > > how i can read it usin program > > It's hard to scrape information about weather from an 404 error page. ;-) > > Find some page with actual weather reports or forecasts and use the > BeautifulSoup module to scrape the information you need. > > Ciao, > Marc 'BlackJack' Rintsch It looks like you might even be able to use the rss module from Python on this sub-page: http://feeds.bbc.co.uk/weather/feeds/rss/5day/world/0008.xml See here for more info on RSS with Python: http://wiki.python.org/moin/RssLibraries Mike From see.signature at no.spam Wed May 16 07:57:35 2007 From: see.signature at no.spam (Eric Brunel) Date: Wed, 16 May 2007 13:57:35 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <7x4pmg716p.fsf@ruckus.brouhaha.com> <4648EC26.8020907@v.loewis.de> Message-ID: On Wed, 16 May 2007 12:22:01 +0200, Neil Hodgson wrote: > Eric Brunel: > >> ... there is no keyboard *on Earth* allowing to type *all* characters >> in the whole Unicode set. > > My keyboard in conjunction with the operating system (US English > keyboard on a Windows XP system) allows me to type characters from any > language. I haven't learned how to type these all quickly but I can get > through a session of testing Japanese input by myself. Its a matter of > turning on different keyboard layouts through the "Text Services and > Input Languages" control panel. Then there are small windows called > Input Method Editors that provide a mapping from your input to the > target language. Other platforms provide similar services. Funny you talk about Japanese, a language I'm a bit familiar with and for which I actually know some input methods. The thing is, these only work if you know the transcription to the latin alphabet of the word you want to type, which closely match its pronunciation. So if you don't know that ?? ? is pronounced "uriba" for example, you have absolutely no way of entering the word. Even if you could choose among a list of characters, are you aware that there are almost 2000 "basic" Chinese characters used in the Japanese language? And if I'm not mistaken, there are several tens of thousands characters in the Chinese language itself. This makes typing them virtually impossible if you don't know the language and/or have the correct keyboard. -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From aleax at mac.com Wed May 2 01:03:07 2007 From: aleax at mac.com (Alex Martelli) Date: Tue, 1 May 2007 22:03:07 -0700 Subject: Python-URL! - weekly Python news and links (Apr 30) References: <1177963548_23061@sp12lax.superfeed.net> <961ig4-hti.ln1@lairds.us> Message-ID: <1hxgfsv.jglywebfrbsdN%aleax@mac.com> Neil Hodgson wrote: > Cameron Laird: > > > ... but the *references* in that object are unlikely to be > > meaningful on the second machine (or, in many cases, on the > > original machine, if at a sufficiently later time). > > The marshaling of the object is responsible for persisting any > contained references in a format that can be revivified on the second > machine. Sometimes these are references to 'short lived' objects in the > original process, in which case they should have been addrefed which > will also lock the process alive. Other times they may be monikers to > stable objects which can be reloaded. Excellent brief summary. If one COM object in ten implemented marshaling correctly, I might still be a "Windows guru" instead of having run away screaming years ago (which played out all right careerwise, actually:-). Everybody needs to read Don Box's "Essential COM", btw; if one author of COM code in ten had read and understood it, etc, etc. Alex From steve at holdenweb.com Fri May 25 08:21:13 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 25 May 2007 08:21:13 -0400 Subject: Newsgroups and mailing lists (was Re: Slightly OT: Why all the spam?) In-Reply-To: References: <3bb44c6e0705220008y10f5deb7v86ed82d3f8241761@mail.gmail.com> Message-ID: Gabriel Genellina wrote: > En Thu, 24 May 2007 21:53:24 -0300, Terry Reedy > escribi?: > >> "Aahz" wrote in message >> news:f34qpt$3oh$1 at panix3.panix.com... >> | First of all, if you're accessing python-list as comp.lang.python, >> you're >> | accessing a newsgroup, *not* a mailing list. Secondly, c.l.py is an >> | unmoderated group; there is no moderator and no control over who posts. >> | However, netnews (Usenet) has a mechanism for cancelling articles, and >> | cancelbots send out cancel messages for spam articles. >> >> This does not address the issue of spam passing thru python-list, which I >> believe is supposed to be somewhat moderated (by people who have rejected >> my help to catch spam) to gmane, where I read it. I presume this is the >> path for stuff injected via google. Or perhaps stuff flows the other >> way. I am not sure. Or perhaps it it injected independently in both or >> all >> three places. > > Or four or N places; anybody can post using any other nntp server that > carries this group (if the server allows him, of course). Mailing lists > are easier to control because there is a single entry point; news aren't > that way. > I *did* try to explain all this a week or two ago. Did I not make myself clear? 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From heikki at osafoundation.org Wed May 30 01:11:33 2007 From: heikki at osafoundation.org (Heikki Toivonen) Date: Tue, 29 May 2007 22:11:33 -0700 Subject: ANN: CaltrainPy 0.1 Message-ID: CaltrainPy is a Caltrain (http://caltrain.com/) schedule program written in Python. It uses Tkinter for GUI. Download link and screenshot here: http://www.heikkitoivonen.net/blog/?p=11 The reason I wrote CaltrainPy was because I recently switched from a Palm OS device to a Windows Mobile device, and I could not find a good Caltrain schedule program for Windows Mobile. I lucked out by noticing that there is a Python port for Windows Mobile (http://pythonce.sourceforge.net/Wikka/HomePage). There seem to be 3 GUI options for Windows Mobile, and I originally chose Tkinter since it seemed the easiest to get started with on Windows Mobile. Since this was my first program using Tkinter there are some rough edges. Most notably I was not able to figure out how to make a working full screen application. Any ideas on how to fix my app to make it a work full screen much appreciated. And any other ideas and patches welcome as well. -- Heikki Toivonen From bbxx789_05ss at yahoo.com Sun May 27 13:49:06 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 27 May 2007 10:49:06 -0700 Subject: itertools.groupby In-Reply-To: References: <1180286272.100790.131670@q75g2000hsh.googlegroups.com> Message-ID: <1180288146.066905.237550@q69g2000hsb.googlegroups.com> On May 27, 11:28 am, Steve Howell wrote: > --- 7stud wrote: > > Bejeezus. The description of groupby in the docs is > > a poster child > > for why the docs need user comments. Can someone > > explain to me in > > what sense the name 'uniquekeys' is used this > > example: [...] > > The groupby method has its uses, but it's behavior is > going to be very surprising to anybody that has used > the "group by" syntax of SQL, because Python's groupby > method will repeat groups if your data is not sorted, > whereas SQL has the luxury of (knowing that it's) > working with a finite data set, so it can provide the > more convenient semantics. > > ___________________________________________________________________________ _________You snooze, you lose. Get messages ASAP with AutoCheck > in the all-new Yahoo! Mail Beta.http://advision.webevents.yahoo.com/mailbeta/newmail_html.html > The groupby method has its uses I'd settle for a simple explanation of what it does in python. From john at datavoiceint.com Wed May 9 10:46:22 2007 From: john at datavoiceint.com (HMS Surprise) Date: 9 May 2007 07:46:22 -0700 Subject: String parsing In-Reply-To: <1178720135.613295.81720@e51g2000hsg.googlegroups.com> References: <1178672992.522463.228620@l77g2000hsb.googlegroups.com> <1178720135.613295.81720@e51g2000hsg.googlegroups.com> Message-ID: <1178721982.838765.44390@n59g2000hsh.googlegroups.com> BTW, here's what I used, the other ideas have been squirreled away in my neat tricks and methods folder. for el in data.splitlines(): if el.find('LastUpdated') <> -1: s = el.split("=")[-1].split('"')[1] print 's:', s Thanks again, jh From http Tue May 29 23:30:22 2007 From: http (Paul Rubin) Date: 29 May 2007 20:30:22 -0700 Subject: itertools.groupby References: <1180286272.100790.131670@q75g2000hsh.googlegroups.com> <7xveecr5xx.fsf@ruckus.brouhaha.com> <6Y6dnb0mTLsaCsbbnZ2dnUVZ_hCdnZ2d@comcast.com> <1180420476.785936.322400@g37g2000prf.googlegroups.com> Message-ID: <7x646b6l9t.fsf@ruckus.brouhaha.com> Raymond Hettinger writes: > The gauntlet has been thrown down. Any creative thinkers > up to the challenge? Give me cool recipes. Here is my version (with different semantics) of the grouper recipe in the existing recipe section: snd = operator.itemgetter(1) # I use this so often... def grouper(seq, n): for k,g in groupby(enumerate(seq), lambda (i,x): i//n): yield imap(snd, g) I sometimes use the above for chopping large (multi-gigabyte) data sets into manageable sized runs of a program. That is, my value of n might be something like 1 million, so making tuples that size (as the version in the itertools docs does) starts being unpleasant. Plus, I think the groupby version makes more intuitive sense, though it has pitfalls if you do anything with the output other than iterate through each item as it emerges. I guess you could always use map instead of imap. From sjmachin at lexicon.net Mon May 21 18:25:53 2007 From: sjmachin at lexicon.net (John Machin) Date: Tue, 22 May 2007 08:25:53 +1000 Subject: Installing Python in a path that contains a blank In-Reply-To: References: Message-ID: <46521C71.8010602@lexicon.net> On 21/05/2007 11:30 PM, Konrad Hinsen wrote: > I am trying to install Python from sources in my home directory on a Mac > cluster (running MacOS X 10.4.8). The path to my home directory contains > a blank, and since the installation procedure insists on getting an > absolute path for the prefix, I cannot avoid installing to a path whose > name contains a blank. Python does not seem to be prepared for this, as > it uses only the part before the blank, resulting in numerous error > messages. > > Does anyone know a workaround? > On Windows, the workaround for pesky paths (i.e. containing blanks or just inconveniently long) is the subst command: command-prompt>subst X: "C:\Documents and Settings" Thereafter X:\foo can be used wherever "C:\Documents and Settings\foo" would otherwise be required. Is there not a similar trick on MacOS X? HTH, John From nagle at animats.com Wed May 2 13:48:12 2007 From: nagle at animats.com (John Nagle) Date: Wed, 02 May 2007 10:48:12 -0700 Subject: gpp (conditional compilation) In-Reply-To: <1178127460.046945.254100@y80g2000hsf.googlegroups.com> References: <1178127460.046945.254100@y80g2000hsf.googlegroups.com> Message-ID: maxwell at ldc.upenn.edu wrote: > I'm trying to use the gpp utility (Gnu points to http://en.nothingisreal.com/wiki/GPP) > to do conditional compilation in Python, and I'm running into a > problem: the same '#' character introduces Python comments and is used > by default to introduce #ifdef etc. lines. Just use an "if" statement. The Python interpreter is so slow it won't matter. John Nagle From rsa4046 at gmail.com Fri May 18 00:22:27 2007 From: rsa4046 at gmail.com (LokiDawg) Date: 17 May 2007 21:22:27 -0700 Subject: trouble with pyvtk Message-ID: <1179462146.957576.193110@o5g2000hsb.googlegroups.com> Am trying to stumble through the demos for mayavi, after having set up PyVTK-0.4.74 (together with numpy, scipy, vtk, and mayavi. I'm trying to use pyvtk to generate a vtk dataset with the following: >> from Numeric import * >>> import scipy >>> import scipy.special >>> x = (arange(50.0)-25)/2.0 >>> y = (arange(50.0)-25)/2.0 >>> r = sqrt(x[:,NewAxis]**2+y**2) >>> z = 5.0*scipy.special.j0(r) >>> import pyvtk >>> z1 = reshape(transpose(z), (-1,)) >>> point_data = pyvtk.PointData(pyvtk.Scalars(z1)) >>> grid = pyvtk.StructuredPoints((50,50, 1), (-12.5, -12.5, 0), (0.5, 0.5, 1)) >>> data = pyvtk.VtkData(grid, point_data) >>> data.tofile('/tmp/test.vtk') All is well until the last line (writing the file), after which the following error occurs: Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/site-packages/pyvtk/__init__.py", line 195, in tofile f.write(self.to_string(format)) File "/usr/lib/python2.4/site-packages/pyvtk/__init__.py", line 177, in to_string ret.append(self.point_data.to_string(format)) File "/usr/lib/python2.4/site-packages/pyvtk/Data.py", line 47, in to_string ret += [a.to_string(format) for a in self.data] File "/usr/lib/python2.4/site-packages/pyvtk/Scalars.py", line 40, in to_string t = self.get_datatype(self.scalars) File "/usr/lib/python2.4/site-packages/pyvtk/common.py", line 149, in get_datatype r = self.get_datatype(o) File "/usr/lib/python2.4/site-packages/pyvtk/common.py", line 149, in get_datatype r = self.get_datatype(o) File "/usr/lib/python2.4/site-packages/pyvtk/common.py", line 149, in get_datatype r = self.get_datatype(o) File "/usr/lib/python2.4/site-packages/pyvtk/common.py", line 149, in get_datatype File "/usr/lib/python2.4/site-packages/pyvtk/common.py", line 149, in get_datatype r = self.get_datatype(o) File "/usr/lib/python2.4/site-packages/pyvtk/common.py", line 140, in get_datatype if is_int(obj): return self.default_int RuntimeError: maximum recursion depth exceeded I'm assuming my pyvtk installation is at issue here (?), but I don't know enough about python to tell what has gone wrong, or how to fix it. Can someone point me in the right direction? From rene at korteklippe.de Tue May 15 09:18:48 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 15 May 2007 15:18:48 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476081.7080609@web.de> <46498514$0$6402$9b4e6d93@newsspool2.arcor-online.net> <4649882E.3060005@web.de> <46499940$0$10199$9b4e6d93@newsspool4.arcor-online.net> <46499BF9.30209@web.de> <4649a2c1$0$10193$9b4e6d93@newsspool4.arcor-online.net> <4649A429.3010406@web.de> <4649ae4a$0$20289$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <4649b336$0$10191$9b4e6d93@newsspool4.arcor-online.net> Thorsten Kampe schrieb: > GOTOs are not understable. Identifiers in foreign languages are > perfectly understable. Just not to you. > For coding problems better solutions (approaches) exist than using > GOTOs (procedural programming, modules). For identifier naming > problems it's not a better approach to stick to English or ASCII. It's > just a different approach. Just by stating your personal opinion that it is not a better but just different approach, you won't convince anyone. There are important arguments for why it actually *is* a better approach -- these have been brought up in this thread many times now. -- Ren? From bdesth.quelquechose at free.quelquepart.fr Tue May 8 17:17:17 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 08 May 2007 23:17:17 +0200 Subject: Towards faster Python implementations - theory In-Reply-To: <1210i.7468$2v1.2505@newssvr14.news.prodigy.net> References: <1210i.7468$2v1.2505@newssvr14.news.prodigy.net> Message-ID: <4640dedf$0$19020$426a34cc@news.free.fr> John Nagle a ?crit : > Some faster Python implementations are under development. > JPython has been around for a while, s/JP/J/ And FWIW, I'm not sure Jython is really faster than CPython... From deets at nospam.web.de Tue May 1 17:17:53 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 01 May 2007 23:17:53 +0200 Subject: Python for Windows other way to getting it? In-Reply-To: <1178051916.033367.205320@h2g2000hsg.googlegroups.com> References: <1178051916.033367.205320@h2g2000hsg.googlegroups.com> Message-ID: <59pp42F2jtk6gU2@mid.uni-berlin.de> noagbodjivictor at gmail.com schrieb: > Hello > I don't have permission to install new application on the PC I'm > using, I need a zipped version of python that I can copy on my > external drive. Where can I get a zip version? http://www.voidspace.org.uk/python/movpy/ Diez From showell30 at yahoo.com Sun May 27 14:08:38 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 27 May 2007 11:08:38 -0700 (PDT) Subject: ten small Python programs In-Reply-To: Message-ID: <301812.53367.qm@web33502.mail.mud.yahoo.com> --- Steven Bethard wrote: > I think I would rewrite the current unit-testing > example to use the > standard library unittest module:: > > # Let's write reusable code, and unit test it. > def add_money(amounts): > # do arithmetic in pennies so as not to > accumulate float errors > pennies = sum([round(int(amount * 100)) for > amount in amounts]) > return float(pennies / 100.0) > import unittest > class TestAddMoney(unittest.TestCase): > def test_float_errors(self): > self.failUnlessEqual(add_money([0.13, > 0.02]), 0.15) > self.failUnlessEqual(add_money([100.01, > 99.99]), 200) > self.failUnlessEqual(add_money([0, > -13.00, 13.00]), 0) > if __name__ == '__main__': > unittest.main() > > I believe I've still kept it to 13 lines. > I approve this change, although in a sense, it's harder for a Python newbie, because it introduces inheritance a little earlier than I would have liked. FWIW I'm in the minority (I think) of people that prefer roll-your-own testing, but I don't want to argue that, because I think it mostly comes down to personal preference. I'll only defend my position by posting this link, which suggests that roll-your-own even has validity in an educational setting: http://www.elkner.net/jeff/testFirst/index.html > P.S. The "right" way to add money is using the > decimal module, but I > couldn't think of a better example. Agreed. Maybe somebody else will come up with something more creative, but I'm happy enough with our current version. ____________________________________________________________________________________Take the Internet to Go: Yahoo!Go puts the Internet in your pocket: mail, news, photos & more. http://mobile.yahoo.com/go?refer=1GNXIC From ashokagk at gmail.com Tue May 1 10:22:28 2007 From: ashokagk at gmail.com (Ashok) Date: 1 May 2007 07:22:28 -0700 Subject: scaling Message-ID: <1178029348.453693.33510@u30g2000hsc.googlegroups.com> hi, IDL language contains a function called BYTSCL to scale all values of Array that lie in the range (Min ? x ? Max) into the range (0 ? x ? Top). Is there a similar function available in python? I need this to scale the pixel values of an image using PIL. thanks in advance for any help ____ AGK From beliavsky at aol.com Thu May 17 09:34:58 2007 From: beliavsky at aol.com (Beliavsky) Date: 17 May 2007 06:34:58 -0700 Subject: Python-URL! - weekly Python news and links (May 16) In-Reply-To: References: Message-ID: <1179408898.460231.292340@k79g2000hse.googlegroups.com> On May 16, 2:45 pm, "Cameron Laird" wrote: > QOTW: "Sometimes you just have to take the path of least distaste". - Grant > Edwards > > "I want to choose my words carefully here, so I'm not misunderstood. I think Cameron Laird does a good job with the Python digest but blundered here. Why did he highlight a foul comment having nothing to do with Python? From vasudevram at gmail.com Mon May 21 13:03:32 2007 From: vasudevram at gmail.com (vasudevram) Date: 21 May 2007 10:03:32 -0700 Subject: Help required with Python App In-Reply-To: References: Message-ID: <1179767012.076587.64210@z24g2000prd.googlegroups.com> On May 21, 8:11 pm, Trevor Hennion wrote: > Hi, > > I am producing a Web based database application for a customer and could > do with some help producing pdf documents from the data. > > The project uses Apache. Postgresql and Python CGI scripts on a Linux > server for a company with 20-25 users. > > I have been looking at thehttp://www.reportlab.org- ReportLab Toolkit, > but am rather busy with the other parts of the project, so if any one > located in the UK - Reading/Basingstoke area has the right > skills and time available now, please contact me. > > I have a small budget available for this work. > > Regards > > Trevor > > PS UK/Reading/Basingstoke area is essential. I don't have the time right now, though I'd be free for some work after a week or two; but I'm not in your area. ReportLab is quite good and has many features. I used it to build my xtopdf toolkit, a toolkit for conversion of other file formats to PDF. You could try using it (ReportLab) directly from the Python scripts in your app. If your needs are only for text to PDF conversion (of the textual data - numbers, strings and dates from the database), then you might want to take a look at xtopdf - see http://www.dancingbison.com/products.html. It may be a bit easier to use than ReportLab itself (it has a small and simple to use API), but only for text to PDF conversion - it doesn't support images as of now. It's released under the same license as ReportLab, the BSD license. xtopdf has sample programs that show you how to use it. It supports setting the font (anywhere in the output, but only one font at a time, headers and footers for each page, and automatic pagination). You can also read this article about it: http://www.packtpub.com/article/Using_xtopdf The article above shows how to use xtopdf to create PDF from various input formats - CSV, text, TDV, XLS, etc. All done very simply with just a few lines of code. You could try using either Reportlab or xtopdf or getting someone to help with using one of them. HTH Vasudev Ram Dancing Bison Enterprises http://www.dancingbison.com From sjmachin at lexicon.net Wed May 2 17:25:29 2007 From: sjmachin at lexicon.net (John Machin) Date: 2 May 2007 14:25:29 -0700 Subject: How to check if a string is empty in python? In-Reply-To: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> References: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> Message-ID: <1178141129.306313.122670@p77g2000hsh.googlegroups.com> On May 3, 6:35 am, noagbodjivic... at gmail.com wrote: > How to check if a string is empty in python? > if(s == "") ?? Please lose the parentheses. if s == "": will work. So will if not s: Have you worked through the tutorial yet? From whamil1 at entergy.com Mon May 21 09:21:15 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Mon, 21 May 2007 08:21:15 -0500 Subject: Random selection Message-ID: <588D53831C701746A2DF46E365C018CE01D2CAA3@LITEXETSP001.etrsouth.corp.entergy.com> > From: Tartifola > Hi, > I have a list with probabilities as elements > > [p1,p2,p3] > > with of course p1+p2+p3=1. I'd like to draw a > random element from this list, based on the probabilities contained in > the list itself, and return its index. > > Any help on the best way to do that? > Thanks >>> ran = random.random() >>> ran 0.70415952329234965 >>> for index, value in enumerate(x): if sum(x[0:index]) > ran: print index, ran break 2 0.704159523292 -- -Bill Hamilton From john at datavoiceint.com Tue May 8 12:47:53 2007 From: john at datavoiceint.com (HMS Surprise) Date: 8 May 2007 09:47:53 -0700 Subject: Atttribute error In-Reply-To: References: <1178641784.974581.14000@p77g2000hsh.googlegroups.com> Message-ID: <1178642873.292218.52090@h2g2000hsg.googlegroups.com> On May 8, 11:37 am, Marc 'BlackJack' Rintsch wrote: > In <1178641784.974581.14... at p77g2000hsh.googlegroups.com>, HMS Surprise > wrote: > > > The snippet below causes an attribute error. > > > AttributeError: module 'urllib' has no attribute 'urlopen' > > > I am using python 2.2.3. According to the documentation at C: > > \Python22\Doc\lib urllib has a function called urlopen. > > Do you have a file called `urllib.py` in the current directory? Then this > gets imported instead of the module in the standard library. > > Add this directly after the ``import`` to see what's happening: > > print urllib.__file__ > print dir(urllib) > > Ciao, > Marc 'BlackJack' Rintsch Thanks for posting Marc. I do have a file named `urllib.py` in the current directory. I copied it from 'C:\Python22\Lib' as I could not get rid of the 'no module named urllib' error message, even though I appended 'C:\Python22\Lib to sys.path'. This changed the error from module not found to a no attribute msg. The maxq program (IDE?, runtime enviroment? , shell?) apparently uses jython so maybe sys.path is not the problem. This is the reason for my thread 'sys.path'. Thanks again, jh From dsampson at NRCan.gc.ca Fri May 11 08:38:08 2007 From: dsampson at NRCan.gc.ca (Sampson, David) Date: Fri, 11 May 2007 08:38:08 -0400 Subject: Python and Decimal integers from DB In-Reply-To: <2FAA57395C1F914DB27CAA4C376058F2025F7B74@S0-OTT-X2.nrn.nrcan.gc.ca> References: <2FAA57395C1F914DB27CAA4C376058F2025F7B74@S0-OTT-X2.nrn.nrcan.gc.ca> Message-ID: <2FAA57395C1F914DB27CAA4C376058F2025F7D00@S0-OTT-X2.nrn.nrcan.gc.ca> Here is the solution, for the record. ==================== import pyodbc conn = pyodbc.connect("DSN=NAPL;UID=NAPL_VIEW;PWD=NAPVIEW") curs = conn.cursor() roll_num = 'A27255' Cols = 'TO_CHAR(X_NO) as X_NO' Table = 'photos' Select = 'Select ' + Cols + ' from ' + Table + ' where roll_number = ' +"'" + roll_num + "'" curs.execute(Select) print "select sucess" rows= curs.fetchall() print "fetch success" for row in rows: print row.X_NO print "done" ==================== X_NO was entered in the DB as a number using the comma as a non-standard separator. Python did not like it in the decimal.py module so we brought it in as a character string using varchar2. Python liked this solution and returned my results. Now I can give the chars to a var and change it to numbers for some vector math Hope this helps people in the future ________________________________ From: python-list-bounces+dsampson=nrcan.gc.ca at python.org [mailto:python-list-bounces+dsampson=nrcan.gc.ca at python.org] On Behalf Of Sampson, David Sent: May 10, 2007 12:58 To: python-list at python.org Subject: Python and Decimal integers from DB Hey folks Freshie looking for help.... This is what I am trying to do. Use PYODBC to hit an oracle DB that has a ODBC connection.\ \The code bellow works when I replace '*' with a specific collumn name that does not have commas in the number. It also works for alphanumberic values. It fails when I try '*' or any collumn that has a comman in the number. The numbers are Latitude longitude readings. I get back "Select Success" but not "fetch success" so I feel as thopugh something is missing on the fetchall() function So how do I get the numbers to be recognized by python? I did lots of searches on python, ODBC, PYODBC, Decimal us and commas as decimals and various combinations. Lots of mailing lists a few tutorials and lots of misses. I came across: Import decimal Decimal.Decimal() This works a bit. It took a coma separated number string and kept the first part. But that works only when I put in a raw value, it doesn't work on the Fetchall function. HELP PLEASE... Cheers ===============PYHTON CODE======================== import pyodbc conn = pyodbc.connect("DSN=NAPL;UID=NAPL_VIEW;PWD=NAPVIEW") curs = conn.cursor() roll_num = 'A27255' Cols = '*' Table = 'photos' Select = 'Select ' + Cols + ' from ' + Table + ' where roll_number = ' +"'" + roll_num + "'" curs.execute(Select) print "select sucess" rows= curs.fetchall() print "fetch success" for row in rows: print row.PHOTO_NUMBER print "done" ==================================== =================Standard Output ======================== Traceback (most recent call last): File "C:\Python25\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py" , line 310, in RunScript exec codeObject in __main__.__dict__ File "U:\My Documents\py_projects\georef\NAPL_DB.py", line 12, in rows= curs.fetchall() File "C:\Python25\lib\decimal.py", line 614, in __new__ self._sign, self._int, self._exp = context._raise_error(ConversionSyntax) File "C:\Python25\lib\decimal.py", line 2325, in _raise_error raise error, explanation InvalidOperation ==================================== -------------- next part -------------- An HTML attachment was scrubbed... URL: From torriem at chem.byu.edu Tue May 22 13:03:43 2007 From: torriem at chem.byu.edu (Michael L Torrie) Date: Tue, 22 May 2007 11:03:43 -0600 Subject: Restart Linux System In-Reply-To: <6a612e880705220934u7fa3c578n71a82c22b9e57089@mail.gmail.com> References: <1179850502.22230.6.camel@contra.chem.byu.edu> <6a612e880705220934u7fa3c578n71a82c22b9e57089@mail.gmail.com> Message-ID: <1179853423.22230.17.camel@contra.chem.byu.edu> On Tue, 2007-05-22 at 09:34 -0700, Alexandre Gans wrote: > > You can use sudo on your user or the bit suid in your application... Just know that you cannot setuid any shebang executable, of which python scripts usually are. From paul at boddie.org.uk Wed May 23 06:12:22 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 23 May 2007 03:12:22 -0700 Subject: Shared Memory Space - Accross Apps & Network In-Reply-To: <1179913683.260600.283420@q69g2000hsb.googlegroups.com> Message-ID: <1179915142.393414.284830@o5g2000hsb.googlegroups.com> On 23 May, 11:48, "D.Hering" wrote: > > Possibly, IPython's new interactive parallel environment is what you > are looking for:http://ipython.scipy.org/moin/Parallel_Computing See this and related projects on the python.org Wiki: http://wiki.python.org/moin/ParallelProcessing Paul From bronger at physik.rwth-aachen.de Fri May 18 14:09:19 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Fri, 18 May 2007 20:09:19 +0200 Subject: Regexes: How to handle escaped characters References: <87tzubqniq.fsf@wilson.homeunix.com> <87irarqkz7.fsf@wilson.homeunix.com> <1179435962.962404.191600@y80g2000hsf.googlegroups.com> <877ir6r3dh.fsf@wilson.homeunix.com> <464d96c4$0$52290$c30e37c6@lon-reader.news.telstra.net> Message-ID: <87646qovg0.fsf@wilson.homeunix.com> Hall?chen! Charles Sanders writes: > Torsten Bronger wrote: > > [...] > >>>> Example string: u"Hollo", escaped positions: [4]. Thus, the >>>> second "o" is escaped and must not be found be the regexp >>>> searches. >>>> >>>> Instead of re.search, I call the function guarded_search(pattern, >>>> text, offset) which takes care of escaped caracters. Thus, while > > I'm still pretty much a beginner, and I am not sure > of the exact requirements, but the following seems to work > for at least simple cases when overlapping matches are not > considered. > > def guarded_search( pattern, text, exclude ): > return [ m for m in re.finditer(pattern,text) > if not [ e for e in exclude if m.start() <= e < m.end() ] ] Yes, this seems to do the trick, thank you! Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From gautier.krings at gmail.com Thu May 24 09:55:42 2007 From: gautier.krings at gmail.com (Gautier Krings) Date: Thu, 24 May 2007 15:55:42 +0200 Subject: problems to write a wav file Message-ID: Hello, I have a small problem for writing a .wav file. I can't find in which format I have to pass my data in the writeframes function of the wave module. here's my code, I am just trying to open a wav file, extracting the data from it, and writing it in another wav file. The problem is that the sound I get in the second wav file isn't the same as from the firs file (in fact it is horrible). import wave, audioop, numpy from numpy.fft import * from math import * signal = wave.open('C:\demo.wav', 'rb' ) Nframes = float(signal.getnframes()) width = signal.getsampwidth() frameRate = signal.getframerate() frame = signal.readframes(1) power =[] while len(frame): power.append(audioop.rms( frame, width )) frame = signal.readframes(1) new_signal = wave.open('C:\demo2.wav', 'wb') new_signal.setsampwidth(width) new_signal.setframerate(frameRate) new_signal.setnchannels(signal.getnchannels()) for j in range(len(power)): data = hex(power[j]) ---> I guess that my problem is located at this line new_signal.writeframes(data) new_signal.close() thanks a lot, -- Gautier Krings gautier.krings at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From nadeemabdulhamid at gmail.com Mon May 21 10:30:09 2007 From: nadeemabdulhamid at gmail.com (nadeemabdulhamid at gmail.com) Date: 21 May 2007 07:30:09 -0700 Subject: Executing Python interpreter from Java Message-ID: <1179757809.058053.50880@u36g2000prd.googlegroups.com> Hello, I'm trying to write some Java code that will launch a python interpreter shell and pipe input/output back and forth from the interpreter's i/o streams and the Java program. The code posted below seems to work just fine under Mac OS X; however, under Windows XP (Java 1.6 and Python 2.5 installed) the program hangs when I give a command to import the Tkinter (Python GUI library) and create a top- level frame window. Specifically, run the program as: % java PythonShell .... (loads Python and displays welcome message) >>> from Tkinter import * >>> t = Tk() >>> After this point a frame window pops up but anything you type further doesn't evoke any further response from the shell. There is a little hiccup that occurs when the Tkinter library is actually loaded (on both the Mac or Windows OS) and the window in which the java program is running loses the focus-- I guess that has something to do with the way the Tk windowing library is loading. I know on the Java documentation for Process it says that it may not work correctly with native windowing libraries on some OSs. If this is what is happening here, does anyone have any suggestions? (Btw, I know about Jython and I do not want to use that for a whole lot of reasons.) Thanks a whole lot! nadeem import java.io.*; import java.util.*; public class PythonShell { // these are out here so the inner class can access them... static BufferedReader in = null; static boolean ok = true; public static void main(String[] args) throws InterruptedException { ProcessBuilder pb = new ProcessBuilder("python", "-i"); // force interactive pb.redirectErrorStream(true); // combine stdout and stderr Process p = null; PrintStream out = null; boolean started = false; try { p = pb.start(); started = true; in = new BufferedReader(new InputStreamReader(p.getInputStream())); out = new PrintStream(p.getOutputStream(), true); } catch (IOException exc) { exc.printStackTrace(); if (started) p.destroy(); return; } final Scanner userIn = new Scanner(System.in); final Thread mainthread = Thread.currentThread(); class ReaderThread implements Runnable { public void run() { try { while (true) { int c = in.read(); if (c == -1) { ok = false; break; } System.out.print((char)c); } } catch (IOException exc) { ok = false; } // try to interrupt the other thread userIn.close(); try { System.in.close(); } catch (IOException exc) {} mainthread.interrupt(); } } Thread rt = new Thread(new ReaderThread()); rt.start(); while (ok) { try { String input = userIn.nextLine(); out.println(input); System.out.println(ok); } catch (NoSuchElementException exc) { ok = false; } } p.destroy(); p.waitFor(); } } /* Input: from Tkinter import * t = Tk() print 'hi' */ From grante at visi.com Tue May 1 23:22:49 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 02 May 2007 03:22:49 -0000 Subject: Read and Write the same file References: <1178060601.700099.263240@y5g2000hsa.googlegroups.com> Message-ID: <133g1096gvhfa3f@corp.supernews.com> On 2007-05-01, Gabriel Genellina wrote: > En Tue, 01 May 2007 20:03:28 -0300, JonathanB > escribi?: > >> Ok, so this is the scenario. I need to create a simple, no-frills XML >> editor for non-technical users. It doesn't have to do anything fancy, >> what I want is a series of text boxes with the text contents of the >> elements pre-printed. Then the users can type their changes into the >> text boxes and click submit and it will load the changes in. So here >> is the problem, this means I need to open the same file as both read >> and write. How do I do this? I'm slowly learning the DOM stuff that I >> need to know to do this, but this file thing I haven't been able to >> find anywhere. > > Open the file for reading; read and parse the document; close the file. > Build form and show to the user. > Get data after user clicks OK. > Build document, open file for writing, write document, close file. > > Reading and writing happen on two separate stages, and you dont have to > keep the file open all the time. A safer way to do this is to write the new version to a temporary file, close the temporary file, then rename it. There's much less chance of losing data that way -- no matter when the program or computer crashes, you've got a complete copy one version or the other. -- Grant Edwards grante Yow! I am having FUN... I at wonder if it's NET FUN or visi.com GROSS FUN? From C.delete_this.Sanders at BoM.GOv.AU Thu May 24 20:50:34 2007 From: C.delete_this.Sanders at BoM.GOv.AU (Charles Sanders) Date: Fri, 25 May 2007 10:50:34 +1000 Subject: installing cx_Oracle. In-Reply-To: References: Message-ID: <465632db$0$21545$c30e37c6@lon-reader.news.telstra.net> Doug Phillips wrote: >> It also works the other way around, at least on the non-empty >> set of systems that contains my workstation. export simply >> marks the variable name for automatic export to the >> environment of subsequent commands. The value at that time >> doesn't matter. What matters is the value that the name has >> at the time the command is run: [snip] > Just tried on a FreeBSD 6.1 development box with stock /bin/sh and it > works there too... As far as I know, it has been like this since the introduction of the Bourne shell in (according to a web search) 1979. Charles From paul at science.uva.nl Wed May 16 07:17:23 2007 From: paul at science.uva.nl (Paul Melis) Date: Wed, 16 May 2007 13:17:23 +0200 Subject: Splitting a quoted string. In-Reply-To: <1179312169.045429.80960@e65g2000hsc.googlegroups.com> References: <1179312169.045429.80960@e65g2000hsc.googlegroups.com> Message-ID: Hi, mosscliffe wrote: > I am looking for a simple split function to create a list of entries > from a string which contains quoted elements. Like in 'google' > search. > > eg string = 'bob john "johnny cash" 234 june' > > and I want to have a list of ['bob', 'john, 'johnny cash', '234', > 'june'] > > I wondered about using the csv routines, but I thought I would ask the > experts first. > > There maybe a simple function, but as yet I have not found it. Here a not-so-simple-function using regular expressions. It repeatedly matched two regexps, one that matches any sequence of characters except a space and one that matches a double-quoted string. If there are two matches the one occurring first in the string is taken and the matching part of the string cut off. This is repeated until the whole string is matched. If there are two matches at the same point in the string the longer of the two matches is taken. (This can't be done with a single regexp using the A|B operator, as it uses lazy evaluation. If A matches then it is returned even if B would match a longer string). import re def split_string(s): pat1 = re.compile('[^ ]+') pat2 = re.compile('"[^"]*"') parts = [] m1 = pat1.search(s) m2 = pat2.search(s) while m1 or m2: if m1 and m2: # Both match, take match occurring earliest in the string p1 = m1.group(0) p2 = m2.group(0) if m1.start(0) < m2.start(0): part = p1 s = s[m1.end(0):] elif m2.start(0) < m1.start(0): part = p2 s = s[m2.end(0):] else: # Both match at the same string position, take longest match if len(p1) > len(p2): part = p1 s = s[m1.end(0):] else: part = p2 s = s[m2.end(0):] elif m1: part = m1.group(0) s = s[m1.end(0):] else: part = m2.group(0) s = s[m2.end(0):] parts.append(part) m1 = pat1.search(s) m2 = pat2.search(s) return parts >>> s = 'bob john "johnny cash" 234 june' >>> split_string(s) ['bob', 'john', '"johnny cash"', '234', 'june'] >>> Paul From aldo at nullcube.com Mon May 14 01:19:36 2007 From: aldo at nullcube.com (Aldo Cortesi) Date: Mon, 14 May 2007 15:19:36 +1000 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <20070514051936.GA29135@nullcube.com> Thus spake Steven D'Aprano (steven at REMOVE.THIS.cybersource.com.au): > If you're relying on cursory visual inspection to recognize harmful code, > you're already vulnerable to trojans. What a daft thing to say. How do YOU recognize harmful code in a patch submission? Perhaps you blindly apply patches, and then run your test suite on a quarantined system, with an instrumented operating system to allow you to trace process execution, and then perform a few weeks worth of analysis on the data? Me, I try to understand a patch by reading it. Call me old-fashioned. > Code exchange regardless of human language is a nice principle, but it > doesn't work in practice. And this is clearly bunk. I have come accross code with transliterated identifiers and comments in a different language, and while understanding was hampered it wasn't impossible. > That's no different from typos in ASCII. There's no doubt that we'll give > the same answer we've always given for this problem: unit tests, pylint > and pychecker. A typo that can't be detected visually is fundamentally different problem from an ASCII typo, as many people in this thread have pointed out. Regards, Aldo -- Aldo Cortesi aldo at nullcube.com http://www.nullcube.com Mob: 0419 492 863 From steve at REMOVEME.cybersource.com.au Tue May 1 00:17:30 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Tue, 01 May 2007 14:17:30 +1000 Subject: re-importing modules References: <8%pZh.18192$Kd3.76@newssvr27.news.prodigy.net> <1177962288.575008.48490@q75g2000hsh.googlegroups.com> <1177967919.968338.3300@l77g2000hsb.googlegroups.com> Message-ID: On Tue, 01 May 2007 00:32:20 +0000, John Nagle wrote: > kyosohma at gmail.com wrote: > >>>In addition to the warning that reload() does not recursively reload >>>modules that the reloaded module depends on, be warned that reloading a >>>module does not magically affect any functions or objects from the old >>>version that you may be holding on to. > > Maybe reloading modules should be deprecated. The semantics > are awful, and it interferes with higher-performance implementations. I'd hate for reload to disappear, it is great for interactive development/debugging, at least under some circumstances. (If you have complex and tangled class hierarchies, it might not be powerful enough.) As for the semantics being awful, I disagree. reload() does exactly what it claims to do, no more, no less. I wouldn't expect reload(module1) to reload modules 2 through 5 just because they were imported by module1. If I wanted them reloaded, I'd say so. I'll admit to being puzzled for about five minutes the first time I found my objects' behaviour wasn't being updated when I did a reload, but it didn't take me long to slap myself in the head. Of course not -- if the old objects are still around, they'll keep their old behaviour. That's kind of an inconvenience, but unavoidable. I certainly DON'T want Python to magically change objects (apart from module objects themselves) on a reload. Maybe reload() should be pulled out of the core Python language and turned into an optional function. If (if!) Jython doesn't do interactive development, then it doesn't need reload(); CPython, which does, does. -- Steven D'Aprano From gherron at islandtraining.com Wed May 30 12:24:59 2007 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 30 May 2007 09:24:59 -0700 Subject: How can an Exception pass over an "except" clause ? In-Reply-To: <1180540010.548057.220270@m36g2000hse.googlegroups.com> References: <1180540010.548057.220270@m36g2000hse.googlegroups.com> Message-ID: <465DA55B.6070809@islandtraining.com> Nebur wrote: > I'm using the contract.py library, running Python 2.4.4. > > Now I'm confronted with the following exception backtrace: > (...) > File "/usr/lib/python2.4/site-packages/contract.py", line 1265, in > _check_preconditions > p = f.__assert_pre > AttributeError: 'function' object has no attribute '__assert_pre' > > For my surprise, I found that the code of contract.py around line 1265 > looks like: > > 1264: try: > 1265: p = f.__assert_pre > 1266: except AttributeError: > 1267: pass > > I'd expect line 1267 to "swallow" the AttributeError siliently. But > the application stops with the above backtrace. > Someone familiar enough with the Python innards ? How can one manage > that an "except" seems to be ignored ? > > Ruben > > Under any normal circumstances, that code can't produce that error. The attribute error will be swallowed by the except clause. However by being *VERY* perverse, I was able to reproduce the above error by overwriting AttributeError with some other exception class (say SyntaxError): AttributeError = SyntaxError Then your code will be will produce a real AttributeError, but miss it because (despite the spelling) it checks for a SyntaxError, Question... I don't know what contract.py is, but could it be doing something that *bad*? You could check py printing AttributeError and see what it really is. In my case it's: >>> print AttributeError exceptions.SyntaxError Gary Herron P.S.: Anyone who does this kind of thing is a danger to society. May their finger fall off before they get a chance to distribute such a program. From mobiledreamers at gmail.com Tue May 1 17:30:12 2007 From: mobiledreamers at gmail.com (mobil) Date: 1 May 2007 14:30:12 -0700 Subject: Removing the continous newline characters from the pythong string Message-ID: <1178055012.135278.104430@p77g2000hsh.googlegroups.com> Hi guys i m trying out newline characters and to clean them up a\n\n\n\n\n\n\n\n\nsss\n\n\n\n\n\n\n\n\n\n\nvvvv\n\n\n\nvsa\n\n\n\nasf \n\nafs hello guys im trying to replace \n\n\n\n\n\n\n\n\n with \n thanks for help \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n also with \n as the browser gives \r carrriage returns thanks for any help or pointers From rurpy at yahoo.com Sun May 20 19:34:13 2007 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 20 May 2007 16:34:13 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179443024.632355.110680@e65g2000hsc.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179289167.723990.223890@u30g2000hsc.googlegroups.com> <464abd12$0$23364$426a34cc@news.free.fr> <1179307776.953405.207680@l77g2000hsb.googlegroups.com> <464ad388$0$28786$426a34cc@news.free.fr> <1179337277.347833.237450@n59g2000hsh.googlegroups.com> <1179355081.828574.241690@h2g2000hsg.googlegroups.com> <1179443024.632355.110680@e65g2000hsc.googlegroups.com> Message-ID: <1179704053.319096.174320@y2g2000prf.googlegroups.com> On May 17, 5:03 pm, "sjdevn... at yahoo.com" wrote: > On May 16, 6:38 pm, r... at yahoo.com wrote: > > Are you worried that some 3rd-party package you have > > included in your software will have some non-ascii identifiers > > buried in it somewhere? Surely that is easy to check for? > > Far easier that checking that it doesn't have some trojan > > code it it, it seems to me. > > What do you mean, "check for"? If, say, numeric starts using math > characters (as has been suggested), I'm not exactly going to stop > using numeric. It'll still be a lot better than nothing, just > slightly less better than it used to be. The PEP explicitly states that no non-ascii identifiers will be permitted in the standard library. The opinions expressed here seems almost unamimous that non-ascii identifiers are a bad idea in any sort of shared public code. Why do you think the occurance of non-ascii identifiers in Numpy is likely? > > > And I'm often not creating a stack trace procedure, I'm using the > > > built-in python procedure. > > > > > And I'm often dealing with mailing lists, Usenet, etc where I don't > > > know ahead of time what the other end's display capabilities are, how > > > to fix them if they don't display what I'm trying to send, whether > > > intervening systems will mangle things, etc. > > > > I think we all are in this position. I always send plain > > text mail to mailing lists, people I don't know etc. But > > that doesn't mean that email software should be contrainted > > to only 7-bit plain text, no attachements! I frequently use > > such capabilities when they are appropriate. > > Sure. But when you're talking about maintaining code, there's a very > high value to having all the existing tools work with it whether > they're wide-character aware or not. I agree. On Windows I often use Notepad to edit python files. (There goes my credibility! :-) So I don't like tab-only indent proposals that assume I can set tabs to be an arbitrary number of spaces. But tab-only indentation would affect every python program and every python programmer. In the case of non-ascii identifiers, the potential gains are so big for non-english spreakers, and (IMO) the difficulty of working with non-ascii identifiers times the probibility of having to work with them, so low, that the former clearly outweighs the latter. > > If your response is, "yes, but look at the problems html > > email, virus infected, attachements etc cause", the situation > > is not the same. You have little control over what kind of > > email people send you but you do have control over what > > code, libraries, patches, you choose to use in your > > software. > > > > If you want to use ascii-only, do it! Nobody is making > > you deal with non-ascii code if you don't want to. > > Yes. But it's not like this makes things so horribly awful that it's > worth my time to reimplement large external libraries. I remain at -0 > on the proposal; > it'll cause some headaches for the majority of > current Python programmers, but it may have some benefits to a > sizeable minority This is the crux of the matter I think. That non-ascii identifiers will spead like a virus, infecting program after program until every piece of Python code is nothing but a mass of wreathing unintellagible non- ascii characters. (OK, maybe I am overstating a little. :-) I (and I think other proponents) don't think this is likely to happen, and the the benefits to non-english speakers of being able to write maintainable code far outweigh the very rare case when it does occur. > and may help bring in new coders. And it's not > going to cause flaming catastrophic death or anything. From rschroev_nospam_ml at fastmail.fm Thu May 3 12:04:22 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 03 May 2007 16:04:22 GMT Subject: ignorance and intolerance in computing communties In-Reply-To: <1178203772.243333.24990@p77g2000hsh.googlegroups.com> References: <1178120019.271716.299590@e65g2000hsc.googlegroups.com> <1178203772.243333.24990@p77g2000hsh.googlegroups.com> Message-ID: Xah Lee schreef: > Xah Lee wrote: > ? > ... > ?Ignorance And Intolerance In Online Computing Communities? > http://xahlee.org/Netiquette_dir/ignorance_intolerance.html > > ... As i have indicated in my post, it is non-trivial to implement a > function that returns the positive angle of a vector.... > ? > > I have now coded this. I think it is probably the most algorithmically > optimal, and rather much simpler than i originally thought. Here's the > Mathematica code: > > vectorAngle[{a1_, a2_}] := Module[{x, y}, > {x, y} = {a1, a2}/Sqrt[a1^2 + a2^2] // N; > If[x == 0 && y == 0, "fucked", > If[x == 0, If[Sign at y === 1, ?/2, -?/2], > If[y == 0, If[Sign at x === 1, 0, ?], > If[Sign at y === 1, ArcCos at x, 2 ? - ArcCos at x] > ] > ] > ] > ] I might be wrong of course, but can't you just use atan2? Only problem is that it returns negative angles for quadrants 3 and 4, but that is easily solved. In Python: from math import atan2, pi, fmod def vectorAngle(x, y): return fmod(atan2(y, x) + 2*pi, 2*pi) No conditionals in sight. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From antroy at gmail.com Tue May 15 03:37:37 2007 From: antroy at gmail.com (Ant) Date: 15 May 2007 00:37:37 -0700 Subject: removing spaces between 2 names In-Reply-To: <1179211287.521561.309130@e65g2000hsc.googlegroups.com> References: <1179208842.114189.233060@e65g2000hsc.googlegroups.com> <1179211287.521561.309130@e65g2000hsc.googlegroups.com> Message-ID: <1179214657.234364.38830@h2g2000hsg.googlegroups.com> On May 15, 7:41 am, 7stud wrote: > On May 15, 12:14 am, Steven Howe wrote: ... > > from string import replace > > st = 'abcd acdfg xtit' > > st.replace(' ','') > > 'abcdacdfgxtit' ... > The methods in the string module are deprecated. Skip the import and > use a string's built in replace() method instead: This is true, but actually Steven *is* using the string's built in replace method - the import isn't used in the code! Obviously the import was a deliberate mistake designed to see if you were awake... ;-) -- Ant... http://antroy.blogspot.com/ From jstroud at mbi.ucla.edu Fri May 18 20:04:06 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 18 May 2007 17:04:06 -0700 Subject: converting strings to most their efficient types '1' --> 1, 'A' ---> 'A', '1.2'---> 1.2 In-Reply-To: <1179529661.555196.13070@k79g2000hse.googlegroups.com> References: <1179529661.555196.13070@k79g2000hse.googlegroups.com> Message-ID: py_genetic wrote: > Hello, > > I'm importing large text files of data using csv. I would like to add > some more auto sensing abilities. I'm considing sampling the data > file and doing some fuzzy logic scoring on the attributes (colls in a > data base/ csv file, eg. height weight income etc.) to determine the > most efficient 'type' to convert the attribute coll into for further > processing and efficient storage... > > Example row from sampled file data: [ ['8','2.33', 'A', 'BB', 'hello > there' '100,000,000,000'], [next row...] ....] > > Aside from a missing attribute designator, we can assume that the same > type of data continues through a coll. For example, a string, int8, > int16, float etc. > > 1. What is the most efficient way in python to test weather a string > can be converted into a given numeric type, or left alone if its > really a string like 'A' or 'hello'? Speed is key? Any thoughts? > > 2. Is there anything out there already which deals with this issue? > > Thanks, > Conor > This is untested, but here is an outline to do what you want. First convert rows to columns: columns = zip(*rows) Okay, that was a lot of typing. Now, you should run down the columns, testing with the most restrictive type and working to less restrictive types. You will also need to keep in mind the potential for commas in your numbers--so you will need to write your own converters, determining for yourself what literals map to what values. Only you can decide what you really want here. Here is a minimal idea of how I would do it: def make_int(astr): if not astr: return 0 else: return int(astr.replace(',', '')) def make_float(astr): if not astr: return 0.0 else: return float(astr.replace(',', '')) make_str = lambda s: s Now you can put the converters in a list, remembering to order them. converters = [make_int, make_float, make_str] Now, go down the columns checking, moving to the next, less restrictive, converter when a particular converter fails. We assume that the make_str identity operator will never fail. We could leave it out and have a flag, etc., for efficiency, but that is left as an exercise. new_columns = [] for column in columns: for converter in converters: try: new_column = [converter(v) for v in column] break except: continue new_columns.append(new_column) For no reason at all, convert back to rows: new_rows = zip(*new_columns) You must decide for yourself how to deal with ambiguities. For example, will '1.0' be a float or an int? The above assumes you want all values in a column to have the same type. Reordering the loops can give mixed types in columns, but would not fulfill your stated requirements. Some things are not as efficient as they might be (for example, eliminating the clumsy make_str). But adding tests to improve efficiency would cloud the logic. James From duncan.booth at invalid.invalid Thu May 3 04:40:30 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 3 May 2007 08:40:30 GMT Subject: Microsoft's Dynamic Languages Runtime (DLR) References: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> <59s6kbF2kq8uoU1@mid.individual.net> <1178145895.865828.18220@p77g2000hsh.googlegroups.com> <59tcidF2lob6mU1@mid.individual.net> Message-ID: Pascal Costanza wrote: > That still doesn't explain what DLR actually does. You can implement > these languages on top of the JVM as well. You could implement them on > any Turing-complete language, for that matter. The interesting question > how well integrated such an implementation is. > > However, Jim Hugunin seems to be willing to give more details on his > blog - the recent entry gives hints that there is indeed something > interesting going on. I'm still waiting for the meat, though... Watch the video he linked from his blog. In short, the implementation looks really well integrated. They start with an example (in Ruby) which creates a C# control and handles the event it generates to call some VB which retrieves a list of strings from the server and then passes it to a 3d animation written in JScript. All seamless, and all running in the local browser (which in the demo is Safari). The significant part of the DLR is (I think) that you can have a single object e.g. a string, but the methods available on that object vary according to the source file from which you are accessing the object. That means in pure Python code the string has python methods, but in Python using the CLR it gains the CLR methods. Presumably in Ruby code it looks like a Ruby string and so on, but (and this is what's new) it is the same object, not a bunch of language specific wrappers around the string type. From clodoaldo.pinto at gmail.com Thu May 24 05:51:57 2007 From: clodoaldo.pinto at gmail.com (Clodoaldo) Date: 24 May 2007 02:51:57 -0700 Subject: Locale case change not working In-Reply-To: References: <1179998221.372699.17600@p77g2000hsh.googlegroups.com> Message-ID: <1180000317.921068.11970@k79g2000hse.googlegroups.com> On May 24, 6:40 am, Peter Otten <__pete... at web.de> wrote: > Clodoaldo wrote: > > When using unicode the case change works: > > >>>> print u'?'.lower() > > ? > > > But when using the pt_BR.utf-8 locale it doesn't: > > >>>> locale.setlocale(locale.LC_ALL, 'pt_BR.utf-8') > > 'pt_BR.utf-8' > >>>> locale.getlocale() > > ('pt_BR', 'utf') > >>>> print '?'.lower() > > ? > > > What am I missing? I'm in Fedora Core 5 and Python 2.4.3. > > > # cat /etc/sysconfig/i18n > > LANG="en_US.UTF-8" > > SYSFONT="latarcyrheb-sun16" > > > Regards, Clodoaldo Pinto Neto > > str.lower() operates on bytes and therefore doesn't handle encodings with > multibyte characters (like utf-8) properly: > > >>> u"?".encode("utf8") > '\xc3\x89' > >>> u"?".encode("latin1") > '\xc9' > >>> import locale > >>> locale.setlocale(locale.LC_ALL, "de_DE.utf8") > 'de_DE.utf8' > >>> print unicode("\xc3\x89".lower(), "utf8") > ? > >>> locale.setlocale(locale.LC_ALL, "de_DE.latin1") > 'de_DE.latin1' > >>> print unicode("\xc9".lower(), "latin1") > > ? > > I recommend that you forget about byte strings and use unicode throughout. Now I understand it. Thanks. Regards, Clodoaldo Pinto Neto From tjreedy at udel.edu Sat May 12 19:32:34 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 12 May 2007 19:32:34 -0400 Subject: ctree data References: Message-ID: "Carl K" wrote in message news:r4idnSn4-LNhttvbnZ2dnUVZ_uWlnZ2d at comcast.com... |A friend needs to convert c-tree plus data to MySql. I can to the "to MySql | part, but need some help with the "from c-tree." If I just wanted to get this | done, I would hunt down the ODBC driver and use some MSy thing. But I am trying | to hone my Python skills, | My searching around has come up with a few ways to use Python to read the data: | | 1. pull what I need from some other py code that uses c-tree: | | http://oltp-platform.cvs.sourceforge.net/oltp-platform/OLTPP/services/PythonScript/PythonTranslate.h?view=markup | http://oltp-platform.cvs.sourceforge.net/oltp-platform/OLTPP/scripts/TestZipCodes.py?view=markup | | 12 a,b,c = ZipCode.Get() | 13 print "Zip code is ", a | 14 print "State is ", b | 15 print "City is ", c | | I am sure this is what I want. I just haven't figured out where to start. | | 2. "Pyrex" to create Python bindings to C API with minimal C knowledge. I took | C and did a few little utilities on my own in the 90's. plus I can make a | tarball. today I am not sure I even qualify for "minimal." | | 3. the C API is present as a shared object (.so), use it from Python with | ctypes. I have no idea what that means. [snip] I personally would start with either 1 or 3, but probably 3 since the skill of using ctypes is transferable to other problems and I want to learn it anyway. Ctypes is a foreign function interface (FFI) module. It is new in the Python stdlib with 2.5 but has been around as a 3rd party module much longer. With a specification of the C API in hand, you should be able to write Python functions that call functions in the shared library. Ctypes handles the interconversion of Python and C datatypes and the calling details. I would start with the simplest thing that you can verify working: open database, get some info that you can print, so you know you really opened it, and close database. Terry Jan Reedy From mensanator at aol.com Tue May 8 20:10:03 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 8 May 2007 17:10:03 -0700 Subject: Muzzle Velocity (was: High resolution sleep (Linux) In-Reply-To: References: <1178274122.142071.91740@y5g2000hsa.googlegroups.com> Message-ID: <1178669403.029697.103530@h2g2000hsg.googlegroups.com> On May 8, 12:59 pm, Dennis Lee Bieber wrote: > On Tue, 8 May 2007 08:24:01 +0200, "Hendrik van Rooyen" > declaimed the following in comp.lang.python: > > > > > So being an idle bugger, I just naturally assumed that the > > speed would have doubled in the intervening time since > > I was last involved in this subject. - hence the 5000. > > Development tends to go in both directions... Massive rounds moving > at, or slightly slower, than "typical" (2000fps) vs very light rounds > moving at really high speeds (the various .17). > > > Did you know that the first military smokeless powder > > round was for the French Lebel? - It threw a bronze > > ball, and could punch through a single brick wall. > > Well, extreme high speed wouldn't help for that -- just get a > surface splatter. Heavy and slower... (or some sort of solid core -- > depleted uranium with a teflon coating) And penetration isn't always desireable. A slow, heavy round will punch a tunnel through your arm muscle, but a fast, light round will take your entire arm off. > -- > 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 quasi at null.set Mon May 7 23:53:44 2007 From: quasi at null.set (quasi) Date: Mon, 07 May 2007 22:53:44 -0500 Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> <08qk33t594ih0ulmjmev90d22lkfnotgoe@4ax.com> <463C2A3A.8332D211@hotmail.com> <0k8p33h90bp5tfajedb4bmd2eik8gfi2ho@4ax.com> Message-ID: On Mon, 7 May 2007 17:00:01 -0400, krw wrote: >In article , >quasi at null.set says... >> On Mon, 7 May 2007 10:55:55 -0400, James Beck >> wrote: >> >> >In article <0k8p33h90bp5tfajedb4bmd2eik8gfi2ho at 4ax.com>, quasi at null.set >> >says... >> >> On Sat, 05 May 2007 07:54:50 +0100, Eeyore >> >> wrote: >> >> >> >> > >> >> > >> >> >quasi wrote: >> >> > >> >> >> Gib Bogle wrote: >> >> >> >> >> >> >Ah, so the firefighters were in on the conspiracy! >> >> >> >> >> >> No, but the firefighters are very much aware that there is more to >> >> >> 9/11 than has been officially revealed. >> >> >> >> >> >> This is even more true at Pentagon. The firefighters there brought >> >> >> dogs trained to search for survivors and/or remains >> >> > >> >> >Sounds like good practice. >> >> > >> >> > >> >> >> and found nothing. >> >> > >> >> >And the significance of this is ? >> >> >> >> The plane was supposed to have passengers. >> >> >> >> quasi >> >> >> >Yep, and they found them all, therefore, there were none for the dogs to >> >find. >> >> You pretty much made that up. >> >> They found nothing -- no bodies, no body parts, no blood, no bones, no >> luggage, no rings (do gold rings melt at jet fuel temperatures?), no >> jewelry (do diamonds melt at jet fuel temperatures?), no plane seats, >> no silverware (ok, maybe they only had plastic). In other words, an >> immediate mystery to the firefighters was the lack of any indication >> that the plane had passengers. Even if you believe that most of the >> passengers were essentially incinerated, it's not believable that all >> of them were. Some of the bodies should have been recoverable right at >> the scene. > >If none of the passenger's remains were ever found, why all the fuss >last year when they found more. That's news to me. We're talking about the Pentagon, not the WTC. Besides, I didn't say that no remains were ever found. What I said was that no passenger remains were found at the Pentagon on 9/11 by the firefighters or their trained rescue dogs. At the WTC, no passenger remains were ever found, as far as I know. Of course, that's not so surprising. What is surprising is the all too convenient find of Mohammed Atta's undamaged passport in the WTC rubble. It wasn't even buried. It was just sitting there, waiting to be found. >IOW, you're a liar. That's way too strong. I'm not saying anything I know to be false. >> Weeks later, parts of the wreckage were supposedly "analyzed" at a >> government lab, and the official report claims they were able to >> isolate DNA for many of the passengers. It doesn't ring true. > >...and a fool. See if you can keep your argument from degenerating to the level of personal attacks. quasi From mcl.office at googlemail.com Mon May 21 08:10:46 2007 From: mcl.office at googlemail.com (mosscliffe) Date: 21 May 2007 05:10:46 -0700 Subject: NEWBIE: Extending a For Statement. Message-ID: <1179749446.179064.222990@z28g2000prd.googlegroups.com> I keep seeing examples of statements where it seems conditionals are appended to a for statement, but I do not understand them. I would like to use one in the following scenario. I have a dictionary of mydict = { 1: 500, 2:700, 3: 800, 60: 456, 62: 543, 58: 6789} for key in mydict: if key in xrange (60,69) or key == 3: print key,mydict[key] I would like to have the 'if' statement as part of the 'for' statement. I realise it is purely cosmetic, but it would help me understand python syntax a little better. Thanks Richard From showell30 at yahoo.com Wed May 30 00:07:23 2007 From: showell30 at yahoo.com (Steve Howell) Date: Tue, 29 May 2007 21:07:23 -0700 (PDT) Subject: itertools.groupby (gauntlet thrown down) In-Reply-To: <7x646b6l9t.fsf@ruckus.brouhaha.com> Message-ID: <172502.46750.qm@web33503.mail.mud.yahoo.com> > Raymond Hettinger writes: > > The gauntlet has been thrown down. Any creative > thinkers > > up to the challenge? Give me cool recipes. > Twin primes? (Sorry, no code, but there's a good Python example somewhere that returns an iterator that keeps doing the sieve, feed it to groupby,...) ____________________________________________________________________________________Shape Yahoo! in your own image. Join our Network Research Panel today! http://surveylink.yahoo.com/gmrs/yahoo_panel_invite.asp?a=7 From giles_brown at hotmail.com Wed May 23 10:08:41 2007 From: giles_brown at hotmail.com (Giles Brown) Date: 23 May 2007 07:08:41 -0700 Subject: Decorator question In-Reply-To: Message-ID: <1179929321.570413.202730@o5g2000hsb.googlegroups.com> On 23 May, 14:46, "Steven W. Orr" wrote: > I just discovered decorators. Very cool. My question is that I can't > figure out how to make a decorator not be restricted to a function so it > would also work on a method. > > Here's my code: > > def g(expr): > def rpt(func): > def wrapper(t): > for ii in range(expr): > print ii, > func(t) > wrapper.__name__ = func.__name__ > wrapper.__dict__ = func.__dict__ > wrapper.__doc__ = func.__doc__ > return func > return wrapper > return rpt > > @g(20) > def f(s): > print 's="%s"'%s > f('Hello') > > It works fine, but now I want to apply the same decorator to a class > method. > > class KK: > # @g(20) This obviously doesn't work. > def f(self, s): > print 's= %s'%s > > k = KK() > k.f('Hello') > > Is there a trick I need? > > TIA > > -- > 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 For this kind of decorator where you don't care about the values of the arguments you could just use *args (and perhaps **kwargs too)? def g(expr): def rpt(func): def wrapper(*args, **kwargs): for ii in range(expr): print ii, func(*args, **kwargs) wrapper.__name__ = func.__name__ wrapper.__dict__ = func.__dict__ wrapper.__doc__ = func.__doc__ return func return wrapper return rpt Giles From S.Mientki-nospam at mailbox.kun.nl Fri May 25 03:29:12 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Fri, 25 May 2007 09:29:12 +0200 Subject: Can I reference 1 instance of an object by more names ? rephrase In-Reply-To: References: <4654289a$0$2326$426a74cc@news.free.fr> <3dc25$4655ebd1$d443bb3a$31378@news.speedlinq.nl> Message-ID: <8c957$46568f73$d443bb3a$15533@news.speedlinq.nl> > Again, I'm confident, again I didn't test. I did, ... ... and unfortunately it still gave errors. So for the moment I'll just stick to my "lots of code solution", and I'll try again, when I've some more understanding of these Python "internals". Anyway, thank you all for your assistance. cheers, Stef Mientki From castironpi at gmail.com Wed May 9 15:41:16 2007 From: castironpi at gmail.com (castironpi at gmail.com) Date: 9 May 2007 12:41:16 -0700 Subject: interesting exercise In-Reply-To: <46416674$0$83110$c30e37c6@lon-reader.news.telstra.net> References: <1178595952.641173.76540@y80g2000hsf.googlegroups.com> <1178601624.812907.23550@u30g2000hsc.googlegroups.com> <1178661305.063868.130730@e65g2000hsc.googlegroups.com> <1178661851.606885.104330@p77g2000hsh.googlegroups.com> <1178670691.209680.119330@o5g2000hsb.googlegroups.com> <46416674$0$83110$c30e37c6@lon-reader.news.telstra.net> Message-ID: <1178739676.565009.35590@u30g2000hsc.googlegroups.com> On May 9, 1:13 am, Charles Sanders wrote: > Michael Tobis wrote: > > Here is the bloated mess I came up with. I did see that it had to be > > recursive, and was proud of myself for getting it pretty much on the > > first try, but the thing still reeks of my sorry old fortran-addled > > mentality. > > Recursion is not necessary, but is much, much clearer. > > Here is one non-recursive version from another aging > fortran programmer. I agree it is less clear than most > of the recursive alternatives. No checks for sorted > input etc, these are left as an exercise for the reader. > > def permute( s, n ): > def _perm( m, n ): > ilist = [0]*n > while True: > yield ilist > i = n-1 > while i >= 0 and ilist[i]>=m-1: i = i - 1 > if i >= 0: > ilist = ilist[0:i] + [ilist[i]+1] + [0]*(n-i-1) > else: > return > > return [ ''.join([s[i] for i in ilist]) > for ilist in _perm(len(s),n) ] > > print "permute('abc',2) = ", permute('abc',2) > print "len(permute('13579',3)) = ", len(permute('13579',3)) > > permute('abc',2) = ['aa', 'ab', 'ac', 'ba', 'bb', 'bc', > 'ca', 'cb', 'cc'] > len(permute('13579',3)) = 125 > > or even this monstrosity ... > > def permute2( s, n ): > return [ ''.join([ s[int(i/len(s)**j)%len(s)] > for j in range(n-1,-1,-1)]) > for i in range(len(s)**n) ] > > print "permute2('abc',2) =", permute2('abc',2) > print "len(permute2('13579',3)) =", len(permute2('13579',3)) > > permute2('abc',2) = ['aa', 'ab', 'ac', 'ba', 'bb', 'bc', > 'ca', 'cb', 'cc'] > len(permute2('13579',3)) = 125 > > Charles Could you explain, this one, actually? Don't forget StopIteration. From bbxx789_05ss at yahoo.com Thu May 3 00:05:09 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 2 May 2007 21:05:09 -0700 Subject: sqlite for mac? In-Reply-To: References: <1177993261.572563.70370@n76g2000hsh.googlegroups.com> <5f56302b0705010308h5c3f64a8ka05cd92de879f6bd@mail.gmail.com> Message-ID: <1178165109.102244.188860@c35g2000hsg.googlegroups.com> On May 1, 6:09 am, Ben Secrest wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > On 2007-05-01, Daniel Nogradi wrote: > > >> Does sqlite come in a mac version? > > > The interface (pysqlite) is part of the python 2.5 standard library > > but you need to install sqlite itself separately (as far as I > > remember) fromwww.sqlite.org > > http://developer.apple.com/documentation/MacOSX/Conceptual/OSX_Techno... > > - -- > Ben Secrest > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.7 (NetBSD) > > iD8DBQFGNy4DeLi5NDZQ3o0RAtVOAJ9AglHEPH/9HUKIsLLWIkaNwoZC8QCaAy7T > MC8VhXY2MyOyp2DaJAPOb0I= > =UGAL > -----END PGP SIGNATURE----- I downloaded pysqlite, ran the setup script, and tested the installation and everything worked fine. However, if I try to import either sqlite, sqlite2, or sqlite3 into a python program, I get an error saying there's no such module. I assume that means pysqlite cannot see the installation of SQlite that came preinstalled on my mac. My python book says to download the SQlite source where automatic code generation has already been performed. I did that. Then my book says says to follow the instructions in the README file. However, the download only has two files: sqlite3.c and sqlite3.h. As a result, I don't know what to do. Any advice? From micke.hale at gmail.com Fri May 11 09:14:27 2007 From: micke.hale at gmail.com (micke.hale at gmail.com) Date: 11 May 2007 06:14:27 -0700 Subject: software testing articles Message-ID: <1178889267.152525.230420@e65g2000hsc.googlegroups.com> Have you ever been interested in software testing? Giving you an in depth analysis/knowledge on software testing!! http://www.top-itarticles.com/softtest/main.asp From jm.suresh at gmail.com Fri May 25 04:14:44 2007 From: jm.suresh at gmail.com (jm.suresh@no.spam.gmail.com) Date: 25 May 2007 01:14:44 -0700 Subject: Find the closest relative In-Reply-To: <1180078850.074308.286570@p77g2000hsh.googlegroups.com> References: <1180074710.011260.276830@n15g2000prd.googlegroups.com> <1180078850.074308.286570@p77g2000hsh.googlegroups.com> Message-ID: <1180080884.492044.109150@n15g2000prd.googlegroups.com> On May 25, 12:40 pm, 7stud wrote: > On May 25, 12:31 am, "jm.sur... at no.spam.gmail.com" > > > > wrote: > > This is how I implemented; I guess there must be elegant way to do > > this... > > > def find_closest_relative(a,b,c): > > c1 = b.__class__ > > c2 = b.__class__ > > > while True: > > if isinstance(a, c1): > > return b > > if isinstance(a, c2): > > return c > > c1 = c1.__base__ > > c2 = c1.__base__ > > > - > > Suresh > > I can't see how your code does what you describe. > > > Now, given one of the instance, I want to find the > > closest relative of the other two. > > What influence would an object have over the closest relative of two > other objects? The closet relative of two other objects is > independent of any third object. Do you want to find the closest > relative of 3 objects? If so, this might work: Sorry, It was nor phrased well. I want to find the closest relative of the first object among the second and third.i.e. I want to choose either second or third object based on how close they are on the class hierarchy to the first object. > > import inspect > > class A(object): pass > class X(object): pass > > class B(A, X): pass #an object of this class has A as a base class > class C(A, X): pass > class D(A, X): pass > > class E(C): pass #an object of this class has A as a base class > class F(D): pass #an object of this class has A as a base class > > def closestRelative(x, y, z): > b1 = inspect.getmro(x.__class__) > b2 = inspect.getmro(y.__class__) > b3 = inspect.getmro(z.__class__) > > for elmt in b1: > if elmt in b2 and elmt in b3: > return elmt > return None > > b = B() > e = E() > f = F() > > print closestRelative(b, e, f) > > However, you should probably post an example of a class structure and > describe what you want to happen when you have three instance of the > various classes. From steven.bethard at gmail.com Wed May 16 23:15:38 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 16 May 2007 21:15:38 -0600 Subject: How do I tell the difference between the end of a text file, and an empty line in a text file? In-Reply-To: <1179352021.803070.200780@k79g2000hse.googlegroups.com> References: <1179352021.803070.200780@k79g2000hse.googlegroups.com> Message-ID: walterbyrd wrote: > Python's lack of an EOF character is giving me a hard time. > > I've tried: > > ----- > s = f.readline() > while s: > . > . > s = f.readline() > -------- > > and > > ------- > s = f.readline() > while s != '' > . > . > s = f.readline() > ------- > > > In both cases, the loop ends as soon it encounters an empty line in > the file, i.e. That's just not true. Did you try that code? >>> open('temp.txt', 'w').write('''\ ... xxxxxxxxxx ... xxxxxxxxxxx ... xxxxxxx ... ... xxxxxxxxxxxxxx ... xxxxxxxxxx ... x ... ''') >>> while s: ... print s, ... s = f.readline() ... >>> f = open('temp.txt') >>> s = f.readline() >>> while s: ... print s, ... s = f.readline() ... xxxxxxxxxx xxxxxxxxxxx xxxxxxx xxxxxxxxxxxxxx xxxxxxxxxx x The file.readline() method returns '\n' for empty lines and '' for end-of-file. STeVe From katietam at gmail.com Wed May 30 14:25:22 2007 From: katietam at gmail.com (Katie Tam) Date: 30 May 2007 11:25:22 -0700 Subject: Off Topic: What is the good book to learn Python ? Message-ID: <1180549522.350380.276570@q66g2000hsg.googlegroups.com> I am new to this filed and begin to learn this langague. Can you tell me the good books to start with ? Katie Tam Network administrator http://www.linkwaves.com/main.asp http://www.linkwaves.com From paul at boddie.org.uk Wed May 23 06:12:09 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 23 May 2007 03:12:09 -0700 Subject: Shared Memory Space - Accross Apps & Network In-Reply-To: <1179913683.260600.283420@q69g2000hsb.googlegroups.com> Message-ID: <1179915129.445750.10290@q69g2000hsb.googlegroups.com> On 23 May, 11:48, "D.Hering" wrote: > > Possibly, IPython's new interactive parallel environment is what you > are looking for:http://ipython.scipy.org/moin/Parallel_Computing See this and related projects on the python.org Wiki: http://wiki.python.org/moin/ParallelProcessing Paul From jakub.stolarski at gmail.com Mon May 14 12:47:11 2007 From: jakub.stolarski at gmail.com (Jakub Stolarski) Date: 14 May 2007 09:47:11 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46473267$0$31532$9b622d9e@news.freenet.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <1179161231.286122.50960@p77g2000hsh.googlegroups.com> On May 13, 5:44 pm, "Martin v. L?wis" wrote: > - should non-ASCII identifiers be supported? why? No. It's good convention to stick with english. And if we stick with english, why we should need non-ASCII characters? Any non-ASCII character makes code less readable. We never know if our code became public. > - would you use them if it was possible to do so? in what cases? No. I don't see any uses. I'm Polish. Polish-english mix looks funny. From sgeiger at ncee.net Tue May 8 10:30:00 2007 From: sgeiger at ncee.net (Shane Geiger) Date: Tue, 08 May 2007 09:30:00 -0500 Subject: ipython environment question Message-ID: <46408968.8030402@ncee.net> """ I'm trying to import ipython shell (which works great!) to set some variables and then run a function (which doesn't work). It seems like such a simple thing. Here's an example script to show what I'm trying to do. Run the script and then try to change the variable project_name from the ipython prompt and then type create() and the new value you assigned will *not* be used. I tried to use "def create(project_name = project_name):" Even that didn't work. What slight of hand is necessary? import os, sys project_name = 'python_packages' group_name = 'sgeiger' repo = '/var/svn' def create(repo=repo,group_name=group_name,project_name=project_name): #def create(): #os.system("sudo mkdir -p " + repo ) #os.system("sudo svnadmin create " + repo) #os.system("sudo chown -R " + group_name + " " + repo) print "sudo mkdir -p " + repo + '/' + project_name print "sudo svnadmin create " + repo + '/' + project_name print "sudo chown -R " + group_name + " " + repo + '/' + project_name if __name__ == '__main__': sys.argv.append('-cl') from IPython.Shell import IPShellEmbed ipshell = IPShellEmbed() print "Please set these variables: project_name, group_name ...and then type create()" ### I even tried to put all my ipshell() # this call anywhere in your program will start IPython -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy -------------- next part -------------- A non-text attachment was scrubbed... Name: sgeiger.vcf Type: text/x-vcard Size: 310 bytes Desc: not available URL: From deets at nospam.web.de Tue May 8 09:00:37 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 08 May 2007 15:00:37 +0200 Subject: Gui thread and async jobs. References: <1178627450.408287.139070@p77g2000hsh.googlegroups.com> Message-ID: <5abajlF2nk767U1@mid.uni-berlin.de> king kikapu wrote: > Hi, i am reading the book "Python Cookbook, 2nd edition" and i > encountered a very handy recipe, the one that is called "Combining > GUIs and Asynchronous I/O with Threads" > > It is talking about retain a main GUI thread, doing async work with > worker threads and have both talk through a Queue object to dispatch > their messages, so the main (GUI) thread remain responsive. > It has a very good example by using Tkinter and Qt that is indeed > working. The only point that make me wonder is that the QUI thread has > to use some polling to check for messages in the Queue. > > Author said that another alternatives exists (by not doing polling) > but the complexity makes them non-practical for the 90% of ocassions. > I remember in C# we deal with that sort of things with events/ > delegates. > Hos the same thing is possible in Python, has anyone any link(s) to > have a look ? It depends on the toolkit you use. Qt has thread-safe custom events in 3.x, and afaik signal/slots (and thus events) are generally thread-safe in 4.x. So, no problems there. Diez From gagsl-py2 at yahoo.com.ar Fri May 4 01:08:44 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 04 May 2007 02:08:44 -0300 Subject: How do I get type methods? References: <1178220806.664557.245780@c35g2000hsg.googlegroups.com> <1178253260.075515.43810@q75g2000hsh.googlegroups.com> Message-ID: En Fri, 04 May 2007 01:34:20 -0300, escribi?: > I'm not against 'dir(MyClass)'; the question is, what should I 'dir()' > to get methods of 'pyuno' type instance? Usually instances don't have its own methods, they get them from the class. So you actually need dir(MyClass). Note that dir() might not show all available methods. -- Gabriel Genellina From tuom.larsen at gmail.com Thu May 10 14:44:41 2007 From: tuom.larsen at gmail.com (tuom.larsen at gmail.com) Date: 10 May 2007 11:44:41 -0700 Subject: Thread-safe dictionary In-Reply-To: <1178821512.229872.98120@n59g2000hsh.googlegroups.com> References: <1178821512.229872.98120@n59g2000hsh.googlegroups.com> Message-ID: <1178822681.175417.97970@u30g2000hsc.googlegroups.com> On May 10, 8:25 pm, tuom.lar... at gmail.com wrote: instead: > class safe_dict(dict): there should be: class safe_dict(object): From infocat at earthlink.net Wed May 30 22:41:32 2007 From: infocat at earthlink.net (Frank Swarbrick) Date: Wed, 30 May 2007 20:41:32 -0600 Subject: Is PEP-8 a Code or More of a Guideline? In-Reply-To: References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <5c1jpkF2tl0ilU1@mid.individual.net> Message-ID: <5c6qutF2tlf3oU1@mid.individual.net> Tim Roberts wrote: > Frank Swarbrick wrote: >> Then you'd really love COBOL! >> >> :-) >> >> Frank >> COBOL programmer for 10+ years > > Hey, did you hear about the object-oriented version of COBOL? They call it > "ADD ONE TO COBOL". I know you were joking, but the COBOL 2002 standard implements OO. It's OK, but quite obviously "bolted on". Frank Python programmer for 3+ days From clodoaldo.pinto at gmail.com Tue May 29 12:11:15 2007 From: clodoaldo.pinto at gmail.com (Clodoaldo) Date: 29 May 2007 09:11:15 -0700 Subject: Unicode to HTML entities In-Reply-To: References: <1180453921.357081.89500@n15g2000prd.googlegroups.com> Message-ID: <1180455075.419150.166050@r19g2000prf.googlegroups.com> On May 29, 12:57 pm, "Richard Brodie" wrote: > "Clodoaldo" wrote in message > > news:1180453921.357081.89500 at n15g2000prd.googlegroups.com... > > >I was looking for a function to transform a unicode string into > >htmlentities. > >>> u'S?o Paulo'.encode('ascii', 'xmlcharrefreplace') > > 'São Paulo' That was a fast answer. I would never find that myself. Thanks, Clodoaldo From joshua at eeinternet.com Wed May 16 15:47:31 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Wed, 16 May 2007 11:47:31 -0800 Subject: How to do basic CRUD apps with Python References: <1179098458.333666.307750@e65g2000hsc.googlegroups.com> <464848fa$0$465$426a74cc@news.free.fr> <1179197198.513508@smirk> Message-ID: <464b537e$0$32552$88260bb3@free.teranews.com> Sorry about the duplicate post! My news reader never showed my first reply! j -- Posted via a free Usenet account from http://www.teranews.com From paul.rudin at ntlworld.com Fri May 18 04:27:59 2007 From: paul.rudin at ntlworld.com (Paul Rudin) Date: Fri, 18 May 2007 09:27:59 +0100 Subject: emacs python debugging: pydb or pdb fringe interaction Message-ID: <87k5v61qpc.fsf@rudin.co.uk> I can't get the gdb fringe interaction functionality to work with either pdb or pydb. Any hints as to versions or incantations I should try? I have the emacs22 from debian unstable emacs-snapshot-gtk package fwiw. From s.mientki at id.umcn.nl Wed May 16 04:41:51 2007 From: s.mientki at id.umcn.nl (stef) Date: Wed, 16 May 2007 10:41:51 +0200 Subject: iteration doesn't seem to work ?? Message-ID: hello, can someone tell me why the following iteration doesn't work, and how I should replace empty strings in a list with a default value. >>> v ['123', '345', '', '0.3'] >>> for items in v: ... if items=='': ... items='3' ... >>> >>> v ['123', '345', '', '0.3'] >>> thanks, Stef Mientki From cavada at irst.itc.it Tue May 22 13:16:14 2007 From: cavada at irst.itc.it (Roberto Cavada) Date: Tue, 22 May 2007 19:16:14 +0200 Subject: ANNOUNCE: pygtkmvc-1.0.1 has been released Message-ID: <4653255E.6060805@irst.itc.it> Version 1.0.1 of pygtkmvc has been released. pygtkmvc can be download from the project homepage: ============== About pygtkmvc ============== pygtkmvc is a fully Python-based implementation of the Model-View-Controller (MVC) and Observer patterns for the PyGTK2 toolkit. MVC is a pattern that can be successfully used to design and develop well structured GUI applications. The MVC pattern basically helps in separating semantics and data of the application, from their representation. The Observer pattern helps to weaken dependencies among parts that should be separated, but need to be connected each other. pygtkmvc provides a powerful and still simple infrastructure to help designing and implement GUI applications based on the MVC and Observer patterns. Features The framework has been designed to be: * Essential and small, it does only what it was designed for. * Not an external dependency for your application: it fits in 80KB and can be released along with it. * Easy to understand and to use; fully documented. * Portable: straightly runs under many platforms. =================== About release 1.0.1 =================== This is a minor release that mainly features a few bug fixes. * New features: - Custom widgets into glade file are now supported by views. * Bug fixes: - Fixed access to properties in multi-threading models. - Fixed a bug in the observable properties registration mechanism. * Many thanks to: - Guillaume Libersat for providing a patch that enable reading custom widgets from glade files. - Phillip Calvin and Andreas Poisel for reporting bugs. - Jeffrey Barish for providing feedback. - Kartik Mistry for his work on Debian package. -- Roberto Cavada

pygtkmvc 1.0.1 - Pygtk MVC is a thin, multiplatform framework that helps to design and develop GUI applications based on the PyGTK toolkit. (22-May-07) ------------------ ITC -> dall'1 marzo 2007 Fondazione Bruno Kessler ITC -> since 1 March 2007 Fondazione Bruno Kessler ------------------ From __peter__ at web.de Sun May 13 02:45:57 2007 From: __peter__ at web.de (Peter Otten) Date: Sun, 13 May 2007 08:45:57 +0200 Subject: Creating a function to make checkbutton with information from a list? References: <1178993091.198864.94590@k79g2000hse.googlegroups.com> Message-ID: Thomas Jansson wrote: > Dear all > > I am writing a program with tkinter where I have to create a lot of > checkbuttons. They should have the same format but should have > different names. My intention is to run the functions and the create > all the buttons with the names from the list. > > I now the lines below doesn't work, but this is what I have so far. I > don't really know how call the element in the dict use in the for > loop. I tried to call +'item'+ but this doesn't work. > > def create_checkbox(self): > self.checkbutton = ["LNCOL", "LFORM", "LPOT", "LGRID", "LERR", > "LCOMP"] > for item in self.checkbutton: > self.+'item'+Checkbutton = Chekcbutton(frame, onvalue='t', > offvalue='f', variable=self.+'item'+) > self.+'item'+Checkbutton.grid() > > How should I do this? You /could/ use setattr()/getattr(), but for a clean design putting the buttons (or associated variables) into a dictionary is preferrable. def create_checkbuttons(self): button_names = ["LNCOL", "LFORM", "LPOT", "LGRID", "LERR", "LCOMP"] self.cbvalues = {} for row, name in enumerate(button_names): v = self.cbvalues[name] = IntVar() cb = Checkbutton(self.frame, variable=v) label = Label(self.frame, text=name) cb.grid(row=row, column=0) label.grid(row=row, column=1) You can then find out a checkbutton's state with self.cbvalues[name].get() Peter From bj_666 at gmx.net Sun May 27 10:42:28 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sun, 27 May 2007 16:42:28 +0200 Subject: totally lost newbie References: Message-ID: In , Steve Howell wrote: >> def key_func(item): >> return (len(item), item) >> >> data = ['viking', 'spam', 'parrot', 'ham', 'eric'] >> data.sort(key=key_func) >> print data >> > > Marc, when did the key feature get introduced, 2.4 or > 2.5? I'm asking on behalf of the newbie, who's going > to struggle with your solution if he's still running > 2.3. It's available in 2.4 but I don't know when it was introduced. Ciao, Marc 'BlackJack' Rintsch From bj_666 at gmx.net Tue May 8 12:57:26 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 08 May 2007 18:57:26 +0200 Subject: File Name Format References: <134147e2gsg6v35@corp.supernews.com> Message-ID: In <134147e2gsg6v35 at corp.supernews.com>, Grant Edwards wrote: > On 2007-05-08, Anand wrote: > >> How do I convert programmatically the file names from WIN32 to UNIX format? > > You don't need to. AFAIK, all legal WIN32 filenames are legal > UNIX file names. Doesn't this depend more on the file system than the operating system? Ciao, Marc 'BlackJack' Rintsch From __peter__ at web.de Tue May 22 04:51:18 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 22 May 2007 10:51:18 +0200 Subject: doctest environment question References: <1179762737.153434.143030@b40g2000prd.googlegroups.com> <1179775483.685881.236940@x18g2000prd.googlegroups.com> <1179818466.394663.222390@k79g2000hse.googlegroups.com> <1179823481.228631.229790@w5g2000hsg.googlegroups.com> Message-ID: tag wrote: > On 22 May, 08:59, Peter Otten <__pete... at web.de> wrote: >> inspect.getmodule(f) returns None because f() is not defined in a module. > OK. But there was a module when I ran interactively? Yes. Looking into the doctest source, there is a -- deprecated -- class called Tester that provides a module. I don't know why this approach was dropped. Peter From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu May 24 06:08:37 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 24 May 2007 12:08:37 +0200 Subject: function nested In-Reply-To: References: Message-ID: <46556401$0$19174$426a34cc@news.free.fr> Gigs_ a ?crit : > > i have this function. > > def f(start): > stack = [] > def f1(start): > for fname in os.listdir(startDir): > path = os.path.join(startDir, fname) > if os.path.isfile(path): > stack.append(path) > else: > f1(path) > return stack > > > this is returning empty list, why? Because that's what you are returning. Perhaps did you mean to actually *call* f1() after defining it ?-) From bbxx789_05ss at yahoo.com Sat May 19 13:47:02 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 19 May 2007 10:47:02 -0700 Subject: docs patch: dicts and sets In-Reply-To: References: <_5-dnU7aIN73j9LbnZ2dnUVZ_uCinZ2d@comcast.com> <1179593927.503393.127350@u30g2000hsc.googlegroups.com> Message-ID: <1179596822.923443.67500@k79g2000hse.googlegroups.com> On May 19, 11:38 am, Steve Holden wrote: > Except in those instances where users added information that was > explicitly wrong. It's a self correcting mechanism. Other reader's will spot the error and post corrections. From gagsl-py2 at yahoo.com.ar Tue May 1 18:54:13 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 01 May 2007 19:54:13 -0300 Subject: removing module References: Message-ID: En Mon, 30 Apr 2007 18:08:30 -0300, Bart escribi?: > I have static linked module in application plugin. > > Thirst thing how to remove this module from memory after Py_Finalize(); > Because there is segfault after - deactivate,activate this plugin. > > PyImport_AppendInittab("module_name",init_module_name); > Py_Initialize(); I don't understand exactly what you want to do. You have a module; it is statically linked; using PyImport_AppendInitTab you tell Python how to initialise it when someone imports the module. > How to check what provides this module ? At first, you have to import the module: import module > import sys > print sys.modules (is loaded?) After importing it, should appear in that list. > dir(module_name) is it enough? This will show the module namespace: usually, classes and functions defined inside it. -- Gabriel Genellina From rw at smsnet.pl Tue May 1 17:18:18 2007 From: rw at smsnet.pl (Rob Wolfe) Date: Tue, 01 May 2007 23:18:18 +0200 Subject: read list of dirnames and search for filenames References: <1178051721.935868.194700@o5g2000hsb.googlegroups.com> Message-ID: <87d51kgs4l.fsf@smsnet.pl> fscked writes: > I cannot seem to get this to work. I am hyst trying to read in a list > of paths and see if the directory or any sub has a filename pattern. > Here is the code: > > import os, sys > from path import path > > myfile = open("boxids.txt", "r") > for line in myfile.readlines(): Instead of this: > d = path(line) try this: d = path(line.strip()) ``readlines`` doesn't remove trailing newline characters from string > for f in d.walkfiles('*Config*.xml'): > print f > > And here is my error: > > Traceback (most recent call last): > File "Untitled.py", line 21, in ? > for f in d.walkfiles('*Config*.xml'): > File "C:\Python24\Lib\site-packages\path.py", line 460, in walkfiles > childList = self.listdir() > File "C:\Python24\Lib\site-packages\path.py", line 328, in listdir > names = os.listdir(self) > WindowsError: [Errno 3] The system cannot find the path specified: u'X: > \\Instructions\\97544546294\n/*.*' > -- HTH, Rob From adam at atlas.st Thu May 10 17:57:34 2007 From: adam at atlas.st (Adam Atlas) Date: 10 May 2007 14:57:34 -0700 Subject: Newbie question about string(passing by ref) In-Reply-To: <1178833659.400428.185630@u30g2000hsc.googlegroups.com> References: <1178833397.076720.279940@l77g2000hsb.googlegroups.com> <1178833659.400428.185630@u30g2000hsc.googlegroups.com> Message-ID: <1178834254.099555.306750@l77g2000hsb.googlegroups.com> On May 10, 5:47 pm, Adam Atlas wrote: > On May 10, 5:43 pm, lazy wrote: > > > I want to pass a string by reference. > > Don't worry, all function parameters in Python are passed by reference. Actually, just to clarify a little bit if you're understanding "pass by reference" in the sense used in PHP, sort of C, etc.: In Python, you have objects and names. When I say all function parameters are passed by reference, I don't mean you're actually passing a reference to the *variable*. (Like in PHP where you pass a variable like &$foo and the function can change that variable's value in the caller's scope.) You can never pass a reference to a variable in Python. But on the other hand, passing a parameter never causes the value to be copied. Basically, you have a variable that's a reference to an object somewhere in memory, and passing it to a function gives that function's scope a new pointer to that same location in memory. So if the function you pass it to assigns some other value to the variable, that's all it's doing: reassigning a local name to point to somewhere else in memory. From wbsmith at gmail.com Tue May 22 15:09:43 2007 From: wbsmith at gmail.com (wbsmith at gmail.com) Date: 22 May 2007 12:09:43 -0700 Subject: reading 3-d (multi-page) tiff images with python/pil Message-ID: <1179860983.736123.186020@x18g2000prd.googlegroups.com> hello all, i am using python (2.5) with the PIL (latest [last?] release), and i am trying to read in these 3-d tiff images we have. basically, i am following some example code that iterates through the images in the 3-d tiff file like this: import Image import numpy img = Image.open("myFile.tif") imgArray = numpy.zeros( ( img.size[0], img.size[1], numFrames ), numpy.uint8 ) frame = 0 try: while 1: img.seek( frame ) imgArray[:,:,frame] = img frame = frame + 1 except EOFError: img.seek( 0 ) pass and i have to get "numFrames" by initializing a counter to zero, looping through the same "seek" statement, and returning the counter once EOF has been reached. two questions: 1) is there a faster way to do this? when i compare the time required to run this code versus analogous matlab code, the python version is about 2 times slower (on average, 1.88 times slower when i time it with a bunch of different images). this may not seem like a lot, but when the images are frequently more than 1GB, it can add up. 2) is there a better way to get the numFrames (or to combine getting the numFrames with the rest of the code) so that i do not have to iterate over the seek() function twice? any help/suggestions much appreciated... thanks, bryan From saif.shakeel at gmail.com Mon May 14 01:56:43 2007 From: saif.shakeel at gmail.com (saif.shakeel at gmail.com) Date: 13 May 2007 22:56:43 -0700 Subject: Removing part of string Message-ID: <1179122203.691267.64200@o5g2000hsb.googlegroups.com> Hi, I am parsing an xml file ,and one part of structure looks something like this: - Infotainment_Control_Bus_CAN_TIMEOUT_AX Timeout N_As/N_Ar Time from transmit request until a CAN frame transmit confirmation is received. In my code i am extracting the data within ,which is Timeout N_As/N_Ar.These tags repeat and will have different timer names..like - Infotainment_Control_Bus_CAN_TIMEOUT_BS Timeout N_Bs Time that the transmitter of a multi-frame message shall wait to receive a flow control (FC) frame before timing out with a network layer error. I need to remove the words Timeout from the data,and take only the abbrevation..i.e.N_As/N_bs like that .In short i have to remove the words which come with name Time,and also the space which comes next to it. and take only the abbreviation.Can someone help me in this. Thanks From showell30 at yahoo.com Sun May 27 09:48:19 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 27 May 2007 06:48:19 -0700 (PDT) Subject: Is PEP-8 a Code or More of a Guideline? In-Reply-To: <87myzqpstb.fsf@benfinney.id.au> Message-ID: <321447.8250.qm@web33514.mail.mud.yahoo.com> --- Ben Finney wrote: > Paul McGuire writes: > > > At this point, I realized that I was taking things > too far > > off-topic, so I decided to start a new thread. > > So, uh, what's the purpose of this thread? Did you > have a specific > point to start off with, or a question to ask? > I'll take the liberty of answering on by behalf of Paul. Purpose of the thread--he realized he was taking another thread off topic, decided to start his own, so that people who don't want debate PEP 8 can more easily ignore it Specific point--he was mostly focused on the pain of using underscores, and while he was still off-topic on the previous thread, he had put his problems in the context of working with German colleagues who have slightly different keyboards than the American keyboard he has, the upcoming complications of Unicode in Python 3, etc. Question to ask--note the subject line, although I'm not sure that's his main question ____________________________________________________________________________________ Sucker-punch spam with award-winning protection. Try the free Yahoo! Mail Beta. http://advision.webevents.yahoo.com/mailbeta/features_spam.html From steve at holdenweb.com Thu May 31 23:45:49 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 31 May 2007 23:45:49 -0400 Subject: c[:]() In-Reply-To: <002801c7a3fb$56cc8030$240110ac@Muse> References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> <135tobve86qj808@corp.supernews.com> <135tru124pie2b3@corp.supernews.com> <135tv1bjqgbmsc9@corp.supernews.com> <002801c7a3fb$56cc8030$240110ac@Muse> Message-ID: Warren Stringer wrote: > As mentioned a while back, I'm now predisposed towards using `do(c)()` > because square brackets are hard with cell phones. The one mitigating factor > for more general use, outside of cell phones, is speed. If a PEP enables a > much faster solution with c[selector()]() then it may be worthwhile. But, I > feel a bit circumspect about suggesting a change as I haven't looked at > Python source, nor have I looked at the BNF, lately. I think Martelli's > recent post on implantation may be relevant: > >> Tuples are implemented as compact arrays of pointer-to-PyObject (so are >> lists, BTW). So, for example, a 10-items tuple takes 40 bytes (plus a >> small overhead for the header) on a 32-bit build, not 80 as it would if >> implemented as a linked list of (pointer-to-object, pointer-to-next) >> pairs; addressing sometuple[N] is O(1), NOT O(N); etc, etc. > > The questions about implementing a working c[:]() are: > 1) Does it break anything? > 2) Does it slow anything down? > 3) Could it speed anything up? > 4) Does it make code easier to read? > 5) What question(s) did I forget to ask? > > 1) No? The fact that c() currently fails on a container implies that > enabling it would not break existing client code. Would this break the > language definition? A couple years ago, I hand transcribed the BNF of > version 2.2 to an alternative to BNF. I would love to know if c[:]() would > break the BNF in a fundamental way. > > 2) I don't know. I've always assumed that Python objects are hash table > entries. How would this change? Would it change? Does the message > "TypeError: 'list' object is not callable" guarantee a short path between > bytecode and hash table? Is there some other mitigating factor? > > 3) Maybe? Does overriding __call__ create any extra indirection? If yes, > then I presume that `do(c)()` would be slower the `c[:]()`. I am writing > rather amorphous code. This may speed it up. > > 4) I posit yes. Am I missing something? What idiom does would c[:]() break? > This correlates with whether `c[:]()` breaks the language definition, in > question 1) > > > Erik Max Francis wrote: >> Warren Stringer wrote: >> >>> I'm still a bit new at this, was wondering why c[:]() doesn't work, and >>> implicitly wondering why it *shouldn't* work. >> It does work. It means "make a sliced copy of `c`, and then call it >> with no arguments." Functionally that is _no different_ from `c()`, >> which means "take `c` and call it with no arguments," because presuming >> `c` is a list, `c[:]` makes a shallow copy. >> >> So if you think `c()` and `c[:]()` should do something different in this >> case, you are profoundly confused about Python's semantics of what >> objects are, what it means to shallow copy a list, and what it means to >> make a function call. That you keep including the slice suggests that >> there's something about its meaning that's not yet clicking. > > I use `c[:]()` because it is unambiguous about using a container > Unfortunately nothing in your proposal addresses the issue that the container object needs to contain only callable objects. The general rule in Python is that you provide the right objects and expect error tracebacks if you do something wrong. So I don't really see why you feel it's necessary to "[be] unambiguous about using a container" when you don't appear to feel the same about its containing only functions. >> If you really want syntax where a function call on a container calls all >> of its elements, then that is trivially easy to do by creating such an >> object and overriding its `__call__` method. >> >> If you're not willing to do that, but still insisting that `c[:]()` >> makes sense, then perhaps it would be more advisable to learn more about >> Python rather than try to suggest profound changes to the language and >> its conventions. > > You're right. At the same time, version 3 is coming up soon. There is a > short window of opportunity for profound changes. > Which closed at the end of April as far as PEPs affecting the initial implementation of version 3 was concerned. The python3000 and python-ideas lists are the correct forum for those issues, though you will of course get all sorts of opinions on c.l.py. > Also, my audacious suggestion has spawned illuminating replies. For this > instance, I have read about shallow copy, before, but haven't been told > where it is used, before now. Other posts led to insights about closures, > and yielding a real solution. This is incredibly useful. I've learned a lot. > That's 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From johnjsal at NOSPAMgmail.com Wed May 9 10:30:43 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 09 May 2007 10:30:43 -0400 Subject: Suggestions for how to approach this problem? In-Reply-To: References: <4640ca5b$0$23392$c3e8da3@news.astraweb.com> <4640cba9$0$30544$c3e8da3@news.astraweb.com> Message-ID: <4641dae6$0$8784$c3e8da3@news.astraweb.com> Necmettin Begiter wrote: > Is this how the text looks like: > > 123 > some information > > 124 some other information > > 126(tab here)something else > > If this is the case (the numbers are at the beginning, and after the numbers > there is either a newline or a tab, the logic might be this simple: They all seem to be a little different. One consistency is that each number is followed by two spaces. There is nothing separating each reference except a single newline, which I want to preserve. But within each reference there might be a combination of spaces, tabs, or newlines. From maksim.kasimov at gmail.com Fri May 25 11:00:29 2007 From: maksim.kasimov at gmail.com (Maksim Kasimov) Date: Fri, 25 May 2007 18:00:29 +0300 Subject: just a bug In-Reply-To: References: <1179841504.782279.86490@u36g2000prd.googlegroups.com> <1180082137.329142.45350@p77g2000hsh.googlegroups.com> <1180090985.066935.218250@h2g2000hsg.googlegroups.com> Message-ID: Jarek Zgoda: > > No, it is not a part of string. It's a part of byte stream, split in a > middle of multibyte-encoded character. > > You cann't get only dot from small letter "i" and ask the parser to > treat it as a complete "i". > ... i know it :)) can you propose something to solve it? ;) -- Maksim Kasimov From charl.loubser at gmail.com Tue May 8 06:50:18 2007 From: charl.loubser at gmail.com (Merrigan) Date: 8 May 2007 03:50:18 -0700 Subject: long lists In-Reply-To: References: <1178522894.357829.28250@u30g2000hsc.googlegroups.com> <1178540073.988964.196860@w5g2000hsg.googlegroups.com> Message-ID: <1178621418.526101.179940@q75g2000hsh.googlegroups.com> On May 7, 10:21 pm, "Gabriel Genellina" wrote: > En Mon, 07 May 2007 09:14:34 -0300, Merrigan > escribi?: > > > The Script it available at this url : > >http://www.lewendewoord.co.za/theScript.py > > I understand this as a learning exercise, since there are lot of utilities > for remote syncing. > > Some comments: > - use os.path.join to build file paths, instead of concatenating strings. > - instead of reassigning sys.stdout before the call to retrlines, use the > callback: > > saveinfo = sys.stdout > fsock = open(tempDir + "remotelist.txt", "a") > sys.stdout = fsock > ftpconn.cwd(remotedir) #This changes to the remote directory > ftpconn.retrlines("LIST") #This gets a complete list of everything in > the directory > sys.stdout = saveinfo > fsock.close() > > becomes: > > fsock = open(os.path.join(tempDir,"remotelist.txt"), "a") > ftpconn.cwd(remotedir) #This changes to the remote directory > ftpconn.retrlines("LIST", fsock.write) #This gets a complete list of > everything in the directory > fsock.close() > (Why mode="a"? Shouldn't it be "w"? Isn't the listing for a single > directory?) > > - Saving both file lists may be useful, but why do you read them again? If > you already have a list of local filenames and remote filenames, why read > them from the saved copy? > - It's very confusing having "filenames" ending with "\n" - strip that as > you read it. You can use fname = fname.rstrip() > - If you are interested on filenames with a certain extension, only > process those files. That is, filter them *before* the processing begins. > > - The time-consuming part appears to be this: > > def comp_are(): > global toup > temptoup = [] > for file1 in remotefiles: > a = file1 > for file2 in localfiles: > b = file2 > if str(a) == str(b): > pass > if str(b) != str(a): > temptoup.append(str(str(b))) > toup = list(sets.Set(temptoup)) > for filename in remotefiles: > fn2up = filename > for item in toup: > if fn2up == item: > toup.remove(item) > else: > pass > toup.sort() > > (It's mostly nonsense... what do you expect from str(str(b)) different > from str(b)? and the next line is just a waste of time, can you see why?) > I think you want to compare two lists of filenames, and keep the elements > that are on one "localfiles" list but not on the other. As you appear to > know about sets: it's the set difference between "localfiles" and > "remotefiles". Keeping the same "globalish" thing: > > def comp_are(): > global toup > toup = list(sets.Set(localfiles) - sets.Set(remotefiles)) > toup.sort() > > Since Python 2.4, set is a builtin type, and you have sorted(), so you > could write: > > def comp_are(): > global toup > toup = sorted(set(localfiles) - set(remotefiles)) > > - Functions may have parameters and return useful things :) > That is, you may write, by example: > > remotefiles = getRemoteFiles(host, remotedir) > localfiles = getLocalFiles(localdir) > newfiles = findNewFiles(localfiles, remotefiles) > uploadFiles(host, newfiles) > > -- > Gabriel Genellina Hmmm, thanks a lot. This has really been helpful. I have tried putting it in the set, and whoops, it workes. Now, I think I need to start learning some more. now the script is running a lot slower... Now to get the rest of it up and running... Thanx for the help! From rene at korteklippe.de Wed May 16 06:57:06 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Wed, 16 May 2007 12:57:06 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464ae078$0$12296$426a34cc@news.free.fr> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179289167.723990.223890@u30g2000hsc.googlegroups.com> <464abd12$0$23364$426a34cc@news.free.fr> <1179307776.953405.207680@l77g2000hsb.googlegroups.com> <464ad388$0$28786$426a34cc@news.free.fr> <464adea8$0$23132$9b4e6d93@newsspool1.arcor-online.net> <464ae078$0$12296$426a34cc@news.free.fr> Message-ID: <464ae380$0$20287$9b4e6d93@newsspool3.arcor-online.net> Christophe schrieb: > Ren? Fleschenberg a ?crit : >> Christophe schrieb: >>> You should know that displaying and editing UTF-8 text as if it was >>> latin-1 works very very well.s >> >> No, this only works for those characters that are in the ASCII range. >> For all the other characters it does not work well at all. > > This alone shows you don't know enouth about UTF-8 to talk about it. > UTF-8 will NEVER use < 128 chars to describe multibyte chars. When you > parse a UTF-8 file, each space is a space, each \n is an end of line and > each 'Z' is a 'Z'. So? Does that mean that you can just display UTF-8 "as if it was Latin-1"? No, it does not. It means you can do that for exactly those characters that are in the ASCII range. For all the others, you can not. -- Ren? From stefan.sonnenberg at pythonmeister.com Mon May 7 04:46:09 2007 From: stefan.sonnenberg at pythonmeister.com (Stefan Sonnenberg-Carstens) Date: Mon, 7 May 2007 10:46:09 +0200 (CEST) Subject: problem with quoted strings while inserting into varchar field of database. In-Reply-To: <1178526655.933789.294700@h2g2000hsg.googlegroups.com> References: <1178475772.423687.118800@e65g2000hsc.googlegroups.com> <1178526655.933789.294700@h2g2000hsg.googlegroups.com> Message-ID: <1068189.54317.BlRUCl8VTQA=.1178527569.squirrel@webmailer.hosteurope.de> On Mo, 7.05.2007, 10:30, Daniele Varrazzo wrote: > On 7 Mag, 08:55, "krishnakant Mane" wrote: >> On 6 May 2007 11:22:52 -0700, Daniele Varrazzo >> >> Every serious database driver has a >> complete and solid SQL escaping >> > mechanism. This mechanism tipically involves putting placeholders in >> > your SQL strings and passing python data in a separate tuple or >> > dictionary. Kinda >> >> > cur.execute("INSERT INTO datatable (data) VALUES (%s);", >> > (pickled_data,)) >> >> I will try doing that once I get back to the lab. >> mean while I forgot to mention in my previous email that I use MySQLdb >> for python-mysql connection. > > OK: MySQLdb implements the escaping mechanism i described. You can > find the documentation if you look for it harder. > >> I did not find any such reference to storing pickled objects in the API. > > Storing pickled object is not different from storing anything else > into BLOB. You would have faced the same problem if you had to write > "O'Reilly" in a VARCHAR field. > > -- Daniele > > -- > http://mail.python.org/mailman/listinfo/python-list > > Why not use qmark parameter passing (PEP 249) ? cur.execute("INSERT INTO datatable (data) VALUES (?);" , (pickled_data,)) Then the DB driver will take care for you. From josiah.carlson at sbcglobal.net Fri May 18 20:48:42 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Sat, 19 May 2007 00:48:42 GMT Subject: Python Web Programming - looking for examples of solid high-traffic sites In-Reply-To: References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> <464da0a9$0$25891$426a74cc@news.free.fr> Message-ID: John Nagle wrote: > Many of the basic libraries for web related functions do have > problems. Even standard modules like "urllib" and "SSL" are buggy, > and have been for years. Outside the standard modules, it gets > worse, especially for ones with C components. Version incompatibility > for extensions is a serious problem. That's reality. > > It's a good language, but the library situation is poor. Python as > a language is better than Perl, but CPAN is better run than Cheese Shop. You know, submitting bug reports, patches, etc., can help make Python better. And with setuptools' easy_setup, getting modules and packages installed from the Cheese Shop is pretty painless. - Josiah From max at alcyone.com Thu May 24 19:39:31 2007 From: max at alcyone.com (Erik Max Francis) Date: Thu, 24 May 2007 16:39:31 -0700 Subject: 0 == False but [] != False? In-Reply-To: References: <1179982400.412340.178710@g4g2000hsf.googlegroups.com> <1rda53hphn117k5scvcqrc7c2e37utfhgu@4ax.com> <1180047740.001604.267170@q66g2000hsg.googlegroups.com> Message-ID: Steve Holden wrote: > Dan Bishop wrote: > >> I have a job as a C++ programmer, and they make us write it like that, >> apparently because the ! operator is hard to see. But "if (x == >> TRUE)" is discouraged. >> > Find a new employer. I'm not joking. Really. He's not. That's a perfect example of a style guideline that not only wastes energy, misses the point, but is totally wrong. -- 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 There is another world, which is not of men. -- Li Bai From kinch1967 at gmail.com Mon May 28 07:50:17 2007 From: kinch1967 at gmail.com (bullockbefriending bard) Date: 28 May 2007 04:50:17 -0700 Subject: speeding things up with C++ In-Reply-To: <1180171179.687276.77930@z28g2000prd.googlegroups.com> References: <1180171179.687276.77930@z28g2000prd.googlegroups.com> Message-ID: <1180353017.372648.10870@z28g2000prd.googlegroups.com> I wonder if Jython might be the answer? Java is going to be faster than Python for the time-critical part of my program. Does anybody have experience getting data structures like nested lists / tuples into a java routine from a running jython program (and then back again)? From bj_666 at gmx.net Thu May 17 06:52:38 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 17 May 2007 12:52:38 +0200 Subject: Newbie: Joining Lists References: <1179395397.157566.209330@l77g2000hsb.googlegroups.com> Message-ID: In <1179395397.157566.209330 at l77g2000hsb.googlegroups.com>, mosscliffe wrote: > ----------------------- CODE ---------------------- > import os > import glob > > filenames = [] > patterns = ('.\\t*.py', '.\\*.c??', '.\\*.txt') # Can these patterns > for glob processing be specified in the glob call *****ONE**** > for pattern in patterns: > filenames = filenames + glob.glob(pattern) # Is there a better > way for this line in joining lists *****TWO**** You can `extend()` the list instead of creating new concatenated copies in each iteration. > Ps \\ is because I needed to get the path element for my test and > windoze does not return a path element if in current directory Maybe using `os.path.abspath()` on the file names is a more portable and robust solution here. If you don't need all the functionality of `glob.glob()` you can write a simple function that takes multiple file name patterns: import fnmatch import os import re def multiglob(patterns): pattern_re = re.compile('|'.join(map(fnmatch.translate, patterns))) return [os.path.abspath(path) for path in os.listdir('.') if pattern_re.match(path)] This lacks `glob.glob()`\s special handling of patterns containing directory names though. Ciao, Marc 'BlackJack' Rintsch From vbr at email.cz Tue May 29 08:31:27 2007 From: vbr at email.cz (vbr at email.cz) Date: Tue, 29 May 2007 14:31:27 +0200 (CEST) Subject: =?us-ascii?Q?Re=3A=20multiline=20regular=20expression=20=28replace=29?= In-Reply-To: <465C0F4E.8080805@yahoo.co.uk> Message-ID: <7075.8075-821-1003092431-1180441886@email.cz> > Od: Zdenek Maxa > P?edm?t: Re: multiline regular expression (replace) > Datum: 29.5.2007 13:46:32 > ---------------------------------------- > half.italian at gmail.com wrote: > > On May 29, 2:03 am, Zdenek Maxa wrote: > > > >> Hi all, > >> > >> I would like to perform regular expression replace (e.g. removing > >> everything from within tags in a XML file) with multiple-line pattern. > >> How can I do this? > >> > >> where = open("filename").read() > >> multilinePattern = "^ .... <\/tag>$" > >> re.search(multilinePattern, where, re.MULTILINE) > >> > >> Thanks greatly, > >> Zdenek > >> > > > > Why not use an xml package for working with xml files? I'm sure > > they'll handle your multiline tags. > > > > http://effbot.org/zone/element-index.htm > > http://codespeak.net/lxml/ > > > > ~Sean > > > > > > Hi, > > that was merely an example of what I would like to achieve. However, in > general, is there a way for handling multiline regular expressions in > Python, using presumably only modules from distribution like re? > > Thanks, > Zdenek > -- > http://mail.python.org/mailman/listinfo/python-list > > > There shouldn't be any problems matching multiline strings using re (even without flags), there might be some problem with the search pattern, however, especially the "..." part :-) if you are in fact using dots - which don't include newlines in this pattern. the flag re.M only changes the behaviour of ^ and $ metacharacters, cf. the docs: re.M MULTILINE When specified, the pattern character "^" matches at the beginning of the string and at the beginning of each line (immediately following each newline); and the pattern character "$" matches at the end of the string and at the end of each line (immediately preceding each newline). By default, "^" matches only at the beginning of the string, and "$" only at the end of the string and immediately before the newline (if any) at the end of the string. you may also check the S flag: re.S DOTALL Make the "." special character match any character at all, including a newline; without this flag, "." will match anything except a newline. see http://docs.python.org/lib/node46.html http://docs.python.org/lib/re-syntax.html Vlasta From electronixtar at gmail.com Sun May 6 04:35:37 2007 From: electronixtar at gmail.com (est) Date: 6 May 2007 01:35:37 -0700 Subject: Newbie prob: How to write a file with 3 threads? Message-ID: <1178440537.257526.40980@y5g2000hsa.googlegroups.com> I need to write a file using 3 threads simutaniously, e.g. Thread 1 write the first byte of test.bin with an "a", second thread write the second byte "b", third thread write the third byte "c". Anyone could give a little example on how to do that? I have my code, but it makes python intepreter crash everytime on my Vista. From bdesth.quelquechose at free.quelquepart.fr Sun May 13 17:55:11 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 13 May 2007 23:55:11 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46473267$0$31532$9b622d9e@news.freenet.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <46477f19$0$19845$426a74cc@news.free.fr> Martin v. L?wis a ?crit : > PEP 1 specifies that PEP authors need to collect feedback from the > community. As the author of PEP 3131, I'd like to encourage comments > to the PEP included below, either here (comp.lang.python), or to > python-3000 at python.org > > In summary, this PEP proposes to allow non-ASCII letters as > identifiers in Python. If the PEP is accepted, the following > identifiers would also become valid as class, function, or > variable names: L?ffelstiel, chang?, ??????, or ??? > (hoping that the latter one means "counter"). > > I believe this PEP differs from other Py3k PEPs in that it really > requires feedback from people with different cultural background > to evaluate it fully - most other PEPs are culture-neutral. > > So, please provide feedback, e.g. perhaps by answering these > questions: > - should non-ASCII identifiers be supported? No. > why? Because it will definitivly make code-sharing impossible. Live with it or else, but CS is english-speaking, period. I just can't understand code with spanish or german (two languages I have notions of) identifiers, so let's not talk about other alphabets... NB : I'm *not* a native english speaker, I do *not* live in an english speaking country, and my mother's language requires non-ascii encoding. And I don't have special sympathy for the USA. And yes, I do write my code - including comments - in english. From roy at panix.com Wed May 30 22:55:10 2007 From: roy at panix.com (Roy Smith) Date: Wed, 30 May 2007 22:55:10 -0400 Subject: Is PEP-8 a Code or More of a Guideline? References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <87abvqpl6v.fsf@benfinney.id.au> <1180571360.883706.244950@q66g2000hsg.googlegroups.com> Message-ID: Dave Hansen wrote: > On May 27, 3:25 pm, Roy Smith wrote: > > Ben Finney wrote: > > > Is C no longer a "major" language? The long-standing convention there > > > is for lower_case_with_underscores. > > > > Which dates back to the days of ASR-33's which only had one case (upper > > The date is about right (actually, a little early: ASR-33, 1965; C, > about 1970), but you can't program C on an ASR-33. Damn, I wish I had known that at the time :-) > Keywords are all > lower case, and always have been. "IF" is a syntax error... I doubt it still works on anything made today, but back in those days, if you typed your login name in all upper case, the terminal was put into lcase mode. Upper case on input was automatically converted to lower case. You typed "IF", the C compiler saw "if", and it all worked. Including \( and \) for curly braces. From Leo.Kislov at gmail.com Fri May 4 01:23:52 2007 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 3 May 2007 22:23:52 -0700 Subject: My Python annoyances In-Reply-To: References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> Message-ID: <1178256232.178432.126290@q75g2000hsh.googlegroups.com> On May 3, 9:27 pm, "Gabriel Genellina" wrote: > En Thu, 03 May 2007 10:49:26 -0300, Ben Collver > escribi?: > > > I tried to write portable Python code. The zlib CRC function returned > > different results on architectures between 32 bit and 64 bit > > architectures. I filed a bug report. It was closed, without a comment > > from the person who closed it. I get the unspoken message: bug reports > > are not welcome. > > You got a comment from me, that you never disputed nor commented further. > I would have changed the status to "invalid" myself, if I were able to do > so. I think it should have been marked as "won't fix" as it's a wart just like 1/2 == 0, but as there are many users of the current behaviour it's "impossible" to fix it in Python 2.x. Maybe in Python 3.0? -- Leo From rtw at freenet.co.uk Sat May 5 16:55:19 2007 From: rtw at freenet.co.uk (Rob Williscroft) Date: Sat, 05 May 2007 15:55:19 -0500 Subject: How do I use the config parser? References: <1178392410.866037.179950@e65g2000hsc.googlegroups.com> Message-ID: wrote in news:1178392410.866037.179950 at e65g2000hsc.googlegroups.com in comp.lang.python: > Hi, > I need a specific example. I have seen the docs, but I don't all the > stuffs there. > > from ConfigParser import ConfigParser > Now I want to know how to read a section, a section attribute's value, > and to write thoses back after reading. > ConfigParser is derived from RawConfigParser, so you need to look at RawConfigParser's docs here: http://docs.python.org/lib/RawConfigParser-objects.html Rob. -- http://www.victim-prime.dsl.pipex.com/ From DustanGroups at gmail.com Sun May 6 07:41:49 2007 From: DustanGroups at gmail.com (Dustan) Date: 6 May 2007 04:41:49 -0700 Subject: change of random state when pyc created?? In-Reply-To: References: <1178408359.113807.181570@l77g2000hsb.googlegroups.com> Message-ID: <1178451709.085624.226940@u30g2000hsc.googlegroups.com> On May 6, 1:00 am, Steven D'Aprano wrote: > On Sun, 06 May 2007 00:20:04 +0000, Alan Isaac wrote: > >> Should you not expect to get the same result each time? Is that not > >> the point of setting a constant seed each time you run the script? > > > Yes. That is the problem. > > If I delete module2.pyc, > > I do not get the same result. > > I think you have missed what John Machin is pointing out. According to > your original description, you get different results even if you DON'T > delete module2.pyc. > > According to your original post, you get the _same_ behaviour the first > time you run the script, regardless of the pyc file being deleted or not. > > You wrote: > > [quote] > module1 sets a seed like this:: > > if __name__ == "__main__": > random.seed(314) > main() > > I execute module1.py from the (Windows) shell. > I get a result, let's call it result1. > I execute it again. I get another result, say result2. > Running it again and again, I get result2. > [end quote] > > So, with module2.pyc file existing, you get result1 the first time you > execute module1.py, and then you get result2 every time from then onwards. Umm... no. module2.pyc is created by the first run. > How is that different from what you wrote next? > > [quote] > Now I delete module2.pyc. > I execute module1.py from the shell. > I get result1. > I execute it again; I get result2. > From then on I get result2, > unless I delete module.pyc again, > in which case I once again get result1. > [end quote] > > You get the same behaviour with or without module2.pyc: the first run of > the script gives different results from subsequent runs. You can reset > that first run by deleting module2.pyc. > > I'm still perplexed how this is possible, but now I'm more perplexed. > > If you want to send me the modules, I will have a look at them as well. > Many eyes make for shallow bugs... > > -- > Steven. From danb_83 at yahoo.com Thu May 24 19:02:20 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: 24 May 2007 16:02:20 -0700 Subject: 0 == False but [] != False? In-Reply-To: <1rda53hphn117k5scvcqrc7c2e37utfhgu@4ax.com> References: <1179982400.412340.178710@g4g2000hsf.googlegroups.com> <1rda53hphn117k5scvcqrc7c2e37utfhgu@4ax.com> Message-ID: <1180047740.001604.267170@q66g2000hsg.googlegroups.com> On May 24, 1:59 am, Tim Roberts wrote: ... > False is just a constant. 0, (), '', [], and False are all constants that > happen to evaluate to a false value in a Boolean context, but they are not > all the same. > > As a general rule, I've found code like "if x == False" to be a bad idea in > ANY language. I have a job as a C++ programmer, and they make us write it like that, apparently because the ! operator is hard to see. But "if (x == TRUE)" is discouraged. From exarkun at divmod.com Thu May 3 08:00:02 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 3 May 2007 08:00:02 -0400 Subject: ascii to unicode line endings In-Reply-To: <1178191837.424765.51090@o5g2000hsb.googlegroups.com> Message-ID: <20070503120002.19381.873455727.divmod.quotient.7875@ohm> On 3 May 2007 04:30:37 -0700, fidtz at clara.co.uk wrote: >On 2 May, 17:29, Jean-Paul Calderone wrote: >> On 2 May 2007 09:19:25 -0700, f... at clara.co.uk wrote: >> >> >> >> >The code: >> >> >import codecs >> >> >udlASCII = file("c:\\temp\\CSVDB.udl",'r') >> >udlUNI = codecs.open("c:\\temp\\CSVDB2.udl",'w',"utf_16") >> >> >udlUNI.write(udlASCII.read()) >> >> >udlUNI.close() >> >udlASCII.close() >> >> >This doesn't seem to generate the correct line endings. Instead of >> >converting 0x0D/0x0A to 0x0D/0x00/0x0A/0x00, it leaves it as 0x0D/ >> >0x0A >> >> >I have tried various 2 byte unicode encoding but it doesn't seem to >> >make a difference. I have also tried modifying the code to read and >> >convert a line at a time, but that didn't make any difference either. >> >> >I have tried to understand the unicode docs but nothing seems to >> >indicate why an seemingly incorrect conversion is being done. >> >Obviously I am missing something blindingly obvious here, any help >> >much appreciated. >> >> Consider this simple example: >> >> >>> import codecs >> >>> f = codecs.open('test-newlines-file', 'w', 'utf16') >> >>> f.write('\r\n') >> >>> f.close() >> >>> f = file('test-newlines-file') >> >>> f.read() >> '\xff\xfe\r\x00\n\x00' >> >>> >> >> And how it differs from your example. Are you sure you're examining >> the resulting output properly? >> >> By the way, "\r\0\n\0" isn't a "unicode line ending", it's just the UTF-16 >> encoding of "\r\n". >> >> Jean-Paul > >I am not sure what you are driving at here, since I started with an >ascii file, whereas you just write a unicode file to start with. I >guess the direct question is "is there a simple way to convert my >ascii file to a utf16 file?". I thought either string.encode() or >writing to a utf16 file would do the trick but it probably isn't that >simple! There's no such thing as a unicode file. The only difference between the code you posted and the code I posted is that mine is self-contained and demonstrates that the functionality works as you expected it to work, whereas the code you posted is requires external resources which are not available to run and produces external results which are not available to be checked regarding their correctness. So what I'm driving at is that both your example and mine are doing it correctly (because they are doing the same thing), and mine demonstrates that it is correct, but we have to take your word on the fact that yours doesn't work. ;) Jean-Paul From carsten at uniqsys.com Tue May 15 07:42:07 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 15 May 2007 07:42:07 -0400 Subject: howto get function from module, known by string names? In-Reply-To: <1179228596.349933.168610@l77g2000hsb.googlegroups.com> References: <1179228596.349933.168610@l77g2000hsb.googlegroups.com> Message-ID: <20070515113739.M82449@uniqsys.com> On 15 May 2007 04:29:56 -0700, dmitrey wrote > hi all, > can anyone explain howto get function from module, known by string > names? > I.e. something like > > def myfunc(module_string1, func_string2, *args): > eval('from ' + module_string1 + 'import ' + func_string2') > return func_string2(*args) To find a module by its name in a string, use __import__. To find an object's attribute by its name in a string, use getattr. Together, that becomes something like this: >>> def myfunc(module_string1, func_string2, *args): ... func = getattr(__import__(module_string1), func_string2) ... return func(*args) ... >>> myfunc("math", "sin", 0) 0.0 >>> myfunc("operator", "add", 2, 3) 5 Hope this helps, -- Carsten Haese http://informixdb.sourceforge.net From kakeez at hotmail.com Fri May 25 09:42:23 2007 From: kakeez at hotmail.com (Karim Ali) Date: Fri, 25 May 2007 13:42:23 +0000 Subject: Reading a file and resuming reading. Message-ID: Hi, Simple question. Is it possible in python to write code of the type: ----------------------------- while not eof <- really want the EOF and not just an empty line! readline by line end while; ----------------------------- What I am using now is the implicit for loop after a readlines(). I don't like this at all as a matter of opinion (my background is C++). But also, in case for one reason or another the program crashes, I want to be able to rexecute it and for it to resume reading from the same position as it left. If a while loop like the one above can be implemented I can do this simply by counting the lines! I appreciate any help. Karim _________________________________________________________________ Windows Live Hotmail. Now with better security, storage and features. www.newhotmail.ca?icid=WLHMENCA149 From dustin at v.igoro.us Wed May 2 01:52:44 2007 From: dustin at v.igoro.us (dustin at v.igoro.us) Date: Wed, 2 May 2007 00:52:44 -0500 Subject: pre-PEP: Standard Microthreading Pattern In-Reply-To: <1178083688.414491.317340@o5g2000hsb.googlegroups.com> References: <1178083688.414491.317340@o5g2000hsb.googlegroups.com> Message-ID: <20070502055244.GG14710@v.igoro.us> On Tue, May 01, 2007 at 10:28:08PM -0700, Michele Simionato wrote: > > while i < n: > > latest = (latest[1], latest[0] + latest[1]) > > yield # cooperative yield > There is an infinite loop here! Whoops. To much editing, not enough actual running of example code :) > BTW, in spite of having a great tradition, the Fibonacci example sucks > as a motivation for microthreading programming. You could show a simple > state machine instead. You're absolutely right, and among good company in pointing it out. Thank you for the suggestion of an alternative! Dustin From kbk at shore.net Tue May 22 19:07:29 2007 From: kbk at shore.net (Kurt B. Kaiser) Date: Tue, 22 May 2007 19:07:29 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200705222307.l4MN7Tld032667@hampton.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 364 open ( +2) / 3769 closed ( +3) / 4133 total ( +5) Bugs : 986 open (+18) / 6701 closed ( +9) / 7687 total (+27) RFE : 258 open ( +2) / 287 closed ( +1) / 545 total ( +3) New / Reopened Patches ______________________ syslog syscall support for SysLogLogger (2007-05-02) http://python.org/sf/1711603 reopened by luke-jr Remove backslash escapes from tokanize.c. (2007-05-16) http://python.org/sf/1720390 opened by Ron Adam Allow T_BOOL in PyMemberDef definitions (2007-05-17) http://python.org/sf/1720595 opened by Angelo Mottola fix 1668596: copy datafiles properly when package_dir is ' ' (2007-05-17) http://python.org/sf/1720897 opened by Raghuram Devarakonda Build on QNX (2007-05-20) http://python.org/sf/1722225 opened by Matt Kraai Curses Menu (2007-05-21) http://python.org/sf/1723038 opened by Fabian Frederick Patches Closed ______________ Removal of Tuple Parameter Unpacking [PEP3113] (2007-03-10) http://python.org/sf/1678060 closed by bcannon Class Decorators (2007-02-28) http://python.org/sf/1671208 closed by jackdied Allow any mapping after ** in calls (2007-03-23) http://python.org/sf/1686487 closed by gbrandl New / Reopened Bugs ___________________ build_clib --build-clib/--build-temp option bugs (2007-05-14) http://python.org/sf/1718574 opened by Pearu Peterson glibc error: corrupted double linked list (CPython 2.5.1) (2007-05-14) http://python.org/sf/1718942 opened by Yang Zhang new functools (2007-05-15) http://python.org/sf/1719222 opened by Aaron Brady Python package support not properly documented (2007-05-15) http://python.org/sf/1719423 opened by Michael Abbott tarfile stops expanding with long filenames (2007-05-16) http://python.org/sf/1719898 opened by Christian Zagrodnick No docs for PyEval_EvalCode and related functions (2007-05-16) http://python.org/sf/1719933 opened by Joseph Eagar sets module documentation: example uses deprecated method (2007-05-16) CLOSED http://python.org/sf/1719995 opened by Jens Quade Compiler is not thread safe? (2007-05-16) http://python.org/sf/1720241 opened by ??PC?? PyGILState_Ensure does not acquires GIL (2007-05-16) http://python.org/sf/1720250 opened by Kuno Ospald Tkinter + thread + urllib => crashes? (2007-05-17) http://python.org/sf/1720705 opened by Hirokazu Yamamoto docu enhancement for logging.handlers.SysLogHandler (2007-05-17) http://python.org/sf/1720726 opened by rhunger Please make sqlite3.Row iterable (2007-05-17) CLOSED http://python.org/sf/1720959 opened by phil automatic imports (2007-05-17) http://python.org/sf/1720992 opened by Juan Manuel Borges Ca?o ERROR - Microsoft Visual C++ Runtime Library (2007-05-18) http://python.org/sf/1721161 reopened by dariounipd ERROR - Microsoft Visual C++ Runtime Library (2007-05-18) http://python.org/sf/1721161 opened by darioUniPD code that writes the PKG-INFO file doesnt handle unicode (2007-05-18) http://python.org/sf/1721241 opened by Matthias Klose make testall shows many glibc detected malloc corruptions (2007-05-18) http://python.org/sf/1721309 reopened by gbrandl make testall shows many glibc detected malloc corruptions (2007-05-18) http://python.org/sf/1721309 opened by David Favor test_bsddb3 malloc corruption (2007-05-18) CLOSED http://python.org/sf/1721313 opened by David Favor emphasize iteration volatility for dict (2007-05-18) CLOSED http://python.org/sf/1721368 opened by Alan emphasize iteration volatility for set (2007-05-18) CLOSED http://python.org/sf/1721372 opened by Alan Small case which hangs (2007-05-18) http://python.org/sf/1721518 opened by Julian Todd A subclass of set doesn't always have __init__ called. (2007-05-19) http://python.org/sf/1721812 opened by David Benbennick email.FeedParser.BufferedSubFile improperly handles "\r\n" (2007-05-19) http://python.org/sf/1721862 opened by Sye van der Veen IDLE hangs in popup method completion (2007-05-19) http://python.org/sf/1721890 opened by Andy Harrington NamedTuple security issue (2007-05-20) CLOSED http://python.org/sf/1722239 reopened by tiran NamedTuple security issue (2007-05-20) CLOSED http://python.org/sf/1722239 opened by Christian Heimes Thread shutdown exception in Thread.notify() (2007-05-20) http://python.org/sf/1722344 opened by Yang Zhang urlparse.urlunparse forms file urls incorrectly (2007-05-20) http://python.org/sf/1722348 opened by Thomas Folz-Donahue Option -OO doesn't remove docstrings (2007-05-21) http://python.org/sf/1722485 opened by Grzegorz Adam Hankiewicz x = [[]]*2; x[0].append doesn't work (2007-05-21) CLOSED http://python.org/sf/1722956 opened by Jeff Britton Crash in ctypes callproc function with unicode string arg (2007-05-22) http://python.org/sf/1723338 opened by Colin Laplace Bugs Closed ___________ sets module documentation: example uses deprecated method (2007-05-16) http://python.org/sf/1719995 closed by gbrandl Please make sqlite3.Row iterable (2007-05-17) http://python.org/sf/1720959 closed by ghaering make testall shows many glibc detected malloc corruptions (2007-05-18) http://python.org/sf/1721309 closed by nnorwitz test_bsddb3 malloc corruption (2007-05-18) http://python.org/sf/1721313 closed by gbrandl emphasize iteration volatility for dict (2007-05-18) http://python.org/sf/1721368 closed by rhettinger emphasize iteration volatility for set (2007-05-18) http://python.org/sf/1721372 closed by rhettinger __getslice__ changes integer arguments (2007-05-03) http://python.org/sf/1712236 closed by rhettinger Docstring for site.addpackage() is incorrect (2007-04-09) http://python.org/sf/1697215 closed by gbrandl yield+break stops tracing (2006-10-24) http://python.org/sf/1583862 closed by luks NamedTuple security issue (2007-05-20) http://python.org/sf/1722239 closed by rhettinger NamedTuple security issue (2007-05-20) http://python.org/sf/1722239 closed by rhettinger x = [[]]*2; x[0].append doesn't work (2007-05-21) http://python.org/sf/1722956 closed by gbrandl New / Reopened RFE __________________ Add File - Reload (2007-05-17) http://python.org/sf/1721083 opened by Raymond Hettinger RFE Closed __________ Cannot use dict with unicode keys as keyword arguments (2007-05-03) http://python.org/sf/1712419 closed by gbrandl From openopt at ukr.net Sun May 6 15:40:47 2007 From: openopt at ukr.net (dmitrey) Date: 6 May 2007 12:40:47 -0700 Subject: howto make Python list from numpy.array? Message-ID: <1178480447.245977.293010@n59g2000hsh.googlegroups.com> howto make Python list from numpy.array? Thx, D. From wildemar at freakmail.de Mon May 21 10:22:38 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Mon, 21 May 2007 16:22:38 +0200 Subject: questions about programming styles In-Reply-To: <46515E7D.5010103@gmail.com> References: <46501710.6090904@gmail.com> <46515E7D.5010103@gmail.com> Message-ID: <4651AB2E.20509@freakmail.de> fdu.xiaojf at gmail.com wrote: > Thanks a lot for all kind replies! > > I think I need a systematic learning of design patterns. I have found > some tutorials > about design pattern about python, but can somebody point me which is > the best to start with ? > When you say "Design Patterns", what do you mean? Do you mean it in the computer-science-vocabulary-sense, as in [Singleton, Observer, Template, ...]? If you're a novice or hobby programmer, let me tell you this: Don't. Or at least: Don't, yet. Design patterns are meant to solve problems that you run into relatively often, but don't let that trick you: You have to get some intuition about them, or they'll make virtually no sense to you. They're not guide as to how to write programs. They help you overcome these "little obstacles" that you commonly run into. But if you really must know: Wikipedia is a good start (duh! ;)). If you mean the term in a looser sense, like how to approach programming, when to use what idiom, etc ...: Don't read too much, just write code, see if it works and if it doesn't, be creative. If it still doesn't work, ask. Like you did. Don't bother with theory all too long; you will understand programming concepts much more easily when you're "in it". And for the light stuff, like the Idea behind OO (classes, methods, etc.), Wikipedia is always good enough. :) W From bignose+hates-spam at benfinney.id.au Fri May 18 21:57:30 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 19 May 2007 11:57:30 +1000 Subject: (Modular-)Application Framework / Rich-Client-Platform in Python References: <8ea03$464dc950$d443bb3a$5229@news.speedlinq.nl> Message-ID: <871whd60dx.fsf@benfinney.id.au> Wildemar Wildenburger writes: > I think what most people think of when they hear "plugin" is: An > Application that can be extended. > An RCP provides no more than the next step: No monolithic app, just > plugins (which can have plugins themselves (which can have plugins > themselves (which ...))). Write a text editor component and use it in > your music-sequencer that also monitors your internet-activity, if you > must. That sounds like Python to me. Write an application as modules (natural and easy in Python), ensure the module interface is clear, and those modules can be used for their functionality elsewhere. You gave an analogy to Emacs. Well, Emacs' plig-in nature comes from two things: a core set of functionality primitives, exposed through a Lisp API; and a Lisp machine. From that framework, anyone can write Lisp plugin programs to make the Emacs framework behave in a particular way. You already have Python, and can embed it in your program. The only missing piece seems to be the primitive operations at the core, which surely depend on what exactly it is you have in mind for your program and can't really be provided in a generic form by some other party. This "framework" you're looking for, what would it actually *do*? If you can't describe what features it would provide, I can't imagine what it actually *does*. -- \ "This sentence contradicts itself -- no actually it doesn't." | `\ -- Douglas Hofstadter | _o__) | Ben Finney From stargaming at gmail.com Fri May 18 02:00:32 2007 From: stargaming at gmail.com (Stargaming) Date: Fri, 18 May 2007 08:00:32 +0200 Subject: omissions in python docs? In-Reply-To: References: <1179419983.750044.65030@n59g2000hsh.googlegroups.com> <1179451395.440662.127760@y80g2000hsf.googlegroups.com> <1179452448.886371.169000@q75g2000hsh.googlegroups.com> Message-ID: Anthony Irwin wrote: > 7stud wrote: > >> On May 17, 7:23 pm, 7stud wrote: >> >> By the way, have the python doc keepers ever visited the php docs? In >> my opinion, they are the best docs of any language I've encountered >> because users can add posts to any page in the docs to correct them or >> post code showing how to get around various idiosyncrasies when using >> the functions. >> > > Hi, > > I also like the php docs and love that you can type any function into > the search at php.net and the documentation just comes up and there is > example code and then user comments also. > For searching, we got at least pyhelp.cgi_. HTH, Stargaming .. _pyhelp.cgi: http://starship.python.net/crew/theller/pyhelp.cgi From Mail.To.Nathaniel at gmail.com Mon May 14 09:09:48 2007 From: Mail.To.Nathaniel at gmail.com (Mail.To.Nathaniel at gmail.com) Date: 14 May 2007 06:09:48 -0700 Subject: Beginner question: module organisation Message-ID: <1179148188.698342.317080@w5g2000hsg.googlegroups.com> Hello :) I am new to python and I don't have much expirience in object-oriented technologies neither. The problem is the following: I have to create a simple python template script that will always follow the same algorithm, let's say: - read a mesh - transform the mesh (let's say, refine) The last step should be a kind of a black box: - the same input data format - some algorithme inside - the same output data format A number of different refine methods should be implemented. The end- user must be able to write easily a new method and call it from the base script without any major change. Something like this would be a solution (no classes created, no OO programming): - a module defining REFINE1(mesh), REFINE2(mesh), ... - in the script: from MODULE import REFINE2 as REFINE REFINE(mesh) Is it a proper solution for this kind of problem? How would you implement this kind of task? From irstas at gmail.com Wed May 30 17:59:16 2007 From: irstas at gmail.com (irstas at gmail.com) Date: 30 May 2007 14:59:16 -0700 Subject: c[:]() In-Reply-To: References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> Message-ID: <1180562356.722411.327340@m36g2000hse.googlegroups.com> On May 31, 12:31 am, "Warren Stringer" wrote: > This is inconsistent: > > why does c[:][0]() work but c[:]() does not? > Why does c[0]() has exactly the same results as c[:][0]() ? > Moreover, c[:][0]() implies that a slice was invoked It's not inconsistent, but [:] probably does something different than you think it does. All it does is create a copy (not in general, but at least if c is a list or a tuple). Since in your example c is a tuple and tuples are immutable, making a copy of it is essentially useless. Why not just use the original? I.e. instead of c[:] you could just write c. That's why c[:][0]() has exactly the same effect as c[0] (), although the former is likely to be slightly slower. c[:]() tries to call the copied tuple. Tuples aren't callable. c[:][0]() calls the first element in the copied tuple, and that element happens to be callable. From pauldominic at nospam.supanet.com Fri May 11 05:25:57 2007 From: pauldominic at nospam.supanet.com (Paul D Ainsworth) Date: Fri, 11 May 2007 10:25:57 +0100 Subject: 4 byte integer Message-ID: <46443344$1_1@glkas0286.greenlnk.net> Greetings everyone. I'm a relative newcomer to python and I have a technical problem. I want to split a 32 bit / 4 byte unsigned integer into 4 separate byte variables according to the following logic: - bit numbers 0..7 byte 1 bit numbers 8..15 byte 2 bit numbers 16..23 byte 3 bit numbers 24..31 byte 4 Each of these byte variables to contain integer data from 0 to 255 (or 0 to FF in hex mode) I had thought that struct.unpack with an input message format of 'I' would be the way to do it, but its reporting an error that it doesn't want to accept an integer. Please can anyone advise? From larry.bates at websafe.com Mon May 21 09:13:54 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 21 May 2007 08:13:54 -0500 Subject: NEWBIE: Extending a For Statement. In-Reply-To: <1179749446.179064.222990@z28g2000prd.googlegroups.com> References: <1179749446.179064.222990@z28g2000prd.googlegroups.com> Message-ID: mosscliffe wrote: > I keep seeing examples of statements where it seems conditionals are > appended to a for statement, but I do not understand them. > > I would like to use one in the following scenario. > > I have a dictionary of > > mydict = { 1: 500, 2:700, 3: 800, 60: 456, 62: 543, 58: 6789} > > for key in mydict: > if key in xrange (60,69) or key == 3: > print key,mydict[key] > > I would like to have the 'if' statement as part of the 'for' > statement. > > I realise it is purely cosmetic, but it would help me understand > python syntax a little better. > > Thanks > > Richard > I find something like the following easy to read and easy to extend the contents of searchkeys in the future. searchkeys=range(60, 69) + [3] goodlist=[(k, v) for k, v in mydict.items() if k in searchkeys] for key, value in goodlist: print k,v -Larry From claird at lairds.us Sat May 26 11:31:15 2007 From: claird at lairds.us (Cameron Laird) Date: Sat, 26 May 2007 15:31:15 +0000 Subject: Ancient projectiles (was: Muzzle Velocity (was: High resolution sleep (Linux)) References: <1178274122.142071.91740@y5g2000hsa.googlegroups.com> Message-ID: <3f0mi4-mj8.ln1@lairds.us> In article , Dennis Lee Bieber wrote: . . . >> Did you know that the first military smokeless powder >> round was for the French Lebel? - It threw a bronze >> ball, and could punch through a single brick wall. >> > Well, extreme high speed wouldn't help for that -- just get a >surface splatter. Heavy and slower... (or some sort of solid core -- >depleted uranium with a teflon coating) . . . Hmmm; now you've got me curious. What *were* the first composite projectiles? Conceivably archers, catapultists, and slings would all have the potential to find advantage in use of coated dense projectiles; is there any evidence of such? There certainly was "mass production" of cheap projectiles (clay pellets, for example). How were stones chosen for large catapults? Was there a body of craft knowledge for balancing density and total mass in selection of stones? From ptmcg at austin.rr.com Fri May 11 23:54:17 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 11 May 2007 20:54:17 -0700 Subject: need help with python In-Reply-To: <1178941040.442541.61840@n59g2000hsh.googlegroups.com> References: <1178934447.719778.197150@h2g2000hsg.googlegroups.com> <1178937249.263856.191460@p77g2000hsh.googlegroups.com> <1178937707.004412.22360@q75g2000hsh.googlegroups.com> <1178939773.253366.79710@h2g2000hsg.googlegroups.com> <1178941040.442541.61840@n59g2000hsh.googlegroups.com> Message-ID: <1178942057.730403.97810@e65g2000hsc.googlegroups.com> On May 11, 10:37 pm, adamur... at hotmail.com wrote: > On May 11, 10:16 pm, Paul McGuire wrote: > > > > > > > On May 11, 9:41 pm, adamur... at hotmail.com wrote: > > > > On May 11, 9:34 pm, Paul McGuire wrote: > > > > > On May 11, 8:47 pm, adamur... at hotmail.com wrote: > > > > > > ya so im pretty much a newb to this whole python thing... its pretty > > > > > cool but i just started today and im already having trouble. i > > > > > started to use a tutorial that i found somewhere and i followed the > > > > > instructions and couldnt get the correct results. heres the code > > > > > stuff... > > > > > > temperature=input("what is the temperature of the spam?") > > > > > if temperature>50: > > > > > print "the salad is properly cooked." > > > > > else: > > > > > print "cook the salad some more." > > > > > > ya i was trying to do that but when i told it what the spams > > > > > temperature was, it just turned off... well it wasnt working at all at > > > > > first until i realized that i hadnt been following the instructions > > > > > completely correctly and that i was supposed to type that code up in a > > > > > notepad then save and open with python... so ya thats when it asked me > > > > > what temperature the spam was and i typed a number then it just closed > > > > > itself... im not really sure what went wrong... itd be real nice if > > > > > someone would be like a mentor or something... > > > > > Well, this list has a varying level of mentoring and newbie-tolerance, > > > > with more latitude for people who have made some effort to start with > > > > before posting things like "here's my homework problem, please send me > > > > the working code so I can hand it in." > > > > > I just ran your code interactively at the Python prompt, and it runs > > > > just fine. See? > > > > > >>> temperature=input("what is the temperature of the spam?") > > > > > what is the temperature of the spam?55>>> if temperature>50: > > > > > ... print "the salad is properly cooked." > > > > ... else: > > > > ... print "the salad is properly cooked." > > > > ... > > > > the salad is properly cooked. > > > > > I think the problem you are having is that, when you run your program > > > > by double-clicking on the xyz.py file in a file browser, the OS > > > > (Windows, I assume?) opens a separate console window, and runs the > > > > program, and then at the end of the program, CLOSES the window. I > > > > think your code is running just fine, I think your "the salad is > > > > whatever" messages get printed out, but afterward, your program ends, > > > > so the window closes before you can see how your salad turned out. > > > > > A simple workaround you can do is to add to the end of your program > > > > this statement: > > > > > input("") > > > > > This will cause the process to stop and wait for you to press the > > > > RETURN key, giving you time to stop and admire your salad results > > > > before closing the window. > > > > > One final note: many people post in a "write like I talk" style. This > > > > is okay while telling your story ("well it wasn't working at all at > > > > first..."), and the ee cummings all-lower-case is passable, but please > > > > drop the "ya"s. They are a verbal tic that may be okay in person, but > > > > do not translate at all to written posts. At least you don't say > > > > "like" every other word, and I thank you for that! :) > > > > > You can get a sense of other writing styles by reading through the > > > > comp.lang.python archives. I would also recommend that you might find > > > > more folks in the "just getting started" phase posting to the python- > > > > tutor mailing list (go tohttp://mail.python.org/mailman/listinfo/tutor), > > > > and you can skim through posts there for many introductory topics. > > > > > Good luck to you, and welcome to Python! > > > > > -- Paul > > > > well... i just discovered another of my mistakes. i was writing it in > > > notepad and not saving it as .py silly me... hoho ya that input thing > > > to get it to make u press enter worked tho... but only with that > > > one... ive got another one that i cant get to work even with the input > > > message to press enter. Sorry about the bad grammar. I'm used to > > > Myspace where no one gives a particular hoot about how you type. I > > > hope this is better. I will follow that link though. Thanks for the > > > help.- Hide quoted text - > > > > - Show quoted text - > > > It's possible that your next program has a runtime error, which will > > raise an exception that, if not handled using try-except, will cause > > the program to exit with a message (a message that will flash by and > > then disappear, as the window closes immediately). > > > One thing you should try is to run your python programs using a > > terminal window (sometimes called a "console window", or "the command > > line"). There are several ways to open one of these, the simplest on > > Windows is to click the "Start" button in the lower left corner, > > select "Run...", and enter the command "cmd". This will open up one > > of these white-letters-on-black-background windows for typing system > > commands. From this command line, you can run your Python programs by > > typing "python blah.py" where blah.py is the name of your Python > > script (which you created in Notepad and saved as blah.py. By running > > scripts this way, you will get to see *all* of your program output, > > without having the window close on you. (and please don't name all > > your scripts "blah.py", you should pick different names...) > > > Another thing you might try is downloading and installing SciTE for > > Windows - a free super-Notepad, with built-in support for editing *and > > running* Python scripts. Enter your Python code, save it as > > "whatever.py", then press F5 - the editor will split down the middle, > > keeping your program in the left half, and show the output messages > > and exceptions on the right. I find this much easier than going back > > and forth between Notepad and a terminal window. Other developer > > editors (often called "IDE"s for Interactive Development Environment) > > work similarly, such as pythonwin or IDLE - there are many others to > > choose from, but coming from Notepad, SciTE will not be a big step, > > but will move you forward. > > > -- Paul > > I was looking around in my Python folder and saw something to do with > that IDLE thing you were talking about. When I right clicked on a .py > file, it said edit with IDLE. I opened it and it was my code but each > line was a different color. It looked confusing so I decide to save > it for later. I knew that I could get the run thing to do the command > thing, but I had forgotten how to get the black window to come up. > > Ok. Well, I tried to us the cmd window. It says python: can't open > file 'area.py' I'm guessing that's not good. It won't open any of > my .py files. It's because of where I saved them. I can see how this > i going to work now. Ok so I'll just move them to the place that the > command line says. Now it still won't run my other program: > > # Area calculation program > > print "Welcome to the Area calculation program" > print "-------------" > print > > # Print out the menu: > print "Please select a shape:" > print "1 Rectangle" > print "2 Circle" > > # Get the user's choice: > shape = input("> ") > > # Calculate the area: > if shape == 1: > height = input("Please enter the height: ") > width = input("Please enter the width: ") > area = height*width > print "The area is", area > else: > radius = input("Please enter the radius: ") > area = 3.14*(radius**2) > print "The area is", area > > Perhaps it isn't written correctly. I don't think it likes the pound > signs. I'm not sure. But, I did go to that mailing list you > recommended. Thanks for that.- Hide quoted text - > > - Show quoted text - Again, this runs just fine for me. Here is the output when run within SciTE: Welcome to the Area calculation program ------------- Please select a shape: 1 Rectangle 2 Circle > 1 Please enter the height: 10 Please enter the width: 20 The area is 200 Welcome to the Area calculation program ------------- Please select a shape: 1 Rectangle 2 Circle > 2 Please enter the radius: 10 The area is 314.0 It seems like you are still struggling with mechanics of files, directories, etc., although your last post indicates you're making some progress there. Now for a better posting hint. When you tell us "Now it still won't run my other program", this isn't really enough to go on. What happens when you type in "python area.py" (assuming that you have used the 'cd' command to change your directory to the one containing area.py)? When you post that something doesn't work, copy/paste the error messages themselves into the post, and the actual Python code that you ran. But your problems do not seem to be Python problems at all, just OS and script execution mechanics. -- Paul From rrr at ronadam.com Fri May 25 13:47:06 2007 From: rrr at ronadam.com (Ron Adam) Date: Fri, 25 May 2007 12:47:06 -0500 Subject: webbrowser module bug? In-Reply-To: <46571707.8020702@cc.umanitoba.ca> References: <1180106384.198363.14120@p47g2000hsd.googlegroups.com> <46571707.8020702@cc.umanitoba.ca> Message-ID: Brian van den Broek wrote: > Ron Adam said unto the world upon 05/25/2007 12:28 PM: >> kyosohma at gmail.com wrote: >>> On May 24, 5:03 pm, Ron Adam wrote: >>>> Is anyone else having problems with the webbrowser module? >>>> >>>> Python 2.5.1c1 (release25-maint, Apr 12 2007, 21:00:25) >>>> [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 >>>> Type "help", "copyright", "credits" or "license" for more information. >>>> >>> import webbrowser >>>> >>> webbrowser.open('http://www.python.org') >>>> True >>>> >>> >>>> >>>> It opens firefox as expected, but the url is ... >>>> >>>> file:///home/ron/%22http://www.python.org%22 >>>> >>>> Which of course doesn't do what is expected. >>>> >>>> Any ideas? > > > >> It works for me on python 2.4 also, but not on later versions. >> >> Looks like I'll need to try to test the url at the point where it calls the >> browser from webbrowser.py. >> >> Can someone else test this on python 2.5? >> >> Ron > > Works fine for me on ubuntu 7.04 (fiesty) with Python 2.5.1c1, which > appear to be your set-up, too. > > Python 2.5.1c1 (release25-maint, Apr 12 2007, 21:00:25) > [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import webbrowser > >>> webbrowser.open('http://www.python.org') > True > >>> > > Best, > > Brian vdB Thanks, This is strange. Now I have no idea where to look. (?) I get the same incorrect results doing... ron at home:~$ python2.5 -m webbrowser 'http://www.python.org' Firefox attempts to open... file:///home/ron/%22http://www.python.org%22 The following works ok: ron at home:~$ firefox 'http://www.python.org' Works in the Ubuntu 2.4.4 dist (But blocks until the browser is closed.) Doesn't work in the Ubuntu 2.5.1c1 dist Python 2.5.1c1 (release25-maint, Apr 12 2007, 21:00:25) Doesn't work in the 2.5 maintenance branch Python 2.5 (release25-maint:54563, May 24 2007, 18:33:45) Works in the 2.6 branch (trunk) Works in the 3.0 branch I'll try uninstalling and reinstalling. The Ubuntu 2.5 dist. None of the svn versions are on the path, so it shouldn't be a path conflict with them. Ron From bbxx789_05ss at yahoo.com Tue May 15 21:50:23 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 15 May 2007 18:50:23 -0700 Subject: inherit from file and create stdout instance? In-Reply-To: <1179272294.058634.140760@k79g2000hse.googlegroups.com> References: <1179267498.154549.58370@h2g2000hsg.googlegroups.com> <1179270178.281061.34860@k79g2000hse.googlegroups.com> <1179272294.058634.140760@k79g2000hse.googlegroups.com> Message-ID: <1179280223.545538.81900@n59g2000hsh.googlegroups.com> >but it is frustrating me that if I try to inherit from file it >works fine for regular files I don't think that is correct characterization at all. What really happens is that when you inherit from file, your class works when you send the __init__ method a string, i.e. a filename. sys.stdout is not a string. Presumably, when you have a file object like sys.stdout already, you don't need to turn it into a file object, and therefore file's init() method is not defined to accept a file object. >Is it just a bad idea to inherit from file to >create a class to write to stdout or am I missing something? It seems to me that the very nature of a file object is to read and write to itself. Yet, in some cases you want your file object to be able to write to another file object. Why would you want your object to be a file object if you can't use any of its methods? From iltchevi at gmail.com Sun May 6 17:22:30 2007 From: iltchevi at gmail.com (ici) Date: 6 May 2007 14:22:30 -0700 Subject: c macros in python. In-Reply-To: <1178485280.394666.51970@n76g2000hsh.googlegroups.com> References: <1178485280.394666.51970@n76g2000hsh.googlegroups.com> Message-ID: <1178486550.469790.230290@y80g2000hsf.googlegroups.com> On May 7, 12:01 am, noagbodjivic... at gmail.com wrote: > Hey, > > I'm writing a script to generate code. I'm a bit tired of typing > outfile.write(....). Does python have a way to c-like macros? Every > instance of o(...) in the code will be replaced by outfile.write(...)? All in Python is pointer to object, and functions too, so o = outfile.write o("Some Text") You can redirect print to file also: print >> outfile, "Text", var1, var2[2:] or o = outfile print >> o, "Text", var1, var2[2:] :) From rw at smsnet.pl Fri May 25 06:38:19 2007 From: rw at smsnet.pl (Rob Wolfe) Date: 25 May 2007 03:38:19 -0700 Subject: psycopg2 & large result set In-Reply-To: <1180084593.130202.241550@q69g2000hsb.googlegroups.com> References: <1180084593.130202.241550@q69g2000hsb.googlegroups.com> Message-ID: <1180089499.011166.33300@o5g2000hsb.googlegroups.com> Jon Clements wrote: > Hi All. > > I'm using psycopg2 to retrieve results from a rather large query (it > returns 22m records); unsurprisingly this doesn't fit in memory all at > once. What I'd like to achieve is something similar to a .NET data > provider I have which allows you to set a 'FetchSize' property; it > then retrieves 'n' many rows at a time, and fetches the next 'chunk' > after you read past the end of the current chunk. I suppose I could > use Python for .NET or IronPython but I'd rather stick with CPython > 2.5 if possible. psycopg2 is DB-API 2.0 [1]_ compliant, so you can use ``fetchmany`` method and set ``cursor.arraysize`` accordingly. [1] .. http://www.python.org/dev/peps/pep-0249/ -- HTH, Rob From nagle at animats.com Fri May 18 13:44:26 2007 From: nagle at animats.com (John Nagle) Date: Fri, 18 May 2007 10:44:26 -0700 Subject: Python Web Programming - looking for examples of solid high-traffic sites In-Reply-To: <464da0a9$0$25891$426a74cc@news.free.fr> References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> <464da0a9$0$25891$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > John Nagle a ?crit : > >> Victor Kryukov wrote: >> >>> Hello list, >>> >>> our team is going to rewrite our existing web-site, which has a lot of >>> dynamic content and was quickly prototyped some time ago. >> >> ... >> >>> Our main requirement for tools we're going to use is rock-solid >>> stability. As one of our team-members puts it, "We want to use tools >>> that are stable, has many developer-years and thousands of user-years >>> behind them, and that we shouldn't worry about their _versions_." The >>> main reason for that is that we want to debug our own bugs, but not >>> the bugs in our tools. >> >> >> You may not be happy with Python, then. > > > John, I'm really getting tired of your systemic and totally > unconstructive criticism. If *you* are not happy with Python, by all > means use another language. Denying the existence of the problem won't fix it. Many of the basic libraries for web related functions do have problems. Even standard modules like "urllib" and "SSL" are buggy, and have been for years. Outside the standard modules, it gets worse, especially for ones with C components. Version incompatibility for extensions is a serious problem. That's reality. It's a good language, but the library situation is poor. Python as a language is better than Perl, but CPAN is better run than Cheese Shop. As a direct result of this, neither the Linux distro builders like Red Hat nor major hosting providers provide Python environments that just work. That's reality. John Nagle From ironfroggy at gmail.com Mon May 7 10:29:06 2007 From: ironfroggy at gmail.com (Calvin Spealman) Date: Mon, 7 May 2007 10:29:06 -0400 Subject: Unittest Automation Message-ID: <76fd5acf0705070729x7c96fc7bqe197fb799baac297@mail.gmail.com> I'm trying to find a better way, a shell one-liner, that I can use to recurse through my project, find all my test_ modules, aggregate the TestCase classes into a suite, and run all my tests. Basically, what py.test does out of the box. Why am I having such trouble doing it? -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From walter at livinglogic.de Fri May 4 09:31:50 2007 From: walter at livinglogic.de (=?UTF-8?B?V2FsdGVyIETDtnJ3YWxk?=) Date: Fri, 04 May 2007 15:31:50 +0200 Subject: Replacement for HTMLGen? In-Reply-To: <463a70b1$0$16345$88260bb3@free.teranews.com> References: <463a70b1$0$16345$88260bb3@free.teranews.com> Message-ID: <463B35C6.6080905@livinglogic.de> Joshua J. Kugler wrote: > I realize that in today's MVC-everything world, the mere mention of > generating HTML in the script is near heresy, but for now, it's what I ened > to do. :) > > That said, can someone recommend a good replacement for HTMLGen? I've found > good words about it (http://www.linuxjournal.com/article/2986), but every > reference to it I find points to a non-existant page > (http://starship.python.net/lib.html is 404, > http://www.python2.net/lib.html is not responding, > http://starship.python.net/crew/friedrich/HTMLgen/html/main.html is 404) > Found http://www.python.org/ftp/python/contrib-09-Dec-1999/Network/, but > that seems a bit old. > > I found http://dustman.net/andy/python/HyperText, but it's not listed in > Cheeseshop, and its latest release is over seven years ago. Granted, I > know HTML doesn't change (much) but it's at least nice to know something > you're going to be using is maintained. > > Any suggestions or pointers? You might try XIST: http://www.livinglogic.de/Python/xist/ Hope that helps! Servus, Walter From g_teodorescu at yahoo.com Mon May 14 04:36:22 2007 From: g_teodorescu at yahoo.com (g_teodorescu at yahoo.com) Date: 14 May 2007 01:36:22 -0700 Subject: How to do basic CRUD apps with Python In-Reply-To: <1179098458.333666.307750@e65g2000hsc.googlegroups.com> References: <1179098458.333666.307750@e65g2000hsc.googlegroups.com> Message-ID: <1179131782.129611.294190@h2g2000hsg.googlegroups.com> walterbyrd a scris: > With PHP, libraries, apps, etc. to do basic CRUD are everywhere. Ajax > and non-Ajax solutions abound. > > With Python, finding such library, or apps. seems to be much more > difficult to find. > > I thought django might be a good way, but I can not seem to get an > answer on that board. > > I would like to put together a CRUD grid with editable/deletable/ > addable fields, click on the headers to sort. Something that would > sort-of looks like an online spreadsheet. It would be nice if the > fields could be edited in-line, but it's not entirely necessary. > > Are there any Python libraries to do that sort of thing? Can it be > done with django or cherrypy? > > Please, don't advertise your PHP/Ajax apps. SqlAlchemy-SqlSoup Example: # SqlSoup. CRUD with one table from sqlalchemy.ext.sqlsoup import SqlSoup # connection: 'postgres://user:password at address:port/db_name' db = SqlSoup('postgres://postgres:postgres at localhost:5432/testdb') # read data person = db.person.select() print person # index is not the same with primary key !!! print person[0].firstname # write in column firstname person[0].firstname = "George" # effective write db.flush() print person[0] print db.person.count() for i in range(0, db.person.count()): print person[i] db.person.insert(id=1000, firstname='Mitu') db.flush # after insert, reload mapping: person = db.person.select() # delete: # record select mk = db.person.selectone_by(id=1000) # delete db.delete(mk) db.flush() person = db.person.select() print person """ FROM DOCUMENTATION: ======= SqlSoup ======= Introduction SqlSoup provides a convenient way to access database tables without having to declare table or mapper classes ahead of time. Suppose we have a database with users, books, and loans tables (corresponding to the PyWebOff dataset, if you're curious). For testing purposes, we'll create this db as follows: >>> from sqlalchemy import create_engine >>> e = create_engine('sqlite:///:memory:') >>> for sql in _testsql: e.execute(sql) #doctest: +ELLIPSIS <... Creating a SqlSoup gateway is just like creating an SqlAlchemy engine: >>> from sqlalchemy.ext.sqlsoup import SqlSoup >>> db = SqlSoup('sqlite:///:memory:') or, you can re-use an existing metadata: >>> db = SqlSoup(BoundMetaData(e)) You can optionally specify a schema within the database for your SqlSoup: # >>> db.schema = myschemaname Loading objects Loading objects is as easy as this: >>> users = db.users.select() >>> users.sort() >>> users [MappedUsers(name='Joe Student',email='student at example.edu', password='student',classname=None,admin=0), MappedUsers(name='Bhargan Basepair',email='basepair at example.edu', password='basepair',classname=None,admin=1)] Of course, letting the database do the sort is better (".c" is short for ".columns"): >>> db.users.select(order_by=[db.users.c.name]) [MappedUsers(name='Bhargan Basepair',email='basepair at example.edu', password='basepair',classname=None,admin=1), MappedUsers(name='Joe Student',email='student at example.edu', password='student',classname=None,admin=0)] Field access is intuitive: >>> users[0].email u'student at example.edu' Of course, you don't want to load all users very often. Let's add a WHERE clause. Let's also switch the order_by to DESC while we're at it. >>> from sqlalchemy import or_, and_, desc >>> where = or_(db.users.c.name=='Bhargan Basepair', db.users.c.email=='student at example.edu') >>> db.users.select(where, order_by=[desc(db.users.c.name)]) [MappedUsers(name='Joe Student',email='student at example.edu', password='student',classname=None,admin=0), MappedUsers(name='Bhargan Basepair',email='basepair at example.edu', password='basepair',classname=None,admin=1)] You can also use the select...by methods if you're querying on a single column. This allows using keyword arguments as column names: >>> db.users.selectone_by(name='Bhargan Basepair') MappedUsers(name='Bhargan Basepair',email='basepair at example.edu', password='basepair',classname=None,admin=1) Select variants All the SqlAlchemy Query select variants are available. Here's a quick summary of these methods: * get(PK): load a single object identified by its primary key (either a scalar, or a tuple) * select(Clause, **kwargs): perform a select restricted by the Clause argument; returns a list of objects. The most common clause argument takes the form "db.tablename.c.columname == value." The most common optional argument is order_by. * select_by(**params): select methods ending with _by allow using bare column names. (columname=value) This feels more natural to most Python programmers; the downside is you can't specify order_by or other select options. * selectfirst, selectfirst_by: returns only the first object found; equivalent to select(...)[0] or select_by(...)[0], except None is returned if no rows are selected. * selectone, selectone_by: like selectfirst or selectfirst_by, but raises if less or more than one object is selected. * count, count_by: returns an integer count of the rows selected. See the SqlAlchemy documentation for details: * http://www.sqlalchemy.org/docs/datamapping.myt#datamapping_query for general info and examples, * http://www.sqlalchemy.org/docs/sqlconstruction.myt for details on constructing WHERE clauses. Modifying objects Modifying objects is intuitive: >>> user = _ >>> user.email = 'basepair+nospam at example.edu' >>> db.flush() (SqlSoup leverages the sophisticated SqlAlchemy unit-of-work code, so multiple updates to a single object will be turned into a single UPDATE statement when you flush.) To finish covering the basics, let's insert a new loan, then delete it: >>> book_id = db.books.selectfirst(db.books.c.title=='Regional Variation in Moss').id >>> db.loans.insert(book_id=book_id, user_name=user.name) MappedLoans(book_id=2,user_name='Bhargan Basepair',loan_date=None) >>> db.flush() >>> loan = db.loans.selectone_by(book_id=2, user_name='Bhargan Basepair') >>> db.delete(loan) >>> db.flush() You can also delete rows that have not been loaded as objects. Let's do our insert/delete cycle once more, this time using the loans table's delete method. (For SQLAlchemy experts: note that no flush() call is required since this delete acts at the SQL level, not at the Mapper level.) The same where-clause construction rules apply here as to the select methods. >>> db.loans.insert(book_id=book_id, user_name=user.name) MappedLoans(book_id=2,user_name='Bhargan Basepair',loan_date=None) >>> db.flush() >>> db.loans.delete(db.loans.c.book_id==2) You can similarly update multiple rows at once. This will change the book_id to 1 in all loans whose book_id is 2: >>> db.loans.update(db.loans.c.book_id==2, book_id=1) >>> db.loans.select_by(db.loans.c.book_id==1) [MappedLoans(book_id=1,user_name='Joe Student',loan_date=datetime.datetime(2006, 7, 12, 0, 0))] Joins Occasionally, you will want to pull out a lot of data from related tables all at once. In this situation, it is far more efficient to have the database perform the necessary join. (Here we do not have "a lot of data," but hopefully the concept is still clear.) SQLAlchemy is smart enough to recognize that loans has a foreign key to users, and uses that as the join condition automatically. >>> join1 = db.join(db.users, db.loans, isouter=True) >>> join1.select_by(name='Joe Student') [MappedJoin(name='Joe Student',email='student at example.edu', password='student',classname=None,admin=0,book_id=1, user_name='Joe Student',loan_date=datetime.datetime(2006, 7, 12, 0, 0))] If you're unfortunate enough to be using MySQL with the default MyISAM storage engine, you'll have to specify the join condition manually, since MyISAM does not store foreign keys. Here's the same join again, with the join condition explicitly specified: >>> db.join(db.users, db.loans, db.users.c.name==db.loans.c.user_name, isouter=True) You can compose arbitrarily complex joins by combining Join objects with tables or other joins. Here we combine our first join with the books table: >>> join2 = db.join(join1, db.books) >>> join2.select() [MappedJoin(name='Joe Student',email='student at example.edu', password='student',classname=None,admin=0,book_id=1, user_name='Joe Student',loan_date=datetime.datetime(2006, 7, 12, 0, 0), id=1,title='Mustards I Have Known',published_year='1989',authors='Jones')] If you join tables that have an identical column name, wrap your join with "with_labels", to disambiguate columns with their table name: >>> db.with_labels(join1).select() [MappedUsersLoansJoin(users_name='Joe Student', users_email='student at example.edu',users_password='student', users_classname=None,users_admin=0,loans_book_id=1, loans_user_name='Joe Student', loans_loan_date=datetime.datetime(2006, 7, 12, 0, 0))] Advanced Use Mapping arbitrary Selectables SqlSoup can map any SQLAlchemy Selectable with the map method. Let's map a Select object that uses an aggregate function; we'll use the SQLAlchemy Table that SqlSoup introspected as the basis. (Since we're not mapping to a simple table or join, we need to tell SQLAlchemy how to find the "primary key," which just needs to be unique within the select, and not necessarily correspond to a "real" PK in the database.) >>> from sqlalchemy import select, func >>> b = db.books._table >>> s = select([b.c.published_year, func.count('*').label('n')], from_obj=[b], group_by=[b.c.published_year]) >>> s = s.alias('years_with_count') >>> years_with_count = db.map(s, primary_key=[s.c.published_year]) >>> years_with_count.select_by(published_year='1989') [MappedBooks(published_year='1989',n=1)] Obviously if we just wanted to get a list of counts associated with book years once, raw SQL is going to be less work. The advantage of mapping a Select is reusability, both standalone and in Joins. (And if you go to full SQLAlchemy, you can perform mappings like this directly to your object models.) Raw SQL You can access the SqlSoup's engine attribute to compose SQL directly. The engine's execute method corresponds to the one of a DBAPI cursor, and returns a ResultProxy that has fetch methods you would also see on a cursor. >>> rp = db.engine.execute('select name, email from users order by name') >>> for name, email in rp.fetchall(): print name, email Bhargan Basepair basepair+nospam at example.edu Joe Student student at example.edu You can also pass this engine object to other SQLAlchemy constructs. """ From python-url at phaseit.net Mon May 21 08:48:54 2007 From: python-url at phaseit.net (Gabriel Genelli) Date: Mon, 21 May 2007 12:48:54 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (May 21) Message-ID: QOTW: "A java class full of static methods translates to a python module populated with functions in general." - Arnaud Delobelle "Neurons are far more valuable than disk space, screen lines, or CPU cycles." - Ben Finney How do people install Python and libraries in a server without root access? http://groups.google.com/group/comp.lang.python/browse_thread/thread/9422609e56653ccd Inference of column data types in csv files, accomodation for wrong items and even Bayesian inference can improve trust in computed results: http://groups.google.com/group/comp.lang.python/browse_thread/thread/29e7bcb8222f6cfc A proposed change on dict and set documented behavior highlights the differences between PHP style for docs and Python's: http://groups.google.com/group/comp.lang.python/browse_thread/thread/5a5be5d1b9c619cd You refactored code, yet your pickled instances still use the old class names and so refuse to load. Here are ways to load them successfully again: http://groups.google.com/group/comp.lang.python/browse_thread/thread/e3dda81818a1be18 The ever-lasting question "Which is the best web framework?" as an excuse to analyze some high traffic sites and its architectures, plus insights from Alex Martelli: http://groups.google.com/group/comp.lang.python/browse_thread/thread/6b80918453856257 John Nagle captures Python in a single taxonomic paragraph, and Alex Martelli details his GUI preferences, in a thread valuable for more than just the beginners its original poster might have imagined: http://groups.google.com/group/comp.lang.python/browse_thread/thread/c755490c2736b64f/ Comparing Python to other languages, plus "popularity" statistics from Google: http://groups.google.com/group/comp.lang.python/browse_thread/thread/b1d18c57d75eff58 Don't use os.close on sockets directly: http://groups.google.com/group/comp.lang.python/browse_thread/thread/6e724f0ab3f3464f One of the longest threads in history, started last week and still going: PEP 3131, allowing non-ASCII identifiers. http://groups.google.com/group/comp.lang.python/browse_thread/thread/ebb6bbb9cc833422 How long does it take to "uniquify" a collection? http://groups.google.com/group/pl.comp.lang.python/msg/dc3618b18e63f3c9 There are many ways to treat data (packaged here in a file) as code. Some of them appear in this thread: http://groups.google.com/group/comp.lang.python/browse_thread/thread/1d7517509be050c3/ How *does* a stylish Pythoneer emit the binary representation of an integer? http://groups.google.com/group/comp.lang.python/browse_thread/thread/90911d344c0f08d/ ======================================================================== 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. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, Planet Python indexes much of the universe of Pybloggers. http://www.planetpython.org/ The Python Papers aims to publish "the efforts of Python enthusiats". http://pythonpapers.org/ 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 bignose+hates-spam at benfinney.id.au Sun May 20 00:27:52 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 20 May 2007 14:27:52 +1000 Subject: What is deployment? References: <68m4i4-9a4.ln1@lairds.us> <7x4pm8tf6v.fsf@ruckus.brouhaha.com> Message-ID: <87646o3yrb.fsf@benfinney.id.au> Paul Rubin writes: > claird at lairds.us (Cameron Laird) writes: > > all those things that happen after narrow-sense installation are > > still part of "deployment". > > Deployment also refers to pre-installation issues, like buying the > hardware that you're going to install on. Agreed. I usually discuss "deployment" as meaning "everything required to take something from the point of working in a vendor's lab environment, to an actual working installation in a production environment". -- \ "Sunday School: A prison in which children do penance for the | `\ evil conscience of their parents." -- Henry L. Mencken | _o__) | Ben Finney From krypto.wizard at gmail.com Mon May 14 19:06:02 2007 From: krypto.wizard at gmail.com (Krypto) Date: 14 May 2007 16:06:02 -0700 Subject: Python Power Point Slides Message-ID: <1179183962.824333.31730@q75g2000hsh.googlegroups.com> Hi, I want to give a short presentation in my group about benefits of python, why should one use python and some basic starting information about python, about its data type, etc. Can somebody point me to the right references on the web. I have searched a lot and I do get quite a few but I thought to check on newsgroup for a better presentation, or if you have prepared any, can you please share it. Thanks From gagsl-py2 at yahoo.com.ar Sun May 27 12:01:37 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 27 May 2007 13:01:37 -0300 Subject: PHP5 programmer learning Python References: <1180280496.946434.26760@q69g2000hsb.googlegroups.com> Message-ID: En Sun, 27 May 2007 12:41:36 -0300, romiro escribi?: > Anyway, my first question was if anyone knows of a tutorial that > focuses on PHP -> Python learning, in such that there might be a block > of PHP code alongside an example of how to do the same thing in I don't know of a specific PHP->Python tutorial, but "Instant Python" would give you a brief tour, and "Dive into Python" is a good book for people with some previous programming background. Both should be easy to find using Google. -- Gabriel Genellina From orsenthil at gmail.com Sat May 19 08:38:37 2007 From: orsenthil at gmail.com (Phoe6) Date: 19 May 2007 05:38:37 -0700 Subject: RFC - n-puzzle.py In-Reply-To: <1179566627.583978.304810@n59g2000hsh.googlegroups.com> References: <1179530104.645902.135250@p77g2000hsh.googlegroups.com> <1179566627.583978.304810@n59g2000hsh.googlegroups.com> Message-ID: <1179578316.956894.164140@y80g2000hsf.googlegroups.com> On May 19, 2:23 pm, Raymond Hettinger wrote: > On May 18, 4:15 pm, Phoe6 wrote: > > I would like to request a code and design review of one of my program. > > n-puzzle.pyhttp://sarovar.org/snippet/detail.php?type=snippet&id=83 > > Nice job, this doesn't look like a beginner program at all. Thanks Raymond. :-) > For feedback, here's a few nits: Yes, I made changes in them all. Thanks for the list comprehension pointer, I missed it. > > Instead of: > short_path = mdists[0] > if mdists.count(short_path) > 1: > write: > short_path = mdists[0] > if short_path in mdists[1:]: I would like to understand the difference between the two if statements. I had used count method, to signify the meaning that, if the least distance occurs more then proceed with block. How is 'in' with list[1:] an advantage? If it is. > Instead of: > if node != 0: > write: > if node: Here again, I went by the meaning of non-zero value nodes and made comparision with node != 0. Just in case, the n-states were represented by '0', '1', '2', '3', I would have gone for node != '0' sticking to the meaning. I think, I should aid it with a comment, otherwise might get confused in the future. Thanks a lot, Raymond. :-) -- Senthil http://uthcode.sarovar.org From maric at aristote.info Thu May 17 12:15:06 2007 From: maric at aristote.info (Maric Michaud) Date: Thu, 17 May 2007 18:15:06 +0200 Subject: An expression that rebinds a variable? In-Reply-To: <1179411429.536764.5620@q75g2000hsh.googlegroups.com> References: <1179411429.536764.5620@q75g2000hsh.googlegroups.com> Message-ID: <464C7F8A.60403@aristote.info> GreenH a ?crit : > Can I know what kind of expressions rebind variables, of course unlike > in C, assignments are not expressions (for a good reason) > So, eval(expr) should bring about a change in either my global or > local namespace, where 'expr' is the expression > For global scope you could use globals().__setitem__('x', 5) but it's not possible in local scope because the dict returned by locals() in function is not where the local variables are really stored. So the preferred way is to use : In [39]: exec "x=5" which the same as : In [40]: eval(compile('x=5', '', 'exec')) -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 4 26 88 00 97 Mobile: +33 6 32 77 00 21 From mail at timgolden.me.uk Tue May 22 08:31:09 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 22 May 2007 13:31:09 +0100 Subject: Installing Python in a path that contains a blank In-Reply-To: <588D53831C701746A2DF46E365C018CE01D2CAA4@LITEXETSP001.etrsouth.corp.entergy.com> References: <588D53831C701746A2DF46E365C018CE01D2CAA4@LITEXETSP001.etrsouth.corp.entergy.com> Message-ID: <4652E28D.9030600@timgolden.me.uk> Hamilton, William wrote: > There's also short filename substitution. "C:\Documents and Settings\foo" > can be replaced with "C:\docume~1\foo". In general, you take the first six > non-space characters and append "~" to it. I've never run into a > situation where was anything other than 1, but I'm pretty sure that > you increment it if you have multiple files/directorys in the same directory > that have the same first six non-space characters. This should work on any > Windows long-filename system where you need 8.3 filenames for backwards > compatibility. Rather than trying to second-guess, you can ask Windows itself to tell you what the short name is for a given long name: import win32api path_name = "C:\Documents and Settings\goldent" print win32api.GetShortPathName (path_name) (and, yes, there is a corresponding GetLongPathName with an additional Unicode version GetLongPathNameW) TJG From jzgoda at o2.usun.pl Sun May 13 15:07:05 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Sun, 13 May 2007 21:07:05 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46473267$0$31532$9b622d9e@news.freenet.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis napisa?(a): > So, please provide feedback, e.g. perhaps by answering these > questions: > - should non-ASCII identifiers be supported? why? No, because "programs must be written for people to read, and only incidentally for machines to execute". Using anything other than "lowest common denominator" (ASCII) will restrict accessibility of code. This is not a literature, that requires qualified translators to get the text from Hindi (or Persian, or Chinese, or Georgian, or...) to Polish. While I can read the code with Hebrew, Russian or Greek names transliterated to ASCII, I would not be able to read such code in native. > For some languages, common transliteration systems exist (in particular, > for the Latin-based writing systems). For other languages, users have > larger difficulties to use Latin to write their native words. This is one of least disturbing difficulties when it comes to programming. -- Jarek Zgoda http://jpa.berlios.de/ From xah at xahlee.org Wed May 23 12:15:17 2007 From: xah at xahlee.org (Xah Lee) Date: 23 May 2007 09:15:17 -0700 Subject: The Concepts and Confusions of Prefix, Infix, Postfix and Fully Functional Notations Message-ID: <1179936917.652372.24780@q69g2000hsb.googlegroups.com> The Concepts and Confusions of Prefix, Infix, Postfix and Fully Functional Notations Xah Lee, 2006-03-15 [This articles explains away the confusion of common terms for notation systems used in computer languages: prefix, infix, postfix, algebraic, functional. These notation's relation to the concept of operators. These are explained using examples from LISP, Mathematica, and imperative languages. Then, it discuss some problems of purely nested notation.] In LISP languages, they use a notation like ?(+ 1 2)? to mean ?1+2?. Likewise, they write ?(if test this that)? to mean ?if (test) {this} else {that}?. LISP codes are all of the form ?(a b c ...)?, where the a b c themselves may also be of that form. There is a wide misunderstanding that this notation being ?prefix notation?. In this article, i'll give some general overview of the meanings of Algebraic Notation and prefix, infix, postfix notations, and explain how LISP notation is a Functional Notation and is not a so-called prefix notation or algebraic notation. The math notation we encounter in school, such as ?1+2?, is called Infix Algebraic Notation. Algebraic notations have the concept of operators, meaning, symbols placed around arguments. In algebraic infix notation, different symbols have different stickiness levels defined for them. e.g. ?3+2*5>7? means ?(3+(2*5))>7?. The stickiness of operator symbols is normally called ?Operator Precedence?. It is done by giving a order specification for the symbols, or equivalently, give each symbol a integer index, so that for example if we have ?a?b?c?, we can unambiguously understand it to mean one of ?(a?b)?c? or ?a?(b?c)?. In a algebraic postfix notation known as Polish Notation, there needs not to have the concept of Operator Precedence. For example, the infix notation ?(3+(2*5))>7? is written as ?3 2 5 * + 7 >?, where the operation simply evaluates from left to right. Similarly, for a prefix notation syntax, the evaluation goes from right to left, as in ?> 7 + * 5 2 3?. While functional notations, do not employ the concept of Operators, because there is no operators. Everything is a syntactically a ?function?, written as f(a,b,c...). For example, the same expression above is written as ?>( +(3, *(2,5)), 7)? or ?greaterThan( plus(3, times(2,5)), 7)?. For lisps in particular, their fully functional notation is historically termed sexp (short for S-Expression, where S stands for Symbolic). It is sometimes known as Fully Parenthesized Notation. For example, in lisp it would be (f a b c ...). In the above example it is: ?(> (+ 3 (* 2 5)) 7)?. The common concepts of ?prefix, postfix, infix? are notions in algebraic notations only. Because in Full Functional Notation, there are no operators, therefore no positioning to talk about. A Function's arguments are simply explicitly written out inside a pair of enclosing delimiters. Another way to see that lisp notation are not ?pre? anything, is by realizing that the ?head? f in (f a b c) can be defined to be placed anywhere. e.g. (a b c f) or even (a f b c), and its syntax syntactical remains the same. In the language Mathematica, f(a b c) would be written as f[a,b,c] where the argument enclosure symbols is the square bracket instead of parenthesis, and argument separator is comma instead of space, and the function symbol (aka ?head?) is placed in outside and in front of the argument enclosure symbols. The reason for the misconception that lisp notations are ?prefix? is because the ?head? appears as the first element in the enclosed parenthesis. Such use of the term ?prefix? is a confusion engenderer because the significance of the term lies in algebraic notation systems that involves the concept of operators. A side note: the terminology ?Algebraic? Notation is a misnomer. It seems to imply that such notations have something to do with the branch of math called algebra while other notation systems do not. The reason the name Algebraic Notation is used because when the science of algebra was young, around 1700s mathematicians are dealing with equations using symbols like ?+ ? =? written out similar to the way we use them today. This is before the activities of systematic investigation into notation systems as necessitated in the studies of logic in 1800s or computer languages in 1900s. So, when notation systems are actually invented, the conventional way of infixing ?+ ? =? became known as algebraic because that's what people think of when seeing them. -------- This post is part of a 3-part exposition: ?The Concepts and Confusions of Prefix, Infix, Postfix and Fully Functional Notations?, ?Prefix, Infix, Postfix notations in Mathematica?, ?How Purely Nested Notation Limits The Language's Utility?, available at: http://xahlee.org/UnixResource_dir/writ/notations.html Xah xah at xahlee.org ? http://xahlee.org/ From kakeez at hotmail.com Fri May 25 11:00:56 2007 From: kakeez at hotmail.com (Karim Ali) Date: Fri, 25 May 2007 15:00:56 +0000 Subject: Reading a file and resuming reading. Message-ID: Hrvoje Niksic wrote: >If you open the file in binary mode, you can easily keep track of the >position in file: > >bytepos = 0 >with file(filename) as f: > for line in f: > ... process line ... > bytepos += len(line) > >If you need to restart the operation, simply seek to the previously >known position: > ># restart with old bytyepos >with file(filename) as f: > f.seek(bytepos) > for line in f: > ... process line ... > bytepos += len(line) >-- Thanks! This works perfectly. I did not know you can iterate directly using the file handle! Karim _________________________________________________________________ Windows Live Hotmail, with safety bar colour coding, helps identify suspicious mail before it takes your daughter out on a date. Upgrade today for a better look. www.newhotmail.ca?icid=WLHMENCA152 From rajarshi.guha at gmail.com Sat May 26 10:44:43 2007 From: rajarshi.guha at gmail.com (Rajarshi) Date: 26 May 2007 07:44:43 -0700 Subject: 0 == False but [] != False? In-Reply-To: <1179982400.412340.178710@g4g2000hsf.googlegroups.com> References: <1179982400.412340.178710@g4g2000hsf.googlegroups.com> Message-ID: <1180190683.374048.186970@q69g2000hsb.googlegroups.com> Thanks a lot for all the responses From http Sun May 13 19:29:02 2007 From: http (Paul Rubin) Date: 13 May 2007 16:29:02 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <7x4pmg716p.fsf@ruckus.brouhaha.com> Alexander Schmolck writes: > Plenty of programming languages already support unicode identifiers, Could you name a few? Thanks. From vatamane at gmail.com Wed May 9 06:05:32 2007 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 9 May 2007 03:05:32 -0700 Subject: view workspace, like in MatLab ? In-Reply-To: References: Message-ID: <1178705132.357431.288150@l77g2000hsb.googlegroups.com> On May 9, 5:00 am, Stef Mientki wrote: > hello, > > is there a function / library / IDE that displays all the user defined variables, > like the workspace in MatLab ? > > thanks, > Stef Mientki Stef, In the Python interactive prompt you can try: [var for var in dir() if not (var.startswith('_') or var=='var')] Example: ------------------- >>> a=10 >>> b=20 >>> [var for var in dir() if not (var.startswith('_') or var=='var')] ['a', 'b'] >>> ------------------- Hope that helps, Nick Vatamaniuc From gagsl-py2 at yahoo.com.ar Tue May 15 21:43:49 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 15 May 2007 22:43:49 -0300 Subject: inherit from file and create stdout instance? References: <1179267498.154549.58370@h2g2000hsg.googlegroups.com> <1179270178.281061.34860@k79g2000hse.googlegroups.com> <1179272294.058634.140760@k79g2000hse.googlegroups.com> Message-ID: En Tue, 15 May 2007 20:38:14 -0300, MisterPete escribi?: > I could make wrappers around all of the file methods but that kind > of defeats the purpose of inheriting from file. It's kind of odd to > inherit from file but then keep a file object (although then it would > at least pass any isinstance(object, file) tests at least) and > overwrite every single method. I'd prefer that I inherit from file > and just get flush and next and everything for free (and any new > methods if they were added). Instead of inheriting from file, you can delegate to a file instance. Python makes it rather easy: py> import sys py> py> class Output: ... file = None ... verbosity = 1 ... def __init__(self, file=None, verbosity=1): ... if file is None: file = sys.stdout ... self.file = file ... self.verbosity = verbosity ... def write(self, string, messageVerbosity=1): ... if messageVerbosity <= self.verbosity: ... self.file.write(string) ... def __getattr__(self, name): ... return getattr(self.file, name) ... def __setattr__(self, name, value): ... if name in dir(self): self.__dict__[name] = value ... else: setattr(self.file, name, value) ... py> f1 = Output(verbosity=100) py> f1.write("Console output\n") Console output py> f1.flush() py> print f1.isatty() True py> print f1.verbosity 100 py> f1.verbosity = 5 py> print f1.verbosity 5 py> py> f2 = Output(open("aaa.txt","w")) py> f2.write("Goes to another file\n") py> f2.flush() py> print f2.isatty() False py> print f2.tell() 22 py> f2.close() As you can see, I'm using file methods and attributes that I didn't redefine explicitely. See the section "Customizing attribute access" on the Python Reference Manual about __getattr__ and __setattr__ -- Gabriel Genellina From thorsten at thorstenkampe.de Tue May 15 09:05:12 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 15 May 2007 14:05:12 +0100 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <464996b9$0$10193$9b4e6d93@newsspool4.arcor-online.net> <4649a72d$0$10186$9b4e6d93@newsspool4.arcor-online.net> <4649aca1$0$23148$9b4e6d93@newsspool1.arcor-online.net> Message-ID: * Ren? Fleschenberg (Tue, 15 May 2007 14:50:41 +0200) > Thorsten Kampe schrieb: > > Just by repeating yourself you don't make your point more valid. > > You are doing just the same. Your argument that encouraging code-sharing > is not a worthwhile goal is an ideologic one, just as the opposite > argument is, too. No, if you claim that something by itself is good and has to be encouraged then you are obliged to prove or give arguments for that. If I say that I don't think that something in general but only in special case is a good thing that should be encouraged then I don't have to proof or give special arguments for that. If you say there is a man in the moon and I say there isn't then you have to proof you point, not me. > (I do think that code sharing is very different from > sharing of material goods). That is why I do not think it makes alot of > sense to argue about it. If you don't consider code sharing to be a > value of its own, then that is of course also not an argument against > this PEP. I just happen to have different beliefs. Exactly. So whether this PEP encourages or discourages code sharing (and I don't think it does either) has nothing to do with the value of this PEP. From saif.shakeel at gmail.com Tue May 8 07:46:10 2007 From: saif.shakeel at gmail.com (saif.shakeel at gmail.com) Date: 8 May 2007 04:46:10 -0700 Subject: replacing string in xml file In-Reply-To: <46405F73.3080501@web.de> References: <1178623414.092046.91120@y5g2000hsa.googlegroups.com> <46405F73.3080501@web.de> Message-ID: <1178624770.794888.198450@e65g2000hsc.googlegroups.com> On May 8, 4:30 pm, Stefan Behnel wrote: > saif.shak... at gmail.com schrieb: > > > > > > > Hi, > > I need to replace a string in xml file with something else.Ex > > > - > > rate > > rate > > > > > > > > - > > > Here i have opened an xml > > file(small part is pasted here).I want to replace the word 'localId' > > with 'dataPackageID' wherever it comes in xml file.I tried this but > > didnt work: > > > import sys > > > file_input = raw_input("Enter The ODX File Path:") > > input_xml = open(file_input,'r') > > This should say > > input_xml = open(file_input,'r').read() > > > input_xml.replace('localId','dataPackageId') > > This gives error ---> AttributeError: 'file' > > object has no attribute 'replace' > > Can someone help me . > > Thanks > > Stefan- Hide quoted text - > > - Show quoted text - There is no error now,but the string is not being replaced,It remains the same,should we save the opened file or something From elventear at gmail.com Tue May 1 13:48:35 2007 From: elventear at gmail.com (elventear) Date: 1 May 2007 10:48:35 -0700 Subject: Problem with inspect.getfile Message-ID: <1178041715.206440.134530@y80g2000hsf.googlegroups.com> Hello, I am trying to use someone else's module that makes use of inspect.getsourcelines. The code was not working for me, so I have been debugging to see why it is not working. I have reduced my problem to getting the wrong file path in the getfile->return object.co_filename call. Basically the path I get is: "/Users/elventear/Documents/UTMEM/Projects/geotools/parsers/parser.py" When the correct path should be: "/Users/elventear/Documents/UTMEM/Projects/packages/geotools/parsers/ parser.py" Finally my PYTHONPATH contains: "/Users/elventear/Documents/UTMEM/Projects/packages" So basically, I am able to resolve correctly the package from withing Python, I don't know why there is this confusion about the filename that contains my objects and methods. Any ideas on how to correct this would be appreciated. This is under MacOSX 10.4.9, Python 2.5 (Build from Fink). Thanks! From grante at visi.com Thu May 17 10:34:49 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 17 May 2007 14:34:49 -0000 Subject: Declaring variables References: <1179334649.990688.73320@o5g2000hsb.googlegroups.com> <134mea4o0svae73@corp.supernews.com> <1179342961.494519.103620@u30g2000hsc.googlegroups.com> Message-ID: <134oq09mlrqju81@corp.supernews.com> On 2007-05-16, HMS Surprise wrote: > No haven't had to endure Pascal. Mostly C/C++, Tcl, and assembler. I must have you mixed up with somebody else who recently mentioned having Pascal as their first real language. -- Grant Edwards grante Yow! It's OKAY -- I'm an at INTELLECTUAL, too. visi.com From moishyyehuda at gmail.com Tue May 15 20:26:54 2007 From: moishyyehuda at gmail.com (moishyyehuda at gmail.com) Date: 15 May 2007 17:26:54 -0700 Subject: transparent images Message-ID: <1179275214.794050.199460@y80g2000hsf.googlegroups.com> Does any one know how to make a transparent image with specifically PIL, but any standard python library will do. I need a spacer, and it has to be transparent. Thanks From fuzzyman at gmail.com Fri May 4 18:33:59 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 4 May 2007 15:33:59 -0700 Subject: Microsoft's Dynamic Languages Runtime (DLR) In-Reply-To: <1178317722.669477.260070@y80g2000hsf.googlegroups.com> References: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> <1178151313.421106.43130@o5g2000hsb.googlegroups.com> <1178151574.302703.205560@l77g2000hsb.googlegroups.com> <1178296035.993859.183720@n59g2000hsh.googlegroups.com> <1178313159.059210.97560@y80g2000hsf.googlegroups.com> <1178315641.763473.168290@h2g2000hsg.googlegroups.com> <1178317722.669477.260070@y80g2000hsf.googlegroups.com> Message-ID: <1178318039.527265.197770@e65g2000hsc.googlegroups.com> On May 4, 11:28 pm, Paul Boddie wrote: > Luis M. Gonz?lez wrote: > > > Indeed, the subject is absolutely on-topic. > > If can't talk about a so called "Dynamic Languages Runtime" in a > > pyhton mailing list, I wonder what it takes to be considered on-topic. > > Frankly, this on-topic/off-topic fascism I see in this list is pissing > > me off a little bit. > > It's less on-topic for comp.lang.lisp, though, unless you want to > perform in a measuring competition with the Lisp crowd whilst hearing > how they did the very same thing as way back > in the 1950s. Despite the permissive licences - it'd be hard to slap a > bad EULA on IronPython now - the whole thing demonstrates Microsoft's > disdain for open standards as usual, How do you work that out? It seems like a very positive move from them. As for SilverLight, there will probably be a fully open implementation by the end of the year. Fuzzyman http://www.voidspace.org.uk/ironpython/index.shtml > but it remains on-topic for > comp.lang.python, I guess. > > Paul From gagsl-py2 at yahoo.com.ar Mon May 21 20:40:49 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 21 May 2007 21:40:49 -0300 Subject: Moving class used in pickle References: Message-ID: En Mon, 21 May 2007 16:24:55 -0300, Berthold H?llmann escribi?: > Jeffrey Barish writes: > >> I have a class derived from string that is used in a pickle. In the new >> version of my program, I moved the module containing the definition of >> the class. Now the unpickle fails because it doesn't find the module. >> I > > You can fiddle with the file class used reading the pickled file. I.e. > the "read()" method could replace each instance of "foo.myclass" by > "greatnewmodule.mynewclass" could bring you back in the game. There is a hook in the pickle module (load_global or find_global) that you can override instead, and it's exactly for this usage, see: http://docs.python.org/lib/pickle-sub.html -- Gabriel Genellina From unews at onlinehome.de Wed May 23 11:38:45 2007 From: unews at onlinehome.de (Uwe Grauer) Date: Wed, 23 May 2007 17:38:45 +0200 Subject: dabo framework dependancies In-Reply-To: <46532f57$0$32303$426a34cc@news.free.fr> References: <1179761984.704369.116310@b40g2000prd.googlegroups.com> <46532f57$0$32303$426a34cc@news.free.fr> Message-ID: daniel gadenne wrote: > Paul McNett wrote: >> Shameless plug: consider using Dabo on top of wxPython - we feel it >> makes wxPython even easier and more pythonic, but admittedly there's a >> bit of a learning curve there too. Even though Dabo is a full >> application framework originally meant for desktop database >> applications, it is modular and you can choose to only use the UI >> bits... http://dabodev.com > > > Hi Paul, > > I'm considering moving over to dabo for wxpython development. > However I do not write traditional database applications > ? la foxpro (I'm a 20 years user of fox...) anymore. > Only xml-fed applications. > > I'm a bit hesitant to jump onboard since dabo seemns to carry > over its own lot of database connectivity dependancy. > > Can you reasonably use dabo for plain datafree application? > > Fran?ois > > Yes, the only database dependency is sqlite as a store for app-preferences. But even this could get changed easily. Uwe From bbxx789_05ss at yahoo.com Fri May 25 03:40:50 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 25 May 2007 00:40:50 -0700 Subject: Find the closest relative In-Reply-To: <1180074710.011260.276830@n15g2000prd.googlegroups.com> References: <1180074710.011260.276830@n15g2000prd.googlegroups.com> Message-ID: <1180078850.074308.286570@p77g2000hsh.googlegroups.com> On May 25, 12:31 am, "jm.sur... at no.spam.gmail.com" wrote: > This is how I implemented; I guess there must be elegant way to do > this... > > def find_closest_relative(a,b,c): > c1 = b.__class__ > c2 = b.__class__ > > while True: > if isinstance(a, c1): > return b > if isinstance(a, c2): > return c > c1 = c1.__base__ > c2 = c1.__base__ > > - > Suresh I can't see how your code does what you describe. > Now, given one of the instance, I want to find the > closest relative of the other two. What influence would an object have over the closest relative of two other objects? The closet relative of two other objects is independent of any third object. Do you want to find the closest relative of 3 objects? If so, this might work: import inspect class A(object): pass class X(object): pass class B(A, X): pass #an object of this class has A as a base class class C(A, X): pass class D(A, X): pass class E(C): pass #an object of this class has A as a base class class F(D): pass #an object of this class has A as a base class def closestRelative(x, y, z): b1 = inspect.getmro(x.__class__) b2 = inspect.getmro(y.__class__) b3 = inspect.getmro(z.__class__) for elmt in b1: if elmt in b2 and elmt in b3: return elmt return None b = B() e = E() f = F() print closestRelative(b, e, f) However, you should probably post an example of a class structure and describe what you want to happen when you have three instance of the various classes. From saif.shakeel at gmail.com Thu May 3 03:35:57 2007 From: saif.shakeel at gmail.com (saif.shakeel at gmail.com) Date: 3 May 2007 00:35:57 -0700 Subject: Searching for a piece of string Message-ID: <1178177757.536983.277330@u30g2000hsc.googlegroups.com> Hi, How can i match a part of string and branch to some part of code. Ex If there is a string like "Timeout" and i want to search only whether the word "Time" is present in it(which is valid in this case).so if i have "CastinTime",still this should hold. I need to use this in a "if" statement and code.Can someone help me in this. Thanks . From nospam at invalid.com Sat May 26 04:19:36 2007 From: nospam at invalid.com (Jack) Date: Sat, 26 May 2007 01:19:36 -0700 Subject: Large Amount of Data References: Message-ID: I suppose I can but it won't be very efficient. I can have a smaller hashtable, and process those that are in the hashtable and save the ones that are not in the hash table for another round of processing. But chunked hashtable won't work that well because you don't know if they exist in other chunks. In order to do this, I'll need to have a rule to partition the data into chunks. So this is more work in general. "kaens" wrote in message news:mailman.8201.1180141324.32031.python-list at python.org... > On 5/25/07, Jack wrote: >> I need to process large amount of data. The data structure fits well >> in a dictionary but the amount is large - close to or more than the size >> of physical memory. I wonder what will happen if I try to load the data >> into a dictionary. Will Python use swap memory or will it fail? >> >> Thanks. >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > Could you process it in chunks, instead of reading in all the data at > once? From nick at craig-wood.com Wed May 2 05:30:04 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 02 May 2007 04:30:04 -0500 Subject: Want to build a binary header block References: Message-ID: Bob Greschke wrote: > This is the idea > > Block = pack("240s", "") > Block[0:4] = pack(">H", W) > Block[4:8] = pack(">H", X) > Block[8:12] = pack(">B", Y) > Block[12:16] = pack(">H", Z)) > > but, of course, Block, a str, can't be sliced. You could do this (note anonymous mappings require python 2.5) >>> from mmap import mmap >>> from struct import pack >>> W,X,Y,Z=1,2,3,4 >>> Block = mmap(-1, 1024) >>> Block[0:2] = pack(">H", W) >>> Block[4:6] = pack(">H", X) >>> Block[8:9] = pack(">B", Y) >>> Block[12:14] = pack(">H", Z) >>> Block[0:16] '\x00\x01\x00\x00\x00\x02\x00\x00\x03\x00\x00\x00\x00\x04\x00\x00' >>> You might also want to consider Construct http://construct.wikispaces.com/ >From the web page: Construct is a python library for parsing and building of data structures (binary or textual). It is based on the concept of defining data structures in a declarative manner, rather than procedural code: more complex constructs are composed of a hierarchy of simpler ones. It's the first library that makes parsing fun, instead of the usual headache it is today. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From exarkun at divmod.com Wed May 2 16:34:35 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 2 May 2007 16:34:35 -0400 Subject: I wish that [].append(x) returned [x] In-Reply-To: <4638e263$0$16368$88260bb3@free.teranews.com> Message-ID: <20070502203435.19381.1440990339.divmod.quotient.7642@ohm> On Wed, 02 May 2007 13:05:08 -0700, Tobiah wrote: > >> In addition to the above good advice, in case you are submitting a query >> to a DB-API compliant SQL database, you should use query parameters >> instead of building the query with string substitution. > >I tried that a long time ago, but I guess I found it to be >more awkward. I imagine that it is quite a bit faster that way? >I'm using MySQLdb. > Given name = raw_input("What is your name?") cursor.execute("INSERT INTO users (name) VALUES ('%s')" % (name,)) if I enter my name to be "'; DELETE FROM users;", then you are probably going to be slightly unhappy. However, if you insert rows into your database like this: cursor.execute("INSERT INTO users (name) VALUES (%s)", (name,)) then I will simply end up with a funny name in your database, instead of being able to delete all of your data. Jean-Paul From bscrivener42 at gmail.com Thu May 31 09:55:00 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: 31 May 2007 06:55:00 -0700 Subject: paste text with newlines into raw_input? In-Reply-To: <1180581322.594132.259100@a26g2000pre.googlegroups.com> References: <1180559052.806975.154890@h2g2000hsg.googlegroups.com> <1180581322.594132.259100@a26g2000pre.googlegroups.com> Message-ID: <1180619700.613805.291110@w5g2000hsg.googlegroups.com> Thanks, I think I need a Tkinter text entry widget, but it will take me a week to learn how to set it up. I'll report back. rick From victor.lebrun at gmail.com Wed May 2 17:37:45 2007 From: victor.lebrun at gmail.com (vml) Date: 2 May 2007 14:37:45 -0700 Subject: python,win32com,scipy and vb 6 : no module named scipy Message-ID: <1178141865.741042.202250@l77g2000hsb.googlegroups.com> Hello, I am really new in python scipy win32com and scipy I tried to setup a COM server to interact with vb 6 the pythom COM server is : from win32com.server import exception, register import pythoncom, win32pdhutil, winerror import math import numpy import sys sys.path.append('D:\\soft\python25\\Lib\\site-packages\\') #from scipy import linalg class Fop: _public_methods_ = [ 'SqVal' ] def SqVal(self,*val): import sys sys.path.append('D:\\soft\python25\\Lib\\site-packages\\') import scipy #print sys.path #mat=numpy.bmat(val) #linalg.inv(mat) return sys.path _reg_verprogid_ = "Python.Fop.3" _reg_progid_ = "Python.Fop" _reg_desc_ = "Python Fop" _reg_clsid_ = "{30BD3490-2632-11cf-AD5B-524153480001}" def Register(): import win32com.server.register return win32com.server.register.UseCommandLine(Fop) if __name__=='__main__': print "Registering COM server..." Register() the vb 6 code is Private Sub Form_Load() Set obj = CreateObject("Python.Fop") Dim ty(1, 1) As Variant ty(0, 0) = 1 ty(1, 1) = 2 ty(1, 0) = 3 ty(0, 1) = 4 toto = obj.SqVal(ty) End Sub I have a problem when I launch the vb 6 code : no module named scipy .... it is quite strange and I do not understand that Do you have any ideas ? thank you very much ! From broek at cc.umanitoba.ca Wed May 23 13:41:41 2007 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Wed, 23 May 2007 13:41:41 -0400 Subject: Properties/Decorators [WAS: Can I reference 1 instance of an object by more names ? rephrase] In-Reply-To: References: <4654289a$0$2326$426a74cc@news.free.fr> <465436E0.7040907@freakmail.de> Message-ID: <46547CD5.70103@cc.umanitoba.ca> Peter Otten said unto the world upon 05/23/2007 01:32 PM: > Brian van den Broek wrote: >> Help on built-in function apply in module __builtin__: >> >> But: >> >> >>> [x for x in dir('__builtin__') if 'apply' in x] >> [] >> >> ? If apply is in the __builtin__ module, why doesn't >> dir('__builtin__') know about it? > > The string "__builtin__" doesn't have an apply attribute; but the > __builtin__ module has: > >>>> import __builtin__ >>>> "apply" in dir(__builtin__) > True > > Peter Doh! Thanks Peter. From aleax at mac.com Thu May 3 01:14:09 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 2 May 2007 22:14:09 -0700 Subject: [ANN] Update to Python Quick Reference Card (for Python 2.4) (v0.67) References: <4bnh33pb644j9qsvij3citqrpb2bmqlsu4@4ax.com> <4638e8a8$0$27396$ba4acef3@news.orange.fr> Message-ID: <1hxiay0.17x1upmcmvc46N%aleax@mac.com> Laurent Pointal wrote: > Casey Hawthorne wrote: > > > PC-cillin flagged this as a dangerous web site. > > Maybe PC-cillin tag as dangerous all sites about Python, the famous snake. > > > PS. And why does it tag my laboratory work page as dangerous ? It's pure > HTML, I worked to have even no javascript, readable with lynx. It's an excellent quick-reference card, BTW (though I don't quite understand why even-numbered pages are flipped upside-down). Alex From wildemar at freakmail.de Wed May 23 08:43:12 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Wed, 23 May 2007 14:43:12 +0200 Subject: Properties/Decorators [WAS: Can I reference 1 instance of an object by more names ? rephrase] In-Reply-To: <4654289a$0$2326$426a74cc@news.free.fr> References: <4654289a$0$2326$426a74cc@news.free.fr> Message-ID: <465436E0.7040907@freakmail.de> Bruno Desthuilliers wrote: > here's an example using a property: > > class cpu_ports(object): > def __init__(self, value=0): > self._d = value > @apply > def value(): > def fset(self, value): > print 'vv' > self._d = value > def fget(self): > return self._d > return property(**locals()) > Wow! I've never seen properties written that way. Kind of takes all the mess out of what it usually is. Nice. BUT! I don't quite get the @apply-decorator here. The rest I get and so I gather what it is sort of kind of supposed to do. I have only found the depricated apply() function in the docs (which I also don't quite get just by scanning it). Is it that? If yes: How does it work? If not: What's going on there? humbly ;) W From nick at craig-wood.com Fri May 4 04:30:03 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Fri, 04 May 2007 03:30:03 -0500 Subject: My Python annoyances References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> <1178202431.147195.249790@u30g2000hsc.googlegroups.com> Message-ID: Thorsten Kampe wrote: > He was using /Windows/ Python in Cygwin *chuckle*... Windows Python > says Ctrl-Z because it doesn't know that it's been run from bash where > Ctrl-Z is for job control. > > And the lesson we learn from that: if you're using Windows Python use > a Windows shell. If you're using a Cygwin shell use Cygwin Python - > unless you know what you're doing (which he wasn't). I've noticed in the past that using cygwin python under a cygwin shell is broken in some subtle ways when building extensions. Using the windows python build in a windows command windows always works though (with mingw as the compiler). -- Nick Craig-Wood -- http://www.craig-wood.com/nick From gregcorradini at gmail.com Wed May 9 09:02:58 2007 From: gregcorradini at gmail.com (Greg Corradini) Date: Wed, 9 May 2007 06:02:58 -0700 (PDT) Subject: Boolean confusion In-Reply-To: <5adu2oF2p0j69U1@mid.uni-berlin.de> References: <10393362.post@talk.nabble.com> <5adu2oF2p0j69U1@mid.uni-berlin.de> Message-ID: <10393705.post@talk.nabble.com> Thank you Diez and Antoon for demystifing this problem. I see where I've been going wrong. Diez B. Roggisch-2 wrote: > > Greg Corradini wrote: > >> >> Hello all, >> I'm having trouble understanding why the following code evaluates as it >> does: >> >>>>> string.find('0200000914A','.') and len('0200000914A') > 10 >> True >>>>> len('0200000914A') > 10 and string.find('0200000914A','.') >> -1 >> >> In the 2.4 Python Reference Manual, I get the following explanation for >> the 'and' operator in 5.10 Boolean operations: >> " The expression x and y first evaluates x; if x is false, its value is >> returned; otherwise, y is evaluated and the resulting value is returned." >> >> Based on what is said above, shouldn't my first expression ( >> string.find('0200000914A','.') and len('0200000914A') > 10) evaluate to >> false b/c my 'x' is false? And shouldn't the second expression evaluate >> to >> True? > > The first evaluates to True because len(...) > 10 will return a boolean - > which is True, and the semantics of the "and"-operator will return that > value. > > And that precisely is the reason for the -1 in the second expression. > > y=-1 > > and it's just returned by the and. > > in python, and is implemented like this (strict evaluation > nonwithstanding): > > def and(x, y): > if bool(x) == True: > return y > return x > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/Boolean-confusion-tf3715438.html#a10393705 Sent from the Python - python-list mailing list archive at Nabble.com. From antroy at gmail.com Tue May 15 07:07:56 2007 From: antroy at gmail.com (Ant) Date: 15 May 2007 04:07:56 -0700 Subject: HappyDoc, Jython and docstrings Message-ID: <1179227276.205531.86230@u30g2000hsc.googlegroups.com> Hi All, I'm looking to provide online python documentation for several jython modules: does anyone know if there are tools to create documentation from docstrings that work in Jython? Jython doesn't provide the pydoc module. I've looked into HappyDoc, which is supposed to work on jython as well as python (since it parses the code tree rather than loading the module), but it seems broken at the moment. It seems to recognise comments after function/class/method names as documentation, but doesn't recognise doc strings. While I can work around this if necessary, does anyone have any solutions? Other programs that do a similar job? Patches for HappyDoc? Cheers, -- Ant... http://antroy.blogspot.com/ From i.read.the at group.invalid Fri May 11 17:23:11 2007 From: i.read.the at group.invalid (Pom) Date: Fri, 11 May 2007 21:23:11 GMT Subject: setting extra data to a wx.textctrl In-Reply-To: <1178890113.188436.228450@h2g2000hsg.googlegroups.com> References: <1178890113.188436.228450@h2g2000hsg.googlegroups.com> Message-ID: <3951i.171103$rm4.1182860@phobos.telenet-ops.be> kyosohma at gmail.com wrote: > On May 10, 10:51 pm, Pom wrote: >> Hello group! >> >> I have an application which uses a lot of mysql data fields, all the >> same data type (floats). >> >> I created a panel which executes a "SELECT * FROM tablename" and makes >> as much fields as needed, using de cursor.description as wx.statictext >> and the cursors field contents copied into wx.textctrls. >> >> At creation time, I loop over all the fields in the record and create a >> tuple which contains ((textctrl1, fieldname1), (textctrl2, fieldname2), >> ...) so I can keep track of which textctrl holds which piece of fielddata. >> >> The problem I'm having is: >> >> to know the fieldname in an text_event, I use event.GetEventObject(), >> then perform an iteration over the tuple and when I find a match I use >> the field name to update the mysqltable. >> When having a few fields, this is ok. But I have over 100 fields in 1 >> record and it really slows things down. >> >> Now my question is: should I use a python dictionary (with an object as >> first lookup field) ? >> >> On windows, I've seen a "Tag" property in a textbox which was meant to >> be used for this kind of stuff. Maybe it's better to override the >> wx.textctrl so I can add an extra string value? >> >> Anyone having the best solution for this ? >> >> thx! > > Both of your ideas seem sound to me. You could also look into using > statically assigned IDs that increment by one. Then you could just > increment or decrement by one and look up the field by ID. Of course, > that might get ugly and there are some IDs that are supposedly > reserved. But it's an idea. > > Also, I've heard that Dabo (http://dabodev.com/) is good for database > work. You might look at that. To get the quickest and most on target > answers to wxPython questions, I recommend the wxPython users-group > mailing list: http://www.wxpython.org/maillist.php > > Mike > thx! From nufuhsus at gmail.com Wed May 9 15:25:24 2007 From: nufuhsus at gmail.com (nufuhsus at gmail.com) Date: 9 May 2007 12:25:24 -0700 Subject: preferred windows text editor? In-Reply-To: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> References: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> Message-ID: <1178738724.695273.191930@n59g2000hsh.googlegroups.com> On May 9, 2:06 pm, "T. Crane" wrote: > Right now I'm using Notepad++. What are other people using? > > trevis I am very noob to this Python game and currently (I was using ActivePython and then IDLE) I have been using a combination of Notepad2 and the interpreter (Python 2.5) on a Windblows X[crement]P[roblem] SP2 machine. Get Notepad2 http://www.flos-freeware.ch/notepad2.html I like IDLE but it seems to stop working after the first few times and I would then re-install it and it would work a few times more. ActivePython was cool but I could not find a version of it that used Python 2.5 (as far as I can see, it only uses 2.4) Notepad2 allows you to launch your script directly from the editor (just like IDLE) and has configurable code highlighting. And it is FREE. From laurent.pointal at limsi.fr Fri May 11 03:09:08 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Fri, 11 May 2007 09:09:08 +0200 Subject: High resolution sleep (Linux) In-Reply-To: <1178808104.915724.176100@n59g2000hsh.googlegroups.com> References: <1178274122.142071.91740@y5g2000hsa.googlegroups.com> <8l90i.911$UU.403@newssvr19.news.prodigy.net> <1178808104.915724.176100@n59g2000hsh.googlegroups.com> Message-ID: John a ?crit : > Anyways, what I need is high resolution sleep, not high resolution > timing. Installing a real time OS seems like overkill. IDEA Maybe try creating threading.Event and waiting for it with a timeout. From gshatadal at rediffmail.com Mon May 28 09:36:40 2007 From: gshatadal at rediffmail.com (Shatadal) Date: 28 May 2007 06:36:40 -0700 Subject: Error in optparse documentation In-Reply-To: References: <1180302882.090651.235860@q75g2000hsh.googlegroups.com> Message-ID: <1180359400.151371.74800@q75g2000hsh.googlegroups.com> On May 28, 2:19 am, Marc 'BlackJack' Rintsch wrote: > In <1180302882.090651.235... at q75g2000hsh.googlegroups.com>, Shatadal > wrote: > > > I think the documentation should be modified so that it is made clear > > that %default in the help string behaves as is claimed only in version > > 2.4 and higher. > > Maybe something should be added for clarity but I don't think it's an > error in the docs. You are reading documentation for Python 2.5 and > expect everything in it to work in older versions too? > > Pick the right documentation fromhttp://www.python.org/doc/versions/ Thanks Marc. I did not know that documentation for previous versions existed. > > Ciao, > Marc 'BlackJack' Rintsch From reizes at gmail.com Thu May 31 19:58:29 2007 From: reizes at gmail.com (reizes at gmail.com) Date: 31 May 2007 16:58:29 -0700 Subject: M2Crypto-0.17 blocks python threads? Message-ID: <1180655909.402928.138290@i38g2000prf.googlegroups.com> I am having a problem with python threads and M2Crypto. It appears the M2Crypto used in multi-thread application blocks other threads from running: Environment: Linux 2.6 (centos 5.0), OpenSSL 0.9.8b, M2Crypto-0.17 I am using echod-thread.py and echo.py as test vehicles. Start up echod-thread.py Connect with echo.py - everything looks ok, but connect with second echo.py and notice that the server does not respond until after the first echo session is terminated. And yes, echod-thread.py does call M2Crypto.threading.init() So my questions are has anyone seen this kind of threading behavior? If so how did you fix it? (NOTE: This used to work with old M2Crytpo-0.13) I edited a version of the server to print some debug messages. Around the main server loop: while 1: print "#### waiting for connection on port 9999" conn, addr = sock.accept() thread.start_new_thread(echo_handler, (ctx, conn, addr)) print "#### started thread, main thread sleeping for 2 seconds" time.sleep(2) # give first session time to start [tablus at belgrade ssl]$ python echod-thread.py #### waiting for connection on port 9999 #### started thread, main thread sleeping for 2 seconds < first echo session thread -- works ok> [tablus at belgrade ssl]$ python echo.py -h belgrade.tablus.com LOOP: SSL connect: before/connect initialization LOOP: SSL connect: SSLv3 write client hello A LOOP: SSL connect: SSLv3 read server hello A LOOP: SSL connect: SSLv3 read server certificate A LOOP: SSL connect: SSLv3 read server key exchange A LOOP: SSL connect: SSLv3 read server done A LOOP: SSL connect: SSLv3 write client key exchange A LOOP: SSL connect: SSLv3 write change cipher spec A LOOP: SSL connect: SSLv3 write finished A LOOP: SSL connect: SSLv3 flush data LOOP: SSL connect: SSLv3 read finished A INFO: SSL connect: SSL negotiation finished successfully Host = belgrade.tablus.com Cipher = DHE-RSA-AES256-SHA Server = /CN=belgrade.tablus.com/ST=CA/C=US/ emailAddress=conalarm_ca at tablus.com/O=Root Certification Authority Ye Newe Threading Echo Servre Echo this Echo this < second echo session thread -- hangs waiting for server to respond until first session exits> [tablus at belgrade ssl]$ python echo.py -h belgrade.tablus.com LOOP: SSL connect: before/connect initialization LOOP: SSL connect: SSLv3 write client hello A From kw at codebykevin.com Fri May 4 10:41:43 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Fri, 04 May 2007 10:41:43 -0400 Subject: Tcl-tk 8.5? In-Reply-To: References: <46382248$0$5105$ba4acef3@news.orange.fr> Message-ID: <1903b$463b4628$4275d90a$25045@FUSE.NET> James Stroud wrote: > M?ta-MCI wrote: >> Any plan to integrate Tcl 8.5 in standard Python? >> > > Better would be to outegrate it and instead use another gui kit as the > standard. > This statement puzzles me, as you are something of a Tkinter expert (you have helped me with some Tk issues). What is so bad about Tkinter? What should replace it in the core library? -- Kevin Walzer Code by Kevin http://www.codebykevin.com From bj_666 at gmx.net Tue May 8 18:23:22 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 09 May 2007 00:23:22 +0200 Subject: Designing a graph study program References: <1178619753.077639.112510@q75g2000hsh.googlegroups.com> <5ab3mgF2o5bfbU1@mid.uni-berlin.de> <1178622700.228390.237310@n59g2000hsh.googlegroups.com> <5ab6p3F2ni551U1@mid.uni-berlin.de> <1178659258.820806.110380@l77g2000hsb.googlegroups.com> Message-ID: In <1178659258.820806.110380 at l77g2000hsb.googlegroups.com>, andrea wrote: > Interesting but what do you mean for two graph-implementatio that > share the same interface?? > I don't have abstract classes or interfaces in python, am I wrong? You are thinking of some kind of types or enforcements. If two classes have some methods with the same names and the same semantics they share the same interface. And a class that isn't meant to be instantiated or doesn't implement all methods is an abstract class. Ciao, Marc 'BlackJack' Rintsch From steve at REMOVE.THIS.cybersource.com.au Thu May 31 06:19:28 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 31 May 2007 20:19:28 +1000 Subject: Good Python style? References: Message-ID: On Thu, 31 May 2007 09:59:07 +0200, Andreas Beyer wrote: > Hi, > > I found the following quite cryptic code, which basically reads the > first column of some_file into a set. > In Python I am used to seeing much more verbose/explicit code. However, > the example below _may_ actually be faster than the usual "for line in ..." > Do you consider this code good Python style? Or would you recommend to > refrain from such complex single-line code?? > > Thanks! > Andreas > > inp = resource(some_file) > # read first entries of all non-empty lines into a set > some_set = frozenset([line.split()[0] for line in \ > filter(None, [ln.strip() for ln in inp])]) It's a little complex, but not excessively so. Any more, and it would probably be too complex. It would probably be easier to read with more readable names and a few comments: some_set = frozenset( # ... from a list comp of the first word in each line [line.split()[0] for line in # ... each line has leading and trailing white space # filtered out, and blanks are skipped filter(None, # strip whitespace and filter out blank lines [line.strip() for line in input_lines] )]) Splitting it into multiple lines is self-documenting: blankless_lines = filter(None, [line.strip() for line in input_lines]) first_words = [line.split()[0] for line in blankless_words] some_set = frozenset(first_words) As for which is faster, I doubt that there will be much difference, but I expect the first version will be a smidgen fastest. However, I'm too lazy to time it myself, so I'll just point you at the timeit module. -- Steven. From bbxx789_05ss at yahoo.com Wed May 23 15:34:52 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 23 May 2007 12:34:52 -0700 Subject: Namespace issue In-Reply-To: Message-ID: <1179948892.900470.215460@u30g2000hsc.googlegroups.com> On May 23, 12:20 pm, Ritesh Raj Sarraf wrote: > As per my understanding, the bad part is that on every call of the method > FetchData(), an import would be done. > > To not let that happen, I can put the import into __init__(). But when I put > in there, I get a NameError saying that my_module is not available even > though it got imported. > All I noticed is that the import has to be part of the method else I end up > getting a NameError. But always importing my_module is also not good. How about something like this: class Dog(object): myimport = None def __init__(self): if not Dog.myimport: print "importing..." import os Dog.myimport = os def test(self): print Dog.myimport.listdir("./") d = Dog() d.test() print print d2 = Dog() d2.test() --output:--- importing... [a bunch of files] [a bunch of files] From steve at REMOVE.THIS.cybersource.com.au Mon May 28 18:32:12 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 29 May 2007 08:32:12 +1000 Subject: Is PEP-8 a Code or More of a Guideline? References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <1180289911.951691.78640@k79g2000hse.googlegroups.com> <1hyttp5.cy5uldv00db3N%aleax@mac.com> Message-ID: On Mon, 28 May 2007 14:12:33 -0700, Alex Martelli wrote: > sjdevnull at yahoo.com wrote: > >> Historically, it's only Java and the Windows world (including non- >> standard Windows-style C++) that use forcedCase significantly (C# >> draws from both). > > I remember meeting that style first in the X Window System (now commonly > known as X11, but it was around for a few years before the 11 arrived), > which is a little bit older than Windows and WAY older than Java. I > don't know if X was the first project to use that style consistently. There was also Hypercard from Apple in (by memory) 1988. Although case was not significant, handlers were usually written mouseDown, mouseUp, openStack, openCard, etc. -- Steven. From carsten at uniqsys.com Wed May 16 09:18:18 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 16 May 2007 09:18:18 -0400 Subject: removing common elemets in a list In-Reply-To: <1179296224.885877.187200@q23g2000hsg.googlegroups.com> References: <1179296224.885877.187200@q23g2000hsg.googlegroups.com> Message-ID: <1179321498.3444.7.camel@dot.uniqsys.com> On Tue, 2007-05-15 at 23:17 -0700, saif.shakeel at gmail.com wrote: > Hi, > Suppose i have a list v which collects some numbers,how do i > remove the common elements from it ,without using the set() opeartor. > Thanks If the list is sorted, you can weed out the duplicates with itertools.groupby: >>> import itertools >>> L = [1,2,3,3,4,4,5] >>> [k for (k,_) in itertools.groupby(L, lambda x:x)] [1, 2, 3, 4, 5] HTH, -- Carsten Haese http://informixdb.sourceforge.net From steve at holdenweb.com Sat May 26 12:00:33 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 26 May 2007 12:00:33 -0400 Subject: Large Amount of Data In-Reply-To: References: Message-ID: Jack wrote: > "John Nagle" wrote in message > news:nfR5i.4273$C96.1640 at newssvr23.news.prodigy.net... >> Jack wrote: >>> I need to process large amount of data. The data structure fits well >>> in a dictionary but the amount is large - close to or more than the size >>> of physical memory. I wonder what will happen if I try to load the data >>> into a dictionary. Will Python use swap memory or will it fail? >>> >>> Thanks. >> What are you trying to do? At one extreme, you're implementing >> something >> like a search engine that needs gigabytes of bitmaps to do joins fast as >> hundreds of thousands of users hit the server, and need to talk seriously >> about 64-bit address space machines. At the other, you have no idea how >> to either use a database or do sequential processing. Tell us more. >> > I have tens of millions (could be more) of document in files. Each of them > has other > properties in separate files. I need to check if they exist, update and > merge properties, etc. > And this is not a one time job. Because of the quantity of the files, I > think querying and > updating a database will take a long time... > And I think you are wrong. But of course the only way to find out who's right and who's wrong is to do some experiments and get some benchmark timings. All I *would* say is that it's unwise to proceed with a memory-only architecture when you only have assumptions about the limitations of particular architectures, and your problem might actually grow to exceed the memory limits of a 32-bit architecture anyway. Swapping might, depending on access patterns, cause you performance to take a real nose-dive. Then where do you go? Much better to architect the application so that you anticipate exceeding memory limits from the start, I'd hazard. > Let's say, I want to do something a search engine needs to do in terms of > the amount of > data to be processed on a server. I doubt any serious search engine would > use a database > for indexing and searching. A hash table is what I need, not powerful > queries. > You might be surprised. Google, for example, use a widely-distributed and highly-redundant storage format, but they certainly don't keep the whole Internet in memory :-) Perhaps you need to explain the problem in more detail if you still need help. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From facundo at taniquetil.com.ar Wed May 2 09:09:16 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Wed, 2 May 2007 13:09:16 +0000 (UTC) Subject: More urllib timeout issues. References: Message-ID: John Nagle wrote: > I took a look at Facundo Batista's work in the tracker, and he > currently seems to be trying to work out a good way to test the > existing SSL module. It has to connect to something to be tested, Right now, test_socket_ssl.py has, besides the previous tests, the capability of executing openssl's s_server and connect to him. I'm lees than a SSL begginer, so I do not have the knowledge to make interesting tests, I just made the obvious ones... If you know SSL, you can take that code and add new tests very easily. Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From cam.ac.uk at mh391.invalid Wed May 2 20:21:42 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 03 May 2007 01:21:42 +0100 Subject: Slicing Arrays in this way In-Reply-To: <4638fe20$0$16403$88260bb3@free.teranews.com> References: <4638fe20$0$16403$88260bb3@free.teranews.com> Message-ID: Tobiah wrote: > > >>> elegant_solution([1,2,3,4,5,6,7,8,9,10]) > [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] That's not an array, it's a list. See the array module for arrays (fixed-length, unlike variable-length lists). -- Michael Hoffman From mail at microcorp.co.za Wed May 30 02:36:56 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 30 May 2007 08:36:56 +0200 Subject: Is PEP-8 a Code or More of a Guideline? References: <316098.9123.qm@web33510.mail.mud.yahoo.com> <465C3861.8010508@aristote.info> Message-ID: <00f901c7a289$8d3aaac0$03000080@hendrik> "Maric Michaud" wrote: >Is typist ok ? It's the google's translation for "dactylo". Typist is fine, although MCP that I am, I tend to think of typist as female... I would call a male one a "typer", but I dont think it is correct English. - Hendrik From michele.simionato at gmail.com Mon May 7 23:48:29 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 7 May 2007 20:48:29 -0700 Subject: how do you implement a reactor without a select? In-Reply-To: <1hxrdhf.179bobg6tzv9cN%aleax@mac.com> References: <1178543812.260333.39280@w5g2000hsg.googlegroups.com> <1hxqfgq.4sjxga1dz7vv3N%aleax@mac.com> <1178552069.229745.124040@l77g2000hsb.googlegroups.com> <1hxrdhf.179bobg6tzv9cN%aleax@mac.com> Message-ID: <1178596109.282088.175300@u30g2000hsc.googlegroups.com> On May 8, 4:53 am, a... at mac.com (Alex Martelli) wrote: > What do you expect from "timers on Linux" that you could not get with a > simple "sleep for the next N milliseconds"? A timer (on Linux or > elsewhere) can jog your process N milliseconds from now, e.g. with a > SIGALRM or SIGPROF, and you can set one with the setitimer syscall > (presumably accessible via ctypes, worst case -- I've never used it from > Python, yet), but how would that help you (compared to plain sleep, > select, poll, or whatever else best fits your need)? I hoped there was a library such thay I could register a Python callable (say a thunk) and having it called by the linux timer at time t without blocking my process. But if a Linux timer will just send to my process an alarm, I would need to code myself a mechanism waiting for the alarm and doing the function call. In that case as you say, I would be better off with a select+timeout or a even with a queue+timeout, which already do most of the job. Michele Simionato From paul at boddie.org.uk Fri May 18 13:16:39 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 18 May 2007 10:16:39 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <464C5382.6080403@v.loewis.de> <1179423799.254286.294930@w5g2000hsg.googlegroups.com> <1179503525.018943.95740@u30g2000hsc.googlegroups.com> Message-ID: <1179508599.868680.177960@e65g2000hsc.googlegroups.com> On 18 Mai, 18:42, "Javier Bezos" wrote: > "Istvan Albert" escribi?: > > > How about debugging this (I wonder will it even make it through?) : > > > class 6??????? > > > 6?? = 0 > > 6????? ?? ?=10 > > This question is more or less what a Korean who doesn't > speak English would ask if he had to debug a program > written in English. Perhaps, but the treatment by your mail/news software plus the delightful Google Groups of the original text (which seemed intact in the original, although I don't have the fonts for the content) would suggest that not just social or cultural issues would be involved. It's already more difficult than it ought to be to explain to people why they have trouble printing text to the console, for example, and if one considers issues with badly configured text editors putting the wrong character values into programs, even if Python complains about it, there's still going to be some explaining to do. One thing that some people already dislike about Python is the "editing discipline" required. Although I don't have much time for people whose coding "skills" involve random edits using badly configured editors, trashing the indentation and the appearance of the code (regardless of the language involved), we do need to consider the need to bring people "up to speed" gracefully by encouraging the proper use of tools, and so on, all without making it seem really difficult and discouraging people from learning the language. Paul From descartes at gmail.com Tue May 8 16:34:26 2007 From: descartes at gmail.com (descartes at gmail.com) Date: 8 May 2007 13:34:26 -0700 Subject: Mod Python Question Message-ID: <1178656466.059754.193160@e51g2000hsg.googlegroups.com> I am very new to Python and Mod_Python and I am running into what looks like a caching problem. I have the following code: --------------------------------------- from mod_python import apache from folder import Messenger def handler(req): msg = Messenger(req): # using req.write msg.write("hello world") return apache.OK ----------------------------------------- So the Messenger class has the method "write" which calls req.write. This will output "hello world" in the browser. However, when I go into Messenger and change the method name from "write" to anything else, it still works. It is as if the class is being cached. I have deleted pyc but that has not done anything either. What is going on? Thanks. From castironpi at gmail.com Thu May 10 20:47:39 2007 From: castironpi at gmail.com (castironpi at gmail.com) Date: 10 May 2007 17:47:39 -0700 Subject: How to find C source Message-ID: <1178844459.271906.92560@o5g2000hsb.googlegroups.com> How do I get to the source for parser.suite()? From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu May 31 13:58:09 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 31 May 2007 19:58:09 +0200 Subject: strange PyLint configuration (was: PEP 8 style enforcing program) References: <1180613790.317480.314600@p47g2000hsd.googlegroups.com> Message-ID: <5c8glhF2tra7sU1@mid.individual.net> Alexander Eisenhuth wrote: > Pylint is one of them (http://www.logilab.org/857) BTW: Why does pylint want all names with underscores? I tested it and it complains about malformed names in e.g. the following cases that are conformant to PEP 8: - single letter as parameter - firstLowerCamelCase names for instances and instance methods in class declarations ("should match [a-z_][a-z0-9_]{2,30}$") - all lowercase method names in class declarations Those policies are barely usable, IMHO, and neither practical. LOL, and it rates my code -1.9/10. The minus is no typo. Regards, Bj?rn -- BOFH excuse #291: Due to the CDA, we no longer have a root account. From sjmachin at lexicon.net Tue May 22 18:26:09 2007 From: sjmachin at lexicon.net (John Machin) Date: Wed, 23 May 2007 08:26:09 +1000 Subject: trying to gzip uncompress a StringIO In-Reply-To: References: <1179854545.199999.247590@k79g2000hse.googlegroups.com> Message-ID: <46536E01.2080702@lexicon.net> On 23/05/2007 7:48 AM, Gabriel Genellina wrote: > En Tue, 22 May 2007 14:22:25 -0300, escribi?: > >> I'm using the code below to read the zipped, base64 encoded WMF file >> saved in an XML file with "Save as XML" from MS Word. As the "At this >> point" comment shows, I know that the base64 decoding is going fine, >> but unzipping from the decodedVersion StringIO object isn't getting me >> anything, because the len(fileContent) call is returning 0. Any >> suggestions? > > Perhaps GzipFile reads from the current position till end (and sees > nothing). > Try rewinding the file: > >> decodedVersion = StringIO.StringIO() >> base64.decode(open(infile, 'r'),decodedVersion) > decodedVersion.seek(0) >> fileObj = gzip.GzipFile(fileobj=decodedVersion); >> fileContent = fileObj.read() >> print len(fileContent) > >>> import StringIO >>> s = StringIO.StringIO() >>> s.write('blahblah\n') >>> s.read() '' >>> s.seek(0) >>> s.read() 'blahblah\n' >>> The error would have been screamingly obvious on an open-reel mag. tape drive :-) I suggest that "perhaps" and "try" are a little too tentative :-) GzipFile (or anything else that reads a file) is entitled to assume that the file(-like) object it is given has had its read head positioned by the caller at wherever the caller wants it to read from. Callers are entitled to assume that the reader will not arbitrarily rewind (or skip backwards/forwards to tape mark!) before reading. Cheers, John From bdesth.quelquechose at free.quelquepart.fr Mon May 21 16:03:48 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 21 May 2007 22:03:48 +0200 Subject: Simple web apps....mod_python or framework? In-Reply-To: <1179752080.489657.102310@a26g2000pre.googlegroups.com> References: <1179752080.489657.102310@a26g2000pre.googlegroups.com> Message-ID: <4651f0bf$0$19493$426a74cc@news.free.fr> cbmeeks a ?crit : > If you guys where going to do a simple web-app (as in, 4-5 tables with > 99% being simple CRUD), would you use a framework (Django, > CodeIgniter, whatever...) or would you do it using maybe mod_python > and Python code? pylons + SQLAlchemy http://pylonshq.com From george.sakkis at gmail.com Mon May 14 22:08:30 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 14 May 2007 19:08:30 -0700 Subject: Subprocess with and without shell Message-ID: <1179194910.310317.38730@y80g2000hsf.googlegroups.com> I'm trying to figure out why Popen captures the stderr of a specific command when it runs through the shell but not without it. IOW: cmd = [my_exe, arg1, arg2, ..., argN] if 1: # this captures both stdout and stderr as expected pipe = Popen(' '.join(cmd), shell=True, stderr=PIPE, stdout=PIPE) else: # this captures only stdout pipe = Popen(cmd, shell=False, stderr=PIPE, stdout=PIPE) # this prints the empty string if not run through the shell print "stderr:", pipe.stderr.read() # this prints correctly in both cases print "stdout:", pipe.stdout.read() Any hints ? George From grante at visi.com Wed May 9 10:58:05 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 09 May 2007 14:58:05 -0000 Subject: Gui thread and async jobs. References: <1178627450.408287.139070@p77g2000hsh.googlegroups.com> Message-ID: <1343obt58trd8c0@corp.supernews.com> On 2007-05-08, king kikapu wrote: > Hi, i am reading the book "Python Cookbook, 2nd edition" and i > encountered a very handy recipe, the one that is called > "Combining GUIs and Asynchronous I/O with Threads" > > It is talking about retain a main GUI thread, doing async work > with worker threads and have both talk through a Queue object > to dispatch their messages, so the main (GUI) thread remain > responsive. It has a very good example by using Tkinter and Qt > that is indeed working. The only point that make me wonder is > that the QUI thread has to use some polling to check for > messages in the Queue. It sounds to me like Qt is missing some rather important features and/or convenience functions. In other toolkits (e.g. wxPython), invoking GUI methods/functions from non-GUI threads is trivial and involves no polling by the GUI thread. For example, if in a wxPython application you wanted to call someGUIobject.method(foo,bar) from a non-GUI thread you just do this: wx.CallAfter(someGUIobject.method,foo,bar) If you look under the covers there is a queue involved, but it's nothing the user has to poll or worry about. -- Grant Edwards grante Yow! Can I have an IMPULSE at ITEM instead? visi.com From kay.schluehr at gmx.net Thu May 10 03:19:11 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 10 May 2007 00:19:11 -0700 Subject: Erlang style processes for Python In-Reply-To: References: <1178759792.268979.206630@p77g2000hsh.googlegroups.com> Message-ID: <1178781551.927028.256380@y80g2000hsf.googlegroups.com> On May 10, 8:31 am, Jacob Lee wrote: > Funny enough, I'm working on a project right now that is designed for > exactly that: PARLEY,http://osl.cs.uiuc.edu/parley. (An announcement > should show up in clp-announce as soon as the moderators release it). My > essential thesis is that syntactic sugar should not be necessary -- that a > nice library would be sufficient. Synsugar is helpfull when you want to control compiler actions. Of course you can do this also by means of __special__ attributes but I guess this becomes clutter when you work with certain exposed sections in the code. > I do admit that Erlang's pattern > matching would be nice, although you can get pretty far by using uniform > message formats that can easily be dispatched on -- the tuple > (tag, sender, args, kwargs) > in the case of PARLEY, which maps nicely to instance methods of a > dispatcher class. Yes, I do think so too. It is more interesting to think about what might be qualify as a message. Destructuring it is not hard in anyway and I do also have a few concerns with naive pattern matching: http://www.fiber-space.de/EasyExtend/doc/gallery/gallery.html#4._Chainlets_and_the_switch-statement > The questions of sharing among multiple physical processes is interesting. > Implicit distribution of actors may not even be necessary if it is easy > enough for two hosts to coordinate with each other. In terms of the > general question of assigning actors to tasklets, threads, and processes, > there are added complications in terms of the physical limitations of > Python and Stackless Python: > - because of the GIL, actors in the same process do not gain the > advantag of true parallel computation > - all tasklet I/O has to be non-blocking > - tasklets are cooperative, while threads are preemptive > - communication across processes is slower, has to be serialized, etc. > - using both threads and tasklets in a single process is tricky Actors don't need locking primitives since their data is locked by virtue of the actors definition. That's also why I'm in favour for a runtime / compiler based solution. Within the shiny world of actors and actresses the GIL has no place. So a thread that runs actors only, does not need to be blocked or block other threads - at least not for data locking purposes. It is used much like an OS level process with better sharing capabilities ( for mailbox addresses and messages ). Those threads shall not take part of the access/release GIL game. They might also not be triggered explicitely using the usual threading API. > PARLEY currently only works within a single process, though one can choose > to use either tasklets or threads. My next goal is to figure out I/O, at > which point I get to tackle the fun question of distribution. > > So far, I've not run into any cases where I've wanted to change the > interpreter, though I'd be interested in hearing ideas in this direction > (especially with PyPy as such a tantalizing platform!). > -- > Jacob Lee I guess you mean tantalizing in both of its meanings ;) Good luck and inform us when you find interesting results. Kay From rahulnag22 at yahoo.com Wed May 9 12:42:45 2007 From: rahulnag22 at yahoo.com (rahulnag22 at yahoo.com) Date: 9 May 2007 09:42:45 -0700 Subject: tkinter - Screen Resolution In-Reply-To: <1178728652.490682.239650@u30g2000hsc.googlegroups.com> References: <1178728652.490682.239650@u30g2000hsc.googlegroups.com> Message-ID: <1178728965.861201.74900@p77g2000hsh.googlegroups.com> On May 9, 10:37 am, rahulna... at yahoo.com wrote: > Hi, > I have developed a GUI using tkinter (grid geometory manager). > The structure is a top frame containing multiple subframes. Each > subframe has a combination of widgets like(Entry, label, > button,listboxes). The subframes are placed with a padx and pady > offset with regards to the other subframes. And the widgets within > these subframes have their own padx and pady offsets. The GUI runs > fine on my linux box, but on a different linux box things get wierd. > I see things like- > 1) The frame width increasing > 2) The widget padx translating to much bigger offsets with reference > to the subframe edges > 3) Widget widths like that for Entry become bigger > > I Know its to do with the screen resolution settings and user settings > on different machines. Can anyone point me in the right > direction(before I start looking into it)as how to account for > different screen resolutions so as to have as uniform a GUI look as > possible across different user machines. > A smaller version of my GUI layout looks something like--> > > ===============Top Frame================= > = - SubFrame - ---------SubFrame--------- > = - - - ''''''''''''''''''''''''''''''''' - > = - - - ' Widget ' - > = - - - ''''''''''''''''''''''''''''''''' - > = - Widget - ----------------------------- > = - - > = - - ---------SubFrame--------- > = - - - - > = - - - ''''''''''''''''''''''''''''''''' - > = - Widget - - ' Widget ' - > = - - - ''''''''''''''''''''''''''''''''' - > = - - - - > = - - - ''''''''''''''''''''''''''''''''' - > = - - - ' Widget ' - > = - Widget - - ''''''''''''''''''''''''''''''''' - > = --------------- ----------------------------- > ========================================= > > Thanks > Rahul From gherron at islandtraining.com Tue May 15 15:05:43 2007 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 15 May 2007 12:05:43 -0700 Subject: Splitting a string In-Reply-To: <1179253692.110024.96330@w5g2000hsg.googlegroups.com> References: <1179253692.110024.96330@w5g2000hsg.googlegroups.com> Message-ID: <464A0487.8050002@islandtraining.com> HMS Surprise wrote: > The string s below has single and double qoutes in it. For testing I > surrounded it with triple single quotes. I want to split off the > portion before the first \, but my split that works with shorter > strings does not seem to work with this one. > > Ideas? > > Thanks, > jvh > > s = ''''D132258\',\'\', > \'status=no,location=no,width=630,height=550,left=200,top=100\')" > target="_blank" class="dvLink" title="Send an Email to selected > employee">''' > > t = s.split('\\') > That can't work because there are no \'s in your string. There are backslashes in your program to escape some of the characters from being meaningful to the python interpreter. However, once the string is parsed and created, it has no backslashes in it. To see this, just print it or use find on it: >>> s = ''''D132258\',\'\', ... \'status=no,location=no,width=630,height=550,left=200,top=100\')" ... target="_blank" class="dvLink" title="Send an Email to selected ... employee">''' >>> print s 'D132258','', 'status=no,location=no,width=630,height=550,left=200,top=100')" target="_blank" class="dvLink" title="Send an Email to selected employee"> >>> s.find('\\') -1 So the question now becomes: Where do you really want to split it? If at the comma then one of these will work for you: >>> print s.split(',')[0] 'D132258' >>> i = s.index(',') >>> print s[:i] 'D132258' Gary Herron From steve at holdenweb.com Thu May 31 16:41:57 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 31 May 2007 16:41:57 -0400 Subject: Standalone HTTP parser? In-Reply-To: References: Message-ID: Christopher Stawarz wrote: > Does anyone know of a standalone module for parsing and generating > HTTP messages? I'm looking for something that will take a string and > return a convenient message object, and vice versa. All the Python > HTTP parsing code I've seen is either intimately bound to the > corresponding socket I/O operations (e.g. httplib, httplib2, > BaseHTTPServer) and/or buried in somebody's framework (e.g. Twisted). > > I want to write some HTTP servers/clients that do asynchronous I/O > using my own engine (multitask), so I need a HTTP package that won't > insist on doing the I/O for me. > Look at rfc822 or the email module - HTTP responses are in the same format, modulo the first line status. Requests too, though with a different format for the first 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From tjreedy at udel.edu Tue May 1 19:44:45 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 1 May 2007 19:44:45 -0400 Subject: Error in python.org homepage. References: <1178013832.880214.134660@l77g2000hsb.googlegroups.com> Message-ID: wrote in message news:1178013832.880214.134660 at l77g2000hsb.googlegroups.com... | Hi to all!!! | | I sended an email to webmaster at python dot org, but was blocked... | why?.... No idea | In the homepage of python.org there is an error: the link that point | to source distribution is not | updated to Python 2.5.1. Just checked and both links now point to http://www.python.org/download/releases/2.5.1/ From nikbaer at gmail.com Tue May 1 18:12:09 2007 From: nikbaer at gmail.com (nik) Date: 1 May 2007 15:12:09 -0700 Subject: ScrolledText? Message-ID: <1178057529.486757.154860@y5g2000hsa.googlegroups.com> I've been trying to get the scrollbar and text box always going to the last line and have been completely unsuccessful. I've tried, ScrolledText, text.see, and text.yview_pickplace without success for instance this was the last setup: self.text = ScrolledText(master, relief=RIDGE) self.text.grid(column=1, row=2, columnspan=10,\ rowspan=5, pady=10, sticky=NSEW) with this text entry: self.text.insert(END, ins) self.text.yview_pickplace("end") Can anybody please tell me what I might be doing wrong, or an example that works, so that I can see what's going wrong. Thanks, Nik From alan.franzoni_invalid at geemail.invalid Fri May 11 08:10:49 2007 From: alan.franzoni_invalid at geemail.invalid (Alan Franzoni) Date: Fri, 11 May 2007 14:10:49 +0200 Subject: vim e autoindentazione commenti Message-ID: Ciao a tutti, alla fine dopo le mille dispute emacs vs vim mi sono messo a provarli entrambi... e mi pare ora di essere diventato un vimmaro (pur se molto 'custom' in quanto lo sto rendendo un bel po' + simile a cream). Una domanda stupida. Forse ? pi? da comp.editors. Come faccio a far s? che vim prosegua automaticamente i commenti su pi? righe? Ho settato la lunghezza massima della riga a 79 caratteri, fin qui tutto ok, ma quando vado a capo, anche se la riga inizia con #, vim non lo aggiunge in automatico all'inizio. Al contrario con altri tipi di file (es. Java) questa aggiunta ? automatica e la trovo molto, molto comoda. Dovrei andae a intaccare il file di indentazione? o quello di sintassi? -- Alan Franzoni - Togli .xyz dalla mia email per contattarmi. Remove .xyz from my address in order to contact me. - GPG Key Fingerprint (Key ID = FE068F3E): 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From grante at visi.com Tue May 8 13:52:36 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 08 May 2007 17:52:36 -0000 Subject: 1.#QNAN Solution References: Message-ID: <1341e74982jkr46@corp.supernews.com> On 2007-05-08, Greg Corradini wrote: > I'm running descriptive stats on mileages from a database > (float numbers, about a million records). My sum returns > 1.#QNAN, which I understand from searching this forum is an > error. Not necessarily. You've ended up with a floating point "not a number" value (AKA a NaN). That might or might not be an error. Whether it's an error not not depends on your input data and your algorithm. > While I'm looking for help in solving this problem, I'm more > interested in a general explanation about the cause of this > problem. If you're asking how you end up with a NaN, there are several ways to generate a NaN: 0/0 Inf*0 Inf/Inf Inf-Inf Almost any operation on a NaN http://en.wikipedia.org/wiki/NaN http://steve.hollasch.net/cgindex/coding/ieeefloat.html -- Grant Edwards grante Yow! Spreading peanut at butter reminds me of visi.com opera!! I wonder why? From kinch1967 at gmail.com Mon May 28 07:46:42 2007 From: kinch1967 at gmail.com (bullockbefriending bard) Date: 28 May 2007 04:46:42 -0700 Subject: speeding things up with C++ In-Reply-To: <1180218941.924926.164270@q75g2000hsh.googlegroups.com> References: <1180171179.687276.77930@z28g2000prd.googlegroups.com> <1180218941.924926.164270@q75g2000hsh.googlegroups.com> Message-ID: <1180352801.967590.15600@i38g2000prf.googlegroups.com> thanks! i'll look into this. On May 27, 5:35 am, Che Guevara wrote: > On May 26, 11:19 am, bullockbefriending bard > wrote: > > > However, I hope someone reading this will be able to tell me that I'm > > being a total pessimist and that in fact it isn't very difficult to do > > what I want to do using SWIG. I'm not asking for a complete solution, > > more like some general pointers from someone who has actually done > > something similar before. > > I do stuff like that with ctypes (http://docs.python.org/lib/module-ctypes.html > )! > I'm sure you can figure out some way to pass/return data to/from your C > ++ lib. > The easiest way - use strings or arrays, but if you dig deeper into > ctyles documentation, > I'm sure you will find a better solution! > > Good luck, > -- misreckoning From rene at korteklippe.de Tue May 15 09:14:20 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 15 May 2007 15:14:20 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <4649AF84.7010208@web.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476081.7080609@web.de> <46498514$0$6402$9b4e6d93@newsspool2.arcor-online.net> <4649882E.3060005@web.de> <46499940$0$10199$9b4e6d93@newsspool4.arcor-online.net> <46499BF9.30209@web.de> <4649a2c1$0$10193$9b4e6d93@newsspool4.arcor-online.net> <4649A429.3010406@web.de> <4649ae4a$0$20289$9b4e6d93@newsspool3.arcor-online.net> <4649AF84.7010208@web.de> Message-ID: <4649b22c$0$20289$9b4e6d93@newsspool3.arcor-online.net> Stefan Behnel schrieb: > That's easy to prevent: just keep your fingers from projects that work with > them and make sure that projects you start do not use them. You keep bringing up that argument that completely neglects reality. The same argument can be used to justify anything else (including the opposite of your position: Don't like the fact that Python does not support non-ASCII identifiers? Pick another language!). Let's introduce gotos and all other kinds of funny stuff -- after all, noone is forced to work on a project that uses it! -- Ren? From rene at korteklippe.de Tue May 15 09:22:52 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 15 May 2007 15:22:52 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <4648252D.5020704@web.de> <46483740.4050406@web.de> <46498cb1$0$6411$9b4e6d93@newsspool2.arcor-online.net> <46499273.6050806@web.de> <46499a54$0$10199$9b4e6d93@newsspool4.arcor-online.net> <46499B16.2070901@web.de> <4649a08c$0$23148$9b4e6d93@newsspool1.arcor-online.net> <4649A22C.8010207@web.de> <4649A46D.8070504@korteklippe.de> Message-ID: <4649b42a$0$23140$9b4e6d93@newsspool1.arcor-online.net> Marc 'BlackJack' Rintsch schrieb: >>>> 2) The with-statement does have proven substantial benefits, IMO. >>> Not to me. I don't use it, so no-one should. >> Now you are starting to troll? > > I thought he starts to argument like you. ;-) I did not argue that way. I doubted that non-ASCII identifiers have proven substantial benefits for *anyone* (except very rare and special cases). That is quite different from the with-statement. -- Ren? From C.delete_this.Sanders at BoM.GOv.AU Wed May 30 23:06:53 2007 From: C.delete_this.Sanders at BoM.GOv.AU (Charles Sanders) Date: Thu, 31 May 2007 13:06:53 +1000 Subject: Is PEP-8 a Code or More of a Guideline? In-Reply-To: <1180571360.883706.244950@q66g2000hsg.googlegroups.com> References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <87abvqpl6v.fsf@benfinney.id.au> <1180571360.883706.244950@q66g2000hsg.googlegroups.com> Message-ID: <465e3bcd$0$90644$c30e37c6@lon-reader.news.telstra.net> Dave Hansen wrote: > > The date is about right (actually, a little early: ASR-33, 1965; C, > about 1970), but you can't program C on an ASR-33. Keywords are all > lower case, and always have been. "IF" is a syntax error... > But the Unix terminal drivers of the day for upper case only terminals translated to lower case and you had to enter \A to get an upper case A, and so on. Still hangs around in the stty options iuclc, -iuclc, olcuc and -olcuc - You can make an x-term window look like an old upper case only terminal. I don't know if any still do it, but old unices used to detect on logon if you typed your user name and password in all caps and then turned on the iuclc and olcuc options, assuming that the reason for the all caps was a upper case only terminal - great fun if you hit caps lock by accident. Charles From rene at korteklippe.de Tue May 15 08:15:41 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 15 May 2007 14:15:41 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <4649A22C.8010207@web.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <4648252D.5020704@web.de> <46483740.4050406@web.de> <46498cb1$0$6411$9b4e6d93@newsspool2.arcor-online.net> <46499273.6050806@web.de> <46499a54$0$10199$9b4e6d93@newsspool4.arcor-online.net> <46499B16.2070901@web.de> <4649a08c$0$23148$9b4e6d93@newsspool1.arcor-online.net> <4649A22C.8010207@web.de> Message-ID: <4649A46D.8070504@korteklippe.de> Stefan Behnel schrieb: >> 1) Which additional potential for bugs and which hindrances for >> code-sharing do you see with the with-statement? > > I'm not sufficiently used to it to understand it immediately when I read it. http://www.python.org/dev/peps/pep-0343/ It is not that hard to grasp. > So I would have to look deeper into patches that use it, for example, and > couldn't accept them at first look. Plus, some editors do not highlight it as > a Python keyword. So it should have been rejected. Support for highlighting that is easily added, contrary to support for displaying all possible Unicode glyphs, let alone typing them in easily. >> 2) The with-statement does have proven substantial benefits, IMO. > > Not to me. I don't use it, so no-one should. Now you are starting to troll? > And since it does not make sense > in public projects, it should also be forbidden in in-house projects. It does make alot of sense in public projects, since it actually *does* make the code clearer. A programmer who does not understand it at first can easily find and understand its documentation. The same is *not* true for things like Kanji glyphs and the like. -- Ren? From bj_666 at gmx.net Wed May 2 07:27:27 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 02 May 2007 13:27:27 +0200 Subject: Calling Exe from Python References: <1178102899.910368.114140@n76g2000hsh.googlegroups.com> Message-ID: In <1178102899.910368.114140 at n76g2000hsh.googlegroups.com>, M Abbas wrote: > This is what i am required to do. > Call an executable from my python script, and when the executable is > fininshed running, i should continue with my python script. > > I have tried "os.exec()" but it calls the executable and never returns > to the calling python script. > I tried "os.fork" it will start an independent process, > since logic of my program depends on the results of executable. Take a look at `os.system()` or the `subprocess` module. Ciao, Marc 'BlackJack' Rintsch From gagsl-py2 at yahoo.com.ar Sun May 20 19:52:54 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 20 May 2007 20:52:54 -0300 Subject: Getting the member of a singleton set References: <1179692840.158236.198150@z24g2000prd.googlegroups.com> Message-ID: En Sun, 20 May 2007 17:27:20 -0300, Arnaud Delobelle escribi?: > Hi all, > > I often find myself needing to get (non-destructively) the value of > the member of a singleton set. Is there a good way to do this (as an > expression?) None of the ones I can think of satisfy me, eg: > > * list(myset)[0] > * iter(myset).next() > * set(myset).pop() > > What I would like is something like a 'peek()' function or method > (would return the same as pop() but wouldn't pop anything). I would > like to know of a better idiom if it exists. If not, isn't there a > need for one? Yes, something like peek() or any() would be useful. But you're not restricted by the builtin methods, you could write your own: def peek(iterable): return iter(iterable).next() maybe converting the possible StopIteration into another exception like EmptyContainer(ValueError). > Note: it is comparatively easier to do this destructively: > myset.pop() > or to bind a name to the member: > element, = myset If you know that your set contains exactly one element, I like the later form. > PS: this problem is not restricted to sets but could occur with many > 'container' types. Yes, and I've seen all your expressions, plus some more, like: for x in container: break All of them are rather ugly... -- Gabriel Genellina From martin at v.loewis.de Thu May 17 11:13:38 2007 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Thu, 17 May 2007 17:13:38 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <9TH1i.1773$mR2.1557@newssvr22.news.prodigy.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <9TH1i.1773$mR2.1557@newssvr22.news.prodigy.net> Message-ID: <464C7122.5010607@v.loewis.de> > I'd suggest restricting identifiers under the rules of UTS-39, > profile 2, "Highly Restrictive". This limits mixing of scripts > in a single identifier; you can't mix Hebrew and ASCII, for example, > which prevents problems with mixing right to left and left to right > scripts. Domain names have similar restrictions. That sounds interesting, however, I cannot find the document your refer to. In TR 39 (also called Unicode Technical Standard #39), at http://unicode.org/reports/tr39/ there is no mentioning of numbered profiles, or "Highly Restrictive". Looking at the document, it seems 3.1., "General Security Profile for Identifiers" might apply. IIUC, xidmodifications.txt would have to be taken into account. I'm not quite sure what that means; apparently, a number of characters (listed as restricted) should not be used in identifiers. OTOH, it also adds HYPHEN-MINUS and KATAKANA MIDDLE DOT - which surely shouldn't apply to Python identifiers, no? (at least HYPHEN-MINUS already has a meaning in Python, and cannot possibly be part of an identifier). Also, mixed-script detection might be considered, but it is not clear to me how to interpret the algorithm in section 5, plus it says that this is just one of the possible algorithms. Finally, Confusable Detection is difficult to perform on a single identifier - it seems you need two of them to find out whether they are confusable. In any case, I added this as an open issue to the PEP. Regards, Martin From skip at pobox.com Wed May 2 22:48:09 2007 From: skip at pobox.com (Skip Montanaro) Date: Thu, 3 May 2007 02:48:09 +0000 (UTC) Subject: curses mystical error output References: <17977.2867.158091.217653@montanaro.dyndns.org> Message-ID: > Maybe the Solaris 10 curses stuff is toast? Maybe. the curses and curses_panel modules were linked against crufty stuff in /usr/lib. I've asked our admins to install ncurses. Hopefully that's the cure. Skip From stefan.sonnenberg at pythonmeister.com Tue May 29 18:43:58 2007 From: stefan.sonnenberg at pythonmeister.com (Stefan Sonnenberg-Carstens) Date: Wed, 30 May 2007 00:43:58 +0200 (CEST) Subject: updates in sqlite3 do not work In-Reply-To: <723eb6930705291530w190a7818i71f49d976217f38@mail.gmail.com> References: <723eb6930705291530w190a7818i71f49d976217f38@mail.gmail.com> Message-ID: <1068189.31888.BlRUCl8VTQA=.1180478638.squirrel@webmailer.hosteurope.de> Did you try a commit() ? SQLite3 works in autocommit mode by default, so it would help to see your code. On Mi, 30.05.2007, 00:30, Chris Fonnesbeck wrote: > I have a script set up to perform UPDATE commands on an sqlite database > using the sqlite3 module. Everything appears to run fine (there are no > error > messages), except that none of the UPDATE commands appear to have actually > updated the table. If I run each command on its own in a sqlite session, > the > UPDATE command works fine, so it is not a SQL syntax issue. UPDATE simply > seems not to work. Any idea what the problem might be? > > Thanks, > Chris > -- > http://mail.python.org/mailman/listinfo/python-list From thorsten at thorstenkampe.de Thu May 31 13:44:34 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Thu, 31 May 2007 18:44:34 +0100 Subject: generating a tree-like structure Message-ID: Hi, This is a fairly general question: is there some kind of module or framework that allows building a tree like structure from certain kind of data? To be specific: I have a program that dumps the content of a LDAP directory including all properties and values and groups the result from the LDAP search by objClass. Now I was thinking: would it be possible to generate from the totally unordered output that the LDAP server gives me, a tree like representation that displays the hierarchy (omitting the values or even properties if necessary)? It should be a textual representation of what you see in GUI programs like "LDAP Administrator" but the output should be represented like the "tree" program in Linux or Windows "tree.com". Any ideas appreciated... Thorsten From iltchevi at gmail.com Sun May 6 17:36:15 2007 From: iltchevi at gmail.com (ici) Date: 6 May 2007 14:36:15 -0700 Subject: exporting a record from a database to a MS Word document. In-Reply-To: <1178470927.793357.204080@n76g2000hsh.googlegroups.com> References: <1178470927.793357.204080@n76g2000hsh.googlegroups.com> Message-ID: <1178487375.194284.176940@u30g2000hsc.googlegroups.com> Levi Campbell wrote: > Is there a way to export a record from a database kept with bsddb to > MS Word, possibly with some type of formatting data? import win32com.client try: import psyco; psyco.full() except ImportError: pass app = win32com.client.Dispatch("Word.Application") app.Visible = True doc = app.Documents.Add() para = doc.Paragraphs.Add() para.Range.Text = "DB Record" para.Range.Bold = True #... doc.Close(True) app.Quit() From tjreedy at udel.edu Thu May 10 23:53:09 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 10 May 2007 23:53:09 -0400 Subject: searching algorithm References: <7dydnfjNWbo9H97bnZ2dnUVZ_oupnZ2d@comcast.com> Message-ID: "Neil Cerutti" wrote in message news:lNM0i.34412$G23.27437 at newsreading01.news.tds.net... | Every node is a tuple of its letter, a list of its children, and | a list of its words. So the two 'pelin' nodes would be (with 'e' | referenced in the 'h' node): | | ('h', [('e', [], ['pelin'])], ['pelin']) | | That would in turn be "stored" in the t, n, i and s nodes. [snip] At the outer level, I would use a list in order to build the structure in pieces, one for each letter, and then add them in. At the top level, the letters do not need explicit storage. The first subtree is for words starting with 'a', etc. In other words, the position of each subtree indicates its starting letter. For most letters, this can be carried on another level. tjr From steven.bethard at gmail.com Sat May 12 14:47:08 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 12 May 2007 12:47:08 -0600 Subject: Dynamic subclassing ? In-Reply-To: <1178976888.443891.116090@y80g2000hsf.googlegroups.com> References: <1178976888.443891.116090@y80g2000hsf.googlegroups.com> Message-ID: manatlan wrote: > I've got an instance of a class, ex : > > b=gtk.Button() > > I'd like to add methods and attributes to my instance "b". > I know it's possible by hacking "b" with setattr() methods. But i'd > like to do it with inheritance, a kind of "dynamic subclassing", > without subclassing the class, only this instance "b" ! > > In fact, i've got my instance "b", and another class "MoreMethods" > > class MoreMethods: > def sayHello(self): > print "hello" > > How could i write ... > > "b = b + MoreMethods" You can simply bind the methods you want to add to the Button instance. That means doing the equivalent of ``b.sayHello = sayHello.__get__(b)``. For example:: >>> class Button(object): ... def set_label(self, label): ... print 'setting label:', label ... >>> def add_methods(obj, cls): ... for name, value in cls.__dict__.items(): ... if callable(value) and hasattr(value, '__get__'): ... setattr(obj, name, value.__get__(obj, type(obj))) ... >>> b = Button() >>> b.set_label('k') setting label: k >>> b.say_hello() Traceback (most recent call last): File "", line 1, in AttributeError: 'Button' object has no attribute 'say_hello' >>> class MoreMethods(object): ... def say_hello(self): ... print 'hello' ... >>> add_methods(b, MoreMethods) >>> b.set_label('m') setting label: m >>> b.say_hello() hello HTH, STeVe From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu May 31 10:30:40 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 31 May 2007 16:30:40 +0200 Subject: [OT] Re: HTML Form/Page and Navigation with multiple buttons In-Reply-To: <1180617750.709628.180070@p77g2000hsh.googlegroups.com> References: <1180617750.709628.180070@p77g2000hsh.googlegroups.com> Message-ID: <465edbfa$0$784$426a34cc@news.free.fr> mosscliffe a ?crit : > I am struggling to find a python example of the scenario - I have. > > I have a python script, which generates a page with a search button > (actually an input field). > > The data from the above submissions is interrogated and the same > script produces a new search option and the a page of results from the > previous search request. - as done by Google's Main search page. > > The user then has the option of a new search or navigating to a > different page of results with the usual Start, Previous, Next and > Last Buttons. > > How can I identify which button has been pressed. Do I need a > separate form for each button and hide all the relevant session fields > in each form or is there a way of identifying which button has been > pressed on the page. This is not really a Python problem - would be the same with any server-side techno... You shouldn't use buttons for navigation, but links. The simplest solution is to pass all the relevant data into the query string (the ?key=val&key2=val2&etc=etc part of the url). In your case, this would be something like resending all the search params, and adding the current page and the action (ie 'action=next' or 'action=first' etc...) From sjdevnull at yahoo.com Wed May 16 00:11:08 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 15 May 2007 21:11:08 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476081.7080609@web.de> <46498514$0$6402$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <1179288668.417582.210470@u30g2000hsc.googlegroups.com> Steven D'Aprano wrote: > On Tue, 15 May 2007 12:01:57 +0200, Rene Fleschenberg wrote: > > > Marc 'BlackJack' Rintsch schrieb: > >> You find it in the sources by the line number from the traceback and > >> the letters can be copy'n'pasted if you don't know how to input them > >> with your keymap or keyboard layout. > > > > Typing them is not the only problem. They might not even *display* > > correctly if you don't happen to use a font that supports them. > > Then maybe you should catch up to the 21st century and install some fonts > and a modern editor. It's not just about fonts installed on my desktop. I still do a _lot_ of debugging/code browsing remotely over terminal connections. I still often have to sit down at someone else's machine and help them troubleshoot, often going through the stack trace for whatever package they're using--and I don't have control over which fonts they decide to install. Even simple high-bit latin1 characters differ on vanilla Windows machines vs. vanilla Linux/Mac machines. I even sometimes read code snippets on email lists and websites from my handheld, which is sadly still memory-limited enough that I'm really unlikely to install anything approaching a full set of Unicode fonts. From jzgoda at o2.usun.pl Tue May 15 06:05:09 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Tue, 15 May 2007 12:05:09 +0200 Subject: Iron Python In-Reply-To: <464981fa$0$8759$ed2619ec@ptn-nntp-reader02.plus.net> References: <464981fa$0$8759$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: Jon Harrop napisa?(a): > Anybody tried it? Me. -- Jarek Zgoda "We read Knuth so you don't have to." From mcl.office at googlemail.com Fri May 4 06:41:30 2007 From: mcl.office at googlemail.com (mosscliffe) Date: 4 May 2007 03:41:30 -0700 Subject: Newbie and Page Re-Loading Message-ID: <1178275290.158007.248180@h2g2000hsg.googlegroups.com> I am very new to this python world, but I do like the look of the language / syntax, though I have had some problems with indenting using a text editor. I have managed to get my ISP to execute .py files on their server. I have created a .py file and it does in fact do the various little tasks I have asked it to do. Now i need to get a bit more serious. I wish to have a web page with a search form at the top and on processing the form re-load my current page, but with the various search results. Do I just add my script name to the Action part of the Form and how can I pass variables, other than form variables to each execution of the script. If I have to use hidden form variables, how would I alter them for each page. I suppose I am looking for some sort of session management, but I have not been able to track one down as yet. I am running on an ISP, with no knowledge of python, so asking about getting packages loaded will not be an option. I have 'Python in a Nutshell', but it is a bit sparse on everyday web page examples. Any help with regard to simple examples or tutorials would be most useful. Thanks Richard From chris at newcenturycomputers.net Wed May 23 09:32:17 2007 From: chris at newcenturycomputers.net (Chris Gonnerman) Date: Wed, 23 May 2007 08:32:17 -0500 Subject: Python on Vista installation issues In-Reply-To: References: <1179868315.458709.114000@p47g2000hsd.googlegroups.com> Message-ID: <46544261.3030206@newcenturycomputers.net> Mattia Gentilini wrote: > will ha scritto: > >> Vista is a 64 bit OS and there is no port of pywin32 for either Vista >> or 64-bit XP >> > Vista exists in BOTH 32 bit and 64 bit versions. > Indeed, and this is running on a Core 2 Duo laptop, a 32 bit platform. The problem is obvious (or seems to be)... the installer for Python (which is a "professional" installer) has set the c:\python25 folder privileges so that the installers for the extensions (which are the pocket-sized installers from the distutils) can't write files in that folder. The site-packages folder is evidently marked "public" (however that is done) so that the installation of files into that folder by the extension installers works fine. But then, there is also a restricted registry key that is blocking the win32all installer from working properly. I hate Vista. Does anyone like it? Okay, that's off topic, but I had to vent. -- ------------------------------------------------------------------------------- Chris Gonnerman Owner, New Century Computers Phone 660-213-3822 Fax 660-213-3339 -------------- next part -------------- An HTML attachment was scrubbed... URL: From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon May 14 12:27:30 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 14 May 2007 18:27:30 +0200 Subject: Asyncore Help? References: Message-ID: <5argviF2qb4baU1@mid.individual.net> Nick Craig-Wood wrote: > http://twistedmatrix.com/trac/ > > The learning curve of twisted is rather brutal, NACK, the tutorial is -- IMHO -- rather easy if you are used to writing Python code and doing asynchronous programming. > but it will do everything you want and a whole lot more! That's true. More Twisted, less work (and less headache). IMHO. Regards, Bj?rn -- BOFH excuse #242: Software uses US measurements, but the OS is in metric... From edreamleo at charter.net Mon May 21 10:37:21 2007 From: edreamleo at charter.net (Edward K Ream) Date: Mon, 21 May 2007 09:37:21 -0500 Subject: Leo 4.4.3 beta 1 released Message-ID: Leo 4.4.3 beta 1 is available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 Leo is a text editor, data organizer, project manager and much more. See: http://webpages.charter.net/edreamleo/intro.html The highlights of Leo 4.4.3: ---------------------------- - Added support for chapters in Leo's core. Chapters are disabled by default. To enable, set @bool use_chapters=True. - Added support for zipped .leo files. - Added a leoBridge module that allows full access to all of Leo's capabilities from programs running outside of Leo. - Removed all gui-dependent code from Leo's core. - Better support for the winpdb debugger. - Added support for @enabled-plugins nodes in settings files. - Added support for @open-with nodes in settings files. - The__wx_gui plugin is now functional. - Many minor improvements, new settings, commands and bug fixes. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html Home: http://sourceforge.net/projects/leo/ Download: http://sourceforge.net/project/showfiles.php?group_id=3458 CVS: http://leo.tigris.org/source/browse/leo/ Quotes: http://webpages.charter.net/edreamleo/testimonials.html -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From konrad.hinsen at laposte.net Mon May 21 09:30:12 2007 From: konrad.hinsen at laposte.net (Konrad Hinsen) Date: Mon, 21 May 2007 15:30:12 +0200 Subject: Installing Python in a path that contains a blank Message-ID: <78EF1A14-FDAF-4A41-B17A-D23159804F6D@laposte.net> I am trying to install Python from sources in my home directory on a Mac cluster (running MacOS X 10.4.8). The path to my home directory contains a blank, and since the installation procedure insists on getting an absolute path for the prefix, I cannot avoid installing to a path whose name contains a blank. Python does not seem to be prepared for this, as it uses only the part before the blank, resulting in numerous error messages. Does anyone know a workaround? Thanks, Konrad. From tjreedy at udel.edu Wed May 9 14:53:17 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 9 May 2007 14:53:17 -0400 Subject: Single precision floating point calcs? References: <1343v0emvdjr545@corp.supernews.com> Message-ID: "Grant Edwards" wrote in message news:1343v0emvdjr545 at corp.supernews.com... | I'm pretty sure the answer is "no", but before I give up on the | idea, I thought I'd ask... | Is there any way to do single-precision floating point | calculations in Python? Make your own Python build from altered source. And run it on an ancient processor/OS/C compiler combination that does not automatically convert C floats to double when doing any sort of calculation. Standard CPython does not have C single-precision floats. The only point I can think of for doing this with single numbers, as opposed to arrays of millions, is to show that there is no point. Or do you have something else in mind? Terry Jan Reedy From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed May 2 10:49:17 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 02 May 2007 16:49:17 +0200 Subject: Is it possible to determine what a function needs for parameters - In-Reply-To: <1178115727.932794.100390@h2g2000hsg.googlegroups.com> References: <1178115727.932794.100390@h2g2000hsg.googlegroups.com> Message-ID: <4638a4eb$0$2033$426a74cc@news.free.fr> rh0dium a ?crit : > Hi all, > > Below is a basic threading program. The basic I idea is that I have a > function which needs to be run using a queue of data. Early on I > specified my function needed to only accept basic parameters ( no > postional *args or *kwargs ) but now I am re-writing it and I want to > accept these. Is there anyway to determine what parameters are needed > by a given function and format the arguments given appropriately. Yes - using inspect.getargspec. I don't have example code at hand yet, but it's not really complicated. From nospam1.reifenberg at gmx.de Wed May 30 11:46:50 2007 From: nospam1.reifenberg at gmx.de (Nebur) Date: 30 May 2007 08:46:50 -0700 Subject: How can an Exception pass over an "except" clause ? Message-ID: <1180540010.548057.220270@m36g2000hse.googlegroups.com> I'm using the contract.py library, running Python 2.4.4. Now I'm confronted with the following exception backtrace: (...) File "/usr/lib/python2.4/site-packages/contract.py", line 1265, in _check_preconditions p = f.__assert_pre AttributeError: 'function' object has no attribute '__assert_pre' For my surprise, I found that the code of contract.py around line 1265 looks like: 1264: try: 1265: p = f.__assert_pre 1266: except AttributeError: 1267: pass I'd expect line 1267 to "swallow" the AttributeError siliently. But the application stops with the above backtrace. Someone familiar enough with the Python innards ? How can one manage that an "except" seems to be ignored ? Ruben From eric.brunel at pragmadev.com Mon May 14 04:49:28 2007 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Mon, 14 May 2007 10:49:28 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> Message-ID: On Sun, 13 May 2007 23:55:11 +0200, Bruno Desthuilliers wrote: > Martin v. L?wis a ?crit : >> PEP 1 specifies that PEP authors need to collect feedback from the >> community. As the author of PEP 3131, I'd like to encourage comments >> to the PEP included below, either here (comp.lang.python), or to >> python-3000 at python.org >> In summary, this PEP proposes to allow non-ASCII letters as >> identifiers in Python. If the PEP is accepted, the following >> identifiers would also become valid as class, function, or >> variable names: L?ffelstiel, chang?, ??????, or ??? >> (hoping that the latter one means "counter"). >> I believe this PEP differs from other Py3k PEPs in that it really >> requires feedback from people with different cultural background >> to evaluate it fully - most other PEPs are culture-neutral. >> So, please provide feedback, e.g. perhaps by answering these >> questions: >> - should non-ASCII identifiers be supported? > > No. > >> why? > > Because it will definitivly make code-sharing impossible. Live with it > or else, but CS is english-speaking, period. I just can't understand > code with spanish or german (two languages I have notions of) > identifiers, so let's not talk about other alphabets... +1 on everything. > NB : I'm *not* a native english speaker, I do *not* live in an english > speaking country, ... and so am I (and this happens to be the same country as Bruno's...) > and my mother's language requires non-ascii encoding. ... and so does my wife's (she's Japanese). > And I don't have special sympathy for the USA. And yes, I do write my > code - including comments - in english. Again, +1. Even when writing code that appears to be "private" at some time, one *never* knows what will become of it in the future. If it ever goes public, its chances to evolve - or just to be maintained - are far bigger if it's written all in english. -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From aleax at mac.com Sat May 12 19:13:48 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 12 May 2007 16:13:48 -0700 Subject: Basic question References: <1178986686.510137.195490@p77g2000hsh.googlegroups.com> <1178991933.421386.58500@u30g2000hsc.googlegroups.com> <1178992910.318929.77790@e51g2000hsg.googlegroups.com> <1178995630.925969.207740@w5g2000hsg.googlegroups.com> Message-ID: <1hy0cy8.eg6p1p135hbo3N%aleax@mac.com> Cesar G. Miguel wrote: > On May 12, 3:40 pm, Dmitry Dzhus wrote: > > > Actually I'm trying to convert a string to a list of float numbers: > > > str = '53,20,4,2' to L = [53.0, 20.0, 4.0, 2.0] > > > > str="53,20,4,2" > > map(lambda s: float(s), str.split(',')) > > > > Last expression returns: [53.0, 20.0, 4.0, 2.0] > > -- > > Happy Hacking. > > > > Dmitry "Sphinx" Dzhushttp://sphinx.net.ru > > Nice! As somebody else alredy pointed out, the lambda is supererogatory (to say the least). > The following also works using split and list comprehension (as > suggested in a brazilian python forum): > > ------------------- > L = [] > file = ['5,1378,1,9', '2,1,4,5'] > str='' > for item in file: > L.append([float(n) for n in item.split(',')]) The assignment to str is useless (in fact potentially damaging because you're hiding a built-in name). L = [float(n) for item in file for n in item.split(',')] is what I'd call Pythonic, personally (yes, the two for clauses need to be in this order, that of their nesting). Alex From steve at holdenweb.com Thu May 17 20:53:39 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 17 May 2007 20:53:39 -0400 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464CDC36.1030709@v.loewis.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <464C5382.6080403@v.loewis.de> <1179423799.254286.294930@w5g2000hsg.googlegroups.com> <464CD15A.9070409@v.loewis.de> <464CDC36.1030709@v.loewis.de> Message-ID: Martin v. L?wis wrote: > Neil Hodgson schrieb: >> Martin v. L?wis: >> >>> ... regardless of whether this PEP gets accepted >>> or not (which it just did). >> Which version can we expect this to be implemented in? > > The PEP says 3.0, and the planned implementation also targets > that release. > Can we take it this change *won't* be backported to the 2.X series? 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From aleax at mac.com Thu May 3 10:51:21 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 3 May 2007 07:51:21 -0700 Subject: newbie: copy base class fields References: <1178201644.920048.205400@y5g2000hsa.googlegroups.com> Message-ID: <1hxj1dx.12vysql15urxvfN%aleax@mac.com> tmp123 wrote: ... > It seems that the statement "self=a" is not the correct way to copy > all the fields of the base class from the __init__ argument to the new > object. Indeed, it isn't. Assigning to self just rebinds the name 'self' as a local variable of method B.__init__ -- really useless. > Of course, it is not an option to copy one by one all the fields of > class A inside the __init__ of B. > > Several variants of the program produces similar results. > > Please, could someone explain which way is the correct way? Somebody else suggested you call A.__init__ from inside B.__init__, and that is correct if what you want to do is "freshly initialize the B instance as an A". However, from the fact that you pass to B.__init__ an argument 'a', it looks as if what you're trying to do is indeed copy each of a's instance variables to self (it's hard to read your mind from the code you've posted, but if I had to guess that would be by guess), where a is an instance of A that's not necessarily "freshly initialized". In this case, you might for example start B.__init__ with: self.__dict__.update(a.__dict__) This is not very elegant or solid, but at least it's short and fast:-). A better way would require having _somewhere_ a list or tuple with the names of all the instance variables you know you want to copy; if that list of names was for example B._names_to_copy, for name in self._names_to_copy: value = getattr(a, name) setattr(self, name, value) IS elegant and robust. The advantages of explicitly controlling what names you're copying (rather than blindly taking whatever happens to be there) are similar to those of avoiding "from wherever import *": you avoid accidental name pollution. The advantages of using getattr and setattr (rather than blindly working on the __dict__s) are those of working correctly and transparently with properties and other similar kinds of descriptors, rather than just "raw" instance variables. Alex From half.italian at gmail.com Mon May 28 16:36:34 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 28 May 2007 13:36:34 -0700 Subject: User input with a default value that can be modified In-Reply-To: References: Message-ID: <1180381487.966364.31700@o11g2000prd.googlegroups.com> On May 28, 11:52 am, "Etienne Hilson" wrote: > Hello the list :-) > > I do a little program that permit the user to manage list of sentences. > This program runs into a linux shell. > The user can add, modify and delete the sentences. > > What I want to do is : > > When the user want to modify one sentence, I would like to do this : > > Modify your sentence : The_sentence_appear_here_followed_by_a_cursor > > And the user can go back with the cursor, like in the bash shell, > delete, modify, and when pressing enter, the new value (or the same if > not modified) is put in my variable. > > Of course, the first think I did as a newbie was : > > new_sentence = raw_input("Modify your sentence : "old_sentence) > > But OF COURSE, stupid am I, the user cannot put the cursor back into > the old sentence ! > > I think about playing with some sophisticated keyboard exercise where > I could program a new input command with a value already appearing as > answer, but I am pretty sure that it exists already. > > What do you think about it ? > > Actually, it is quite difficult to find anything on it, because the > keywords are not very obvious (input, default answer, ...) > > Thank you for your help. > > Etienne > -- > (\__/) > (='.'=) Ceci est un petit lapin. Copiez/collez-le dans > (")_(") votre signature pour l'aider ? dominer le monde Check into the readline module. This is what I came up with. A second thread injects the text into the open readline instance. Hopefully the experts will show the _right_ way to do it. import readline, threading import time class write(threading.Thread): def __init__ (self, s): threading.Thread.__init__(self) self.s = s def run(self): time.sleep(.01) readline.insert_text(self.s) readline.redisplay() write("Edit this sentence").start() s = raw_input("prompt:") print s ~Sean From ebgssth at gmail.com Mon May 21 09:57:31 2007 From: ebgssth at gmail.com (js ) Date: Mon, 21 May 2007 22:57:31 +0900 Subject: howto check does module 'asdf' exist? (is available for import) In-Reply-To: <1179753436.736228.321400@x35g2000prf.googlegroups.com> References: <1179753436.736228.321400@x35g2000prf.googlegroups.com> Message-ID: Why not just use try? Trying to import a module is a python idiom. http://www.diveintopython.org/file_handling/index.html On 21 May 2007 06:17:16 -0700, dmitrey wrote: > howto check does module 'asdf' exist (is available for import) or no? > (without try/cache of course) > Thx in advance, D. > > -- > http://mail.python.org/mailman/listinfo/python-list > From gh at gregor-horvath.com Fri May 18 13:06:06 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Fri, 18 May 2007 19:06:06 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179503525.018943.95740@u30g2000hsc.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <464C5382.6080403@v.loewis.de> <1179423799.254286.294930@w5g2000hsg.googlegroups.com> <1179503525.018943.95740@u30g2000hsc.googlegroups.com> Message-ID: <43323$464ddcff$547078de$3808@news.chello.at> Istvan Albert schrieb: > On May 17, 2:30 pm, Gregor Horvath wrote: > >> Is there any difference for you in debugging this code snippets? > >> class T?rstock(object): > > Of course there is, how do I type the ? ? (I can copy/paste for > example, but that gets old quick). > I doubt that you can debug the code without Unicode chars. It seems that you do no understand German and therefore you do not know what the purpose of this program is. Can you tell me if there is an error in the snippet without Unicode? I would refuse to try do debug a program that I do not understand. Avoiding Unicode does not help a bit in this regard. Gregor From rowan at sylvester-bradley.org Thu May 10 08:16:45 2007 From: rowan at sylvester-bradley.org (rowan at sylvester-bradley.org) Date: 10 May 2007 05:16:45 -0700 Subject: Change serial timeout per read In-Reply-To: References: <1178754931.060029.135800@w5g2000hsg.googlegroups.com> Message-ID: <1178799405.221408.232080@o5g2000hsb.googlegroups.com> > you will probably have to make the port non blocking, and roll your own > using different time.sleep(n) values between invocations to port.read(1) calls What I actually want to do is to respond immediately if the expected string comes in, but not raise a timeout unless it takes longer than the maximum time. So if the device I'm communicating with usually responds in a second, but _can_ take up to 20 seconds, I don't want to do a sleep(20) then read the port since this will slow everything down a lot in an average world. I want to keep checking for the expected string, and act upon it as soon as I've got it, only raising a timeout if I haven't got it after 20 seconds. I guess to do this using non- blocking calls I have to do something like: timesofar = 0 returnstring = port.read(1) while len(returnstring)= timeout: raise SerialException('Timeout') time.sleep(checkportinterval) timesofar += checkpointinterval returnstring += port.read(1) This seems rather messy. What I've tried this morning is to produce a modified version of uspp with a second optional timeout parameter in its read() function. If this is present, the timeout given is sent to the port using SetCommTimeouts(). If it's not present, the timeouts specified when the port was opened are sent. At first sight, with minimal testing on Windows, this seems to be working, and will leave my application code a lot cleaner than the non-blocking plus sleep approach. Of course I don't know whether my method will work on Linux, and there may be problems I haven't found yet. Rowan From sjmachin at lexicon.net Sat May 5 20:17:55 2007 From: sjmachin at lexicon.net (John Machin) Date: Sun, 06 May 2007 10:17:55 +1000 Subject: FIXED: webmaster@python.org In-Reply-To: References: Message-ID: <463D1EB3.8060400@lexicon.net> On 6/05/2007 9:11 AM, Aahz wrote: > In article , Aahz wrote: >> In article , >> Carsten Haese wrote: >>> I just tried sending an email to webmaster at python.org to request a >>> website change, and the email bounced back with this excerpt from the >>> delivery failure report: >> Oops! I've informed the appropriate people. >> For now, either hang on to your request or send it directly to me. >> Thanks for letting us know! > > Okay, anyone who was trying to send e-mail to the webmasters should try > again. uh-huh, but PyPI search doesn't return, and PyPI browse cops this: """ Error... There's been a problem with your request psycopg.ProgrammingError: ERROR: could not serialize access due to concurrent update delete from browse_tally """ From gagsl-py2 at yahoo.com.ar Mon May 7 03:39:36 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 07 May 2007 04:39:36 -0300 Subject: Problem to Download ftp file References: <1D011717865DAE46B56AA1455F02CAC5C952DB@n1ex> Message-ID: En Mon, 07 May 2007 02:27:59 -0300, Shakil Ahmed escribi?: > Actually i need to know that how can i download a ftp file from ncbi by > using python module ftputil. > > import ftputil > > host = ftputil.FTPHost('ftp.ncbi.nih.gov/repository/OMIM/morbidmap', > 'anonymous', 'password') The "host" is the first part, "ftp.ncbi.nih.gov". The remaining parts are a directory and a filename. You should write: host = ftputil.FTPHost('ftp.ncbi.nih.gov','anonymous', 'password') host.chdir('repository/OMIM') host.download('morbidmap','path/to/local/file/morbidmap','b') See the ftputil documentation for more info. -- Gabriel Genellina From mail at microcorp.co.za Thu May 24 04:24:20 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 24 May 2007 10:24:20 +0200 Subject: Lists vs tuples (newbie) References: Message-ID: <000201c79eb1$28bb1de0$03000080@hendrik> "Neil Cerutti" wrote: > On 2007-05-22, Duncan Booth wrote: > > "Hendrik van Rooyen" wrote: > > > >> Aside from the hashing issue, there is nothing that a tuple can do > >> that can't be done as well or better by a list. > > > > There are a few other cases where you have to use a tuple, for > > example in a try..except statement the exception specification > > must be an exception to be caught or a tuple of exception > > specifications: a list won't work to catch multiple exceptions. > > I use tuples simply because of their mellifluous appellation. > I did not realise that you kept a bee... :-) - Hendrik From S.Mientki-nospam at mailbox.kun.nl Thu May 24 16:01:36 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Thu, 24 May 2007 22:01:36 +0200 Subject: Python and GUI In-Reply-To: References: <1179761984.704369.116310@b40g2000prd.googlegroups.com> <4651CDBC.1070508@ulmcnett.com> Message-ID: <5abb0$4655ee4c$d443bb3a$510@news.speedlinq.nl> > > Finally, consider wax (http://zephyrfalcon.org/labs/wax.html). In my > view, this is *exactly* what python needs, and its not being maintained > anymore as far as I can tell. What I like about it is: > > 1) it is small...I can include the entire wax distribution in my app > with only a 780k footprint. > 2) it is a very thin layer on wx, so when something doesn't quite work, > I can immediately fall back onto wx, mixing and matching wax and wx > objects. it's just that the wax objects have more pythonic calling and > use properties > Sorry I don't know wax, but I wonder "a GUI designer without screenshots", is that Pythonic ;-) cheers, Stef From mahall at ncsa.uiuc.edu Wed May 30 14:29:38 2007 From: mahall at ncsa.uiuc.edu (Matteo) Date: 30 May 2007 11:29:38 -0700 Subject: Appending a log file and see progress as program executes In-Reply-To: References: Message-ID: <1180549778.237118.291090@p47g2000hsd.googlegroups.com> On May 30, 1:03 pm, "Karim Ali" wrote: > Hi, > > I am writing a program that will take several days to execute :) and would > like to append to a log file but be able to open that file at any time and > see the errors that have occured. > > So this is what I am doing: > > ---------------------------------------------- > flog = open('out.log', 'a') > .... > when needed: > sys.stdout=flog > print "error message" > -------------------------------------------- I imagine that your problem is that stdout is buffered, and hence only writes to the output when the buffer is full. To ameliorate this, you can use flog.flush() after every print statement. Other alternatives: - Use stderr for printing log messages, and run python in unbuffered mode (python -u script.py) You can store the log file by redirecting stderr. Using bash, this would be: python -u script.py 2>out.log - Write an autoflush class: class AutoFlush: def __init__(self, stream): self.stream = stream def write(self, text): self.stream.write(text) self.stream.flush() ... flog=open('out.log','a') flog=AutoFlush(flog) print >>flog,"I'm a message!" Note that instead of changing stdout, you can also print directly to a file with: print >>flog,"Something to print" cheers, -matt From S.Mientki-nospam at mailbox.kun.nl Mon May 14 16:09:32 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Mon, 14 May 2007 22:09:32 +0200 Subject: os.listdir() doesn't work ?? Message-ID: hello, I want to find all files with the extension "*.txt". From the examples in "Learning Python, Lutz and Asher" and from the website I see examples where you also may specify a wildcard filegroup. But when I try this files = os.listdir('D:\\akto_yk\\yk_controle\\*.txt') I get an error message WindowsError: [Errno 123] The filename, directory name, or volume label syntax is incorrect: 'D:\\akto_yk\\yk_controle\\*.txt/*.*' What am I doing wrong ? thanks, Stef Mientki From fabiofz at gmail.com Wed May 30 08:56:39 2007 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Wed, 30 May 2007 09:56:39 -0300 Subject: Pydev 1.3.4 Released Message-ID: Hi All, Pydev and Pydev Extensions 1.3.4 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: ----------------------------------------------------------------- * Mark Occurrences: 'global' used in the global scope is correctly treated. * Code Analysis: __builtins__ considered in global namespace Release Highlights in Pydev: ---------------------------------------------- * Debugger: Breakpoints working correctly on external files opened with 'File > Open File...'. * Debugger: Python 2.5 accepts breakpoints in the module level. * Debugger: Unicode variables can be shown in the variables view. * Editor: Coding try..except / try..finally auto-dedents. * Code Completion: __builtins__ considered a valid completion * Pydev Package Explorer: Opens files with correct editor (the pydev editor was forced). 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 xah at xahlee.org Thu May 3 10:49:33 2007 From: xah at xahlee.org (Xah Lee) Date: 3 May 2007 07:49:33 -0700 Subject: ignorance and intolerance in computing communties In-Reply-To: <1178120019.271716.299590@e65g2000hsc.googlegroups.com> References: <1178120019.271716.299590@e65g2000hsc.googlegroups.com> Message-ID: <1178203772.243333.24990@p77g2000hsh.googlegroups.com> Xah Lee wrote: ? ... ?Ignorance And Intolerance In Online Computing Communities? http://xahlee.org/Netiquette_dir/ignorance_intolerance.html ... As i have indicated in my post, it is non-trivial to implement a function that returns the positive angle of a vector.... ? I have now coded this. I think it is probably the most algorithmically optimal, and rather much simpler than i originally thought. Here's the Mathematica code: vectorAngle[{a1_, a2_}] := Module[{x, y}, {x, y} = {a1, a2}/Sqrt[a1^2 + a2^2] // N; If[x == 0 && y == 0, "fucked", If[x == 0, If[Sign at y === 1, ?/2, -?/2], If[y == 0, If[Sign at x === 1, 0, ?], If[Sign at y === 1, ArcCos at x, 2 ? - ArcCos at x] ] ] ] ] Btw, if we can use any Mathematica's buildin function, this is actually just vectorAngle2[{a1_, a2_}] := Arg@(Complex @@ {a1, a2}) I'm still interested, if someone would show the source code, of how Perl, Python, or Lisp or Java, implement the function that finds the angle of a complex number. Originally, i was also hoping perhaps there's some math trick by dot product or combination of trig functions, that obviates the need to check which quadrant the vector is in ... Xah xah at xahlee.org ? http://xahlee.org/ From deepbroke3 at gmail.com Tue May 22 14:22:42 2007 From: deepbroke3 at gmail.com (deepbroke3 at gmail.com) Date: 22 May 2007 11:22:42 -0700 Subject: Make $404 a day from home! Message-ID: <1179858162.039899.122240@x18g2000prd.googlegroups.com> http://adsenseonline.info - Find out how to make a fortune working from home! From half.italian at gmail.com Thu May 10 17:28:03 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 10 May 2007 14:28:03 -0700 Subject: Newbie look at Python and OO In-Reply-To: <1178832102.256466.235020@l77g2000hsb.googlegroups.com> References: <1178812734.860473.236370@y80g2000hsf.googlegroups.com> <1178832102.256466.235020@l77g2000hsb.googlegroups.com> Message-ID: <1178832483.730331.248430@n59g2000hsh.googlegroups.com> On May 10, 2:21 pm, half.ital... at gmail.com wrote: > walterbyrd wrote: > > I learned to program with Pascal, way back when. Went into software > > development for a while, then went into systems admin. Have programmed > > in several languages, just learning Python. > > > Some things I find odd: > > > 1) 5/-2 == -3? > > > 2) list assignment handling, pointing two vars to the same list: > > > With simple data types: > > >>> a = 5 > > >>> b = a > > >>> a = 3 > > >>> a,b > > (3, 5) > > > Which is what I'd expect, since I have changed a, but not b. > > > But with lists: > > >>> a = list("1234") > > >>> b = a > > >>> a.append("5") > > >>> a,b > > (['1', '2', '3', '4', '5'], ['1', '2', '3', '4', '5']) > > > b changes even though I have not touched b. I know why, but this is > > not what I would ordinarilly expect, it does not seem intuitive. And, > > IMO, it gets worse: > > > >>> a = list("1234") > > >>> b = a > > >>> a = a + ['5'] > > >>> a,b > > (['1', '2', '3', '4', '5'], ['1', '2', '3', '4']) > > > Sometimes changing a changes b, and sometimes not. You also have to > > remember that subseqent changes to a will not change b - after some > > operation but not others. To those who think in Python, I'm sure this > > all seems normal. But, having programmed in about one dozen other > > language, this seems downright bizare to me. I know why it works like > > this, but it seems like an odd way to do things. > > > 3) ambiguous use of the form: this.that() > > > Sometimes, this.that() means module.funcion() as in: > > > >>> os.dirlist(".") > > > Other times, "this" is sort of like a parameter to the "that" > > function: > > > >>> a = list("1234") > > >>> "_".join(a) > > '1_2_3_4_5' > > > And still other times, is seems that "this" is an object, acted upon > > by "that" : > > > >>> a = list("1234") > > >>> b = "_".join(a) > > >>> b.split("_") > > ['1', '2', '3', '4', '5'] > > > BTW: it seems a bit odd to that the positions of the string, and the > > delimitor, are reversed between the complementory functions join(), > > and split(). I suppose if it weren't for OO, we have something > > terribly complicated, like: > > > split(str, "_") > > join(str, "_") > > > Again, those who think in Python, will understand right away that: > > > math.count(x) > > > is counting the substring "x" in the "math" string. But can you see > > where that might be confused to be a function called count() in the > > math module? > > > I'm not complaining. Python is a great language in many respects. But, > > I would take some issue with those claiming Python is intuitive and > > easy. IMO: there seems to be many ambiguous, unintuitve, and > > confusing, aspects to Python. > > These conversations are funny to me. I use Python every day and I > have never actually thought about the implications of binding objects > to names, or two names pointing to the same object. Problems of this > sort just never come up in actual programming for me. It just works. > > Python was my virgin language, so maybe that just makes it natural to > me, but it seems like people coming from other languages get hung up > on testing out the differences and theories rather than just > programming in it. Alas, maybe I have yet to get deep enough to run > into these kinds of problems. > > The question of what math is in math.count(x) makes sense, but this > one never comes up either (or rarely). I usually know what the object > is that I'm working with. > > ~Sean After thought: I do run into problems testing boolean values on a regular basis. Probably should learn all the rules on them and use them properly, but as a general rule I just don't use them, and test for the value instead. ~Sean From mailmaverick666 at gmail.com Mon May 7 03:14:32 2007 From: mailmaverick666 at gmail.com (rishi pathak) Date: Mon, 7 May 2007 12:44:32 +0530 Subject: N00b question on Py modules In-Reply-To: <1178521238.333095.111370@h2g2000hsg.googlegroups.com> References: <1178521238.333095.111370@h2g2000hsg.googlegroups.com> Message-ID: <180b672e0705070014j7a7bc4fbn957443bc5aca2e4@mail.gmail.com> Hi this variable is local to function do this def setExitCode(): global _exitcode _exitcode = 1 On 7 May 2007 00:00:38 -0700, lokesh.jagasia at gmail.com < lokesh.jagasia at gmail.com> wrote: > > Hi. Sorry to sound like a noob but that's what I am when it comes to > Python. I just wrote the below module and it behaves funny. > > My python module: > > _exitcode = 0 > > def setExitCode(): > _exitcode = 1 this variable is local to function if __name__ == '__main__': > print _exitcode > setExitCode() > print _exitcode > > Actual O/P: > 0 > 0 > > I expected to see an output of 0 followed by 1. But it turns out that > the _exitcode variable is not changed at all. It seems that > setExitCode() might be editing a local copy of the _exitcode variable. > But then, how do I tell it to change the value of the module variable > and not its local variable. > > I've been through the modules section of Python docs and a few ebooks > as well, all suggest that it shouldn't be working this way. > > Please help out ppl. > > Thanks > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Regards-- Rishi Pathak National PARAM Supercomputing Facility Center for Development of Advanced Computing(C-DAC) Pune University Campus,Ganesh Khind Road Pune-Maharastra -------------- next part -------------- An HTML attachment was scrubbed... URL: From aisaac at american.edu Wed May 9 09:42:53 2007 From: aisaac at american.edu (Alan Isaac) Date: Wed, 09 May 2007 13:42:53 GMT Subject: change of random state when pyc created?? References: Message-ID: "Peter Otten" <__peter__ at web.de> wrote in message news:f1rt61$kfg$03$1 at news.t-online.com... > Alan Isaac wrote: > There is nothing wrong with the random module -- you get the same numbers on > every run. When there is no pyc-file Python uses some RAM to create it and > therefore your GridPlayer instances are located in different memory > locations and get different hash values. This in turn affects the order in > which they occur when you iterate over the GridPlayer.players_played set. Thanks!! This also explains Steven's results. If I sort the set before iterating over it, the "anomaly" disappears. This means that currently the use of sets (and, I assume, dictionaries) as iterators compromises replicability. Is that a fair statement? For me (and apparently for a few others) this was a very subtle problem. Is there a warning anywhere in the docs? Should there be? Thanks again!! Alan Isaac From kinch1967 at gmail.com Sat May 19 19:46:41 2007 From: kinch1967 at gmail.com (bullockbefriending bard) Date: 19 May 2007 16:46:41 -0700 Subject: regex matching question In-Reply-To: <464F86F0.8080100@lexicon.net> References: <1179595319.239229.262160@l77g2000hsb.googlegroups.com> <464F86F0.8080100@lexicon.net> Message-ID: <1179618401.049401.152850@e65g2000hsc.googlegroups.com> > Backslash? Your example uses a [forward] slash. correct.. my mistake. i use forward slashes. > Are you sure you don't want to allow for some spaces in the data, for > the benefit of the humans, e.g. > 1,2 / 3,4 / 5,6 / 7,8 / 9,10 / 11,12 you are correct. however, i am using string as a command line option and can get away without quoting it if there are no optional spaces. > Always use "raw" strings for patterns, even if you don't have > backslashes in them -- and this one needs a backslash; see below. knew this, but had not done so in my code because wanted to use '\' as a line continuation character to keep everything within 80 columns. have adopted your advice regarding \Z below and now am using raw string. > For clarity, consider using "mobj" or even "m" instead of "match" to > name the result of re.match. good point. > > if match == None or match.group(0) != results: > > Instead of > if mobj == None .... > use > if mobj is None ... > or > if not mobj ... > > Instead of the "or match.group(0) != results" caper, put \Z (*not* $) at > the end of your pattern: > mobj = re.match(r"pattern\Z", results) > if not mobj: > > HTH, > John very helpful advice. thanks! From JoeSalmeri at hotmail.com Sat May 19 09:03:15 2007 From: JoeSalmeri at hotmail.com (Joe Salmeri) Date: Sat, 19 May 2007 09:03:15 -0400 Subject: pyodbc.Error Crash References: Message-ID: <2ZSdnRVR063AaNPbnZ2dnUVZ_u6rnZ2d@comcast.com> Thanks, I reported them there first and then posted here in case they monitor the forum more frequently and so others would be aware of the problems found. Joe "Gabriel Genellina" wrote in message news:mailman.7887.1179559771.32031.python-list at python.org... > En Fri, 18 May 2007 20:48:49 -0300, Joe Salmeri > escribi?: > >> I believe this bug is also related to the other problem I just reported. > > I think you'll get best results reporting them to the author(s) directly: > http://pyodbc.sourceforge.net/ and click on "Bug tracker" > > -- > Gabriel Genellina > From steve at holdenweb.com Thu May 31 22:07:44 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 31 May 2007 22:07:44 -0400 Subject: c[:]() In-Reply-To: <001a01c7a3ed$a49c93d0$240110ac@Muse> References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> <135tobve86qj808@corp.supernews.com> <135tru124pie2b3@corp.supernews.com> <135tv1bjqgbmsc9@corp.supernews.com> <003301c7a3ab$f2bdf960$240110ac@Muse> <001801c7a3cc$e9f0b270$240110ac@Muse> <001a01c7a3ed$a49c93d0$240110ac@Muse> Message-ID: <465F7F70.9080403@holdenweb.com> Warren Stringer wrote: >>> What?!? I started this thread. >>> >> No you didn't. Your original post was a reply to a message whose subject >> line was 'Re: "is" and ==', and included the header >> >> In-Reply-To: <1180504773.374529.161740 at q66g2000hsg.googlegroups.com> > > You're right, thanks. > >>>> I think the fundamental mistake you have made is to convince yourself >> that >>>> c[:]() >>>> >>>> is legal Python. It isn't, it never has been. > > In my opinion, it is better to ask me directly what I think than to assume > what I am thinking. Describing a situation in second person -- using "you" > -- tends to have more interpretation than fact. When the interpretation is > wrong, the person who is at the receiving end of that "you" may be compelled > to reply. Sometimes that correction includes another "you"; interpretation > spawns interpretation -- soon, facts are replaced by projectiles. > Well I don't think there's much chance of that here. Please accept my apologies if I misunderstood you. >>> In summation: >>> I started this thread asking why c[:]() wouldn't work >>> I did not hijack another thread >>> I posted working examples (with one typo, not quoted here) >>> I am extremely annoyed by this post >>> >>> Tis best not to assume what other people are thinking >>> >> Probably best not to try to help them too, if this is the response. > > I do appreciate your help. Responding on topic helps. Negative feedback > regarding typos helps. And, your statement: > > > Perhaps you didn't express yourself too clearly. > > makes me feel all warm and fuzzy like ... why thank you! > Well clearly I'd rather you were responsible for the miscommunication than I, but I don't *have* to be right about everything. And mostly I try to help. >> Next >> time you want assistance try to ensure that you copy and paste your >> examples instead of trying to duplicate them from memory. > > Agreed. Fortunately, others got the gist of what I was saying. > > Oddly enough, as annoying as it was, your post helped my form, while other > posters have helped my content. I bet you'd make a good editor. > > Cheers, > > \~/ > Sorry to have annoyed you. I don't always get up people's noses. Glad my remarks were of at least *some* assistance. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From mikeminer53 at hotmail.com Wed May 23 12:43:52 2007 From: mikeminer53 at hotmail.com (mkPyVS) Date: 23 May 2007 09:43:52 -0700 Subject: Resizing listbook's listview pane In-Reply-To: <1179932659.180278.72990@w5g2000hsg.googlegroups.com> Message-ID: <1179938632.345997.268460@g4g2000hsf.googlegroups.com> Sorry, copied from wxpython submit as well.. I'm using wxpython 2.8... Primariy I want the resize to happen programatically during object creation/post creation... I can worry about app size changes later. Thanks, From zefria at gmail.com Thu May 31 03:57:47 2007 From: zefria at gmail.com (Daniel Gee) Date: 31 May 2007 00:57:47 -0700 Subject: trouble with wxPython intro In-Reply-To: References: <1180581067.908739.252960@a26g2000pre.googlegroups.com> Message-ID: <1180596444.594675.61310@z28g2000prd.googlegroups.com> That's so simple I'm embarrassed. I should have noticed the change from the example before to this one. It works now, thank you. From john at datavoiceint.com Tue May 8 12:42:39 2007 From: john at datavoiceint.com (HMS Surprise) Date: 8 May 2007 09:42:39 -0700 Subject: sys.path In-Reply-To: References: <1178638540.056691.161750@e65g2000hsc.googlegroups.com> Message-ID: <1178642559.235494.44510@y80g2000hsf.googlegroups.com> On May 8, 10:40 am, Klaus Alexander Seistrup wrote: > HMS Surprise wrote: > > Have I misused .extend? > > The .extend() method expects an iterable, try .append() instead. > > Cheers, > > -- > Klaus Alexander Seistruphttp://klaus.seistrup.dk/ Thanks Klaus. That certainly cleaned up sys.path. Now if I can get the system to search there for my lib file. From arunmail at gmail.com Wed May 16 05:05:00 2007 From: arunmail at gmail.com (lazy) Date: 16 May 2007 02:05:00 -0700 Subject: url question - extracting (2 types of) domains In-Reply-To: References: <1179281042.229172.246760@k79g2000hse.googlegroups.com> Message-ID: <1179306300.286029.18420@k79g2000hse.googlegroups.com> Thanks. Hmm, the url list is quite huge(40M). I think it will take a lot of time,for a whois lookup I guess. But yeah, thats seems to be a good way. Probably I will try it with a smaller set (10K) and see the time it takes. If not, I guess I will just build a table of known domains(.com,.org,.co.il etc ) and then I can find the root domain(significant_domain) atleast for those and I hope majority of them fall into this :) On May 16, 12:32 am, Michael Bentley wrote: > On May 15, 2007, at 9:04 PM, lazy wrote: > > > > > Hi, > > Im trying to extract the domain name from an url. lets say I call > > it full_domain and significant_domain(which is the homepage domain) > > > Eg: url=http://en.wikipedia.org/wiki/IPod, > > full_domain=en.wikipedia.org ,significant_domain=wikipedia.org > > > Using urlsplit (of urlparse module), I will be able to get the > > full_domain, but Im wondering how to get significant_domain. I will > > not be able to use like counting the number of dots. etc > > > Some domains maybe like foo.bar.co.in (where significant_domain= > > bar.co.in) > > I have around 40M url list. Its ok, if I fallout in few(< 1%) cases. > > Although I agree that measuring this error rate itself is not clear, > > maybe just based on ituition. > > > Anybody have clues about existing url parsers in python to do this. > > Searching online couldnt help me much other than > > the urlparse/urllib module. > > > Worst case is to try to build a table of domain > > categories(like .com, .co.il etc and look for it in the suffix rather > > than counting dots and just extract the part till the preceding dot), > > but Im afraid if I do this, I might miss some domain category. > > The best way I know to get an *authoritive* answer is to start with > the full_domain and try a whois lookup. If it returns no records, > drop everything before the first dot and try again. Repeat until you > get a good answer -- this is the significant_domain. > > hth, > Michael From elventear at gmail.com Mon May 14 11:35:16 2007 From: elventear at gmail.com (elventear) Date: 14 May 2007 08:35:16 -0700 Subject: Recursion limit problems In-Reply-To: References: <1178921877.442519.165740@u30g2000hsc.googlegroups.com> Message-ID: <1179156916.706892.144770@y80g2000hsf.googlegroups.com> On May 12, 12:25 am, "Gabriel Genellina" wrote: > En Fri, 11 May 2007 19:17:57 -0300, elventear > escribi?: > "The only required property is that objects which compare equal have the > same hash value; it is advised to somehow mix together (e.g., using > exclusive or) the hash values for the components of the object that also > play a part in comparison of objects. If a class does not define a > __cmp__() method it should not define a __hash__() operation either; if it > defines __cmp__() or __eq__() but not __hash__(), its instances will not > be usable as dictionary keys. If a class defines mutable objects and > implements a __cmp__() or __eq__() method, it should not implement > __hash__(), since the dictionary implementation requires that a key's hash > value is immutable (if the object's hash value changes, it will be in the > wrong hash bucket)." Thanks for the information. I have a doubt regarding the wording in the paragraph on top. Since I am defining a hash for my object, it makes sense that I should be able to define equality. But I am not sure about inequality, in my specific case. The paragraph above mentions that __cmp__ should be defined if I define a __hash__, but in the default behaviour of __cmp__ inequality is included. So what should I do? Also why is equality necessary to be defined? Do dicts only use __hash__ or do they use equality as well? Thanks! From rahulnag22 at yahoo.com Thu May 10 14:24:37 2007 From: rahulnag22 at yahoo.com (rahulnag22 at yahoo.com) Date: 10 May 2007 11:24:37 -0700 Subject: tkinter - Screen Resolution In-Reply-To: References: <1178728652.490682.239650@u30g2000hsc.googlegroups.com> Message-ID: <1178821476.983121.236070@o5g2000hsb.googlegroups.com> On May 10, 1:29 am, "Eric Brunel" wrote: > On Wed, 09 May 2007 18:37:32 +0200, wrote: > > Hi, > > I have developed a GUI usingtkinter(grid geometory manager). > > The structure is a top frame containing multiple subframes. Each > > subframe has a combination of widgets like(Entry, label, > > button,listboxes). The subframes are placed with a padx and pady > > offset with regards to the other subframes. And the widgets within > > these subframes have their own padx and pady offsets. The GUI runs > > fine on my linux box, but on a different linux box things get wierd. > > I see things like- > > 1) The frame width increasing > > 2) The widget padx translating to much bigger offsets with reference > > to the subframe edges > > 3) Widget widths like that for Entry become bigger > > > I Know its to do with the screen resolution settings and user settings > > on different machines. Can anyone point me in the right > > direction(before I start looking into it)as how to account for > > different screen resolutions so as to have as uniform a GUI look as > > possible across different user machines. > > [snip] > > For some reason, tk uses different default units for coordinates and font > sizes: a coordinate specified as just a number is considered to be in > pixels (a.k.a screen points); a font size specified as just a number is > considered to be in points, i.e 1/72 inch. So these units are the same > only if your screen resolution is exactly 72 dpi, which is usually not the > case. > > If this is actually your problem, the way to correct it is quite simple: > the tk command "tk scaling 1" tells tk that a point and a pixel are the > same thing. To issue it, you may have to use explicitely the tcl > interpreter used byTkinterby doing: > aWidget.tk.call('tk', 'scaling', 1) > where aWidget is anyTkinterwidget. This is what I had to do with Python > 2.1; it may be easier with later Python/Tkinterversions. > > HTH > -- > python -c "print ''.join([chr(154 - ord(c)) for c in > 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" This is just what I watned...Thanks that works great -Rahul From larry.bates at websafe.com Wed May 2 18:46:32 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 02 May 2007 17:46:32 -0500 Subject: Cannot execute Windows commands via Python in 64-bit In-Reply-To: <1178145527.014102.11480@l77g2000hsb.googlegroups.com> References: <1178143060.952025.85520@h2g2000hsg.googlegroups.com> <1178145527.014102.11480@l77g2000hsb.googlegroups.com> Message-ID: minitotoro wrote: > On May 2, 3:07 pm, Larry Bates wrote: >> nsjmetz... at gmail.com wrote: >>> I have a script that runs fine in Windows 2003 (32-bit). It basically >>> calls the Windows defrag command. When I try the exact same code on >>> Windows 2003 (64-bit) I get the following message: >>> C:\Scripts>autodefrag.py >>> Starting defragment: defrag -v C: >>c:/Scripts/DEFRAG20070502.log >>> 'defrag' is not recognized as an internal or external command, >>> operable program or batch file. >>> I have tried defrag.exe and even giving it the full path to >>> defrag.exe. Always the same result. Here is the python code that is >>> generating this error: >>> cmd = "defrag -v C: >>c:/Scripts/DEFRAG20070502.log" >>> print "Starting defragment: ", cmd >>> errorlevel = os.system(cmd) >>> Anyone know what the heck is going on and how to fix it? This code >>> works fine on my 32-bit windows machines. >>> Thanks. >> Sounds like system can't find defrag. Usually this is because of a path >> issue. Are you running the script in the foreground or scheduled? Can >> you open a command prompt and enter the command and have it work? If >> you give full path, this shouldn't be the problem. >> >> -Larry > > I have tried foreground and scheduled (neither works). I can run > defrag from the command prompt with no problem. If I give it the full > path in the script it still fails. I am completely befuddled. Help. > Copy and paste the traceback here for us. -Larry From deets at nospam.web.de Wed May 30 14:31:17 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 30 May 2007 20:31:17 +0200 Subject: is there a standard way to "install" egg-files under windows ? In-Reply-To: <4c205$465dbe2b$d443bb3a$17537@news.speedlinq.nl> References: <4c205$465dbe2b$d443bb3a$17537@news.speedlinq.nl> Message-ID: <5c5u7lF2v1pm3U1@mid.uni-berlin.de> Stef Mientki schrieb: > hello, > > after 4 months playing around with Python, > and I still have troubles with egg files. > Sometimes it works, sometimes it doesn't. > > If I google on "python egg", I get lost of links, > which contains huge pages of information, > and I'm totally scared off. > > I've used several methods, > the last one, success with 1 egg file, no success with another egg-file: > - download ez_setup.py and put it in a sub-directory of the Python path > - open an Python IDE > - open the ez_setup.py in the IDE > - dump the egg files in the same directory as ez_setup.py > - set in the IDE, the commandline parameters to the egg-filename (no path) > - run ez_setup.py in the IDE > > Can someone tell how to install an egg file in just 1 line ? > Or even better, can there be an icon on the desktop, where I just can > drop the egg-file ? setuptools - which you install using the ez_setup.py - will install a script called easy_install. Under unix, this is installed in /usr/bin, I'm not sure where it is installed under windows - go use a search. But this script takes an egg-file as argument, and installs it. So - either open the shell of your choice and type easy_install or maybe you can even use that via drag-n-drop to a desktop-link to that easy_install-script, as dropping an egg over a program icon should pass that as first argument. Diez From maxerickson at gmail.com Mon May 28 21:33:05 2007 From: maxerickson at gmail.com (Max Erickson) Date: Tue, 29 May 2007 01:33:05 +0000 (UTC) Subject: Python command line error References: <1180398300.682311.224210@i38g2000prf.googlegroups.com> Message-ID: Mick Duprez wrote: > Hi All, > > I've installed Python 2.5 on a number of machines but on one I'm > having problems with the CLI. > If I fire up the 'cmd' dos box and type 'python' I get a line of > gibberish and it locks up the cli, if I run the 'command' dos box > I get a few lines of garbage and it crashes/closes the dos box. > > I've tried a re-install, checked my system paths etc but I can't > get it to work, it works ok for running scripts from a dbl click > in explorer for instance and from Idle, I just can't run scripts > from the command line. > > I have installed - > xp pro sp2 > Python25 > wxPython2.8 unicode > PIL > numpy > > any clues to what's causing this behavior? > tia, > Mick. > What kind of gibberish? Actual garbage characters and the like? Anyway, maybe try running which; this one should be easy to get going: http://gnuwin32.sourceforge.net/packages/which.htm But I have never used it, I use the one in this package: http://unxutils.sourceforge.net/ It expects 'python.exe' or whatever, not just 'python', I would expect the gnuwin32 version to behave similarly. max From john at datavoiceint.com Tue May 15 17:59:11 2007 From: john at datavoiceint.com (HMS Surprise) Date: 15 May 2007 14:59:11 -0700 Subject: Name of function caller Message-ID: <1179266351.304587.182070@n59g2000hsh.googlegroups.com> Is there a way that a function may access the doc string or func_name of the caller? Thanks, jvh From gagsl-py2 at yahoo.com.ar Sun May 6 02:50:52 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 06 May 2007 03:50:52 -0300 Subject: invoke user's standard mail client References: <1178266064.922925.125760@y80g2000hsf.googlegroups.com> Message-ID: En Fri, 04 May 2007 05:07:44 -0300, luc.saffre at gmail.com escribi?: > the simplest way to launch the user's standard mail client from a > Python program is by creating a mailto: URL and launching the > webbrowser: > But this method is limited: you cannot specify a file to be attached > to the mail. And I guess that there would be problems if the body text > is too complex. > Does somebody know about a better method? > It should be possible at least on Windows, since Acrobat Reader is > able to do it. On Windows you can use MAPI. -- Gabriel Genellina From saif.shakeel at gmail.com Mon May 7 07:03:51 2007 From: saif.shakeel at gmail.com (saif.shakeel at gmail.com) Date: 7 May 2007 04:03:51 -0700 Subject: assisging multiple values to a element in dictionary Message-ID: <1178535831.870912.44220@p77g2000hsh.googlegroups.com> Hi, I have a dictionary which is something like this: id_lookup={ 16:'subfunction', 26:'dataId', 34:'parameterId', 39:'subfunction', 44:'dataPackageId', 45:'parameterId', 54:'subfunction', 59:'dataId', 165:'subfunction', 169:'subfunction', 170:'dataPackageId', 174:'controlParameterId' } How do i assign multiple values to the key here.Like i want the key 170 to take either the name 'dataPackageID' or the name 'LocalId'.I use this in my code,and hence if either comes it should work . Can someone help me. Thanks From machicoane at gmail.com Mon May 14 09:14:31 2007 From: machicoane at gmail.com (Thierry) Date: 14 May 2007 06:14:31 -0700 Subject: Yet Another Software Challenge Message-ID: <1179148471.466017.156290@q75g2000hsh.googlegroups.com> For those interested in programming riddles, I would like to announce a new programming challenge I'm just launching at http://software.challenge.googlepages.com This challenge is in its early stage and thus set to be continuously improved. I would be especially interested in your comments and feedbacks about this initiative and its relevance. Enjoy! Thierry From max at alcyone.com Mon May 14 01:46:34 2007 From: max at alcyone.com (Erik Max Francis) Date: Sun, 13 May 2007 22:46:34 -0700 Subject: Asyncore Help? In-Reply-To: References: Message-ID: Paul Kozik wrote: > While basic socket work was rather easy to deal with, this has proved > significantly more difficult. Are there any good free sources for > information on Asyncore, and dealing with TCP? You haven't said specifically what you're having a problem with. The more general name for asyncore/asynchat is Medusa, and there are some resources with more examples available here: http://www.nightmare.com/medusa/ http://www.amk.ca/python/code/medusa.html -- 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 used to walk around / Like nothing could happen to me -- TLC From mail at microcorp.co.za Wed May 16 06:28:58 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 16 May 2007 12:28:58 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de><1179160242.787344.48060@h2g2000hsg.googlegroups.com> <1179258692.237438.110860@p77g2000hsh.googlegroups.com> <464ad4a2$0$23143$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <04f501c797a5$0409d620$03000080@hendrik> "Stefan Behnel" wrote: > Hendrik van Rooyen wrote: > > "Beautiful is better than ugly" > > Good point. Today's transliteration of German words into ASCII identifiers > definitely looks ugly. Time for this PEP to be accepted. > Nice out of context quote. :-) Now look me in the eye and tell me that you find the mix of proper German and English keywords beautiful. And I will call you a liar. - Hendrik From jeff at taupro.com Fri May 18 11:22:07 2007 From: jeff at taupro.com (Jeff Rush) Date: Fri, 18 May 2007 10:22:07 -0500 Subject: A Few More Forrester Survey Questions Message-ID: <464DC49F.1090608@taupro.com> I'm down to the wire here on answering the Forrester survey but am stumped on a few questions I hope someone can help me out with. 1) What -existing- examples of the use of Python to create social web applications are there? These include chat, collaboration, forum boards, and editable content pages, RSS feeds. I know I use a lot of these, but under pressure I'm not coming up with a lot of names. Can you throw a few my way? 2) How easy is it to install an application written in the language? How is the application deployed? I'm having some trouble understanding the difference between "deployment" and "installation". I suspect those words may have a special meaning to Java developers (who designed the survey) or to Big Corporate IT developers. Ideas? I can tell the story of distutils, python eggs and PyPI, and py2exe and py2mumble for the Mac -- is there more to the story than that? 3) What is the value of the language to developers? Yeah, a very common, slippery question. Toss me some good explanations of why -you- value Python. Readable, free, cross-platform, powerful. What else? I'll synthesize something out of everyone's answers. Thanks for any one-line answers you can dash off to me today. Jeff Rush Python Advocacy Coordinator From arkanes at gmail.com Thu May 10 12:30:59 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 10 May 2007 11:30:59 -0500 Subject: Newbie look at Python and OO In-Reply-To: <1178812734.860473.236370@y80g2000hsf.googlegroups.com> References: <1178812734.860473.236370@y80g2000hsf.googlegroups.com> Message-ID: <4866bea60705100930r3c813568gdbaebcb6b7a4614e@mail.gmail.com> On 10 May 2007 08:58:54 -0700, walterbyrd wrote: > I learned to program with Pascal, way back when. Went into software > development for a while, then went into systems admin. Have programmed > in several languages, just learning Python. > > Some things I find odd: > > 1) 5/-2 == -3? > Integer division. A gotcha, I grant you. Fixable with a __future__ import which will become the default soonish. > 2) list assignment handling, pointing two vars to the same list: > > With simple data types: > >>> a = 5 > >>> b = a > >>> a = 3 > >>> a,b > (3, 5) > > Which is what I'd expect, since I have changed a, but not b. > > But with lists: > >>> a = list("1234") > >>> b = a > >>> a.append("5") > >>> a,b > (['1', '2', '3', '4', '5'], ['1', '2', '3', '4', '5']) > > b changes even though I have not touched b. I know why, but this is > not what I would ordinarilly expect, it does not seem intuitive. And, > IMO, it gets worse: > I don't like the word "intuitive", because it's meaningless. Something intuitive is something that you already know. You're taking a model of variables and references from another language, and assuming Python works the same way when it doesn't. There's no good reason to assume this, and it's well documented that you shouldn't. The problem comes when people try to teach Python by telling you it's "pass by reference" or "it's like a pointer" - it's not, and you need to be taught how it *actually* works, which isn't especially complicated (easier to grasp than pointers, in my experience). > >>> a = list("1234") > >>> b = a > >>> a = a + ['5'] > >>> a,b > (['1', '2', '3', '4', '5'], ['1', '2', '3', '4']) > > Sometimes changing a changes b, and sometimes not. You also have to > remember that subseqent changes to a will not change b - after some > operation but not others. To those who think in Python, I'm sure this > all seems normal. But, having programmed in about one dozen other > language, this seems downright bizare to me. I know why it works like > this, but it seems like an odd way to do things. > You have to disabuse yourself of the idea that assignment and "changing" are the same thing. People without previous programming experience rarely stumble on this particular hurdle. > 3) ambiguous use of the form: this.that() > > Sometimes, this.that() means module.funcion() as in: > > >>> os.dirlist(".") > > Other times, "this" is sort of like a parameter to the "that" > function: > this.that() is *always* looking up "that" in "this" and calling it. It never does anything else. What "that" you get depends on what "this" is, and I don't know how you could ever expect anything else. > >>> a = list("1234") > >>> "_".join(a) > '1_2_3_4_5' > > And still other times, is seems that "this" is an object, acted upon > by "that" : > > >>> a = list("1234") > >>> b = "_".join(a) > >>> b.split("_") > ['1', '2', '3', '4', '5'] > > BTW: it seems a bit odd to that the positions of the string, and the > delimitor, are reversed between the complementory functions join(), > and split(). I suppose if it weren't for OO, we have something > terribly complicated, like: > > split(str, "_") > join(str, "_") > Join takes a iterable, not a string. It's "reversed" from what you might expect so that it can generically work over any sort of sequence or iterable. > Again, those who think in Python, will understand right away that: > > math.count(x) > > is counting the substring "x" in the "math" string. But can you see > where that might be confused to be a function called count() in the > math module? > This is a good reason not to give a variable which contains a string a name like "math". The language can't protect you from this, and how would you expect it to? Obviously, especially as the standard lib grows, it can be difficult to avoid these sorts of name collisions. But context is everything and in well written code it shouldn't be hard to disambiguate these sort of things. > I'm not complaining. Python is a great language in many respects. But, > I would take some issue with those claiming Python is intuitive and > easy. IMO: there seems to be many ambiguous, unintuitve, and > confusing, aspects to Python. > > -- > http://mail.python.org/mailman/listinfo/python-list > From arkanes at gmail.com Fri May 4 10:30:06 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 4 May 2007 09:30:06 -0500 Subject: My Python annoyances In-Reply-To: References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> <1178202431.147195.249790@u30g2000hsc.googlegroups.com> Message-ID: <4866bea60705040730o20d10aeeo5227c192b206290a@mail.gmail.com> On 5/4/07, Ben Collver wrote: > Ben Collver wrote: > > Chris Mellon wrote: > >> Code like this is working directly against Python philosophy. You > >> probably got told this on #python, too. There's hardly any > >> circumstance where you should need to validate the exact class of an > >> object, and as long as they have the same interface theres no harm > >> whatsoever in tempfile changing it's return value between Python > >> versions. > > > > I am unqualified to comment on the Python philosophy, but I would like > > for my function to do some basic error checking on its arguments. > > By "basic error checking" I mean "verify that the file argument actually > is a file-like object". By same interface, do you mean that I should > check for the methods that I depend on? That sounds easy enough. > You should "check" for the methods by calling them. If the object doesn't support the method in question, you will get a runtime exception. Premature inspection of an object is rarely useful and often outright harmful. From bbxx789_05ss at yahoo.com Thu May 24 16:38:16 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 24 May 2007 13:38:16 -0700 Subject: How can I time a method of a class in python using Timeit In-Reply-To: <1180031029.147000.55680@m36g2000hse.googlegroups.com> References: <1180020970.039576.319230@m36g2000hse.googlegroups.com> <1180027843.322955.57280@q75g2000hsh.googlegroups.com> <1180028334.650900.283930@m36g2000hse.googlegroups.com> <1180028476.396282.316330@q69g2000hsb.googlegroups.com> <1180031029.147000.55680@m36g2000hse.googlegroups.com> Message-ID: <1180039095.342612.195560@k79g2000hse.googlegroups.com> On May 24, 12:23 pm, "silverburgh.me... at gmail.com" wrote: > On May 24, 12:41 pm, 7stud wrote: > > > > > Actually, you can do this: > > > class Dog(object): > > def aFunction(self): > > result = 20 + 2 > > def run(self): > > #do stuff > > aFunction() > > #do other stuff > > import timeit > > > t = timeit.Timer("d.aFunction()", "from __main__ import Dog; d = > > Dog()") > > print t.timeit() > > > Since you only want to time aFunction(), you can call it directly. > > Can 't = timeit.Timer()' run inside a thread? > And I have multiple threads running this 't = timeit.Time()' function? Are you seeing an error like this: Exception in thread Thread-1: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.4//lib/ python2.4/threading.py", line 442, in __bootstrap self.run() File "test1.py", line 34, in run print t.timeit() File "/Library/Frameworks/Python.framework/Versions/2.4//lib/ python2.4/timeit.py", line 161, in timeit timing = self.inner(it, self.timer) File "", line 3, in inner TypeError: __init__() takes exactly 2 arguments (1 given) That was produced by this code: ---------- import time import timeit import threading t = timeit.Timer("inst.f()", "from __main__ import Dog; inst=Dog()") print t class Dog(threading.Thread): def __init__(self, id): self.id = id threading.Thread.__init__(self) def f(self): result = 20 + 3 def run(self): print t print t.timeit() d = Dog("d") d.start() -------------- I can't explain that error. This works: -------------- import time import timeit import threading t = timeit.Timer("inst.f()", "from __main__ import Dog; inst=Dog()") class Dog(threading.Thread): def f(self): result = 20 + 3 def run(self): print t.timeit() d = Dog() d.start() ----------- From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed May 9 09:58:34 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 09 May 2007 15:58:34 +0200 Subject: Simulating simple electric circuits References: <5a9838F2nlbanU1@mid.individual.net> Message-ID: <5ae2cbF2olorvU1@mid.individual.net> Stef Mientki wrote: > Bjoern Schliessmann wrote: >> - sources (here begin currents) >> - ground (here end currents) > that doesn't bring you anywhere ;-) It does :) > Current doesn't start or end at some location, > current flows through a closed circuit. The part I omit is the voltage source. All currents I need in my system flow from plus to ground. > And let's forget about capacitors, inductors and semi-conductors > for this moment ! Yep, because I largely don't have any here, only in few special cases (where I also can use some kind of "current priority"). > Here is a simulation package, although designed for MatLab, > it might give you a good idea of what your need. > http://www.swarthmore.edu/NatSci/echeeve1/Ref/mna/MNA6.html Wow ... Overkill :) > There are few simulation related packages, > but not directly suited for electronics > http://www.mcs.vuw.ac.nz/cgi-bin/wiki/SimPy I once looked at this, but couldn't find out how to use it with my problem. :\ > http://www.linuxjournal.com/article/7542 > http://pyastra.sourceforge.net/ > http://www.nelsim.com/scriptsim/python_man.html Those are all a bit daunting ... > As an little test I wrote a PIC simulator (only core) in Python, > it's very rough code (generated in a few evenings), > if you're interested I could look it up. Thank you for the offer. I'm presently having problems understanding even the examples, so I'll call in if I get so far. Regards, Bj?rn -- BOFH excuse #380: Operators killed when huge stack of backup tapes fell over. From noagbodjivictor at gmail.com Wed May 2 10:05:05 2007 From: noagbodjivictor at gmail.com (noagbodjivictor at gmail.com) Date: 2 May 2007 07:05:05 -0700 Subject: open("output/mainwindow.h",'w') doesn't create a folder for me Message-ID: <1178114705.586725.295480@n76g2000hsh.googlegroups.com> Hello I have done python for some time now. I'm forgetting things. This is the faulty line : outfile = open("output/mainwindow.h",'w') I thought it would have created the folder ouput and the file mainwindow.h for me but it's throwing an error From tdelaney at avaya.com Tue May 15 20:09:59 2007 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Wed, 16 May 2007 10:09:59 +1000 Subject: Trying to choose between python and java Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1ED9D@au3010avexu1.global.avaya.com> Duncan Booth wrote: > "Hamilton, William " wrote: > >> >> No, they'll work just fine. They just won't work with Python 3. >> It's not like the Python Liberation Front is going to hack into your >> computer in the middle of the night and delete you 2.x installation. > > Is that a breakaway group from the PSU? Splitters! Tim Delaney From fw3 at hotmail.co.jp Sat May 5 01:33:02 2007 From: fw3 at hotmail.co.jp (wang frank) Date: Sat, 05 May 2007 05:33:02 +0000 Subject: Do I have to quit python to load a module? In-Reply-To: <1178311024.265842.242870@o5g2000hsb.googlegroups.com> Message-ID: Hi, When I edit a module, I have to quit python and then restart python and then import the module. Are there any way to avoid quit python to load an updated module? When I am debugging a module code, I need to constantly make changes. It is not convenient to quit and reload. Thanks Frank _________________________________________________________________ ??????????????????2???????????????? http://campaign.live.jp/dizon/ From edward.dodge at gmail.com Wed May 2 16:52:08 2007 From: edward.dodge at gmail.com (Edward) Date: 2 May 2007 13:52:08 -0700 Subject: ignorance and intolerance in computing communties In-Reply-To: <1178120019.271716.299590@e65g2000hsc.googlegroups.com> References: <1178120019.271716.299590@e65g2000hsc.googlegroups.com> Message-ID: <1178139128.848251.102020@y80g2000hsf.googlegroups.com> On May 2, 8:33 am, Xah Lee wrote: > As i have indicated in my post, it is non-trivial to implement a > function that returns the positive angle of a vector. For example, it > can be done with sign checking of the coordinate components (in total > 4 cases, which can be done as 2 levels of nesting if, or simply 4 > if.), and or the evaluation of Min[Abs[ArcCos[x],Abs[ArcSin[x]]], or > use clever ways with dot product, or ArcTan. It is not a trivial to > know which algorithm is in general more efficient. (this is important, > since finding the angle of a vector is a basic function, that may > needs to be called millions times directly or indirectly) Further, > consider the inverse trig function, it is likely 99.99% of people with > a PH D in math wouldn't know how these are actually implemented. So, > the question of whether calling one of the inverse trig function is > more robust or efficient than another is a open question. And, besides > the algorithmic level, the question also entails how the language > actually implement the inverse trig functions. "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil." The question you are asking depends a great deal on other factors outside of the coding environment such as the compiler and the hardware. If you are coding for a specific language/compiler/hardware combination, all you need do is profile different versions of your code until you're happy with the results. From kinch1967 at gmail.com Sat May 19 18:40:39 2007 From: kinch1967 at gmail.com (bullockbefriending bard) Date: 19 May 2007 15:40:39 -0700 Subject: regex matching question In-Reply-To: References: <1179595319.239229.262160@l77g2000hsb.googlegroups.com> Message-ID: <1179614439.044253.141170@u30g2000hsc.googlegroups.com> thanks for your suggestion. i had already implemented the all pairs different constraint in python code. even though i don't really need to give very explicit error messages about what might be wrong with my data (obviously easier to do if do all constraint validation in code rather than one regex), there is something to be said for your suggestion to simplify my regex further - it might be sensible from a maintainability/readability perspective to use regex for *format* validation and then validate all *values* in code. from my cursory skimming of friedl, i get the feeling that the all pairs different constraint would give rise to some kind of fairly baroque expression, perhaps likely to bring to mind the following quotation from samuel johnson: "Sir, a woman's preaching is like a dog's walking on his hind legs. It is not done well; but you are surprised to find it done at all." however, being human, sometimes some things should be done, just because they can :)... so if anyone knows hows to do it, i'm still interested, even if just out of idle curiosity! On May 20, 12:57 am, Marc 'BlackJack' Rintsch wrote: > In <1179595319.239229.262... at l77g2000hsb.googlegroups.com>, > > > > bullockbefriending bard wrote: > > first, regex part: > > > I am new to regexes and have come up with the following expression: > > ((1[0-4]|[1-9]),(1[0-4]|[1-9])/){5}(1[0-4]|[1-9]),(1[0-4]|[1-9]) > > > to exactly match strings which look like this: > > > 1,2/3,4/5,6/7,8/9,10/11,12 > > > i.e. 6 comma-delimited pairs of integer numbers separated by the > > backslash character + constraint that numbers must be in range 1-14. > > > i should add that i am only interested in finding exact matches (doing > > some kind of command line validation). > > > [...] > > > the idea in the above code being that i want to use the regex match as > > a test of whether or not the input string (results) is correctly > > formatted. if the string results is not exactly matched by the regex, > > i want my program to barf an exception and bail out. apart from > > whether or not the regex is good idiom, is my approach suitably > > pythonic? > > I would use a simple regular expression to extract "candidates" and a > Python function to split the candidate and check for the extra > constraints. Especially the "all pairs different" constraint is something > I would not even attempt to put in a regex. For searching candidates this > should be good enough:: > > r'(\d+,\d+/){5}\d+,\d+' > > Ciao, > Marc 'BlackJack' Rintsch From hafeliel at yahoo.com Thu May 24 11:18:36 2007 From: hafeliel at yahoo.com (Gre7g Luterman) Date: Thu, 24 May 2007 09:18:36 -0600 Subject: What is an instance and what isn't? Message-ID: I suppose I was lulled into complacency by how Python makes so many things look like classes, but I'm starting to realize that they're not, are they? I'm writing a C program which handles Python objects in different ways based on their type. I do a PyInstance_Check(PyObj) to determine if the PyObj is an instance, but it is returning 0 on a lot of stuff that I thought would be an instance. So I did the following simple test on three things that look like instances: 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. >>> class a: pass ... >>> type(a()) >>> type(Exception()) >>> class b(dict): pass ... >>> type(b()) I was relieved that a() returns an instance, but I was surprised that Exceptions aren't really instances at all. And what's the deal with derving a class from a standard type like a dictionary? I thought for sure, that would be an instance, but this shows it is a class?!? Can anyone explain the last one and/or give me a simple test I can do in C to determine whether a Python object is "instance-like"? Many thanks, Gre7g From gagsl-py2 at yahoo.com.ar Fri May 4 00:40:37 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 04 May 2007 01:40:37 -0300 Subject: Organizing code - import question References: Message-ID: En Thu, 03 May 2007 12:41:00 -0300, Brian Blais escribi?: > I am trying to organize some of my code, and am having a little trouble > with the import logic. I find I often have something like: > > MyPackage/ > Part1/ # wants to use functions in Common/ > __init__.py # does "from MyClass1 import MyClass1", etc,... > MyClass1.py > MyClass1a.py # depends on MyClass1 > MyClass1b.py # depends on MyClass1 > > Part2/ # wants to use functions in Common/ > __init__.py # does "from MyClass2 import MyClass2", etc,... > MyClass2.py # depends on MyClass1 also, such as containing a > list of MyClass1 > MyClass2a.py # depends on MyClass2 > MyClass2b.py # depends on MyClass2 > > Common/ > __init__.py # does "import fun1,fun2", etc,... > fun1.py > fun2.py > > > > So I have some common utilities that both classes want to access, and I > have two separate class definitions, of which one depends on the other. > In MyClass2.py, I can't seem to do: > > import Common.fun1 > > or > > from Part1.MyClass1 import MyClass1 To be able to do that, MyPackage should be on sys.path If its *container* (i.e. the directory containing MyPackage, perhaps site-packages) is already on sys.path, you could prefix all imports with the package name: import MyPackage.Common.fun1, or from MyPackage.Part1 import MyClass1 (Dont forget the __init__.py on MyPackage, to make it a real package) If you are using Python 2.5, you can use relative imports. Read the "What's new" document. In MyClass2.py you could use, then: from ..Common import fun1, or: from ..Part1.MyClass1 import MyClass1 -- Gabriel Genellina From bj_666 at gmx.net Wed May 9 04:06:55 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 09 May 2007 10:06:55 +0200 Subject: error in the if, elif, else statement ? References: <1178696786.705128.320750@l77g2000hsb.googlegroups.com> Message-ID: In <1178696786.705128.320750 at l77g2000hsb.googlegroups.com>, juan-manuel.behrendt wrote: > Hello together, > > I wrote a script for the engineering software abaqus/CAE. It worked > well until I implemented a selection in order to variate the variable > "lGwU" through an if elif, else statement. I am going to post the > first 82 lines of the script, since the error message points at line > 80: > > from abaqusConstants import * > from abaqus import * > > def CreateSchraube(name, l, flag=None, flag2=None): > import part > vp = session.currentViewportName > model = session.sessionState[vp]['modelName'] > m = mdb.models[model] > s = m.ConstrainedSketch(name='__profile__', sheetSize=1000.0) > s.ConstructionLine(point1=(0.0, -500.0), point2=(0.0, 500.0)) > > if flag==1: > > dh = 15.0 > z = 15.0 > dz = 60.0 > d = 72.0 > f = 1.0 > dD = f*62.0 > lGwO = 110.0 > > if flag2==11: # here appears the > beginning of the new impletation in order to variate lGwU > lGwU = 0.8*d # you can see these inner > if, elif, else statement 4 times, because > elif flag2==12: # the outer if, elif, > else statement (which works!) has 4 cases > lGwU = 1.0*d > elif flag==13: > lGwU = 1.2*d > else: pass > > elif flag==2: > > dh = 15.0 > z = 15.0 > dz = 60.0 > d = 72.0 > f = 1.0 > dD = f*62.0 > lGwO = 110.0 > > if flag2==11: > lGwU = 0.8*d > elif flag2==12: > lGwU = 1.0*d > elif flag==13: > lGwU = 1.2*d > else: pass > > elif flag==3: > > dh = 25.0 > z = 15.0 > dz = 68.0 > d = 80.0 > f = 1.0 > dD = f*71.5 > lGwO = 120.0 > > if flag2==11: > lGwU = 0.8*d > elif flag2==12: > lGwU = 1.0*d > elif flag==13: > lGwU = 1.2*d > else: pass > > elif flag==4: > > dh = 25.0 > z = 15.0 > dz = 68.0 > d = 80.0 > f = 1.0 > dD = f*71.5 > lGwO = 120.0 > > if flag2==11: > lGwU = 0.8*d > elif flag2==12: > lGwU = 1.0*d > elif flag==13: > lGwU = 1.2*d > else: pass > > else: pass > > xyCoords = ((dh/2, -z), (dz/2, -z), (dz/2, 0), (d/2, 0), # > this is line 80, where the error message points at > (d/2, lGwU), (dD/2, (d-dD)/ > (2*tan(radians(12)))+lGwU), > (dD/2, l-lGwO-z-(d-dD)/ > (2*tan(radians(20)))), (d/2, l-lGwO-z), (d/2, l-z), (dh/2, l-z), (dh/ > 2, -z)) > > So, a lot of code, I hope somebody will read it. > My Problem ist the error message, which says: > > " #* UnboundLocalError: local variable 'lGwU' referenced before > assignment > #*File "C:\ABAQUS_Products\6.6-3\abaqus_plugins\Schraube.py", line > 80, in > #*CreateSchraube > #* xyCoords = ((dh/2, -z), (dz/2, -z), (dz/2, 0), (d/2, 0), " > > So the error message is quite clear, however it is not suitable to > what I've written in my script, because the local variable 'lGwU' IS > assigned before referenced and, furthermore in line 80 lGwU does not > appear. It is not assigned, otherwise you would not get this error. The line number is also correct because it's the start of the construct or "logical line" where the name is referenced. Just look at the very next line in the source. > Another strange thing is, that the first two cases, where lGwU = 0.8*d > and lGwU = 1.0*d is, do work in my abaqus script. > So the error message only occurs if I choose lGwU = 1.2*d. Take a look at the condition for that case(s). You are testing `flag` instead of `flag2`. Maybe you should have written ``raise SomeError`` or ``assert False`` instead of all those useless ``else: pass``. If this branch is taken, obviously `lGwU` is not bound. Ciao, Marc 'BlackJack' Rintsch From jorgen.maillist at gmail.com Tue May 8 08:05:26 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Tue, 8 May 2007 14:05:26 +0200 Subject: changing a var by reference of a list Message-ID: <11e49df10705080505l10dac51aw2a25cdf1d1fa40b5@mail.gmail.com> Hi, I am trying to simplify my code, and want to automate the assigning of variables I get back from a set. I was thinking of putting the variables I want changed in a list: L = [self._varA, self._varB ] self._varA is a variable I want to change when I pass L to a function. I know doing this; L[0] = 12 Will replace the entry self._varA with 12, but is there a way to indirectly change the value of self._varA, through the list, something like a by-reference in C++ or a pointer-pointer? With regards, - Jorgen From laurent.pointal at limsi.fr Mon May 14 07:45:12 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Mon, 14 May 2007 13:45:12 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46473267$0$31532$9b622d9e@news.freenet.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis a ?crit : > PEP 1 specifies that PEP authors need to collect feedback from the > community. As the author of PEP 3131, I'd like to encourage comments > to the PEP included below, either here (comp.lang.python), or to > python-3000 at python.org > > In summary, this PEP proposes to allow non-ASCII letters as > identifiers in Python. If the PEP is accepted, the following > identifiers would also become valid as class, function, or > variable names: L?ffelstiel, chang?, ??????, or ??? > (hoping that the latter one means "counter"). > > I believe this PEP differs from other Py3k PEPs in that it really > requires feedback from people with different cultural background > to evaluate it fully - most other PEPs are culture-neutral. > > So, please provide feedback, e.g. perhaps by answering these > questions: > - should non-ASCII identifiers be supported? why? > - would you use them if it was possible to do so? in what cases? I strongly prefer to stay with current standard limited ascii for identifiers. Ideally, it would be agreable to have variables like greek letters for some scientific vars, for french people using ???? in names... But... (I join common obections): * where are-they on my keyboard, how can I type them ? (i can see french ????, but us-layout keyboard dont know them, imagine kanji or greek) * how do I spell this cyrilic/kanji char ? * when there are very similar chars, how can I distinguish them? (without dealing with same representation chars having different unicode names) * is "am?d?" variable and "amede" the same ? * its an anti-KISS rule. * not only I write code, I read it too, and having such variation possibility in names make code really more unreadable. (unless I learn other scripting representation - maybe not a bad thing itself, but its not the objective here). * I've read "Restricting the language to ASCII-only identifiers does not enforce comments and documentation to be English, or the identifiers actually to be English words, so an additional policy is necessary, anyway." But even with comments in german or spanish or japanese, I can guess to identify what a (well written) code is doing with its data. It would be very difficult with unicode spanning identifiers. ==> I wouldn't use them. So, keep ascii only. Basic ascii is the lower common denominator known and available everywhere, its known by all developers who can identify these chars correctly (maybe 1 vs I or O vs 0 can get into problems with uncorrect fonts). Maybe, make default file-encoding to utf8 and strings to be unicode strings by default (with a s"" for basic strings by example), but this is another problem. L.Pointal. From __peter__ at web.de Thu May 31 14:42:33 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 31 May 2007 20:42:33 +0200 Subject: Adding tuples to a dictionary References: <1180636210.328300.298850@p77g2000hsh.googlegroups.com> Message-ID: Maciej Blizi?ski wrote: > Hi Pythonistas! > > I've got a question about storing tuples in a dictionary. First, a > small test case which creates a list of dictionaries: > > import time > > list_of_dicts = [] > keys = [str(x) for x in range(200000)] > prev_clk = time.clock() > for i in range(20): > my_dict = {} > for key in keys: > my_dict[key] = key > list_of_dicts.append(my_dict) > new_clk = time.clock() > print i, new_clk - prev_clk > prev_clk = new_clk > > It creates dictionaries and stores them in a list, printing out > execution times. The size of each dictionary is constant, so is the > execution time for each iteration. > > 0 0.1 > 1 0.1 > 2 0.1 > 3 0.08 > 4 0.09 > > ...and so on. > > Then, just one line is changed: > my_dict[key] = key > into: > my_dict[key] = (key, key) > > Full code: > > list_of_dicts = [] > keys = [str(x) for x in range(200000)] > prev_clk = time.clock() > for i in range(20): > my_dict = {} > for key in keys: > my_dict[key] = (key, key) > list_of_dicts.append(my_dict) > new_clk = time.clock() > print i, new_clk - prev_clk > prev_clk = new_clk > > The difference is that instead of single values, tuples are added to > the dictionary instead. When the program is run again: > > 0 0.27 > 1 0.37 > 2 0.49 > 3 0.6 > ... > 16 2.32 > 17 2.45 > 18 2.54 > 19 2.68 > > The execution time is rising linearly with every new dictionary > created. > > Next experiment: dictionaries are not stored in a list, they are just > left out when an iteration has finished. It's done by removing two > lines: > > list_of_dicts = [] > > and > > list_of_dicts.append(my_dict) > > Full code: > > keys = [str(x) for x in range(200000)] > prev_clk = time.clock() > for i in range(20): > my_dict = {} > for key in keys: > my_dict[key] = (key, key) > new_clk = time.clock() > print i, new_clk - prev_clk > prev_clk = new_clk > > The time is constant again: > > 0 0.28 > 1 0.28 > 2 0.28 > 3 0.26 > 4 0.26 > > I see no reason for this kind of performance problem, really. It > happens when both things are true: dictionaries are kept in a list (or > more generally, in memory) and they store tuples. > > As this goes beyond my understanding of Python internals, I would like > to kindly ask, if anyone has an idea about how to create this data > structure (list of dictionaries of tuples, assuming that size of all > dictionaries is the same), in constant time? Disable garbage collection: import gc gc.disable() It uses inappropriate heuristics in this case. Peter From steven.bethard at gmail.com Tue May 22 16:38:37 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 22 May 2007 14:38:37 -0600 Subject: converting text and spans to an ElementTree In-Reply-To: References: Message-ID: Gabriel Genellina wrote: > the idea would be as follows: > > - For each span generate two tuples: (start_offset, 1, end_offset, > element) and (end_offset, 0, -start_offset, element). If start==end use > (start_offset, -1, start_offset, element). > - Collect all tuples in a list, and sort them. The tuple is made so when > at a given offset there is an element that ends and another that starts, > the ending element comes first (because it has a 0). For all the > elements that end at a given point, the shortest comes first. > - Initialize an empty list (will be used as a stack of containers), and > create a root Element as your "current container" (CC), the variable > "last_used" will keep the last position used on the text. > - For each tuple in the sorted list: > - if the second item is a 1, an element is starting. Insert it into > the CC element, push the CC onto the stack, and set the new element as > the new CC. The element data is text[last_used:start_offset], and move > last_used to start_offset. > - if the second item is a 0, an element is ending. Discard the CC, pop > an element from the stack as the new CC. The element data is > text[last_used:end_offset], move last_used up to end_offset. > - if the second item is a -1, it's an element with no content. Insert > it into the CC element. Thanks a lot! This put me on the right track (though the devil's definitely in the details). It's working now:: >>> tree = xmltools.text_and_spans_to_etree('aaa aaa aaaccc cccaaa', [ ... (etree.Element('a'), 0, 21), ... (etree.Element('b'), 11, 11), ... (etree.Element('c'), 11, 18), ... ]) >>> etree.tostring(tree) 'aaa aaa aaaccc cccaaa' >>> tree = xmltools.text_and_spans_to_etree('bbb\naaaccc\ncccaaa', [ ... (etree.Element('a'), 0, 17), ... (etree.Element('b'), 0, 4), ... (etree.Element('c'), 7, 14), ... (etree.Element('b'), 14, 14), ... ]) >>> etree.tostring(tree) 'bbb\naaaccc\ncccaaa' >>> tree = xmltools.text_and_spans_to_etree('abc', [ ... (etree.Element('a'), 0, 3), ... (etree.Element('b'), 0, 3), ... (etree.Element('c'), 0, 3), ... ]) >>> etree.tostring(tree) 'abc' And for the sake of any poor soul who runs into a similar problem, here's the code I wrote using Gabriel's hints above:: def text_and_spans_to_etree(text, spans): # Create a list of element starts and ends, sorting them in the # order they would appear in an XML version of the text. So for # example, with XML text like: # a b a # we will see: # starting # starting # ending # ending empty = -1 starting = 0 ending = 1 tuples = [] root_elem = None for i, (elem, start, end) in enumerate(spans): # validate spans if start < 0 or end > len(text): msg = 'spans must be in the range 0-%i' raise ValueError(msg % len(text)) # save the first element that spans the entire text as the root elif root_elem is None and start == 0 and end == len(text): root_elem = elem # insert a single tuple for empty elements elif start == end: tuples.append((start, empty, -end, i, elem)) # insert starts and ends for all other elements else: tuples.append((start, starting, -end, i, elem)) tuples.append((start, ending, -end, -i, elem)) tuples.sort() # make sure we found a root element if root_elem is None: raise ValueError('one element must span the entire text') # iterate through the element starts and ends, # updating element texts, tails and children last_offset = 0 last_elem = root_elem last_type = starting stack = [root_elem] for start, offset_type, neg_end, _, elem in tuples: # start of an element: # add it as a child and add it to the stack # next text chunk goes up to the start offset if offset_type is starting: stack[-1].append(elem) stack.append(elem) offset = start # end of an element: # pop if off the stack # next text chunk goes up to the end offset elif offset_type is ending: if elem is not stack[-1]: print elem, stack[-1] assert False assert elem is stack.pop() offset = -neg_end # empty element: # add it as a child # next text chunk goes up to the start offset elif offset_type is empty: stack[-1].append(elem) offset = start # should never get here else: assert False # calculate the next text chunk, and then determine what to do # with it based on what we did the last time around: # * started an element -> set its .text # * ended an element (or inserted an empty) -> set its .tail last_text = text[last_offset:offset] if last_type is starting: last_elem.text = last_text elif last_type is ending: last_elem.tail = last_text elif last_type is empty: last_elem.tail = last_text else: assert False # save what we did this time for inspection next time last_offset = offset last_type = offset_type last_elem = elem # add any final text before the close of the root element last_elem.tail = text[last_offset:] return root_elem Thanks again, STeVe From stargaming at gmail.com Fri May 18 02:47:29 2007 From: stargaming at gmail.com (Stargaming) Date: Fri, 18 May 2007 08:47:29 +0200 Subject: alternative to eclipse [ python ide AND cvs ] In-Reply-To: References: Message-ID: yomgui schrieb: > Hi, > > Eclipse is just not really working on linux 64 bit > (I tried ubuntu and centos, it is freesing and crashing > and extremly slow) > > I use eclipse for python and cvs, what is "the" good alternative ? > > thanks > > yomgui Well, basically any editor that features plugins IMO. Although this sounds much like a "which editor is the best?" question (what will enrage us even more than non-ASCII identifiers ), I'd suggest Vim. It is available at almost all platforms I guess (linux 64 bit should be *no* problem at all). You can make it match your personal editing preferences (I recently got in touch with the `:map` command -- wonderful one), extend it (there are lots of plugins as for example snippetsEmu that allows some Textmate-like autocompletion) and let it work with CVS (never tried it but a `search for CVS`_ yields dozens of results). Ah -- and it works with python very well. Lots of plugins again, good highlighting, indentation support, built-in python shell (when compiled with +python). (If you're going to give it a try, put something like ``autocmd FileType python map :w:!python "%"`` into your .vimrc to get the IDE-feeling (F5 for write+execute) back in.) Regards, Stargaming .. _search for CVS: http://www.vim.org/scripts/script_search_results.php?keywords=cvs&script_type=&order_by=rating&direction=descending&search=search From bbxx789_05ss at yahoo.com Tue May 1 13:12:38 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 1 May 2007 10:12:38 -0700 Subject: sqlite for mac? In-Reply-To: References: <1177993261.572563.70370@n76g2000hsh.googlegroups.com> Message-ID: <1178039558.882802.214030@n59g2000hsh.googlegroups.com> On May 1, 4:08 am, "Daniel Nogradi" wrote: > > Does sqlite come in a mac version? > > The interface (pysqlite) is part of the python 2.5 standard library > but you need to install sqlite itself separately (as far as I > remember) fromwww.sqlite.org > > Daniel I'm using python 2.4.4 because the download said there were more mac modules available for 2.4.4. than 2.5, and I can't seem to locate a place to download sqlite for mac. From yavannadil at yahoo.com Sun May 6 05:41:20 2007 From: yavannadil at yahoo.com (yavannadil at yahoo.com) Date: 6 May 2007 02:41:20 -0700 Subject: How do I get type methods? In-Reply-To: References: <1178220806.664557.245780@c35g2000hsg.googlegroups.com> <1178253260.075515.43810@q75g2000hsh.googlegroups.com> <1178283588.694886.204250@c35g2000hsg.googlegroups.com> <1178289484.265718.198060@c35g2000hsg.googlegroups.com> <1178353143.859683.200420@e65g2000hsc.googlegroups.com> Message-ID: <1178444479.979329.216840@l77g2000hsb.googlegroups.com> On May 5, 5:21 pm, Carsten Haese wrote: > 'pyuno' objects are proxy objects that represent UNO objects, services, > and interfaces. Since all attribute lookups are handled by the UNO > bridge, the proxy object doesn't actually know what attributes it has, > which is why it won't respond anything useful to the usual dir() > inspection. I suspected something like that, but couldn't quite believe as CORBA proxies generated by C++/C/Java/Lisp/Python IDL compiler are normal classes which know what methods they have... > To list the methods and properties that the UNO object behind a pyuno > proxy object has, you need to use UNO inspection capabilities. Something > like the following seems to work: Thanks a lot! After reading your example I googled and found unohelper.inspect, which provides all information. But I still need instances, as 'dir(XSingleComponentFactory)' gives just ['__doc__', '__module__', '__pyunointerface__'], and 'unohelper.inspect(XSingleComponentFactory, sys.stdout)' gives segmentation fault. Sincerely yours, Dmitri From stefan.behnel-n05pAM at web.de Tue May 15 06:58:59 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 15 May 2007 12:58:59 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46498cb1$0$6411$9b4e6d93@newsspool2.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <4648252D.5020704@web.de> <46483740.4050406@web.de> <46498cb1$0$6411$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <46499273.6050806@web.de> Ren? Fleschenberg wrote: > you have failed to do that, in my opinion. All you have presented are > vague notions of rare and isolated use-cases. I don't think software development at one of the biggest banks in Germany can be considered a "rare and isolated use case". Admittedly, it's done in Java, but why should Python fail to support unicode identifiers in the way Java does? Stefan From zubeido at yahoo.com.br Mon May 21 16:37:12 2007 From: zubeido at yahoo.com.br (aiwarrior) Date: 21 May 2007 13:37:12 -0700 Subject: Unable to strip \n characters In-Reply-To: <1179727531.061286.139560@x35g2000prf.googlegroups.com> References: <1179658203.040541.220800@p77g2000hsh.googlegroups.com> <1179727531.061286.139560@x35g2000prf.googlegroups.com> Message-ID: <1179779832.177031.210370@b40g2000prd.googlegroups.com> On May 21, 7:05 am, Asun Friere wrote: > On May 20, 10:49 pm, Michael Bentley > wrote: > > > On May 20, 2007, at 7:41 AM, Michael Bentley wrote: > > > > (upload.strip()) > > > Oops: (upload.strip(),) or upload.strip() > > Superfluous though the braces around your original were, it should > still run ... > ie. (a) == a When you mean superfluous you mean it makes a diffrence in run-time or just code style? From roy at panix.com Thu May 3 09:38:56 2007 From: roy at panix.com (Roy Smith) Date: Thu, 03 May 2007 09:38:56 -0400 Subject: How to check if a string is empty in python? References: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> <1178154290.811928.208900@h2g2000hsg.googlegroups.com> <1hxia6q.18rflwk1mez8vhN%aleax@mac.com> <1178195992.473679.137560@n59g2000hsh.googlegroups.com> Message-ID: In article <1178195992.473679.137560 at n59g2000hsh.googlegroups.com>, Ant wrote: > On May 3, 5:59 am, a... at mac.com (Alex Martelli) wrote: > > Steven D'Aprano wrote: > > > On Wed, 02 May 2007 21:19:54 -0400, Roy Smith wrote: > > > > > > for c in s: > > > > raise "it's not empty" > > > > > String exceptions are depreciated and shouldn't be used. > > > > >http://docs.python.org/api/node16.html > > > > They're actually deprecated, not depreciated. > > In Steven's defence, string exceptions *are* probably worth less, as > there's no longer such a demand for them. You just wait until they start showing up on Antiques Roadshow :-) From JHoover at fbi.gov Mon May 28 17:19:00 2007 From: JHoover at fbi.gov (Gordon Airporte) Date: Mon, 28 May 2007 17:19:00 -0400 Subject: itertools.groupby In-Reply-To: <1180286272.100790.131670@q75g2000hsh.googlegroups.com> References: <1180286272.100790.131670@q75g2000hsh.googlegroups.com> Message-ID: 7stud wrote: > Bejeezus. The description of groupby in the docs is a poster child > for why the docs need user comments. Can someone explain to me in > what sense the name 'uniquekeys' is used this example: > This is my first exposure to this function, and I see that it does have some uses in my code. I agree that it is confusing, however. IMO the confusion could be lessened if the function with the current behavior were renamed 'telescope' or 'compact' or 'collapse' or something (since it collapses the iterable linearly over homogeneous sequences.) A function named groupby could then have what I think is the clearly implied behavior of creating just one iterator for each unique type of thing in the input list, as categorized by the key function. From efrat_regev at yahoo.com Tue May 1 17:40:58 2007 From: efrat_regev at yahoo.com (Efrat Regev) Date: Wed, 02 May 2007 00:40:58 +0300 Subject: Grabbing the output of a long-winded shell call (in GNU/Linux) In-Reply-To: <59plp3F2l64obU1@mid.uni-berlin.de> References: <46378364$1@news.bezeqint.net> <1178047885.767785.35320@h2g2000hsg.googlegroups.com> <46379600.3060502@yahoo.com> <59plp3F2l64obU1@mid.uni-berlin.de> Message-ID: <4637B3EA.9050105@yahoo.com> Diez B. Roggisch wrote: > Efrat Regev schrieb: >> draghuram at gmail.com wrote: >>> On May 1, 2:23 pm, Efrat Regev wrote: >>> >>>> So my question is if there's a way to "grab" the output as it's being >>>> generated. It doesn't matter if the solution is blocking (as opposed to >>>> callback based), since threads can handle this. I just don't know >>>> how to >>>> "grab" the output. I appreciate your time in reading (and answering >>>> this), as I've been googling several hours for this. >>> >>> There may be more pythonic solution than what I suggest here but this >>> is what I have done when I needed similar functionality. Basically run >>> your command in the background and redirect its stdout/err to a temp >>> file. You may run the command either in the background or in a >>> separate thread. You can then run the command "tail --retry -- >>> pid= -n+0 -F " and grab the output. The tail command >>> exits once the real command is done. > > Or instead use the python subprocess module and read the commands > stdin/out/err from the Popen-object. > > Diez Excellent, thanks! BTW: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440554 (found this after seeing responses on list) From sturlamolden at yahoo.no Tue May 15 13:21:38 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 15 May 2007 10:21:38 -0700 Subject: Trying to choose between python and java In-Reply-To: References: Message-ID: <1179249698.074211.303700@o5g2000hsb.googlegroups.com> On May 15, 7:30 am, Anthony Irwin wrote: > #1 Does python have something like javas .jar packages. Yes. .egg files. > #2 What database do people recommend for using with python that is > easy to distribute across linux, mac, windows. Depends on your needs: 1. Berkely DB - not relational, zero administration, very fast (bundled with Python). 2. SQLite - zero administration, quite fast (bundled with Python). 3. MySQL - relational database server, fast, GPL 4. Oracle - relational database server, sluggish, commercial > #3 Is there any equivalent to jfreechart and jfreereport > (http://www.jfree.orgfor details) in python. Yes. reportlab matplotlib > #4 If I write a program a test it with python-wxgtk2.6 under linux are > the program windows likely to look right under windows and mac? Yes. But you should test anyway. > #5 someone said that they used to use python but stopped because the > language changed or made stuff depreciated Python is no worse than Java with respect to that. From bignose+hates-spam at benfinney.id.au Tue May 29 05:32:49 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 29 May 2007 19:32:49 +1000 Subject: Periodic tasks. References: <1180420430.610215.96330@a26g2000pre.googlegroups.com> Message-ID: <87lkf8nfem.fsf@benfinney.id.au> Ramashish Baranwal writes: > I am trying to execute some tasks periodically, those familiar with > unix can think of it as equivalent to cron jobs. Can you not use cron? If not, why not? Is there an equivalent service you can use? > I have tried looking around, but couldn't find a way. Using the services provided by the operating system would be far preferable to re-inventing a scheduler service. -- \ Contentsofsignaturemaysettleduringshipping. | `\ | _o__) | Ben Finney From stefan.behnel-n05pAM at web.de Mon May 14 06:17:36 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 14 May 2007 12:17:36 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <4648252D.5020704@web.de> Message-ID: <46483740.4050406@web.de> Eric Brunel wrote: > On Mon, 14 May 2007 11:00:29 +0200, Stefan Behnel >> Any chance there are still kanji-enabled programmes around that were >> not hit >> by the bomb in this scenario? They might still be able to help you get >> the >> code "public". > > Contrarily to what one might think seeing the great achievements of > open-source software, people willing to maintain public code and/or make > it evolve seem to be quite rare. If you add burdens on such people - > such as being able to read and write the language of the original code > writer, or forcing them to request a translation or transliteration from > someone else -, the chances are that they will become even rarer... Ok, but then maybe that code just will not become Open Source. There's a million reasons code cannot be made Open Source, licensing being one, lack of resources being another, bad implementation and lack of documentation being important also. But that won't change by keeping Unicode characters out of source code. Now that we're at it, badly named english identifiers chosen by non-english native speakers, for example, are a sure way to keep people from understanding the code and thus from being able to contribute resources. I'm far from saying that all code should start using non-ASCII characters. There are *very* good reasons why a lot of projects are well off with ASCII and should obey the good advice of sticking to plain ASCII. But those are mainly projects that are developed in English and use English documentation, so there is not much of a risk to stumble into problems anyway. I'm only saying that this shouldn't be a language restriction, as there definitely *are* projects (I know some for my part) that can benefit from the clarity of native language identifiers (just like English speaking projects benefit from the English language). And yes, this includes spelling native language identifiers in the native way to make them easy to read and fast to grasp for those who maintain the code. It should at least be an available option to use this feature. Stefan From penis.Mosely5 at gmail.com Fri May 18 02:36:55 2007 From: penis.Mosely5 at gmail.com (penis.Mosely5 at gmail.com) Date: 17 May 2007 23:36:55 -0700 Subject: Naked Boobs! - Download for Free !!! Message-ID: <1179470215.915964.209640@w5g2000hsg.googlegroups.com> http://nudepicks.blogspot.com/ - Naked Boobie Downloads! From steven.bethard at gmail.com Wed May 16 23:19:08 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 16 May 2007 21:19:08 -0600 Subject: how do I count spaces at the beginning of a string? In-Reply-To: <1179367338.906430.97420@k79g2000hse.googlegroups.com> References: <1179367338.906430.97420@k79g2000hse.googlegroups.com> Message-ID: walterbyrd wrote: > The strings start with whitespace, and have a '*' or an alphanumeric > character. I need to know how many whitespace characters exist at the > beginning of the string. You really need to stop posting the same message multiple times. A possible answer using regular expressions: >>> import re >>> whitespace_matcher = re.compile(r'^\s+') >>> match = whitespace_matcher.search(' abc def ghi') >>> len(match.group()) 8 STeVe From tjreedy at udel.edu Sun May 13 16:56:22 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 13 May 2007 16:56:22 -0400 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476081.7080609@web.de> Message-ID: "Stefan Behnel" wrote in message news:46476081.7080609 at web.de... | For example, I could write | | def zieheDreiAbVon(wert): | return zieheAb(wert, 3) | | and most people on earth would not have a clue what this is good for. However, | someone who is fluent enough in German could guess from the names what this does. | | I do not think non-ASCII characters make this 'problem' any worse. It is ridiculous claims like this and the consequent refusal to admit, address, and ameliorate the 50x worse problems that would be introduced that lead me to oppose the PEP in its current form. Terry Jan Reedy From horpner at yahoo.com Wed May 9 14:17:39 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 09 May 2007 18:17:39 GMT Subject: Inheritance problem References: <1178734168.255175.248800@e51g2000hsg.googlegroups.com> Message-ID: On 2007-05-09, amidzic.branko at gmail.com wrote: > I'm trying to solve a problem using inheritance and > polymorphism in python 2.4.2 It's not an inheritance problem, it's a notation problem. Python uses explicit 'self', saving you the trouble of devising a naming convention for data members. > I think it's easier to explain the problem using simple example: > > class shortList: > def __init__(self): > self.setList() > > def setList(self): > a = [1,2,3] > print a You need to use self.a = [1, 2, 3] print self.a The notation you used creates a local variable, but you need a data member. > class longList(shortList): > def __init__(self): > shortList.setList() > self.setList() > > def setList(self): > a.extend([4,5,6]) > print a Similarly: self.a.extend([4, 5, 6]) print self.a Does that give you better results? -- Neil Cerutti If we stay free of injuries, we'll be in contention to be a healthy team. --Chris Morris From nogradi at gmail.com Sun May 13 13:00:18 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Sun, 13 May 2007 19:00:18 +0200 Subject: elementtree and entities In-Reply-To: References: Message-ID: <5f56302b0705131000k49b5ac65v219feffbb8fe018@mail.gmail.com> > > How does one prevent elementtree converting & to & (and similarly > > for other entities)? > > > >>>> from xml.etree import ElementTree as et > >>>> x = et.Element( 'test' ) > >>>> x.text = '&' > >>>> et.tostring( x ) > > '&' > > > > Sometimes I would like to have the output '&' > > > > elementtree is for processing xml. If you want to output something which > isn't xml then you'll have to use a different library or mess about with > the xml after it has been generated: > > et.tostring(x).replace('&', '&') > > does what you want, but you won't be able to parse it again with anything > which expects xml. Thanks for the reply, I'll just live with replace then. From adam at atlas.st Wed May 2 17:13:25 2007 From: adam at atlas.st (Adam Atlas) Date: 2 May 2007 14:13:25 -0700 Subject: __dict__s and types and maybe metaclasses... Message-ID: <1178140405.468223.146220@l77g2000hsb.googlegroups.com> Suppose I want to create a type (i.e. a new-style class via the usual `class blah(...)` mechanism) but, during the process of creating the type, I want to replace its __dict__ so I can override some behaviors during the initial assignment of its members. That is, I have `class blah(...): a = 123; b = 456; ...`, and I want to substitute my own dict subclass which will thus receive __setitem__(a, 123), __setitem__(b, 456), and so on. Is this possible? Maybe with metaclasses? I've experimented with them a bit, but I haven't found any setup that works. From see.signature at no.spam Wed May 16 04:37:58 2007 From: see.signature at no.spam (Eric Brunel) Date: Wed, 16 May 2007 10:37:58 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <7x4pmg716p.fsf@ruckus.brouhaha.com> <4648EC26.8020907@v.loewis.de> Message-ID: On Wed, 16 May 2007 02:14:58 +0200, Steven D'Aprano wrote: > On Tue, 15 May 2007 09:09:30 +0200, Eric Brunel wrote: > >> Joke aside, this just means that I won't ever be able to program math in >> ADA, because I have absolutely no idea on how to do a 'pi' character on >> my keyboard. > > Maybe you should find out then? Personal ignorance is never an excuse for > rejecting technology. My "personal ignorance" is fine, thank you; how is yours?: there is no keyboard *on Earth* allowing to type *all* characters in the whole Unicode set. So my keyboard may just happen to provide no means at all to type a greek 'pi', as it doesn't provide any to type Chinese, Japanese, Korean, Russian, Hebrew, or whatever character set that is not in usage in my country. And so are all keyboards all over the world. Have I made my point clear or do you require some more explanations? -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From mccredie at gmail.com Wed May 2 18:17:45 2007 From: mccredie at gmail.com (Matimus) Date: 2 May 2007 15:17:45 -0700 Subject: Slicing Arrays in this way In-Reply-To: <4638fe20$0$16403$88260bb3@free.teranews.com> References: <4638fe20$0$16403$88260bb3@free.teranews.com> Message-ID: <1178144265.751484.318830@y80g2000hsf.googlegroups.com> On May 2, 3:03 pm, Tobiah wrote: > >>> elegant_solution([1,2,3,4,5,6,7,8,9,10]) > [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] > > -- > Posted via a free Usenet account fromhttp://www.teranews.com >>> seq = range(1,11) >>> seq [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> zip( seq[0::2],seq[1::2] ) [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)] if you _really_ need lists then... >>> map(list, zip( seq[0::2],seq[1::2] )) [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] From carsten at uniqsys.com Wed May 9 22:20:19 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 09 May 2007 22:20:19 -0400 Subject: change of random state when pyc created?? In-Reply-To: References: <5ae25fF2oggbqU1@mid.uni-berlin.de> Message-ID: <1178763619.3366.25.camel@localhost.localdomain> On Thu, 2007-05-10 at 01:25 +0000, Alan Isaac wrote: > Did this thread not demonstrate that even sophisticated users > do not see into this "implication" immediately? Knowing that maps don't have reproducible ordering is one thing. Realizing that that's the cause of the problem that's arbitrarily and wrongly attributed to the 'random' module, in a piece of code that's not posted to the public, and presumably not trimmed down to the shortest possible example of the problem, is quite another. I'll venture the guess that most Python programmers with a modicum of experience will, when asked point blank if it's safe to rely on a dictionary to be iterated in a particular order, answer no. > Replicability > of results is a huge deal in some circles. Every software engineer wants their results to be replicable. Software engineers also know that they can only expect their results to be replicable if they use deterministic functions. You wouldn't expect time.time() to return the same result just because you're running the same code, would you? > I think the docs > for sets and dicts should include a red flag: do not use > these as iterators if you want replicable results. It does, at least for dicts: "Keys and values are listed in an arbitrary order." If this wording is not present for sets, something to this effect should be added. Regards, -- Carsten Haese http://informixdb.sourceforge.net From i3dmaster at gmail.com Fri May 18 19:57:56 2007 From: i3dmaster at gmail.com (i3dmaster) Date: 18 May 2007 16:57:56 -0700 Subject: unittest for threading function always failed... In-Reply-To: <1179530016.500072.177880@y80g2000hsf.googlegroups.com> References: <1179530016.500072.177880@y80g2000hsf.googlegroups.com> Message-ID: <1179532675.996634.33030@k79g2000hse.googlegroups.com> On May 18, 4:13 pm, i3dmaster wrote: > I am having a little difficulty to figure out why this unittest for a > Thread subclass always fails... > > # unittest code: > > class SPThreadUnitTest(unittest.TestCase): > > def testgetresult(self): > from random import randint > self.i = randint(1,10) > def p(n): return n > self.t = spthread.SPThread(target=p, args=(self.i)) > self.t.start() > #self.t._res = self.t._target(self.t._args) > self.assertEquals(self.i,self.t.getresult()) > > #spthread.SPThread code: > > import threading > class SPThread(threading.Thread): > > def __init__(self,target=None,args=None): > threading.Thread.__init__(self) > self._target = target > self._args = args > self._res = None > > def getresult(self): > return self._res > > def run(self): > self._res = self._target(self._args) > > A simple little test. But no matter what, the self._res didn't get any > value but None, so the assertion of self.i and self.t.getresult() > always fails. If I use the commented out code, it works. So the > start() function has some tricky stuff? Can someone point me out where > the problem is? > > Thanks, > Jim oh wft... I got it now. its the join() call... From Wiseman1024 at gmail.com Sat May 5 11:52:15 2007 From: Wiseman1024 at gmail.com (Wiseman) Date: 5 May 2007 08:52:15 -0700 Subject: Python regular expressions just ain't PCRE In-Reply-To: References: <1178323901.381993.47170@e65g2000hsc.googlegroups.com> Message-ID: <1178380335.646708.260540@h2g2000hsg.googlegroups.com> On May 5, 5:12 am, "Terry Reedy" wrote: > I believe the current Python re module was written to replace the Python > wrapping of pcre in order to support unicode. I don't know how PCRE was back then, but right now it supports UTF-8 Unicode patterns and strings, and Unicode character properties. Maybe it could be reintroduced into Python? > I don't remember those being in the pcre Python once had. Perhaps they are > new. At least today, PCRE supports recursion and recursion check, possessive quantifiers and once-only subpatterns (disables backtracking in a subpattern), callouts (user functions to call at given points), and other interesting, powerful features. From martin at v.loewis.de Tue May 8 02:59:40 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 08 May 2007 08:59:40 +0200 Subject: getmtime differs between Py2.5 and Py2.4 In-Reply-To: <1hxrebv.5tn2pnql23q7N%aleax@mac.com> References: <463FA51D.1060600@v.loewis.de> <463fb305$0$326$e4fe514c@news.xs4all.nl> <1178585991.924458.154570@l77g2000hsb.googlegroups.com> <1hxrebv.5tn2pnql23q7N%aleax@mac.com> Message-ID: <46401FDC.4010705@v.loewis.de> > the difference (rounding to an int number of seconds) is just about one > hour; in certain parts of the world (Europe and Africa), that could > indeed be a timezone issue. With the help of Tony Meyer, we rediscovered the explanation: because of a bug in the Microsoft C run-time library, the UTC time reported by 2.4 may have been off by one hour (it wasn't local time - just off by one hour). This was due to DST issues. They have been fixed in 2.5, which now reports the correct UTC value. Regards, Martin From rahulnag22 at yahoo.com Tue May 15 19:00:10 2007 From: rahulnag22 at yahoo.com (rahulnag22 at yahoo.com) Date: 15 May 2007 16:00:10 -0700 Subject: tkFileDialog.askopenfilename() Message-ID: <1179270010.433011.23580@y80g2000hsf.googlegroups.com> Hi, When I call tkFileDialog.askopenfilename() , the dialog box opens with the current directory as the default directory. Is it possible to open the dialog box with a directory other than the current directory. Can we pass in a user defined starting directory. Thanks Rahul From gagsl-py2 at yahoo.com.ar Wed May 2 12:32:21 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 02 May 2007 13:32:21 -0300 Subject: DiffLib Question References: <1178095577.190066.158960@y80g2000hsf.googlegroups.com> <1178097127.286181.216520@y80g2000hsf.googlegroups.com> <1178097973.516943.248720@y80g2000hsf.googlegroups.com> Message-ID: En Wed, 02 May 2007 06:26:13 -0300, whitewave escribi?: > Thank you for your reply. But I don't fully understand what the > charjunk and linejunk is all about. I'm a bit newbie in python using > the DiffLib. I'm I using the right code here? I will I implement the > linejunk and charjunk using the following code? Usually, Differ receives two sequences of lines, being each line a sequence of characters (strings). It uses a SequenceMatcher to compare lines; the linejunk argument is used to ignore certain lines. For each pair of similar lines, it uses another SequenceMatcher to compare characters inside lines; the charjunk is used to ignore characters. As you are feeding Differ with a single string (not a list of text lines), the "lines" it sees are just characters. To ignore whitespace and newlines, in this case one should use the linejunk argument: def ignore_ws_nl(c): return c in " \t\n\r" a = difflib.Differ(linejunk=ignore_ws_nl).compare(d1,d2) dif = list(a) print ''.join(dif) I n a d d i t i o n , t h e c o n s i d e r e d p r o b l e m d o e s n o t h a v e a m e a n i n g f u l t r a d i t i o n a l t y p e o f- + a d j o i n t- + p r o b l e m e v e n f o r t h e s i m p l e f o r m s o f t h e d i f f e r e n t i a l e q u a t i o n a n d t h e n o n l o c a l c o n d i t i o n s . D u e- + t o t h e s e f a c t s , s o m e s e r i o u s d i f f i c u l t i e s a r i s e i n t h e a p p l i c a t i o n o f t h e c l a s s i c a l m e t h o d s t o s u c h a- + p r o b l e m .+ I hope this is what you were looking for. -- Gabriel Genellina From castironpi at gmail.com Tue May 8 01:57:23 2007 From: castironpi at gmail.com (castironpi at gmail.com) Date: 7 May 2007 22:57:23 -0700 Subject: interesting exercise In-Reply-To: <1hxrks6.3v5xj5a4jv0bN%aleax@mac.com> References: <1178595952.641173.76540@y80g2000hsf.googlegroups.com> <1178598876.913274.184850@p77g2000hsh.googlegroups.com> <1178599363.051648.235280@w5g2000hsg.googlegroups.com> <1178599567.894918.288450@l77g2000hsb.googlegroups.com> <1hxrks6.3v5xj5a4jv0bN%aleax@mac.com> Message-ID: <1178603843.672376.90010@l77g2000hsb.googlegroups.com> On May 8, 12:24 am, a... at mac.com (Alex Martelli) wrote: > wrote: > > ... > > > def p(a,b): > > if list( a ) != sorted( list( a ) ): raise ValueError, "String not > > ordered." > > if not b: return [''] > > return [i+j for i in list(a) for j in p(a,b-1)] > > No need for 2/3 of the list(...) calls. sorted(a) and sorted(list(a)) > will ALWAYS be the same sequence; "for i in a" and "for i in list(a)" > will always iterate on the same sequence [as long as you're not changing > a inside the iteration, which, in this case, you aren't]. > > Alex Ah quite true. list( a ) != sorted( a ). ...for i in a for... From DustanGroups at gmail.com Sat May 5 07:07:00 2007 From: DustanGroups at gmail.com (Dustan) Date: 5 May 2007 04:07:00 -0700 Subject: Looping over lists In-Reply-To: References: <1hxlsky.tgi88sj7tfrN%aleax@mac.com> Message-ID: <1178363220.575060.219310@y5g2000hsa.googlegroups.com> On May 5, 3:15 am, kaens wrote: > I think the for i in range() is more readable (Maybe because I'm > coming from a c-style syntax language background) - but what would > the benefits of using enumerate be (other that being more . . . > pythonesque?) It doesn't create a whole new list just for iterating. > On 5/5/07, Dennis Lee Bieber wrote: > > > On Fri, 4 May 2007 19:26:17 -0700, a... at mac.com (Alex Martelli) > > declaimed the following in comp.lang.python: > > > > for i in range(n): > > > for j in range(i+1, n): > > > print a[i], a[j] > > > Ah, but wouldn't the cleaner Python be something like > > > >>> a = [1, 2, 3, 4, 5, 3, 6] #just to confuse matters > > >>> for pos, val in enumerate(a): > > ... for v2 in a[pos+1:]: > > ... print val, v2 > > ... > > 1 2 > > 1 3 > > 1 4 > > 1 5 > > 1 3 > > 1 6 > > 2 3 > > 2 4 > > 2 5 > > 2 3 > > 2 6 > > 3 4 > > 3 5 > > 3 3 > > 3 6 > > 4 5 > > 4 3 > > 4 6 > > 5 3 > > 5 6 > > 3 6 > > > -- > > 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/ > > -- > >http://mail.python.org/mailman/listinfo/python-list From hq4ever at gmail.com Fri May 4 07:57:21 2007 From: hq4ever at gmail.com (Maxim Veksler) Date: Fri, 4 May 2007 14:57:21 +0300 Subject: Non blocking sockets with select.poll() ? In-Reply-To: <20070504112137.19381.249713413.divmod.quotient.8262@ohm> References: <20070504112137.19381.249713413.divmod.quotient.8262@ohm> Message-ID: On 5/4/07, Jean-Paul Calderone wrote: > On Fri, 4 May 2007 13:04:41 +0300, Maxim Veksler wrote: > >Hi, > > > >I'm trying to write a non blocking socket port listener based on > >poll() because select is limited to 1024 fd. > > > >Here is the code, it never gets to "I did not block" until I do a > >telnet connection to port 10000. > > > > What were you expecting? > I'll try to explain. I'm doing a little experiment: Capturing the whole tcp 1-65535 range of the machine, allowing me to connect to the my service on the machine on every port. I know that it's probably the most dumb thing to do with TCP/IP communication please don't forget it's an experiment. My first attempt was made with select.select please see here http://article.gmane.org/gmane.comp.python.general/516155/ and the next attempt for slice-by 1024 which also didn't work, here: http://article.gmane.org/gmane.comp.python.general/517036/ Now, after I realized I won't be able to implement this using select.select I turned to select.poll(). My problem now it that I'm able to register more then 1024 socket fd but now I can't replicate the behaviour select gave me. When I used select for <1024 sockets, I was able to telnet to each of the 1024 ports and select.select would return the proper object to do accept() on it, shortly speaking: no exception was thrown, you can see the working code in the second link above. The situation I have now with the code attached below is that if I try querying one of the registered ports I get the following : TERM1: """ ./listener_sockets_range_poll.py . . Asking 10182 Asking 10183 Asking 10184 Asking 10185 Asking 10186 Found 10186 Traceback (most recent call last): File "./listener_sockets_range_poll.py", line 35, in conn, addr = nb_active_socket.accept() File "/usr/lib/python2.5/socket.py", line 167, in accept sock, addr = self._sock.accept() socket.error: (11, 'Resource temporarily unavailable') """ TERM2: """ telnet localhost 10100 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. Connection closed by foreign host. """ and the code running is this: """ #!/usr/bin/env python import socket import select class PollingSocket(socket.socket): __poll = select.poll() def __init__(self, port_number): self.tcp_port_number = port_number socket.socket.__init__(self, socket.AF_INET, socket.SOCK_STREAM) self.setblocking(0) self.bind(('0.0.0.0', self.tcp_port_number)) self.listen(5) self.__poll.register(self) def poll(self, timeout = 0): return self.__poll.poll(timeout) def debugPollingSocket(port_num): print "BIND TO PORT: ", port_num return PollingSocket(port_num) all_sockets = map(debugPollingSocket, xrange(10000, 19169)) print "We have this in stock:" for nb_active_socket in all_sockets: print nb_active_socket.tcp_port_number while 1: for nb_active_socket in all_sockets: print "Asking", nb_active_socket.tcp_port_number if nb_active_socket.poll(1): print "Found", nb_active_socket.tcp_port_number conn, addr = nb_active_socket.accept() while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close() """ > Jean-Paul Thank you, Maxim. -- Cheers, Maxim Veksler "Free as in Freedom" - Do u GNU ? From walterbyrd at iname.com Thu May 10 17:11:58 2007 From: walterbyrd at iname.com (walterbyrd) Date: 10 May 2007 14:11:58 -0700 Subject: Newbie look at Python and OO In-Reply-To: <1178830137.877510.290070@w5g2000hsg.googlegroups.com> References: <1178812734.860473.236370@y80g2000hsf.googlegroups.com> <464380c4$0$25791$426a74cc@news.free.fr> <1178830137.877510.290070@w5g2000hsg.googlegroups.com> Message-ID: <1178831518.601877.180280@y5g2000hsa.googlegroups.com> Nevermind my previous question. I found the answer in "Learning Python" >> Python internally caches and reuses short strings as an optimization, there really is just a single string, 'spam', in memory, shared by S1 and S2; hence, the is identity test reports a true result. To trigger the normal behavior, we need to use longer strings that fall outside the cache mechanism: << From adam at atlas.st Thu May 10 17:47:39 2007 From: adam at atlas.st (Adam Atlas) Date: 10 May 2007 14:47:39 -0700 Subject: Newbie question about string(passing by ref) In-Reply-To: <1178833397.076720.279940@l77g2000hsb.googlegroups.com> References: <1178833397.076720.279940@l77g2000hsb.googlegroups.com> Message-ID: <1178833659.400428.185630@u30g2000hsc.googlegroups.com> On May 10, 5:43 pm, lazy wrote: > I want to pass a string by reference. Don't worry, all function parameters in Python are passed by reference. From mangabasi at gmail.com Wed May 23 14:22:44 2007 From: mangabasi at gmail.com (Mangabasi) Date: 23 May 2007 11:22:44 -0700 Subject: Inheriting from Python list object(type?) In-Reply-To: Message-ID: <1179944564.022226.80550@p47g2000hsd.googlegroups.com> On May 23, 12:47 pm, "Jerry Hill" wrote: > On 23 May 2007 09:58:36 -0700, Mangabasi wrote: > > > There must be a way to inherit from the list type without having to > > redefine all the methods and attributes that regular lists have. > > Like this: > > class Point(list): > def __init__(self, x, y, z = 1): > list.__init__(self, [x, y, z]) > > def __getattr__(self, name): > if name == 'x': return self[0] > if name == 'y': return self[1] > if name == 'z': return self[2] > > def __setattr__(self, name, value): > if name == 'x': self[0] = value > if name == 'y': self[1] = value > if name == 'z': self[2] = value > > Does that show you what you need? > > -- > Jerry Hi Jerry, It is very close. It worked for many operations except when I tried >>> from numpy import array >>> p = Point(4,5) >>> a = array(p) Traceback (most recent call last): File "", line 1, in ? ValueError: invalid __array_struct__ >>> a = array([4, 5, 1]) >>> I can define an __array__ method for this to work but I am wondering if we can make this behave like a real list? Thanks for your help. From bbxx789_05ss at yahoo.com Tue May 1 09:43:40 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 1 May 2007 06:43:40 -0700 Subject: Store variable name in another variable In-Reply-To: <1178023417.680239.156910@n59g2000hsh.googlegroups.com> References: <1177592072.498517.139260@b40g2000prd.googlegroups.com> <4631120a$0$27375$ba4acef3@news.orange.fr> <1178023417.680239.156910@n59g2000hsh.googlegroups.com> Message-ID: <1178027019.940290.193090@y5g2000hsa.googlegroups.com> On May 1, 6:43 am, loial wrote: > OK, I have it working with dictionaries. > > However I have another scenerio : > > I am reading a file containing records like the following : > > > > > .. > .. > > I need to substitute MYVARIABLE with the current value of MYVARIABLE > in my python script and write the file out again. > > The file may contain many more lines and many substitution values on > any line > > Assuming that MYVARIABLE is currently set to JOHN then the output > would be > > > > > > Can this be done in Python? s = "hello world, goodbye world" result = s.replace("world", "moon") print result From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri May 4 13:00:03 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 04 May 2007 19:00:03 +0200 Subject: Newbie and Page Re-Loading In-Reply-To: <1178275290.158007.248180@h2g2000hsg.googlegroups.com> References: <1178275290.158007.248180@h2g2000hsg.googlegroups.com> Message-ID: <463b6678$0$10433$426a34cc@news.free.fr> mosscliffe a ?crit : > I am very new to this python world, but I do like the look of the > language / syntax, though I have had some problems with indenting > using a text editor. There's no shortage of smart code editor having a decent support for Python. > > I have managed to get my ISP to execute .py files on their server. Great. > I have created a .py file and it does in fact do the various little > tasks I have asked it to do. > > Now i need to get a bit more serious. > > I wish to have a web page with a search form at the top and on > processing the form re-load my current page, but with the various > search results. > > Do I just add my script name to the Action part of the Form your script's url would actually be better. > and how > can I pass variables, other than form variables to each execution of > the script. If I have to use hidden form variables, how would I alter > them for each page. Since you're talking about redisplaying the page with results added, I assume this page is dynamically created by another python script. If so, you can put the form's generation in a function that will take page-specific params and put them in the appropriate hidden fields. Then just call that function from the script generating your web page. > I suppose I am looking for some sort of session management, Depends... But if it's just to know which page called the script, you don't need sessions here. > but I have > not been able to track one down as yet. I'm suppose your doing CGI scripts. I've seen some basic session management for CGI somewhere, but that's mostly old stuff. > I am running on an ISP, with > no knowledge of python, so asking about getting packages loaded will > not be an option. You can install packages in your own space - you'll just have to make sure that there in your python path. > I have 'Python in a Nutshell', but it is a bit sparse on everyday web > page examples. "everyday web pages examples" in Python usually imply a more sophisticated framework and a long running process (think Zope, Django, CherryPy, Pylons, mod_python, wsgi, fcgi etc...) From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri May 4 16:48:33 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 04 May 2007 22:48:33 +0200 Subject: Newbie and Page Re-Loading In-Reply-To: <1178302555.479739.227920@o5g2000hsb.googlegroups.com> References: <1178275290.158007.248180@h2g2000hsg.googlegroups.com> <463b6678$0$10433$426a34cc@news.free.fr> <1178302555.479739.227920@o5g2000hsb.googlegroups.com> Message-ID: <463b9c04$0$10333$426a34cc@news.free.fr> mosscliffe a ?crit : > Bruno, > > Many thanks for your very helpful reply. > > I am trying WingIDE Personal as an editor, up to now it seems OK. > > My ISP is running Python 2.4.3 and does not know about mod_python. > Few ISPs want to deploy mod_python... > I do not want to run a framework yet. I would like to understand > python at script level, before adding more aspects to learn, like > frameworks. Bottom-top approach, hu ?-) Anyway, "the script level" can be a bit restrictive - you may at least want to use modules and functions... > I think I get your idea about hidden fields and how to alter them. > > My single page script should work something like this > > DisplayHTMLHeaderandBodyHeader > Check if this is a Re-Load (HiddenField would not exist first time I > am assuming) > Display SearchSection with previous SearchRequest What do you call "previous search request" ? > If SearchRequest is True: Get and Display Results > Display TrailerHTMLandTrailerBody > Does the above make sense or is there a better way ? This (almost) makes sens in this context. As far as I'm concerned, I'd split this in: - a module handling all search logic - a module/script/whatever handling all the "display" logic - a script calling on the first if necessary to get 'raw' search results, then calling on the second (with whatever appropriate parameters, including stuff like search results) and returning the result. > How do I get the directory of my modules into the Python Path import sys sys.path.append('/path/to/my/modules') > Is there a lightweight Https Server I could run locally (WINXP), which > would run .py scripts, without lots of installation modifications ? http://docs.python.org/lib/module-CGIHTTPServer.html Don't know what it's worth, and it seems to have a serious limitation (no possible redirect), but that may help testing your scripts. FWIW, a cgi script can be directly called if you setup the correct environnement vars and pass the correct args (which can be done from another script !-) From whamil1 at entergy.com Fri May 4 08:52:10 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Fri, 4 May 2007 07:52:10 -0500 Subject: Strange terminal behavior after quitting Tkinter application In-Reply-To: <1178257164.415485.155290@q75g2000hsh.googlegroups.com> Message-ID: <588D53831C701746A2DF46E365C018CE01D2CA8C@LITEXETSP001.etrsouth.corp.entergy.com> > -----Original Message----- > From: Chris > Subject: Re: Strange terminal behavior after quitting Tkinter application > Clicking 'Quit' or on the window's 'x' causes the application to quit > without messing up the terminal. With root.mainloop() commented out, > though, no combination of root.quit(), root.destroy(), and sys.exit() > stops the terminal from getting messed up. > > So, I should call mainloop() for my application...except that I want > to use the commandline, too, and calling mainloop() freezes the > commandline. I wonder if there is another way to use the commandline > and have a GUI? I couldn't find any clear information about that. Can you run it in the background? IIRC, if you put an ampersand ('&') at the end of the command line, it will run as a background process and leave your command line available for other tasks. (The marker may be something other than &, it's been a long, long time since I've used *nix in a gui environment.) --- -Bill Hamilton From nick at craig-wood.com Tue May 15 05:30:03 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 15 May 2007 04:30:03 -0500 Subject: Subprocess with and without shell References: <1179194910.310317.38730@y80g2000hsf.googlegroups.com> Message-ID: George Sakkis wrote: > I'm trying to figure out why Popen captures the stderr of a specific > command when it runs through the shell but not without it. IOW: > > cmd = [my_exe, arg1, arg2, ..., argN] > if 1: # this captures both stdout and stderr as expected > pipe = Popen(' '.join(cmd), shell=True, stderr=PIPE, stdout=PIPE) > else: # this captures only stdout > pipe = Popen(cmd, shell=False, stderr=PIPE, stdout=PIPE) > > # this prints the empty string if not run through the shell > print "stderr:", pipe.stderr.read() > # this prints correctly in both cases > print "stdout:", pipe.stdout.read() > > Any hints ? Post an example which replicates the problem! My effort works as expected -- z.py ---------------------------------------------------- #!/usr/bin/python from subprocess import Popen, PIPE cmd = ["./zz.py"] for i in range(2): if i: # this captures both stdout and stderr as expected print "With shell" pipe = Popen(' '.join(cmd), shell=True, stderr=PIPE, stdout=PIPE) else: # this captures only stdout print "Without shell" pipe = Popen(cmd, shell=False, stderr=PIPE, stdout=PIPE) # this prints the empty string if not run through the shell print "stderr:", pipe.stderr.read() # this prints correctly in both cases print "stdout:", pipe.stdout.read() ---zz.py---------------------------------------------------- #!/usr/bin/python import sys print >>sys.stdout, "Stdout" print >>sys.stderr, "Stderr" ------------------------------------------------------------ Produces $ ./z.py Without shell stderr: Stderr stdout: Stdout With shell stderr: Stderr stdout: Stdout -- Nick Craig-Wood -- http://www.craig-wood.com/nick From jstroud at mbi.ucla.edu Tue May 8 06:22:05 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 08 May 2007 10:22:05 GMT Subject: interesting exercise In-Reply-To: <1178601624.812907.23550@u30g2000hsc.googlegroups.com> References: <1178595952.641173.76540@y80g2000hsf.googlegroups.com> <1178601624.812907.23550@u30g2000hsc.googlegroups.com> Message-ID: sherry wrote: > On May 8, 9:31 am, Steven D'Aprano > wrote: >> On Mon, 07 May 2007 20:45:52 -0700, Michael Tobis wrote: >>> I have a reasonably elegant solution but it's a bit verbose (a couple >>> dozen lines which I'll post later if there is interest). Is there some >>> clever Pythonism I didn't spot? >> Peering into my crystal ball, I see that your algorithm does the wrong >> thing, and contains bugs too. You certainly don't need to partion the >> sequence into three sub-sequences, or do that trick with the metaclass, >> and it is more efficient to use list.extend() than sum. >> >> Hang on... stupid crystal ball... that's somebody else's code. Maybe you >> should just post your code here, so we can look at it? >> >> In the meantime, here's a simple generator to do permutations with >> repetition: >> >> def permute_with_repetitions(seq): >> if len(seq) <= 1: >> yield list(seq) >> else: >> for i, item in enumerate(seq): >> for tail in permute_with_repetitions(seq[:i] + seq[i+1:]): >> yield [item] + tail >> >> It doesn't do a test for the sequence containing duplicates, and I leave >> it as anexerciseto do selections of fewer items. >> >> -- >> Steven. > > Dear Steven > I ran into your message quite accidentally while researching about > some details on 'Exercise' and thought of sharing some of my > findings. > I've read at 'http://www.medical-health-care-information.com/Health- > living/exercise/index.asp > that Swimming, cycling, jogging, skiing, aerobic dancing, walking or > any of dozens of other activities can help your heart. Whether it's > included in a structured exercise program or just part of your daily > routine, all physical activity adds up to a healthier heart. > I hope the above is of some help to you as well. Regards, Sherrybove. > This takes annoying past annoying to some new level of hell to which even satan himself wouldn't venture. From carsten at uniqsys.com Thu May 10 15:12:01 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 10 May 2007 15:12:01 -0400 Subject: Comparing dates problem In-Reply-To: <1178823142.101246.220660@l77g2000hsb.googlegroups.com> References: <1178746479.776908.319930@p77g2000hsh.googlegroups.com> <1178748764.663230.186570@y80g2000hsf.googlegroups.com> <1178823142.101246.220660@l77g2000hsb.googlegroups.com> Message-ID: <1178824321.3367.119.camel@dot.uniqsys.com> On Thu, 2007-05-10 at 11:52 -0700, kyosohma at gmail.com wrote: > I'm sure there is a hack for doing something like what you suggest, > but it would be messy. The problem is that I get a datetime object > returned and division really isn't something you can do to one of > those objects. Besides, if I had seconds returned, I would want to > multiply by 60, not divide. If you subtract that datetime object from the current datetime, you'll get a timedelta object that gives you the number of days and seconds (and microseconds, if you care) between the two datetimes: >>> import datetime >>> dt1 = datetime.datetime(2007,5,1,12,0,0) >>> dt2 = datetime.datetime.now() >>> delta = dt2 - dt1 >>> delta.days 9 >>> delta.seconds 11219 Now, if 60 seconds are one minute, 11219 seconds are how many minutes? (Answer left as an exercise for the reader.) Hope this helps, -- Carsten Haese http://informixdb.sourceforge.net From bj_666 at gmx.net Sat May 26 05:40:21 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 26 May 2007 11:40:21 +0200 Subject: Large Amount of Data References: Message-ID: In , Jack wrote: > I have tens of millions (could be more) of document in files. Each of them > has other properties in separate files. I need to check if they exist, > update and merge properties, etc. > And this is not a one time job. Because of the quantity of the files, I > think querying and updating a database will take a long time... But databases are exactly build and optimized to handle large amounts of data. > Let's say, I want to do something a search engine needs to do in terms > of the amount of data to be processed on a server. I doubt any serious > search engine would use a database for indexing and searching. A hash > table is what I need, not powerful queries. You are not forced to use complex queries and an index is much like a hash table, often even implemented as a hash table. And a database doesn't have to be an SQL database. The `shelve` module or an object DB like zodb or Durus are databases too. Maybe you should try it and measure before claiming it's going to be too slow and spend time to implement something like a database yourself. Ciao, Marc 'BlackJack' Rintsch From turbana at gmail.com Wed May 2 19:11:42 2007 From: turbana at gmail.com (Ian Clark) Date: Wed, 2 May 2007 16:11:42 -0700 Subject: Slicing Arrays in this way In-Reply-To: <1178146865.383519.326430@c35g2000hsg.googlegroups.com> References: <4638fe20$0$16403$88260bb3@free.teranews.com> <1178146865.383519.326430@c35g2000hsg.googlegroups.com> Message-ID: Yeah, having an elegant_solution() function would solve soo many of my problems. ;) Ian From steve at REMOVE.THIS.cybersource.com.au Fri May 11 23:41:12 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 12 May 2007 13:41:12 +1000 Subject: stealth screen scraping with python? References: <1178911975.308104.297380@n59g2000hsh.googlegroups.com> Message-ID: On Fri, 11 May 2007 12:32:55 -0700, different.engine wrote: > Folks: > > I am screen scraping a large volume of data from Yahoo Finance each > evening, and parsing with Beautiful Soup. > > I was wondering if anyone could give me some pointers on how to make > it less obvious to Yahoo that this is what I am doing, as I fear that > they probably monitor for this type of activity, and will soon ban my > IP. Write a virus to hijack tens of thousands of Windows PCs around the world, and use your army of zombie-PCs to do the screen scraping for you. Each one only needs to scrape a small amount of data, and Yahoo will have no way of telling that it is you. *wink* -- Steven. From malaclypse2 at gmail.com Wed May 23 14:43:43 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 23 May 2007 14:43:43 -0400 Subject: Inheriting from Python list object(type?) In-Reply-To: <1179945116.372121.24770@m36g2000hse.googlegroups.com> References: <1179945116.372121.24770@m36g2000hse.googlegroups.com> Message-ID: <16651e80705231143y527445edm6b7c145212047810@mail.gmail.com> On 23 May 2007 11:31:56 -0700, Mangabasi wrote: > When I modified this to: > > class Point(list): > def __init__(self,x,y): > super(Point, self).__init__([x, y]) > self.x = x > self.y = y > > It worked. Are you sure? >>> p = Point(10, 20) >>> p [10, 20] >>> p.x 10 >>> p.x = 15 >>> p [10, 20] >>> p[0] 10 >>> p.x 15 >>> That doesn't look like what you were asking for in the original post. I'm afraid I don't know anything about numpy arrays or what special attributes an object may need to be put into a numpy array though. -- Jerry From anton.vredegoor at gmail.com Mon May 14 15:40:11 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Mon, 14 May 2007 21:40:11 +0200 Subject: Sorting troubles In-Reply-To: <1179164193.047412.231310@n59g2000hsh.googlegroups.com> References: <1179158708.433792.127150@h2g2000hsg.googlegroups.com> <1179162617.578315.133640@h2g2000hsg.googlegroups.com> <1179164193.047412.231310@n59g2000hsh.googlegroups.com> Message-ID: seyensubs at yahoo.com wrote: > I see. I figured that list comprehensions made another list(duh), but > I thought I could relink the object(List) to the new list and keep it > once the function ended. > > Is it possible to pass a reference(to an object.. Like 'List', > basically) to a function and change the reference to point to > something created inside a function? Or all data unreturned from a > function is lost and no references kept?(The second, I'd guess, since > it's local temporary scope, but you never know, maybe Python can :) ) Maybe this (untested): def qsort(seq): if seq: pivot = seq.pop() Q = L,R = [],[] for x in seq: Q[x>=pivot].append(x) qsort(R) seq[:] = L+[pivot]+R A. From yucetekol at gmail.com Sun May 27 21:40:48 2007 From: yucetekol at gmail.com (yuce) Date: 27 May 2007 18:40:48 -0700 Subject: python -- prolog bridge error In-Reply-To: <1180224507.324418.52170@q69g2000hsb.googlegroups.com> References: <1180224507.324418.52170@q69g2000hsb.googlegroups.com> Message-ID: <1180316448.193656.262300@o5g2000hsb.googlegroups.com> Hello, PySWIP requires "libpl.dll" to be on the path. There are two ways to do this: 1) Add 'bin' directory of SWI-Prolog to the PATH (it's C:\Program Files \pl\bin on my system), 2) Or, copy 'libpl.dll' and 'pthreadVC.dll' to C:\WINDOWS\system32 That should solve the problem, happy hacking :) Yuce Tekol On 27 May?s, 03:08, "Eric_Dex... at msn.com" wrote: > I am getting an error with pyswip on xp that says the .dll isn't > installed as a shared library. Is there a manual way to install > the .dll as such??? prolog seems to work fine it is just the bridge > that gives an error From donn at u.washington.edu Tue May 15 12:33:35 2007 From: donn at u.washington.edu (Donn Cave) Date: Tue, 15 May 2007 09:33:35 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> <4648294F.2000704@web.de> <46487a6c$0$2400$426a74cc@news.free.fr> Message-ID: In article , Duncan Booth wrote: > Yes, non-English speakers have to learn a set of technical words which are > superficially in English, but even English native speakers have to learn > non-obvious meanings, or non-English words 'str', 'isalnum', 'ljust'. > That is an unavoidable barrier, but it is a limited vocabulary and a > limited set of syntax rules. What I'm trying to say is that we shouldn't > raise the entry bar any higher than it has to be. > > The languages BTW in the countries I mentioned are: in Nigeria all school > children must study both their indigenous language and English, Brazil and > Uruguay use Spanish and Nepali is the official language of Nepal. [Spanish in Brazil? Not as much as you might think.] This issue reminds me a lot of CP4E, which some years back seemed to be an ideological driver for Python development. Computer Programming 4 Everyone, for those who missed it. I can't say it actually had a huge effect on Python, which has in most respects gone altogether the opposite direction, but it was always on the table and certainly must have had some influence. One of the reasons these initiatives make soggy footing for a new direction is that everyone's an expert, when it comes to one or another feature that may or may not work for children, but no one has a clue when it comes to the total package, sometimes to the point of what seems like willful blindness to the deficiencies of a favorite programming language. If we have a sound language proposal backed by a compelling need, fine, but don't add a great burden to the language for the sake of great plans for Nepalese grade school programmers. Donn Cave, donn at u.washington.edu From robert.kern at gmail.com Fri May 18 14:19:07 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 18 May 2007 13:19:07 -0500 Subject: namespace question In-Reply-To: References: Message-ID: T. Crane wrote: > Hi, > > If I define a class like so: > > class myClass: > import numpy > a = 1 > b = 2 > c = 3 > > def myFun(self): > print a,b,c > return numpy.sin(a) > > > I get the error that the global names a,b,c,numpy are not defined. Fairly > straightforward. But if I am going to be writing several methods that keep > calling the same variables or using the same functions/classes from numpy, > for example, do I have to declare and import those things in each method > definition? Is there a better way of doing this? Put your imports at the module level. I'm not sure what you intended with a, b, c so let's also put them at the top level. import numpy a = 1 b = 2 c = 4 class myClass: def myFun(self): print a, b, c return numpy.sin(a) OTOH, if a, b, c were supposed to be attached to the class so they could be overridden in subclasses, or be default values for instances, you can leave them in the class definition, but access them through "self" or "myClass" directly. import numpy class myClass: a = 1 b = 2 c = 4 def myFun(self): print self.a, self.b, myClass.c return numpy.sin(self.a) -- 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 paul at boddie.org.uk Sun May 20 11:36:18 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 20 May 2007 08:36:18 -0700 Subject: zipfile [module and file format, both] stupidly broken In-Reply-To: References: Message-ID: <1179675378.137903.83170@y80g2000hsf.googlegroups.com> Thorsten Kampe wrote: > > Don't be silly. Where would you look for the URL to report bugs? On > the website of the project, of course. It's not that easy to find on > python.org (although not as hard as Martin says): > > Core Development > Links for Developers > Bug Manager or This is the "in crowd" route. > About > Help > Got a Python problem or question? > Python Bug Tracker And this is the "it's not my fault, it's yours" route. > Both ways are kind of misleading (or non-intuitive) as you do not want > to engage in Core Development to report a bug. Lots of good projects > have a prominent link on their website (start page) how to report > bugs. Python hasn't. Indeed. The big problem with python.org in its current form is the navigation, as I have complained about already. Unfortunately, I never did get round to tooling up with the python.org toolchain because it involved installing large numbers of packages, including some directly from a Subversion repository, along with a few which actually conflicted with others on my system, and I wasn't about to start either uninstalling lots of things or messing around with environment settings just to throw it all together and make the tentative edits necessary to reduce the above "beware of the leopard" syndrome. The "last straw" was picking through Twisted 2 installation details for the benefit of a solution which apparently doesn't even use Twisted in any reasonable sense. Meanwhile, the Wiki (that's Documentation > Wiki) just keeps getting better. A "best of" edition of that particular resource (with simple approval mechanisms) might prove more accessible and more likely to get improved by the community. Paul P.S. I still respect the work done on the python.org visuals - I think they have mostly stood the test of time. And I don't envy anyone who had the task of going through python.org and reorganising all the pieces of content to still link to each other properly and look the same as everything else. From arnodel at googlemail.com Fri May 4 12:50:50 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 4 May 2007 09:50:50 -0700 Subject: How safe is a set of floats? In-Reply-To: <1178294650.738576.205690@q75g2000hsh.googlegroups.com> References: <1178288509.067493.5140@e65g2000hsc.googlegroups.com> <1hxkw5d.1ipc1zfocmqm9N%aleax@mac.com> <1178294650.738576.205690@q75g2000hsh.googlegroups.com> Message-ID: <1178297450.812110.322140@q75g2000hsh.googlegroups.com> On May 4, 5:04 pm, Paul McGuire wrote: > Does set membership test for equality ("==") or identity ("is")? I > just did some simple class tests, and it looks like sets test for > identity. Sets are like dictionaries, they test for equality: >>> a=1,2 >>> b=1,2 >>> a is b False >>> a in set([b]) True -- Arnaud From tenax.raccoon at gmail.com Wed May 30 12:16:18 2007 From: tenax.raccoon at gmail.com (Jason) Date: 30 May 2007 09:16:18 -0700 Subject: Anyone else has seen "forrtl: error (200) ..." In-Reply-To: References: Message-ID: <1180541778.029551.17350@p77g2000hsh.googlegroups.com> On May 30, 9:33 am, Alexander Eisenhuth wrote: > Hello, > > Ctrl+C is not passed to the interpreter (i guess it) while I'm executing a > script. Instead i get: > forrtl: error (200): program aborting due to control-C event > > If I start python in interactive mode Ctrl+C is passed: > > bash-3.2$ python > Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win > 32 > Type "help", "copyright", "credits" or "license" for more information. > >>> raw_input() > Traceback (most recent call last): > File "", line 1, in > KeyboardInterrupt > >>> > > Any idea ? > > Thanks > Alexander Forrtl indicates that your script is running a Fortran library or program. Remember that Python exceptions only apply during Python. If a Fortran DLL performs a divide-by-zero error, or accesses invalid memory, it will kill the interpreter instead of throwing a Python exception. With Compaq Visual Fortran, the Fortran library calls can kill your entire program if a function receives an invalid value. (Try raising a negative real number to a fractional exponent, for example.) I'd guess that the Fortran code is intercepting the CTRL-C signal and killing the running script. Without knowing anything about your script and the library calls it makes, I can't give you much advice. There may be little that you can do, especially if you don't have the Fortran source code in question and/or can't recompile it. Maybe someone with some Fortran/Python experience can assist you. --Jason From half.italian at gmail.com Mon May 28 04:48:53 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 28 May 2007 01:48:53 -0700 Subject: Can python create a dictionary from a list comprehension? In-Reply-To: References: <1180299312.207986.4340@k79g2000hse.googlegroups.com> <1180299814.129770.93220@o11g2000prd.googlegroups.com> Message-ID: <1180342133.550619.124250@o11g2000prd.googlegroups.com> On May 28, 12:25 am, Marc 'BlackJack' Rintsch wrote: > In <1180299814.129770.93... at o11g2000prd.googlegroups.com>, half.italian > wrote: > > > [entries.__setitem__(int(d.date.strftime('%m'))], d.id) for d in > > links] > > > btw...I was curious of this too. I used 'dir(dict)' and looked for a > > method that might do what we wanted and bingo! > > This is really ugly. Except `__init__()` it's always a code smell if you > call a "magic" method directly instead of using the corresponding > syntactic sugar or built in function. And using a list comprehension just > for side effects is misleading because the reader expects a (useful) list > to be build when stumbling over a list comp and it's wasteful because an > unnecessary list of `None`\s is build and thrown away for no reason other > than to have a one liner. This is not Perl! ;-) > > Ciao, > Marc 'BlackJack' Rintsch It's ugly I agree, but it was the first solution I found. I need you guys for the _right_ solutions :) I have stumbled over the same situation myself. I don't see that the list comprehension itself is misleading. If nothing is catching the empty list that is returned, it signals that the returned list is unimportant, and if wrapped by a call to dict() its obvious also. Do you think we just shouldn't use list comprehensions to build dictinaries at all? Or is Stefan's solution acceptable (and pythonic)? ~Sean From claird at lairds.us Wed May 16 14:03:44 2007 From: claird at lairds.us (Cameron Laird) Date: Wed, 16 May 2007 18:03:44 +0000 Subject: Trying to choose between python and java References: Message-ID: <0ltrh4-ifk.ln1@lairds.us> In article , Paul Melis wrote: >Anthony Irwin wrote: >> Hi All, >> >> I am currently trying to decide between using python or java and have a >> few quick questions about python that you may be able to help with. >> >> #1 Does python have something like javas .jar packages. A jar file >> contains all the program files and you can execute the program with java >> -jar program.jar >> >> I am sort of hoping python has something like this because I feel it >> makes it easier to distribute between platforms e.g. linux, mac windows >> etc. > >It depends on what you see as the benefit of jar's. If it is purely a >matter of packing your whole application up into a single file that you >can distribute then there are a number of tools to do that, each with >their limits. Search for cx_freeze or py2exe (win32 only). . . . From JoeSalmeri at hotmail.com Thu May 31 20:36:33 2007 From: JoeSalmeri at hotmail.com (Joe Salmeri) Date: Thu, 31 May 2007 20:36:33 -0400 Subject: getmtime differs between Py2.5 and Py2.4 References: <463FA51D.1060600@v.loewis.de> <463fb305$0$326$e4fe514c@news.xs4all.nl> <1178585991.924458.154570@l77g2000hsb.googlegroups.com> <1hxrebv.5tn2pnql23q7N%aleax@mac.com> <46401FDC.4010705@v.loewis.de> Message-ID: Hi Martin, Please see my response to Tony Meyer titled "Python 2.5.1 broke os.stat module" I provide a sample program that demonstrates that the results that are produced by the Python 2.4.2 os.stat module ALWAYS match the results that Windows Explorer displays as well as the results of the dir /tc, dir /ta, and dir /tw commands. When you run that sample program using Python 2.5.1 the results that it produces do NOT match what Windows returns. In my small sample test the Python 2.5.1 os.stat results were wrong more than 50% of the time. I can see that you guys have already spent alot of time investigating this but surely the results should match what Windows Explorer says or what the dir command returns??? Unless you are saying that a fully patched Windows XP SP2 + WindowsUpdates system is using that broken Microsoft c runtime library which is causing Explorer and cmd.exe to return incorrect results. Even if that was the case, it would not explain how when I manually set the 3 timestamps for a file to 01/02/2003 12:34:56 that Windows and Python 2.4.2 display the correct date and time but Python 2.5.1 displays the wrong one. Thanks for your assistance. Joe ""Martin v. L?wis"" wrote in message news:46401FDC.4010705 at v.loewis.de... >> the difference (rounding to an int number of seconds) is just about one >> hour; in certain parts of the world (Europe and Africa), that could >> indeed be a timezone issue. > > With the help of Tony Meyer, we rediscovered the explanation: because > of a bug in the Microsoft C run-time library, the UTC time reported by > 2.4 may have been off by one hour (it wasn't local time - just off > by one hour). This was due to DST issues. They have been fixed in 2.5, > which now reports the correct UTC value. > > Regards, > Martin From rurpy at yahoo.com Thu May 17 01:37:45 2007 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 16 May 2007 22:37:45 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179344264.595644.136440@h2g2000hsg.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179333797.634234.245830@k79g2000hse.googlegroups.com> <1179344264.595644.136440@h2g2000hsg.googlegroups.com> Message-ID: <1179380265.871800.199340@k79g2000hse.googlegroups.com> On May 16, 1:37 pm, "sjdevn... at yahoo.com" wrote: > On May 16, 12:54 pm, Gregor Horvath wrote: > > > Istvan Albert schrieb: > > > > Here is something that just happened and relates to this subject: I > > > had to help a student run some python code on her laptop, she had > > > Windows XP that hid the extensions. I wanted to set it up such that > > > the extension is shown. I don't have XP in front of me but when I do > > > it takes me 15 seconds to do it. Now her Windows was set up with some > > > asian fonts (Chinese, Korean not sure), looked extremely unfamiliar > > > and I had no idea what the menu systems were. We have spent quite a > > > bit of time figuring out how to accomplish the task. I had her read me > > > back the options, but something like "hide extensions" comes out quite > > > a bit different. Surprisingly tedious and frustrating experience. > > > So the solution is to forbid Chinese XP ? > > It's one solution, depending on your support needs. > > Independent of Python, several companies I've worked at in Ecuador > (entirely composed of native Spanish-speaking Ecuadoreans) use the > English-language OS/application installations--they of course have the > Spanish dictionaries and use Spanish in their documents, but for them, > having localized application menus generates a lot more problems than > it solves. Isn't the point of PEP-3131 free choice? How would Ecuadoreans feel if their government mandated all computers must use English? From bdesth.quelquechose at free.quelquepart.fr Wed May 2 19:36:50 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 03 May 2007 01:36:50 +0200 Subject: How to check if a string is empty in python? In-Reply-To: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> References: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> Message-ID: <463916c4$0$2415$426a74cc@news.free.fr> noagbodjivictor at gmail.com a ?crit : > How to check if a string is empty in python? > if(s == "") ?? > if not s: print "s is empty" From sjmachin at lexicon.net Sun May 20 18:49:39 2007 From: sjmachin at lexicon.net (John Machin) Date: 20 May 2007 15:49:39 -0700 Subject: converting strings to most their efficient types '1' --> 1, 'A' ---> 'A', '1.2'---> 1.2 In-Reply-To: <1179677080.830078.169270@p77g2000hsh.googlegroups.com> References: <1179529661.555196.13070@k79g2000hse.googlegroups.com> <1179551680.283157.19000@y80g2000hsf.googlegroups.com> <464FA156.2070704@lexicon.net> <1179658331.911424.173140@e65g2000hsc.googlegroups.com> <46503B2E.6030902@lexicon.net> <1179677080.830078.169270@p77g2000hsh.googlegroups.com> Message-ID: <1179701379.612492.21880@n15g2000prd.googlegroups.com> On May 21, 2:04 am, Paddy wrote: > On May 20, 1:12 pm, John Machin wrote: > > > > > On 20/05/2007 8:52 PM, Paddy wrote: > > > > On May 20, 2:16 am, John Machin wrote: > > >> On 19/05/2007 3:14 PM, Paddy wrote: > > > >>> On May 19, 12:07 am, py_genetic wrote: > > >>>> Hello, > > >>>> I'm importing large text files of data using csv. I would like to add > > >>>> some more auto sensing abilities. I'm considing sampling the data > > >>>> file and doing some fuzzy logic scoring on the attributes (colls in a > > >>>> data base/ csv file, eg. height weight income etc.) to determine the > > >>>> most efficient 'type' to convert the attribute coll into for further > > >>>> processing and efficient storage... > > >>>> Example row from sampled file data: [ ['8','2.33', 'A', 'BB', 'hello > > >>>> there' '100,000,000,000'], [next row...] ....] > > >>>> Aside from a missing attribute designator, we can assume that the same > > >>>> type of data continues through a coll. For example, a string, int8, > > >>>> int16, float etc. > > >>>> 1. What is the most efficient way in python to test weather a string > > >>>> can be converted into a given numeric type, or left alone if its > > >>>> really a string like 'A' or 'hello'? Speed is key? Any thoughts? > > >>>> 2. Is there anything out there already which deals with this issue? > > >>>> Thanks, > > >>>> Conor > > >>> You might try investigating what can generate your data. With luck, > > >>> it could turn out that the data generator is methodical and column > > >>> data-types are consistent and easily determined by testing the > > >>> first or second row. At worst, you will get to know how much you > > >>> must check for human errors. > > >> Here you go, Paddy, the following has been generated very methodically; > > >> what data type is the first column? What is the value in the first > > >> column of the 6th row likely to be? > > > >> "$39,082.00","$123,456.78" > > >> "$39,113.00","$124,218.10" > > >> "$39,141.00","$124,973.76" > > >> "$39,172.00","$125,806.92" > > >> "$39,202.00","$126,593.21" > > > >> N.B. I've kindly given you five lines instead of one or two :-) > > > >> Cheers, > > >> John > > > > John, > > > I've had cases where some investigation of the source of the data has > > > completely removed any ambiguity. I've found that data was generated > > > from one or two sources and been able to know what every field type is > > > by just examining a field that I have determined wil tell me the > > > source program that generated the data. > > > The source program that produced my sample dataset was Microsoft Excel > > (or OOo Calc or Gnumeric); it was induced to perform a "save as CSV" > > operation. Does that help you determine the true nature of the first column? > > > > I have also found that the flow generating some data is subject to > > > hand editing so have had to both put in extra checks in my reader, and > > > on some occasions created specific editors to replace hand edits by > > > checked assisted hand edits. > > > I stand by my statement; "Know the source of your data", its less > > > likely to bite! > > > My dataset has a known source, and furthermore meets your "lucky" > > criteria (methodically generated, column type is consistent) -- I'm > > waiting to hear from you about the "easily determined" part :-) > > > Cheers, > > John > > John, > Open up your Excel spreadsheet and check what the format is for the > column. It's not a contest. If you KNOW what generated the data then > USE that knowledge. It would be counter-productive to do otherwise > surely? > > (I know, don't call you Shirley :-) > ... and I won't call you Patsy more than this once :-) Patsy, re-read. The scenario is that I don't have the Excel spreadsheet; I have a CSV file. The format is rather obviously "currency" but that is not correct. The point is that (1) it was methodically [mis-]produced by a known source [your criteria] but the correct type of column 1 can't be determined by inspection of a value or 2. Yeah, it's not a contest, but I was kinda expecting that you might have taken first differences of column 1 by now ... Cheers, John From manatlan at gmail.com Fri May 11 11:42:29 2007 From: manatlan at gmail.com (manatlan) Date: 11 May 2007 08:42:29 -0700 Subject: PyGTK : a NEW simple way to code an app Message-ID: <1178898148.924772.200450@w5g2000hsg.googlegroups.com> I was a fan of "SimpleGladeApp/tepache way" to build a pygtk app. I've build a new efficient/dynamic way to build a pygtk app ... Here is an example : ================================================= class Fen(GladeApp): """ Window win .title="Hello" @delete_event VBox HBox Label jo .label="kokotte" entry myEntry .text="kuku" gtkBuTTon b2 .label="33" @clicked Label jo .label="koko" Button b .label="3" @clicked """ def init(self,m): self.jo.set_text(m) pass def on_b_clicked(self,*a): self.quit(3) def on_b2_clicked(self,*a): self.quit(33) def on_win_delete_event(self,*args): self.quit(4) f=Fen("koko2") print f.loop() ================================================= How it works : in fact, the __doc__ is converted as a "glade file" the tree of object is indented (like python way) you can see some common pygtk widget ... line starting with a dot is an property of the parent object. line starting with a @ is a declaration of a event of the parent object. widgets are not case sensitive, and can start with "Gtk". If a second word is provided it will be used as an "id", otherwise an unique id will be build according the type of widget. the window is created with glade, widgets are provided as attributs of the instance, and signals are autoconnected on method "on_[widgetId]_[event](self,*args)" (if a signal is missing in your class, it warns you at run time) .... It will not replace the use of glade-3 for complex widget ... but I think it's an easy way to code very easily/quickly a simple pygtk window/form. I think it could be really useful/handly for beginners too. for people which are involved in pygtk/python/gui ... i'd like to hear your comments/ideas ... Rq: i don't provide the code now, but it will be released in next version of "GladeApp" ( http://manatlan.infogami.com/GladeApp ) it works already, but i need to make "packing properties available" too ... From bblais at bryant.edu Thu May 3 12:33:10 2007 From: bblais at bryant.edu (Brian Blais) Date: Thu, 03 May 2007 12:33:10 -0400 Subject: Organizing code - import question In-Reply-To: <1178207662.200235.252900@e65g2000hsc.googlegroups.com> References: <1178207662.200235.252900@e65g2000hsc.googlegroups.com> Message-ID: <463A0EC6.3010008@bryant.edu> Carlos Hanson wrote: > It looks like you need __init__.py in MyPackage. Then you can import > starting with MyPackage. For example, you might use one of the > following: > > import MyPackage > from MyPackage.Common import * > etc > that means that MyPackage must be in the sys path too? It doesn't seem like a contained-module sees the container in any way. bb -- ----------------- bblais at bryant.edu http://web.bryant.edu/~bblais From bbxx789_05ss at yahoo.com Thu May 10 15:36:44 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 10 May 2007 12:36:44 -0700 Subject: which is more pythonic/faster append or +=[] In-Reply-To: <1178739061.919664.128260@y80g2000hsf.googlegroups.com> References: <1hxtelz.7f6rvnw4cyxmN%aleax@mac.com> <1178726923.909537.209300@l77g2000hsb.googlegroups.com> <1178739061.919664.128260@y80g2000hsf.googlegroups.com> Message-ID: <1178825802.319573.113930@w5g2000hsg.googlegroups.com> > Is there any documentation for the syntax you used with timeit? This is the syntax the docs describe: --- Python Reference Library 10.10.1: When called as a program from the command line, the following form is used: python timeit.py [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement ...] --- Then in the examples in section 10.10.2, the docs use a different syntax: ---- % timeit.py 'try:' ' str.__nonzero__' 'except AttributeError:' ' pass' 100000 loops, best of 3: 15.7 usec per loop % timeit.py 'if hasattr(str, "__nonzero__"): pass' 100000 loops, best of 3: 4.26 usec per loop % timeit.py 'try:' ' int.__nonzero__' 'except AttributeError:' ' pass' 1000000 loops, best of 3: 1.43 usec per loop % timeit.py 'if hasattr(int, "__nonzero__"): pass' 100000 loops, best of 3: 2.23 usec per loop --- and then there is Alex Martelli's syntax: >>>brain:~ alex$ python -mtimeit 'L=range(3); n=23' 'x=L[:]; x.append(n)' From half.italian at gmail.com Fri May 25 03:05:39 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 25 May 2007 00:05:39 -0700 Subject: sockets, gethostname() changing In-Reply-To: <1180065033.520142.37050@q66g2000hsg.googlegroups.com> References: <1180062244.266857.300830@m36g2000hse.googlegroups.com> <1180063489.535893.182970@x35g2000prf.googlegroups.com> <1180065033.520142.37050@q66g2000hsg.googlegroups.com> Message-ID: <1180076739.557165.196900@x35g2000prf.googlegroups.com> On May 24, 8:50 pm, 7stud wrote: > Thanks for the response. > > On May 24, 9:24 pm, half.ital... at gmail.com wrote: > > > I can't imagine why your hostname would be changing, unless you > > installed some of their proprietary software thats messing around with > > things. > > When I first started using Terminal, I noticed that the prompt in > Terminal changed when I was connected to the internet. > > > What is the hostname set to in Sys Prefs->Sharing? > > My Name's Computer > > > Try > > setting it there. What are the before and after connection names you > > get? > > If I add the line: > > host = socket.gethostname() > print host #<---------- > > and I'm not connected to the internet and I run the program, I get: > > my-names-computer.local > > When I'm connected to the internet, I get: > > dialup-9.999.999.999.dial9.xxxxxxx.level9.net That would bug me to high hell. A router in the middle would probably stop that. From tony.meyer at gmail.com Thu May 24 01:17:01 2007 From: tony.meyer at gmail.com (Tony Meyer) Date: 23 May 2007 22:17:01 -0700 Subject: Accessing iTunes with Python via the Windows SDK In-Reply-To: <1179980636.045976.145070@q75g2000hsh.googlegroups.com> References: <1179980636.045976.145070@q75g2000hsh.googlegroups.com> Message-ID: <1179983821.769700.45870@d30g2000prg.googlegroups.com> On May 24, 4:23 pm, Denrael wrote: > I've been playing with the iTunes sdk on windows, and have come across > a strange problem. With the following code: > > import win32com.client > iTunes = win32com.client.gencache.EnsureDispatch("iTunes.Application") > curr = iTunes.CurrentTrack > name = curr.Name > skipped = curr.SkippedCount [...] > I get an error indicating that SkippedCount isn't a valid attribute: [...] The object you get back from iTunes.CurrentTrack (the traceback shows this) is an IITTrack. If you check the iTunes SDK, you'll see that IITTrack objects don't have a "SkippedCount" attribute - IITFileOrCDTrack objects do (from memory, this excludes things like radio links). You need to conver the IITrack object to a IITFileOrCDTrack object (assuming that it is one); you can do this with win32com.client.CastTo, as follows: """ import win32com.client iTunes = win32com.client.gencache.EnsureDispatch("iTunes.Application") curr = win32com.client.CastTo(iTunes.CurrentTrack, "IITFileOrCDTrack") name = curr.Name skipped = curr.SkippedCount skipdate = curr.SkippedDate print name print skipped print skipdate """ Cheers, Tony From bj_666 at gmx.net Thu May 31 04:10:35 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 31 May 2007 10:10:35 +0200 Subject: c[:]() References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> Message-ID: In , Warren Stringer wrote: > Oops! guess I should have tested my rather hasty complaint about executable > containers. This is nice: > > def a(): return 'b' > def b(): print 'polly! wakey wakey' > c = {} > c['a'] = b > c[a()]() #works! > > > c[a()]() is a switch statement with an amorphous selector- very handy in its > own right. But, using a() as a generator would be more expressive. This > seems to work: > > c = [a,a] > [d() for d in c] If you are using the list comprehension just for the side effect of calling `d` then consider this bad style. You are building a list of `None` objects just to have a "cool" one liner then. > But that still isn't as simple or as direct as: > > c[:]() > > Which would you rather explain to a 12-year-old writing code for the first > time? for func in funcs: func() Because it is explicit and readable and matches the english description "for every function in functions: call that function" very closely while a list comprehension or your "perlish" line noise is much more magic to explain and harder to remember. Ciao, Marc 'BlackJack' Rintsch From milliondollarexecutive at gmail.com Wed May 2 23:44:11 2007 From: milliondollarexecutive at gmail.com (Midex) Date: 2 May 2007 20:44:11 -0700 Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? In-Reply-To: <1178162456.929395.139390@q75g2000hsh.googlegroups.com> References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> <1178162456.929395.139390@q75g2000hsh.googlegroups.com> Message-ID: <1178163851.199354.14450@n59g2000hsh.googlegroups.com> On 3 maio, 00:20, Don Stockbauer wrote: > Ask yourself WHY havn't I seen this footage before? > > **************************** > > "Don, why havent you seen this footage before?" he asked himself, self- > referentially in the best tradition of Douglas R. Hofstadter. > > 'Er, because I haven't seen it before?" Don responded in a > tautological fashion. > > (uproarius laughter ensues) You're that ignorant and brainwashed lost that you can't see that the media didn't want youto see this footage and thus why you havn't seen it before? 9/11 has been covered ad nauseum in the mainstream press. You would think you'd seen everything there was to see of footage from that day. But rather what we saw was high repitition of a small select canon of footage which doesn't show you what actually happenened on that say. You are in the middle of a totalitarian state of rule and you think its funny? They lied to you about WMDs and you think its funny that 650,000 civilians are now dead for nothing, for OIL for PROFITS in the hands of those who lied to you and helped those lies remain unknown to the public. You did not receive one penny of the war booty. Actually the greatest cherry of irony is that you paid for their expidition and supplied your soldiers and their lives. You have betrayed youself, you have betrayed your soldiers who were waiting for you to bring them home. They all know they truth about 9/11. There are 10,000 US soliders AWOL in the US at the moment and that is NOT CONSCRIPTED soldiers. The signed up., the saw the evil and they fled. And where are you oh King of Fools? The disertion rate for the Iraq war is higher than the conscripted disertion rates for the Vietnam war. The US soldiers are crying out for the American people to bring them home. They know the lies about 9/11. http://www.youtube.com/watch?v=NmGMzmGGDOA From greenbergj at wit.edu Fri May 18 21:39:54 2007 From: greenbergj at wit.edu (Jordan Greenberg) Date: Fri, 18 May 2007 21:39:54 -0400 Subject: namespace question In-Reply-To: References: Message-ID: T. Crane wrote: > Hi, > > If I define a class like so: > > class myClass: > import numpy > a = 1 > b = 2 > c = 3 > > def myFun(self): > print a,b,c > return numpy.sin(a) > > > I get the error that the global names a,b,c,numpy are not defined. Fairly > straightforward. But if I am going to be writing several methods that keep > calling the same variables or using the same functions/classes from numpy, > for example, do I have to declare and import those things in each method > definition? Is there a better way of doing this? > > thanks, > trevis > > Put the import at the top level, and you forgot self when accessing attributes. import numpy class myClass: a=1 b=2 c=3 def myFun(self): print self.a, self.b, self.c return numpy.sin(a) From siona at chiark.greenend.org.uk Wed May 16 09:13:34 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 16 May 2007 14:13:34 +0100 (BST) Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: Steven D'Aprano wrote: >On Tue, 15 May 2007 09:09:30 +0200, Eric Brunel wrote: >> Joke aside, this just means that I won't ever be able to program math in >> ADA, because I have absolutely no idea on how to do a 'pi' character on >> my keyboard. >Maybe you should find out then? Personal ignorance is never an excuse for >rejecting technology. The funny thing is, I could have told you exactly how to type a 'pi' character 18 years ago, when my main use of computers was typesetting on a Mac. These days ... I've just spent 20 minutes trying to find out how to insert one into this text (composed in emacs on a remote machine, connected via ssh from konsole). -- \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 Leo.Kislov at gmail.com Tue May 8 00:40:14 2007 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 7 May 2007 21:40:14 -0700 Subject: getmtime differs between Py2.5 and Py2.4 In-Reply-To: <463fb305$0$326$e4fe514c@news.xs4all.nl> References: <463FA51D.1060600@v.loewis.de> <463fb305$0$326$e4fe514c@news.xs4all.nl> Message-ID: <1178599214.484104.171330@o5g2000hsb.googlegroups.com> On May 7, 4:15 pm, Irmen de Jong wrote: > Martin v. L?wis wrote: > >> Is this a bug? > > > Why don't you read the responses posted earlier? John Machin > > replied (in <1178232636.415630.106... at l77g2000hsb.googlegroups.com>) > > that you are mistaken: There is NO difference between the outcome > > of os.path.getmtime between Py2.5 and Py2.4. It always did return > > UTC, and always will. > > > Regards, > > Martin > > Err.....: > > [E:\Projects]dir *.py > > Volume in drive E is Data Serial number is 2C4F:9C2D > Directory of E:\Projects\*.py > > 31-03-2007 20:46 511 log.py > 25-11-2006 16:59 390 p64.py > 7-03-2007 23:07 207 sock.py > 3-02-2007 16:15 436 threads.py > 1.544 bytes in 4 files and 0 dirs 16.384 bytes allocated > 287.555.584 bytes free > > [E:\Projects]c:\Python24\python.exe -c "import os; print os.path.getmtime('p64.py')" > 1164470381 > > [E:\Projects]c:\Python25\python.exe -c "import os; print os.path.getmtime('p64.py')" > 1164466781.28 > > This is python 2.4.4 and Python 2.5.1 on windows XP. > The reported time clearly differs. Let me guess: your E drive uses FAT filesystem? -- Leo From gagsl-py2 at yahoo.com.ar Mon May 21 07:01:45 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 21 May 2007 08:01:45 -0300 Subject: TIFF to PDF References: <1179687595.142454.23850@z24g2000prd.googlegroups.com> <1179744141.027494.60590@r3g2000prh.googlegroups.com> Message-ID: En Mon, 21 May 2007 07:42:21 -0300, revuesbio escribi?: > os.system('"C:\Program Files\GnuWin32\bin\tiff2pdf.exe" -o C:\test.pdf > C:\test.TIF') \ is used as a escape character in strings. Use either \\ or a raw string, that is: os.system('"C:\\Program Files\\GnuWin32\\bin\\tiff2pdf.exe" -o C:\\test.pdf C:\\test.TIF') os.system(r'"C:\Program Files\GnuWin32\bin\tiff2pdf.exe" -o C:\test.pdf C:\test.TIF') (This should be added to the Python FAQ - the most related entry is about raw strings ending in \) -- Gabriel Genellina From edreamleo at charter.net Fri May 4 08:12:15 2007 From: edreamleo at charter.net (Edward K Ream) Date: Fri, 4 May 2007 07:12:15 -0500 Subject: Where are the strings in gc.get_objects? Message-ID: Hello all. I'm tracking down memory leaks in my app. To do this I wrote a script to show the numbers of each different type of object. But it doesn't show strings! Here is the script: import gc,types def printDict(d): keys = d.keys() ; keys.sort() print '-' * 30 for key in keys: n = d.get(key) print '%+6d %s' % (n,key) d = {} ; d2 = {} for obj in gc.get_objects(): t = type(obj) r = repr(t) n = d.get(r,0) d[r] = n + 1 if t == types.InstanceType: t = obj.__class__ r = repr(t) n = d2.get(r,0) d2[r] = n + 1 printDict(d) printDict(d2) And here is example output. The first part of the listing shows the 'raw' type of each object, the second part of the listing shows type(obj.__class__) for instance types. ------------------------------ +1925 +1 +47 +2858 +2877 +1 +1 +3 +1 +1 +1 +1 +536 +27 +1 +1 +538 +11942 +14 +8493 +3 +70 +1997 +3704 +4441 +72 +226 +181 +1 +29740 +1 +53 +105 +362 ------------------------------ +1 +1 +30 +1 +5 +9 +1 +51 +15 +11 +3 +61 +7 +3 +19 +5 +1 +9 +6 +1545 +2 +1 +2 +3 +2 +1 +3 +2 +2 +1 +1 +3 +3 +1 +1 +2 +3 +3 +1 +1 +1 +3 +3 +3 +3 +3 +3 +3 +3 +3 +3 +3 +3 +3 +3 +3 +3 +1 +3 +3 +5 +2 +2 +2 +2 +2 +6 +2 +2 +3 +3 +3 +3 +2 +2 +3 +1 +1 +12 +20 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +3 +3 +1 +1 +1 +1 +1 +5 +1 +2 +10 +2 I get similar results on both Python 2.4 and Python 2.5. I'm running on XP. Can anyone explain were the strings are? I expect at least twice the number of strings as there are leoNodes.vnode objects. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From mail at microcorp.co.za Tue May 15 11:22:00 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 15 May 2007 17:22:00 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179160242.787344.48060@h2g2000hsg.googlegroups.com> Message-ID: <016701c79704$c9d39ae0$03000080@hendrik> wrote: >(2) Several posters have claimed non-native english speaker >status to bolster their position, but since they are clearly at >or near native-speaker levels of fluency, that english is not >their native language is really irrelevant. I dispute the irrelevance strongly - I am one of the group referred to, and I am here on this group because it works for me - I am not aware of an Afrikaans python group - but even if one were to exist - who, aside from myself, would frequent it? - would I have access to the likes of the effbot, Steve Holden, Alex Martelli, Irmen de Jongh, Eric Brunel, Tim Golden, John Machin, Martin v Loewis, the timbot and the Nicks, the Pauls and other Stevens? - I somehow doubt it. Fragmenting this resource into little national groups based on language would be silly, if not downright stupid, and it seems to me just as silly to allow native identifiers without also allowing native reserved words, because you are just creating a mess that is neither fish nor flesh if you do. And the downside to going the whole hog would be as follows: Nobody would even want to look at my code if I write "terwyl" instead of 'while', and "werknemer" instead of "employee" - so where am I going to get help, and how, once I am fully Python fit, can I contribute if I insist on writing in a splinter language? And while the Mandarin language group could be big enough to be self sustaining, is that true of for example Finnish? So I don't think my opinion on this is irrelevant just because I miss spent my youth reading books by Pelham Grenfell Wodehouse, amongst others. And I also don't regard my own position as particularly unique amongst python programmers that don't speak English as their native language - Hendrik From stefan.sonnenberg at pythonmeister.com Sun May 6 03:05:20 2007 From: stefan.sonnenberg at pythonmeister.com (Stefan Sonnenberg-Carstens) Date: Sun, 06 May 2007 09:05:20 +0200 Subject: invoke user's standard mail client In-Reply-To: References: <1178266064.922925.125760@y80g2000hsf.googlegroups.com> Message-ID: <463D7E30.8070307@pythonmeister.com> Gabriel Genellina schrieb: > En Fri, 04 May 2007 05:07:44 -0300, luc.saffre at gmail.com > escribi?: > > >> the simplest way to launch the user's standard mail client from a >> Python program is by creating a mailto: URL and launching the >> webbrowser: >> But this method is limited: you cannot specify a file to be attached >> to the mail. And I guess that there would be problems if the body text >> is too complex. >> Does somebody know about a better method? >> It should be possible at least on Windows, since Acrobat Reader is >> able to do it. >> > > On Windows you can use MAPI. > > import win32api win32api.ShellExecute(0,'open','mailto:',None,None,0) From bdesth.quelquechose at free.quelquepart.fr Sun May 13 18:09:39 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 14 May 2007 00:09:39 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46476081.7080609@web.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476081.7080609@web.de> Message-ID: <4647827d$0$3755$426a74cc@news.free.fr> Stefan Behnel a ?crit : > Anton Vredegoor wrote: > >>>In summary, this PEP proposes to allow non-ASCII letters as >>>identifiers in Python. If the PEP is accepted, the following >>>identifiers would also become valid as class, function, or >>>variable names: L?ffelstiel, chang?, ??????, or ??? >>>(hoping that the latter one means "counter"). >> >>I am against this PEP for the following reasons: >> >>It will split up the Python user community into different language or >>interest groups without having any benefit as to making the language >>more expressive in an algorithmic way. > > > > We must distinguish between "identifiers named in a non-english language" and > "identifiers written with non-ASCII characters". > > While the first is already allowed as long as the transcription uses only > ASCII characters, the second is currently forbidden and is what this PEP is about. > > So, nothing currently keeps you from giving names to identifiers that are > impossible to understand by, say, Americans (ok, that's easy anyway). > > For example, I could write > > def zieheDreiAbVon(wert): > return zieheAb(wert, 3) > > and most people on earth would not have a clue what this is good for. Which is exactly why I don't agree with adding support with non-ascii identifiers. Using non-english identifiers should be strongly discouraged, not openly supported. > However, > someone who is fluent enough in German could guess from the names what this does. > > I do not think non-ASCII characters make this 'problem' any worse. It does, by openly stating that it's ok to write unreadable code and offering support for it. > So I must > ask people to restrict their comments to the actual problem that this PEP is > trying to solve. Sorry, but we can't dismiss the side-effects. Learning enough CS-oriented technical english to actually read and write code and documentation is not such a big deal - even I managed to to so, and I'm a bit impaired when it comes to foreign languages. From fw3 at hotmail.co.jp Mon May 21 19:58:36 2007 From: fw3 at hotmail.co.jp (wang frank) Date: Mon, 21 May 2007 23:58:36 +0000 Subject: A newbie question In-Reply-To: <1179789726.619470.223710@36g2000prm.googlegroups.com> Message-ID: Thanks all for the help. It solves my problem. I want to build a class type for fixed point operation for a specifc chip. I could not use the build in complex data type. It is a daunting job for me since I has not use python before. Frank >From: Dan Bishop >To: python-list at python.org >Subject: Re: A newbie question >Date: 21 May 2007 16:22:06 -0700 > >On May 21, 6:04 pm, "wang frank" wrote: > > Hi, > > > > I am trying to write a python class with a new data type such as: > > class Cc14: > > def __init__(self, realpart, imagpart): > > self.r=realart > > self.i=imagpart > > > > def __add__(self,x): > > return self.r+x,r, self.i+x.i > > > > If I have > > x=Cc14(4,5) > > y=Cc14(4,5) > > z=x+y > > > > z will be a tuple instead of Cc14. How can I return a Cc14 class? > >return Cc14(self.r+x,r, self.i+x.i) > >FYI, Python has a built-in "complex" type. > >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ ??????????????????????????????? http://chizumaga.jp/ From stefan.behnel-n05pAM at web.de Fri May 11 07:48:30 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Fri, 11 May 2007 13:48:30 +0200 Subject: module error for elementtree In-Reply-To: <1178883408.495131.253680@p77g2000hsh.googlegroups.com> References: <1178867119.666923.204000@h2g2000hsg.googlegroups.com> <1178868155.638154.112200@h2g2000hsg.googlegroups.com> <1178883408.495131.253680@p77g2000hsh.googlegroups.com> Message-ID: <4644580E.2000300@web.de> saif.shakeel at gmail.com wrote: > On May 11, 12:22 pm, half.ital... at gmail.com wrote: >> On May 11, 12:05 am, saif.shak... at gmail.com wrote: >> >> >> >> >> >>> #!/usr/bin/env python >>> from elementtree import ElementTree as Element >>> tree = et.parse("testxml.xml") >>> for t in tree.getiterator("SERVICEPARAMETER"): >>> if t.get("Semantics") == "localId": >>> t.set("Semantics", "dataPackageID") >>> tree.write("output.xml") >>> Hi, >>> For the above code to work elementtree is >>> imported in first line ,but when running it says : >>> ImportError: No module named elementtree.ElementTree >>> Does thie module exists as default or a patch is needed? >>> Thanks >> http://groups.google.com/group/comp.lang.python/browse_frm/thread/e09... >> >> Read carefully.- Hide quoted text - >> >> - Show quoted text - > > The commands are given in that link are more so for a linux system .I > am developing in windows.how should i go about to make it work As said: read carefully. Stefan From michael at jedimindworks.com Mon May 14 05:41:54 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Mon, 14 May 2007 04:41:54 -0500 Subject: Asyncore Help? In-Reply-To: References: Message-ID: <99BAEEE5-B42C-441F-8011-C827A3ACC7C5@jedimindworks.com> On May 14, 2007, at 4:30 AM, Nick Craig-Wood wrote: > The learning curve of twisted is rather brutal :-) From __peter__ at web.de Fri May 25 15:21:33 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 25 May 2007 21:21:33 +0200 Subject: Module listing in order. References: <1179905562.541601.264400@m36g2000hse.googlegroups.com> <1180120016.349259.9540@x18g2000prd.googlegroups.com> Message-ID: Ramashish Baranwal wrote: >> > I want a way to get the contents in the order of their declaration, >> > i.e. [B, A, D]. Does anyone know a way to get it? >> >> My suggestion would be to actually parse the text of the module. "Brute >> force" is what it's called ;). But doing so with, say, pyparsing >> shouldn't be *very* difficult. > Nevertheless, it would be interesting to see how it can be done.:) >>> import pyclbr >>> classes = pyclbr.readmodule("mymodule") >>> sorted(classes, key=lambda name: classes[name].lineno) ['B', 'A', 'D'] Peter From bj_666 at gmx.net Sat May 26 07:34:32 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 26 May 2007 13:34:32 +0200 Subject: Newbie: Struggling again 'map' References: <1180173252.906992.262570@q75g2000hsh.googlegroups.com> Message-ID: In <1180173252.906992.262570 at q75g2000hsh.googlegroups.com>, mosscliffe wrote: > for x,y in map(None, lista, listb): # Also fine - extends as > expected > print "MAP:", x, "<>", y > > for x,y in map("N/A", lista, listb): ########## Fails - Can not call a > 'str' > print "MAP:", x, "<>", y > > def fillwith(fillchars): > return fillchars > > for x,y in map(fillwith("N/A"), lista, listb): ########## Fails also - > Can not call a 'str' > print "MAP:", x, "<>", y `map()` expects a function as first argument that will be applied to the elements in the other the arguments which have to be iterable. That you can give `None` as a function and the resulting behavior is IMHO a very ugly thing and has not much to to with the semantics expected from a `map()` function. The `None` is not the default fill value but a placeholder for the identity function. Ciao, Marc 'BlackJack' Rintsch From showell30 at yahoo.com Sun May 27 12:03:44 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 27 May 2007 09:03:44 -0700 (PDT) Subject: PHP5 programmer learning Python In-Reply-To: <1180280496.946434.26760@q69g2000hsb.googlegroups.com> Message-ID: <990728.45996.qm@web33514.mail.mud.yahoo.com> --- romiro wrote: > > Anyway, my first question was if anyone knows of a > tutorial that > focuses on PHP -> Python learning, in such that > there might be a block > of PHP code alongside an example of how to do the > same thing in > Python. I know exactly what you mean, and I couldn't find anything in my quick Google search either. Maybe you could send us a couple small snippets of PHP code, and we could translate them for you? You may also find this helpful, if you just want to get a real quick look at some representative Python code: http://wiki.python.org/moin/SimplePrograms In case you're not aware that Python has a tutorial, here's a link for you, but it doesn't have the focus on transition from PHP that you're looking for. http://docs.python.org/tut/ ____________________________________________________________________________________Get the Yahoo! toolbar and be alerted to new email wherever you're surfing. http://new.toolbar.yahoo.com/toolbar/features/mail/index.php From m.yanowitz at kearfott.com Wed May 9 16:39:03 2007 From: m.yanowitz at kearfott.com (Michael Yanowitz) Date: Wed, 9 May 2007 16:39:03 -0400 Subject: Checking if string inside quotes? Message-ID: <009601c7927a$14e18d60$0d7d12ac@kearfott.com> Hello: If I have a long string (such as a Python file). I search for a sub-string in that string and find it. Is there a way to determine if that found sub-string is inside single-quotes or double-quotes or not inside any quotes? If so how? Thanks in advance: Michael Yanowitz From gagsl-py2 at yahoo.com.ar Thu May 10 19:05:48 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 10 May 2007 20:05:48 -0300 Subject: keyword checker - keyword.kwlist References: <5UK0i.237$Hb2.206@read3.inet.fi> Message-ID: En Thu, 10 May 2007 17:03:13 -0300, escribi?: > I tried the trick but the error stays. I really don't know what to do > anymore. > > And what about the print function. Why does it print newline even if > there is colon after variable? I'm lost. > > I'm using Eclipe enviroment and Pydev for it. My python interpreter is > 2.5.1. To see exactly what you get, use repr(my_input). I think that you will get 'else\n' Try again using my_input = raw_input("...").strip() as Peter Otten suggested before -- Gabriel Genellina From S.Mientki-nospam at mailbox.kun.nl Fri May 18 17:37:35 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Fri, 18 May 2007 23:37:35 +0200 Subject: (Modular-)Application Framework / Rich-Client-Platform in Python In-Reply-To: References: <8ea03$464dc950$d443bb3a$5229@news.speedlinq.nl> Message-ID: <3750e$464e1bda$d443bb3a$11610@news.speedlinq.nl> Wildemar Wildenburger wrote: > Stef Mientki wrote: >> I took a look at Eclipse page you mentioned but after reading the >> first page I still don't understand what you mean (and I never read >> beyond the first page ;-). >> > Well, what can I say ... > ;) > > >> With a plugin system, I can think of a complete operating system, >> or I can think of something like a DTP, or simply Word, >> or I can think of something like Signal WorkBench >> etc. >> > Yes exactly. As I said: Nothing in particular. Just an environment that > loads and unloads little bits if functionality, whatever those may be. > I think what most people think of when they hear "plugin" is: An > Application that can be extended. > An RCP provides no more than the next step: No monolithic app, just > plugins (which can have plugins themselves (which can have plugins > themselves (which ...))). Write a text editor component and use it in > your music-sequencer that also monitors your internet-activity, if you > must. > > >> I think if you don't express what all of the tasks of that framework >> will be, >> it's not well possible to create one. >> >> > Oh, but it is! Eclipse is such a framework. Pitty is, it's written in > Java. ;) > > >> Do you want just launching of applications, or do they have to >> communicate, >> exchange data, launch each other, create together one document or more >> general control one process, >> and lots of more questions ;-) >> > Who knows? Thats the beauty of it. Eclipse has been conceived as an > IDE/Text-Editor. But now it is just a platform for others to build > plugins for. Such as an IDE. There are plans to make an eclipse-based > general PIM (called Haystack, I think). The concept is very simple, but > for some reason, highly unusual at present. I'm pretty sure that this > will change sooner or later. I took a look at some of the examples build with eclipse, and I might be wrong, but it's just another IDE, (like Delphi, Lazarus, Visual Basic, Kylix, Pida, Envisage, VisualWX, wxGlade, ...) what am I missing ? To have an IDE as good as Delphi in pure Python, would be still be great ;-) cheers, Stef Mientki From steve at holdenweb.com Sat May 19 13:26:41 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 19 May 2007 13:26:41 -0400 Subject: Python compared to other language In-Reply-To: <1179590470.964307.105720@l77g2000hsb.googlegroups.com> References: <1179540061.598417.13870@y80g2000hsf.googlegroups.com> <1179555855.410877.51390@k79g2000hse.googlegroups.com> <1179590470.964307.105720@l77g2000hsb.googlegroups.com> Message-ID: walterbyrd wrote: > On May 19, 7:23 am, Steve Holden wrote: > >> The reason you can do this with Python is precisely because the >> developers have ironed out the wrinkles between platforms by putting the >> requisite conditionals in the C source. > > But that is my point. With Python, the language itself takes care of > the platform differences, so the same Python code will run on > different platforms. I realize that, at a lower level, everything is > done is C. But, from the developers point of view: developing code in > C requires more attention to platform specifics, than does developing > code in Python. > That I can agree with, but it isn't the same as "not portable". It would have been better to say "more difficult to port". 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From gagsl-py2 at yahoo.com.ar Mon May 28 04:47:21 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 28 May 2007 05:47:21 -0300 Subject: os.path.walk not pruning descent tree (and I'm not happy with that behavior?) References: <1180316372.126765.213530@r19g2000prf.googlegroups.com> <465A91EE.5020402@aristote.info> Message-ID: En Mon, 28 May 2007 05:25:18 -0300, Maric Michaud escribi?: > Gabriel Genellina a ?crit : >> - iterate backwards: >> >> for i in range(len(names)-1, -1, -1): >> fname = names[i] >> if fname[:1]=='.': >> names.remove(fname) >> > > This is not about iterating backward, this is about iterating over the > index of each element instead of iterating over the element (which must > be done begining by the end). In fact this code is both inefficient and > contains a subtle bug. If two objects compare equals in the list, you > will remove the wrong one. > > It should be : > > for i in range(len(names)-1, -1, -1): > if names[i][:1]=='.': > del names[i] Yes, sure, this is what I should have written. Thanks for the correction! >> - filter and reassign in place > > Seems the best here. > >> (the [:] is important): > > Not so. Unless "names" is referenced in another namespace, simple > assignment is enough. But this is exactly the case; the visit function is called from inside the os.path.walk code, and you have to modify the names parameter in-place for the caller to notice it (and skip the undesided files and folders). -- Gabriel Genellina From steve at holdenweb.com Wed May 30 02:31:48 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 30 May 2007 02:31:48 -0400 Subject: Professional Grant Proposal Writing Workshop (July 2007: University of Montana, Missoula) In-Reply-To: <20070529221801.E1BE2866672050BC@thegrantinstitute.com> References: <20070529221801.E1BE2866672050BC@thegrantinstitute.com> Message-ID: Anthony Jones wrote: [...] > > At its foundation, this course will address the basics of foundation, > corporation, and government grant research. However, this course will > teach a strategic funding research approach that encourages students to > see research not as something they do before they write a proposal, but > as an integrated part of the grant seeking process. Students will be > exposed to online and database research tools, as well as publications > and directories that contain information about foundation, corporation, > and government grant opportunities. Focusing on funding sources and > basic social science research, this course teaches students how to use > research as part of a strategic grant acquisition effort. > > > > Registration > > $597.00 tuition includes all materials and certificates. > I wonder if I could get a grant to attend this course? 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From nick at craig-wood.com Tue May 29 01:33:50 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 29 May 2007 00:33:50 -0500 Subject: Module listing in order. References: <1179905562.541601.264400@m36g2000hse.googlegroups.com> <1180120016.349259.9540@x18g2000prd.googlegroups.com> Message-ID: Ramashish Baranwal wrote: > > > I want a way to get the contents in the order of their declaration, > > > i.e. [B, A, D]. Does anyone know a way to get it? > > > > My suggestion would be to actually parse the text of the module. "Brute > > force" is what it's called ;). But doing so with, say, pyparsing > > shouldn't be *very* difficult. > > > > Just out of curiosity: Why do you need the order? > > > Thank you for your replies, and sorry for my late response. > > Gabriel, unfortunately I am not a python expert so don't know how to > play with module creation. I tried to look into __import__ function, > but can't see a way to get what I want. > > Wildemar, your approach seems workable. I am going to have a look at > it. > > Well, my requirement doesn't turn out to be an actual requirement > now.:) I am using a web framework Django, that lets you define classes > for database tables. The classes so defined can refer to other classes > representing db tables. It also allows you to export those table data > in a db-neutral format e.g. xml via the python classes so defined. > Exporting does not require an order, but I thought that importing the > data back may require data of classes which are referred by other > classes to be present. I just verified that its not so. So I don't > need to do it immediately. Actually I had a requirement to do exactly this. I was using python as a definition language, making classes to define other things. It worked very nicely but I needed to get the classes in definition order. Here is how I did it with metaclasses class _Definition_Metaclass(type): """ A metaclass to add a _class_sequence attribute to each definition so we know which order they were defined in. """ _class_sequence = 0 def __init__(cls, name, bases, dict): _class_sequence = _Definition_Metaclass._class_sequence _Definition_Metaclass._class_sequence += 1 cls._class_sequence = _class_sequence class Definition(object): __metaclass__ = _Definition_Metaclass class A(Definition): pass class B(A): pass class C(A): pass class D(Definition): pass class E(C): pass objects = [] for obj in locals().values(): try: if issubclass(obj, Definition): objects.append(obj) except TypeError: pass objects_sorted = sorted(objects, key=lambda x: x._class_sequence) print objects # Gives something like # [, , , , , ] print objects_sorted # Gives # [, , , , , ] -- Nick Craig-Wood -- http://www.craig-wood.com/nick From fidtz at clara.co.uk Thu May 3 07:30:37 2007 From: fidtz at clara.co.uk (fidtz at clara.co.uk) Date: 3 May 2007 04:30:37 -0700 Subject: ascii to unicode line endings In-Reply-To: References: <1178122765.162546.59680@l77g2000hsb.googlegroups.com> Message-ID: <1178191837.424765.51090@o5g2000hsb.googlegroups.com> On 2 May, 17:29, Jean-Paul Calderone wrote: > On 2 May 2007 09:19:25 -0700, f... at clara.co.uk wrote: > > > > >The code: > > >import codecs > > >udlASCII = file("c:\\temp\\CSVDB.udl",'r') > >udlUNI = codecs.open("c:\\temp\\CSVDB2.udl",'w',"utf_16") > > >udlUNI.write(udlASCII.read()) > > >udlUNI.close() > >udlASCII.close() > > >This doesn't seem to generate the correct line endings. Instead of > >converting 0x0D/0x0A to 0x0D/0x00/0x0A/0x00, it leaves it as 0x0D/ > >0x0A > > >I have tried various 2 byte unicode encoding but it doesn't seem to > >make a difference. I have also tried modifying the code to read and > >convert a line at a time, but that didn't make any difference either. > > >I have tried to understand the unicode docs but nothing seems to > >indicate why an seemingly incorrect conversion is being done. > >Obviously I am missing something blindingly obvious here, any help > >much appreciated. > > Consider this simple example: > > >>> import codecs > >>> f = codecs.open('test-newlines-file', 'w', 'utf16') > >>> f.write('\r\n') > >>> f.close() > >>> f = file('test-newlines-file') > >>> f.read() > '\xff\xfe\r\x00\n\x00' > >>> > > And how it differs from your example. Are you sure you're examining > the resulting output properly? > > By the way, "\r\0\n\0" isn't a "unicode line ending", it's just the UTF-16 > encoding of "\r\n". > > Jean-Paul I am not sure what you are driving at here, since I started with an ascii file, whereas you just write a unicode file to start with. I guess the direct question is "is there a simple way to convert my ascii file to a utf16 file?". I thought either string.encode() or writing to a utf16 file would do the trick but it probably isn't that simple! I used a binary file editor I have used a great deal for all sorts of things to get the hex values. Dom From mauriceling at acm.org Tue May 22 08:06:14 2007 From: mauriceling at acm.org (Maurice LING) Date: Tue, 22 May 2007 12:06:14 GMT Subject: [ANN] The Python Papers Volume 2 Issue 2 Message-ID: <4652DCD1.5090304@acm.org> Hi everyone, After some delays yesterday, Volume 2 Issue 2 of The Python Papers had been officially released today. Download it from www.pythonpapers.org This issue marks a major landmark in our publication. We present a number of industry articles. These include "Python in Education" and "MPD WebAMP", as well as a great insight into Python in Germany, a wrap-up of PyCon 2007, a preview of EuroPython 2007 and a look at some great videos prepared by primary school students. Our peer-reviewed section reproduces two selected papers which were originally presented at the Open Source Developer's Conference 2006 (Melbourne, Australia). Thank you everyone for all your support. Cheers Maurice Ling (Associate Editor) From nagle at animats.com Fri May 4 02:15:28 2007 From: nagle at animats.com (John Nagle) Date: Thu, 03 May 2007 23:15:28 -0700 Subject: urllib.quote fails on Unicode URL Message-ID: The code in urllib.quote fails on Unicode input, when called by robotparser. That bit of code needs some attention. - It still assumes ASCII goes up to 255, which hasn't been true in Python for a while now. - The initialization may not be thread-safe; a table is being initialized on first use. The code is too clever and uncommented. "robotparser" was trying to check if a URL, "http://www.highbeam.com/DynamicContent/%E2%80%9D/mysaved/privacyPref.asp%22" could be accessed, and there are some wierd characters in there. Unicode URLs are legal, so this is a real bug. Logged in as Bug #1712522. John Nagle From showell30 at yahoo.com Mon May 28 12:35:45 2007 From: showell30 at yahoo.com (Steve Howell) Date: Mon, 28 May 2007 09:35:45 -0700 (PDT) Subject: ten small Python programs In-Reply-To: <301fc$465af7b4$d443bb3a$22913@news.speedlinq.nl> Message-ID: <81871.97803.qm@web33505.mail.mud.yahoo.com> --- Stef Mientki wrote: > Steve Howell wrote: > > I've always thought that the best way to introduce > new > > programmers to Python is to show them small code > > examples. > > > This is really a nice piece of missing Python. > Thanks. > The wxPython demo program is written as an > interactive tutorial, > with a few hundred examples, nicely ordered in > groups. > The user can view the demo, the code and the help > text. > The user can also change the code and see the > results right away. > Do you have a link? > It would even be nicer, if everybody could drop > her/his examples > in a standard way, so they would be automatically > incorporated in > something like the wxPython interactive demo. > Can you elaborate? ____________________________________________________________________________________ 8:00? 8:25? 8:40? Find a flick in no time with the Yahoo! Search movie showtime shortcut. http://tools.search.yahoo.com/shortcuts/#news From timr at probo.com Fri May 4 01:59:36 2007 From: timr at probo.com (Tim Roberts) Date: Fri, 04 May 2007 05:59:36 GMT Subject: pack/unpack zero terminated string References: <1178114191.580368.59520@c35g2000hsg.googlegroups.com> Message-ID: <6sil331jshkktelqg6i5fm6bb8hgihngg0@4ax.com> tmp123 wrote: > >After review the "struct" documentation, it seems there are no option >to pack/unpack zero terminated strings. Right. Just as there is no way to describe such a thing as a C struct. You'll have to unpack the fields by hand, which is that case won't be hard. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From thomas.guest at gmail.com Tue May 22 07:22:04 2007 From: thomas.guest at gmail.com (tag) Date: 22 May 2007 04:22:04 -0700 Subject: doctest environment question In-Reply-To: References: <1179762737.153434.143030@b40g2000prd.googlegroups.com> <1179775483.685881.236940@x18g2000prd.googlegroups.com> <1179818466.394663.222390@k79g2000hse.googlegroups.com> Message-ID: <1179832924.787540.195680@y2g2000prf.googlegroups.com> On 22 May, 10:11, "Gabriel Genellina" wrote: > The version given by Peter Otten may do what you want, but I'd consider if > you really need an announce_function in the first place, given all the > other ways you already have to do the same thing. > Implicitely rebinding globals does not look good. Thanks for the advice Gabriel. The use case I have is that I'd like to be able to decorate classes and even modules in this way: import announce import spam announce.announce_module(spam) ... code which calls into spam module Here, "announce.announce_module" has a look in "spam", finds all the functions and instancemethods, and decorates them (rebinds them) by announcing calls to these functions and instancemethods. It's something I've found useful, though clearly the behaviour of "spam" has been drastically changed. I'd appreciate advice on better ways to achieve this kind of thing, or why it doesn't look good. From rrr at ronadam.com Sat May 26 11:43:56 2007 From: rrr at ronadam.com (Ron Adam) Date: Sat, 26 May 2007 10:43:56 -0500 Subject: webbrowser module bug? In-Reply-To: <1180135131.139874.237560@w5g2000hsg.googlegroups.com> References: <1180118146.617722.300670@g4g2000hsf.googlegroups.com> <1180135131.139874.237560@w5g2000hsg.googlegroups.com> Message-ID: <465855BC.6040902@ronadam.com> Paul Boddie wrote: > Ron Adam wrote: >> Reseting the default browser with the gnome default application window >> confirmed this. The browser selection can either have the quotes around >> the args "%s" paremteter, or not depending on how and what sets it. >> >> Seems to me it should be quoted unless spaces in path names are never a >> problem in Linux. So this could be both a python bug and a Gnome desktop >> bug. Firefox probably does the right thing by putting the quotes around >> it, but that causes problems for webbrowser.py, which doesn't expect them. > > Quoting arguments in the way described is the safe, easy option (with > some potential problems with ' characters that can be worked around), > and I imagine that it's done precisely because other applications > could pass a path with spaces as the URL, and that such applications > would be invoking the command in a shell environment. Sadly, this > conflicts with any other precautionary measures, causing a degree of > "overquoting". > > Resetting the GNOME default is a workaround, but I'm not convinced > that it would be satisfactory. What happens if you try and open an > HTML file, in the file browser or some other application which uses > the desktop preferences, where the filename contains spaces? I'm not sure how to test this. Most things I can think of call the web browser directly. Maybe a link in an email? Yes, it is a work around. The webbrowser module needs to be smarter about quotes. As I said, this is fixed in 2.6 already. I emailed the module maintainer, and will probably file a bug report too. Ron From gagsl-py2 at yahoo.com.ar Wed May 16 23:08:01 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 17 May 2007 00:08:01 -0300 Subject: zipfile stupidly broken References: <1179368078.682948.291370@n59g2000hsh.googlegroups.com> Message-ID: En Wed, 16 May 2007 23:14:38 -0300, Asun Friere escribi?: > On May 17, 5:38 am, "Gabriel Genellina" > wrote: > >> This is not a good place for reporting bugs - use >> http://sourceforge.net/bugs/?group_id=5470 > > I disagree. Given that most suspected bugs aren't, new users > especially would be wise to post their "bugs' here before filing a bug > report. My first replies were auto censored. This was the most neutral answer I could think of. The original post was not a typical bug report. -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Sun May 27 06:48:54 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 27 May 2007 07:48:54 -0300 Subject: totally lost newbie References: <1180261154.969654.147850@n15g2000prd.googlegroups.com> Message-ID: En Sun, 27 May 2007 07:19:15 -0300, mark escribi?: > I posted earlier on this but have changed my approach so here is my > latest attempt at solving a problem. I have been working on this for > around 12 hours straight and am still struggling with it. Almost done. Just two things: - You have defined a function to convert the file format into tuples. But you are not consistent with the ordering: in the file they come rank+space+suit. When you convert to tuple you use (suit,rank). Inside the comparison function you use a[0] as rank and a[1] as suit again. Be consistent. - The sort expects a list of tuples, but you still use the lines read from the file; you forgot to call the function above to convert them. -- Gabriel Genellina From martin at v.loewis.de Sat May 19 03:34:40 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 19 May 2007 09:34:40 +0200 Subject: fun with unicode files In-Reply-To: <6579x7eo.fsf@python.net> References: <6579x7eo.fsf@python.net> Message-ID: <464EA890.7010708@v.loewis.de> Thomas Heller wrote: > I wonder: do I really have to check for the BOM manually, or is there a > Python function which does that? If it can also be ASCII (or ansi?), then yes, you need to manually check for the BOM. This is because you need to make an explicit decision in the fallback case - Python cannot know whether it is ASCII if it is not UTF-16. For example, it might also be Latin-1 or UTF-8 if it is not UTF-16, or, say, iso-2022-jp. Regards, Martin From jstroud at mbi.ucla.edu Tue May 8 16:55:19 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 08 May 2007 13:55:19 -0700 Subject: interesting exercise In-Reply-To: References: <1178595952.641173.76540@y80g2000hsf.googlegroups.com> <1178601624.812907.23550@u30g2000hsc.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Tue, 08 May 2007 10:22:05 +0000, James Stroud wrote: > > >>This takes annoying past annoying to some new level of hell to which >>even satan himself wouldn't venture. > > > And thank you for sharing that piece of spam with us again. It was so much > less enjoyable to see it the second time. > > Seriously James, with more and more people using automated spam filters, > it might not be such a wise idea to keep having your name associated with > spam content. > > Thank you for the tip. James From uniomni at internode.on.net Fri May 18 04:08:08 2007 From: uniomni at internode.on.net (Ole Nielsen) Date: Fri, 18 May 2007 18:08:08 +1000 Subject: Anyone use PyPar (Python MPI implementation) recently? Message-ID: <000601c79923$ac78a000$f701a8c0@cuttlefish> Cheers and thanks Ole -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven at REMOVE.THIS.cybersource.com.au Mon May 7 05:12:35 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 07 May 2007 09:12:35 -0000 Subject: Properties on old-style classes actually work? References: Message-ID: On Mon, 07 May 2007 10:44:35 +0200, Paul Melis wrote: > Hello, > > The python library docs read in section 2.1 > (http://docs.python.org/lib/built-in-funcs.html): > > " > ... > > property( [fget[, fset[, fdel[, doc]]]]) > Return a property attribute for new-style classes (classes that > derive from object). > > ... > " > > > But in 2.4 at least properties also seem to work for old-style classes: Unfortunately, they don't -- they seem to work until you try assigning to them. Here's the same property implemented with a new-style and old-style class: class New(object): def __init__(self, s): self._value = s def upgetter(self): return self._value.upper() def upsetter(self, s): self._value = s value = property(upgetter, upsetter) class Old: def __init__(self, s): self._value = s def upgetter(self): return self._value.upper() def upsetter(self, s): self._value = s value = property(upgetter, upsetter) Properties work with new-style classes: >>> obj = New('norwegian blue') >>> obj.value 'NORWEGIAN BLUE' >>> obj.value = 'nobody expects the spanish inquisition!' >>> obj.value 'NOBODY EXPECTS THE SPANISH INQUISITION!' At first, they seem to work with old-style classes: >>> obj = Old('norwegian blue') >>> obj.value 'NORWEGIAN BLUE' But problems occur once you try assigning to it: >>> obj.value = 'nobody expects the spanish inquisition!' >>> obj.value 'nobody expects the spanish inquisition!' And now it is easy to see why: >>> obj.__dict__['value'] 'nobody expects the spanish inquisition!' >>> obj.__dict__['_value'] 'norwegian blue' The call to assign obj.value over-rides the property with the raw value, and from that moment on, obj.value is no longer a property, but just an ordinary instance attribute. -- Steven. From fb at frank-buss.de Thu May 3 11:11:13 2007 From: fb at frank-buss.de (Frank Buss) Date: Thu, 3 May 2007 17:11:13 +0200 Subject: ignorance and intolerance in computing communties References: <1178120019.271716.299590@e65g2000hsc.googlegroups.com> <1178203772.243333.24990@p77g2000hsh.googlegroups.com> Message-ID: Xah Lee wrote: > I'm still interested, if someone would show the source code, of how > Perl, Python, or Lisp or Java, implement the function that finds the > angle of a complex number. So you have forgotten to cross-post to comp.lang.java :-) I think at least for strict floating-point Java uses the netlib: http://www.netlib.org/fdlibm/e_atan2.c For normal floating-point calculations I assume Java uses something like FPATAN on x86'er computers: http://www.ews.uiuc.edu/~cjiang/reference/vc107.htm But you can download the source code of the JVM to verify it yourself: https://openjdk.dev.java.net/ -- Frank Buss, fb at frank-buss.de http://www.frank-buss.de, http://www.it4-systems.de From trentm at activestate.com Fri May 4 12:21:52 2007 From: trentm at activestate.com (Trent Mick) Date: Fri, 04 May 2007 09:21:52 -0700 Subject: ANN: ActivePython 2.5.1.1 is now available Message-ID: <463B5DA0.7010204@activestate.com> I'm happy to announce that ActivePython 2.5.1.1 is now available for download from: http://www.activestate.com/products/activepython/ This is a patch release that updates ActivePython to core Python 2.5.1. This release also fixes a couple problems with running pydoc from the command line on Windows. See the release notes for full details: http://aspn.activestate.com/ASPN/docs/ActivePython/2.5/relnotes.html What is ActivePython? --------------------- ActivePython is ActiveState's binary distribution of Python. Builds for Windows, Mac OS X, Linux, HP-UX and AIX are made freely available. ActivePython includes the Python core and the many core extensions: zlib and bzip2 for data compression, the Berkeley DB (bsddb) and SQLite (sqlite3) database libraries, OpenSSL bindings for HTTPS support, the Tix GUI widgets for Tkinter, ElementTree for XML processing, ctypes (on supported platforms) for low-level library access, and others. The Windows distribution ships with PyWin32 -- a suite of Windows tools developed by Mark Hammond, including bindings to the Win32 API and Windows COM. See this page for full details: http://aspn.activestate.com/ASPN/docs/ActivePython/2.5/whatsincluded.html As well, ActivePython ships with a wealth of documentation for both new and experienced Python programmers. In addition to the core Python docs, ActivePython includes the "What's New in Python" series, "Dive into Python", the Python FAQs & HOWTOs, and the Python Enhancement Proposals (PEPs). An online version of the docs can be found here: http://aspn.activestate.com/ASPN/docs/ActivePython/2.5/welcome.html We would welcome any and all feedback to: ActivePython-feedback at activestate.com.com Please file bugs against ActivePython at: http://bugs.activestate.com/query.cgi?set_product=ActivePython On what platforms does ActivePython run? ---------------------------------------- ActivePython includes installers for the following platforms: - Windows/x86 - Mac OS X - Linux/x86 - Solaris/SPARC - Solaris/x86 - Windows/x64 ("x64" is also known as "AMD64") - Linux/x86_64 ("x86_64" is also known as "AMD64") - HP-UX/PA-RISC - AIX/PowerPC Extra Bits ---------- ActivePython releases also include the following: - ActivePython25.chm: An MS compiled help collection of the full ActivePython documentation set. Linux users of applications such as xCHM might find this useful. This package is installed by default on Windows. Extra bits are available from: http://downloads.activestate.com/ActivePython/etc/ Thanks, and enjoy! Trent, Python Tech Lead -- Trent Mick trentm at activestate.com From stefan.behnel-n05pAM at web.de Tue May 15 08:20:18 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 15 May 2007 14:20:18 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <4649A46D.8070504@korteklippe.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <4648252D.5020704@web.de> <46483740.4050406@web.de> <46498cb1$0$6411$9b4e6d93@newsspool2.arcor-online.net> <46499273.6050806@web.de> <46499a54$0$10199$9b4e6d93@newsspool4.arcor-online.net> <46499B16.2070901@web.de> <4649a08c$0$23148$9b4e6d93@newsspool1.arcor-online.net> <4649A22C.8010207@web.de> <4649A46D.8070504@korteklippe.de> Message-ID: <4649A582.8000905@web.de> Ren? Fleschenberg wrote: > Now you are starting to troll? Sorry, I was omitting the signs of sarcasm as I thought that would be clear from the previous posts in this thread (which I was citing). Feel free to re-read my post. Stefan From stefan.behnel-n05pAM at web.de Mon May 28 15:30:36 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 28 May 2007 21:30:36 +0200 Subject: expat parser In-Reply-To: References: Message-ID: <465B2DDC.7020209@web.de> Sebastian Bassi wrote: > I have this code: > > import xml.parsers.expat > def start_element(name, attrs): > print 'Start element:', name, attrs > def end_element(name): > print 'End element:', name > def char_data(data): > print 'Character data:', repr(data) > p = xml.parsers.expat.ParserCreate() > p.StartElementHandler = start_element > p.EndElementHandler = end_element > p.CharacterDataHandler = char_data > fh=open("/home/sbassi/bioinfo/smallUniprot.xml","r") > p.ParseFile(fh) > > And I get this on the output: > > ... > Start element: sequence {u'checksum': u'E0C0CC2E1F189B8A', u'length': > u'393'} > Character data: u'\n' > Character data: u'MPKKKPTPIQLNPAPDGSAVNGTSSAETNLEALQKKLEELELDEQQRKRL' > Character data: u'\n' > Character data: u'EAFLTQKQKVGELKDDDFEKISELGAGNGGVVFKVSHKPSGLVMARKLIH' > ... > End element: sequence > ... > > Is there a way to have the character data together in one string? I > guess it should not be difficult, but I can't do it. Each time the > parse reads a line, return a line, and I want to have it in one > variable. Any reason you are using expat and not cElementTree's iterparse? Stefan From deets at nospam.web.de Wed May 23 08:18:42 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 23 May 2007 14:18:42 +0200 Subject: Basic Class/Instance Question References: <1179921235.622391.230150@h2g2000hsg.googlegroups.com> Message-ID: <5bipp2F2rd8ijU1@mid.uni-berlin.de> Siah wrote: > I think that's because: No idea what is because of what. Please quote essential parts of the posting you refer to. >>>> [] is [] > False >>>> () is () > True This is an implementation artifact. The interpreter chose to create only one instance for the empty tuple for optimization reasons. But you shouldn't rely on this. For example, for small numbers, 1 is 1 is usually true, but not for larger: 10000000000000 is 10000000000000 Diez From bj_666 at gmx.net Sun May 6 04:51:16 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sun, 06 May 2007 10:51:16 +0200 Subject: Newbie prob: How to write a file with 3 threads? References: <1178440537.257526.40980@y5g2000hsa.googlegroups.com> Message-ID: In <1178440537.257526.40980 at y5g2000hsa.googlegroups.com>, est wrote: > I need to write a file using 3 threads simutaniously, e.g. Thread 1 > write the first byte of test.bin with an "a", second thread write the > second byte "b", third thread write the third byte "c". Anyone could > give a little example on how to do that? Simplest solution is: don't do that. Write from one thread and send the date from the other threads via a `Queue.Queue` to the writing thread. Send the number of the thread with the data so the writer thread knows in which order the data has to be written. > I have my code, but it makes python intepreter crash everytime on my > Vista. Show minimal (non-)working code, tell us the exception plus traceback and explain "crash". Ciao, Marc 'BlackJack' Rintsch From james.b.looney at lmco.com Mon May 14 17:44:48 2007 From: james.b.looney at lmco.com (Looney, James B) Date: Mon, 14 May 2007 15:44:48 -0600 Subject: os.listdir() doesn't work ?? In-Reply-To: References: <1179173881.163830.54930@n59g2000hsh.googlegroups.com> Message-ID: The case sensitivity has to do with the OS you're on. So, using glob from Un*x is case sensitive, but from Windows it isn't. -----Original Message----- From: python-list-bounces+james.b.looney=lmco.com at python.org [mailto:python-list-bounces+james.b.looney=lmco.com at python.org] On Behalf Of Stef Mientki Sent: Monday, May 14, 2007 3:39 PM To: python-list at python.org Subject: Re: os.listdir() doesn't work ?? Michel Claveau wrote: > Hi! > > >> You want the glob module > > Warning: glob has "unix like behavior"; just a little different with > windows's DIR Don't know the details of "Unix" but I thought "unix" was case-sensitive, and glob.glob doesn't seem to be, at least not on windows systems ;-) cheers, Stef Mientki -- http://mail.python.org/mailman/listinfo/python-list From duncan.booth at invalid.invalid Thu May 31 03:43:32 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 31 May 2007 07:43:32 GMT Subject: c[:]() References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <1180562356.722411.327340@m36g2000hse.googlegroups.com> Message-ID: irstas at gmail.com wrote: > On May 31, 12:31 am, "Warren Stringer" wrote: >> This is inconsistent: >> >> why does c[:][0]() work but c[:]() does not? >> Why does c[0]() has exactly the same results as c[:][0]() ? >> Moreover, c[:][0]() implies that a slice was invoked > > It's not inconsistent, but [:] probably does something different than > you think it does. All it does is create a copy (not in general, but > at least if c is a list or a tuple). Since in your example c is a > tuple and tuples are immutable, making a copy of it is essentially > useless. Why not just use the original? I.e. instead of c[:] you could > just write c. That's why c[:][0]() has exactly the same effect as c[0] > (), although the former is likely to be slightly slower. An extremely minor point (and implementation specific), but while [:] will copy a list it won't copy a tuple. Likewise 'list(aList)' will always copy a list, 'tuple(aTuple)' won't copy a tuple. So in this particular example the slice is completely redundant. >>> c is c[:] is c[:][:][:][:] is tuple(c) True From steve at REMOVE.THIS.cybersource.com.au Wed May 2 13:28:07 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 03 May 2007 03:28:07 +1000 Subject: Any way to refactor this? References: <461fe75c$0$11278$c3e8da3@news.astraweb.com> <461ff01c$0$29118$426a74cc@news.free.fr> <4638af08$0$448$c3e8da3@news.astraweb.com> Message-ID: On Wed, 02 May 2007 11:37:14 -0400, John Salerno wrote: > Bruno Desthuilliers wrote: > >> From a purely efficiency POV, there are some obviously possible >> improvements. The first one is to alias visual.cylinder, so you save on >> lookup time. The other one is to avoid useless recomputation of >> -hatch_length and hatch_length*2. >> >> def _create_3D_xhatches(): >> cy = visual.cylinder >> for x in xrange(-axis_length, axis_length + 1): >> if x == 0: continue >> b = -hatch_length >> c = hatch_length*2 >> cy(pos=(x, b, 0), axis=(0, c, 0), radius=hatch_radius) >> cy(pos=(x, 0, b), axis=(0, 0, c), radius=hatch_radius) >> cy(pos=(b, x, 0), axis=(c, 0, 0), radius=hatch_radius) >> cy(pos=(0, x, b), axis=(0, 0, c), radius=hatch_radius) >> cy(pos=(b, 0, x), axis=(c, 0, 0), radius=hatch_radius) >> cy(pos=(0, b, x), axis=(0, c, 0), radius=hatch_radius) > > Doesn't this call to "cy" still call the function multiple times? I'm not sure I understand what you mean, but here goes anyway... Well, yes, but you have to call it six times per loop, with six different sets of arguments, that's why there are six calls to it. I don't think there's any way to reduce that (although if there is, the Original Poster would probably love to hear about it). Bruno's code has two micro-optimizations. The first is to avoid looking up visual.cylinder each time (six times the number of loops) and instead only look it up once. If axis_length is (say) 100, you save 1200 name look-ups of arbitrary complexity. (Perhaps visual inherits from Klass, which inherits from Spam, which inherits from Parrot, which inherits from Foo, which inherits from Bar, which has a method "cylinder". Name look-ups can be time consuming.) The second is to avoid calculating -hatch_length and hatch_length*2 for each call, but to calculate them only once per loop. Again, only a micro-optimization, but arithmetic in Python is more work than in (say) C, because of the whole object oriented framework. So if you can avoid having to look up hatch_length.__mul__ repeatedly, you may see a small but significant time saving. -- Steven. From maney at two14.net Sat May 19 12:31:38 2007 From: maney at two14.net (Martin Maney) Date: Sat, 19 May 2007 16:31:38 +0000 (UTC) Subject: zipfile stupidly broken References: Message-ID: Nick Craig-Wood wrote: > To search 64k for all zip files would slow down the opening of all zip > files whereas most zipfiles don't have comments. No, actually it would only slow down for files which do have comments, assuming I understand the code correctly. IME most zipfiles don't have any comments at all, and would be unaffected. To be honest, if I had even known that zipfiles could have comments before I ran into this, I'd long since forgotten it. > You don't need to do that, you can just "monkey patch" the _EndRecData > function. For a quick & dirty test, sure. If I were certain I'd only ever use this on one machine for a limited time (viz, no system upgrades that replace zipfile.py) it might suffice. But that doesn't generalize worth a damn. -- Education makes people easy to lead, but difficult to drive; easy to govern, but impossible to enslave. -- Henry Peter Brougham From tjreedy at udel.edu Wed May 16 01:21:45 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 16 May 2007 01:21:45 -0400 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de><1hy2qg3.iqfvwnrvr9kjN%aleax@mac.com><1hy69gm.eh6m866urk03N%aleax@mac.com> <20070516044923.GA29008@nullcube.com> Message-ID: "Aldo Cortesi" wrote in message news:20070516044923.GA29008 at nullcube.com... | I must admit to a fascination with language myself - I even have a degree in | English literature to prove it! To be fair to Steven, I've asked some of my | colleagues here in Sydney about their reactions to the phrase "by eye", and | none of them have yet come up with anything that has the strong pejorative | taint Steven gave it. At any rate, it's clear that the phrase is not well | defined anywhere (not even in the OED), and I'm sure there are substantial | regional variations in interpretation. As a native American, yes, 'by eye' is sometimes, maybe even often used with a perjorative intent. | In cases like these, however, context is paramount, so I will quote sentences | that started this petty bickering: However, in this context | | > The security implications have not been sufficiently explored. I don't want | > to be in a situation where I need to mechanically "clean" code (say, from a | > submitted patch) with a tool because I can't reliably verify it by eye. I read it just as Aldo claims . | Surely, in context, the meaning is clear? "By eye" here means nothing more nor | less than a literal reading suggests. Taking these sentences to be an argument | for a slip-shod, careless approach to code, as Steven did, is surely perverse. Perhaps because in this context, it is not at all clear what the 'more exact' method would be. Terry Jan Reedy From __peter__ at web.de Thu May 10 02:21:14 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 10 May 2007 08:21:14 +0200 Subject: elegant python style for loops References: <1178776272.535735.166540@h2g2000hsg.googlegroups.com> Message-ID: ian.team.python at saltmob.com wrote: > To step through a list, the python style is avoid an explicit index. > But what if the same hidden index is to be used for more than one list > > for example:- > for key,value in listKeys,listValues : > newdict[key]=value > > won't work as it is a tuple of lists, as opposed to a list of tuples. > Is there an elegant solution to this? Is there a way to merge lists > into a list of tuples to allow moving through multiple lists, or is > the for i in range(len(listkeys)): the only solution? > > Any suggestions? zip() creates a list of tuples, or better, itertools.izip() lazily creates tuples as you go. Peter From aleax at mac.com Sat May 12 19:24:09 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 12 May 2007 16:24:09 -0700 Subject: Dynamic subclassing ? References: <1178976888.443891.116090@y80g2000hsf.googlegroups.com> Message-ID: <1hy0dfh.1d8mafv1fwburaN%aleax@mac.com> manatlan wrote: > I've got an instance of a class, ex : > > b=gtk.Button() > > I'd like to add methods and attributes to my instance "b". > I know it's possible by hacking "b" with setattr() methods. But i'd > like to do it with inheritance, a kind of "dynamic subclassing", > without subclassing the class, only this instance "b" ! > > In fact, i've got my instance "b", and another class "MoreMethods" > > class MoreMethods: > def sayHello(self): > print "hello" > > How could i write ... > > "b = b + MoreMethods" > > so "b" will continue to be a gtk.Button, + methods/attributs of > MoreMethods (it's what i call "dynamic inheritance") ...so, things > like this should work : > > - b.set_label("k") > - b.sayHello() > > I can't find the trick, but i'm pretty sure it's possible in an easy > way. I think what you're asking for is totally weird, and with just about zero advantages compared with several saner alternatives that have already been proposed in this thread and that you have rejects, but sure, it's possible: def addaclass(aninst, onemoreclass): aninst.__class__ = type(aninst.__aclass__.__name__, (aninst.__aclass__, onemoreclass), {}) Alex From islamguide at msn.com Sun May 6 06:18:31 2007 From: islamguide at msn.com (happy) Date: 6 May 2007 03:18:31 -0700 Subject: Did you read about that? Message-ID: <1178446711.502374.286790@l77g2000hsb.googlegroups.com> you can take a look for this web sites http://www.imanway.com/vb/forumdisplay.php?f=90 http://www.geocities.com/islamone_l/index.htm or read this ================================================== What is Islam? ABOUT THE WORDS "ISLAM" AND "MUSLIM" The name of this religion is Islam, the root of which is S-L-M, which means peace. The word "Salam," derived from the same root, may also mean greeting one another with peace. One of the beautiful names of God is that He is Peace. But Islam means more than that: it means submission to the One God, and it means living in peace with the Creator -- peace within one's self, peace with other people, and peace with the environment. Thus, Islam is a total system of living. A Muslim is supposed to live in peace and harmony with all these segments. It follows that a Muslim is any person, anywhere in the world, whose obedience, allegiance, and loyalty are to God, the Lord of the Universe. IS "MUSLIM" THE SAME AS ARAB? The followers of Islam are called Muslims. Muslims are not to be confused with Arabs. Muslims may be Arabs, Turks, Persians, Indians, Pakistanis, Malaysians, Indonesians, Europeans, Africans, Americans, Chinese, or other nationalities. An Arab could be a Muslim, a Christian, a Jew or an atheist. Any person who adopts the Arabic language is called an Arab. The language of the Qur'an (the Holy Book of Islam) is Arabic. Muslims all over the world try to learn or improve their Arabic, so that they may be able to read the Qur'an and understand its meaning. They pray in the language of the Qur'an, Arabic. Islamic supplications to God could be (and are) delivered in any language. There are one billion Muslims in the world; there are about 200 million Arabs. Among those two hundred million Arabs, approximately ten percent are not Muslims. Thus Arab Muslims constitute only about twenty percent of the Muslim population of the world. - ALLAH THE ONE AND THE ONLY GOD "Allah" was the Arabic word for God long before the birth of Muhammad, peace be upon him. Muslims believe that Allah is the name of the One and Only God. He is the Creator of all human beings. He is the God for the Christians, the Jews, the Muslims, the Buddhists, the Hindus, the atheists, and all others. Muslims worship God, whose name is Allah. They put their trust in Him and they seek His help and His guidance. MUHAMMAD Muhammad was chosen by God to deliver His Message of Peace, namely Islam. He was born in 570 C.E. (Common Era) in Makkah, Arabia. He was entrusted with the Message of Islam when he was at the age of forty years. The revelation that he received is called the Qur'an, while the message is called Islam. Muhammad is the very last Prophet of God to mankind. He is the final Messenger of God. His message was and is still to the Christians, the Jews and the rest of mankind. He was sent to those religious people to inform them about the true mission of Jesus, Moses, Jacob, Isaac, and Abraham. Muhammad is considered to be the summation and the culmination of all the prophets and messengers that came before him. He purified the previous messages from adulteration and completed the Message of God for all humanity. He was entrusted with the power of explaining, interpreting and living the teaching of the Qur'an. ISLAM AND NON-MUSLIMS Muslims are required to respect all those who are faithful and God conscious people, namely those who received messages. Christians and Jews are called People of the Book. Muslims are asked to call upon the People of the Book for common terms, namely, to worship One God, and to work together for the solutions of the many problems in the society. Christians and Jews lived peacefully with Muslims throughout centuries in the Middle East and other Asian and African countries. The second Caliph, Umar, chose not to pray in the church in Jerusalem, so as not to give later Muslims an excuse to take it over. Christians entrusted the Muslims, and as such the key of the Church in Jerusalem is still in the hands of the Muslims. When Jews fled from Spain during the Inquisition, they were welcomed by the Muslims. They settled in the heart of the Islamic Caliphate. They enjoyed positions of power and authority. Throughout the Muslim world, churches, synagogues and missionary schools were built within the Muslim neighborhoods. These places were protected by Muslims during bad times and good, and have continued to receive this protection during the contemporary crises in the Middle East =============================================================== What is the Qur'?n? The Qur'?n is the name given to Allah's speech that He revealed to His servant and Messenger Muhammad (peace be upon him); speech that is recited as an act of worship, is miraculous, and cannot be imitated by man. It is the name of Allah's Book, and no other book is called by this name. The connection between the Creator and his Creation is by way of His Messengers, and these Messengers only know what Allah wants from them by way of revelation, either directly or indirectly. The rational mind cannot dismiss the possibility of revelation, since nothing is difficult for the all-powerful Creator revelation is a communication between two beings: one that speaks, commands, and gives, and another who is addressed, commanded, and receives. Prophet Muhammad (peace be upon him) - as with every Prophet - never confused himself with the One who gave the revelation to him. As a human being, he felt his weakness before Allah, feared Allah's wrath if he should disobey, and hoped for Allah's mercy. Proves why it is impossible that Mohammad (Pbuh) wrote the Quran : 1. No matter how brilliant or insightful a person might be, there is no way that he could discuss the happenings of nations lost to antiquity, issues of belief and Divine Law, the rewards and punishments of Heaven and Hell, and future events, all in such great detail without any contradiction and with a most perfect style and literary form. The Prophet (peace be upon him) had never once read a book nor met with any historian 2. The Qur'?n makes to the disbelievers a stern challenge that they will never be able to produce a chapter similar to it. Such a challenge would never have come from the Messenger (peace be upon him) 3. The Qur'?n, in some places, sternly rebukes Muhammad (peace be upon him) where he acted upon his own judgment in something and did not decide on what is best. The Qur'?n clarified the truth and showed the error of the Prophet (peace be upon him). 4. Many verses of the Qur'?n begin with the imperative verb "Say!" As a matter of fact, this occurs more than three hundred times, addressing Muhammad (peace be upon him) and directing him with respect to what he should say. He, thus, did not follow his own desires; he followed only what was revealed to him. 5. Complete harmony exists between what the Qur'?n says regarding the physical world and what has been discovered by modern science. This has been a source of amazement for a number of contemporary western researchers. ==================================================== Who was Muhammad? Muhammad (peace be upon him) was born in Makkah in the year 570, during the period of history Europeans called the Middle Ages. Muhammad was the son of Aamenah and Abdullah, from the tribe of Quraysh. He was a direct descendant of Ishmael, the eldest son of prophet Abraham. Muhammad's father died just before he was born, and his mother passed away when he was six. He was raised by this grandfather, the chief of Makkah; and upon his grandfather's death, Muhammad came under the care of his uncle, Abu Talib. Muhammad was a shepherd in his youth. As he grew up, he became known for his truthfulness, generosity, and sincerity; earning the title of al Amin, the trustworthy one. Muhammad was frequently called upon to arbitrate disputes and counsel his fellow Makkans. At age 25, Muhammad married Khadijah, an honorable and successful businesswoman. They were blessed with two sons and four daughters. It was an ideal marriage and they lived a happy family life. Muhammad was of a contemplative nature and had long detested the decadence and cruelty of his society. It became his habit to meditate from time to time in the cave of Hira' near the summit of Jabal an- Nur, the "Mountain of Light" on the outskirts of Makkah. How did Muhammad become a Messenger of God? At the age of 40, while engaged in a meditative retreat, Muhammad received his first revelation from God through the Archangel Gabriel. This revelation, which continued for twenty three years, is known as the Qur'an Muhammad began to share the revelations he received from God with the people of Makkah. They were idol worshippers, and rejected Muhammad's call to worship only One God. They opposed Muhammad and his small group of followers in every way. These early Muslims suffered bitter persecution. In 622, God gave the Muslim community the command to emigrate. This event, the hijrah or migration, in which they left Makkah for the city of Madinah, some 260 miles to the North, marks the beginning of the Muslim calendar. Madinah provided Muhammad and the Muslims a safe and nurturing haven in which the Muslim community grew. After several years, the Prophet and his followers returned to Makkah and forgave their enemies. Then, turning their attention to the Ka'bah (the sanctuary that Abraham built), they removed the idols and rededicated it to the worship of the One God. Before the Prophet died at the age of 63, most of the people of Arabia had embraced his message. In less than a century, Islam had spread to Spain in the west, as far east as China. From sturlamolden at yahoo.no Wed May 2 18:00:15 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 2 May 2007 15:00:15 -0700 Subject: Lazy evaluation: overloading the assignment operator? In-Reply-To: <59scumF2lqg76U1@mid.uni-berlin.de> References: <1178133344.415521.118710@n76g2000hsh.googlegroups.com> <59scumF2lqg76U1@mid.uni-berlin.de> Message-ID: <1178143215.240679.151360@u30g2000hsc.googlegroups.com> On May 2, 11:08 pm, "Diez B. Roggisch" wrote: > And AFAIK the general overhead of laziness versus eager evaluation does > not pay off - haskell is a tad slower than e.g. an ML dialect AFAIK. In the numerical Python community there is already a prototype compiler called 'numexpr' which can provide efficient evaluation of expressions like y = a*b + c*d. But as long as there is no way of overloading an assignment, it cannot be seamlessly integrated in an array framework. One will e.g. have to type up Python expressions as strings and calling eval() on the string instead of working directly with Python expressions. In numerical work we all know how Fortran compares with C++. Fortran knows about arrays and can generate efficient code. C++ doesn't and have to resort to temporaries returned from overloaded operators. The only case where C++ can compare to Fortran is libraries like Blitz++, where for small fixes-sized arrays the temporary objects and loops can be removed using template meta-programming and optimizing compilers. NumPy has to generate a lot of temporary arrays and traverse memory more than necessary. This is a tremendous slow down when arrays are too large to fit in the CPU cache. Numexpr deals with this, but Python cannot integrate it seamlessly. I think it is really a matter of what you are trying to do. Some times lazy evaluation pays off, some times it doesn't. But overloaded assignment operators have more use than lazy evaluation. It can be used and abused in numerous ways. For example one can have classes where every assignment results in the creation of a copy, which may seem to totally change the semantics of Python code (except that it doesn't, it's just an illusion). Sturla Molden From deets at nospam.web.de Mon May 7 10:13:08 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 07 May 2007 16:13:08 +0200 Subject: how do you implement a reactor without a select? References: <1178543812.260333.39280@w5g2000hsg.googlegroups.com> Message-ID: <5a8qfkF2mq8leU1@mid.uni-berlin.de> > Notice that I copied the Twisted terminology, but > I did not look at Twisted implementation because I did not want to > use a select (I assume that the GUI mainloops do not use it either). Why do you assume that? It's a wrong assumption. Yielding a thread/process until the OS wakes it up because of IO to be performed is the proper way to go. And at least in unix, IO is _everything_, also mouse-movements and keyboard events. Most probably the OS will have specialized APIs (or some wrapper lib has) that allow for reactor registration for events of different kinds including timers. But basically, it's select - I mean you could easily offer a timer as a file-object as well. Not sure if that's done though. > The trick I use is to store the actions to perform (which are > callables identified by an integer) in an event dictionary and > to run them in the mainlooop if the current time is greater than > the scheduled time. > I had to add a time.sleep(.001) call in the default_action to avoid > consuming 100% > of the CPU in the loop. > I wonder if real mainloops are done in this way and how bad/good is > this implementation compared to a serious one. Any suggestion/hint/ > advice > is well appreciated. Thanks, It's ok, but of course more wasteful than it needs to be - better would be full delegation to the OS. Diez From aleax at mac.com Mon May 28 17:12:33 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 28 May 2007 14:12:33 -0700 Subject: Is PEP-8 a Code or More of a Guideline? References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <1180289911.951691.78640@k79g2000hse.googlegroups.com> Message-ID: <1hyttp5.cy5uldv00db3N%aleax@mac.com> sjdevnull at yahoo.com wrote: > Historically, it's only Java and the Windows world (including non- > standard Windows-style C++) that use forcedCase significantly (C# > draws from both). I remember meeting that style first in the X Window System (now commonly known as X11, but it was around for a few years before the 11 arrived), which is a little bit older than Windows and WAY older than Java. I don't know if X was the first project to use that style consistently. Alex From bbxx789_05ss at yahoo.com Wed May 16 11:29:47 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 16 May 2007 08:29:47 -0700 Subject: setting an attribute In-Reply-To: <464abfaf$0$15544$426a74cc@news.free.fr> References: <1179300898.223314.76430@y80g2000hsf.googlegroups.com> <464abfaf$0$15544$426a74cc@news.free.fr> Message-ID: <1179329387.313770.246780@w5g2000hsg.googlegroups.com> On May 16, 2:24 am, Bruno Desthuilliers wrote: > 7stud a ?crit : > > > > > "When you bind (on either a class or an instance) an attribute whose > > name is not special...you affect only the __dict__ entry for the > > attribute(in the class or instance, respectively)." > > > In light of that statement, how would one explain the output of this > > code: > > > class Test(object): > > x = [1, 2] > > > def __init__(self): > > self.x[0] = 10 > > > print Test.__dict__ #{.....'x':[1,2]....} > > t = Test() > > print t.x #[10, 2] > > print t.__dict__ #{} > > print Test.__dict__ #{.....'x':[10,2]...} > > > It looks to me like self.x[0] is binding on an instance whose > > attribute name is not special, > > self.x[0] = 10 doesn't bind self.x - it's just syntactic sugar for > self.x.__setitem__(0, 10) (which itself is syntactic sugar for > list.__setitem__(self.x, 0, 10)) > > > yet it doesn't affect any __dict__ > > entry for the attribute in the instance > > Of course. The name 'x' is looked up in the instance, then in the class. > Since there's no binding (only a method call on a class attribute), > instance's dict is not affected. Thanks. From rrr at ronadam.com Fri May 25 12:28:16 2007 From: rrr at ronadam.com (Ron Adam) Date: Fri, 25 May 2007 11:28:16 -0500 Subject: webbrowser module bug? In-Reply-To: <1180106384.198363.14120@p47g2000hsd.googlegroups.com> References: <1180106384.198363.14120@p47g2000hsd.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: > On May 24, 5:03 pm, Ron Adam wrote: >> Is anyone else having problems with the webbrowser module? >> >> Python 2.5.1c1 (release25-maint, Apr 12 2007, 21:00:25) >> [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> import webbrowser >> >>> webbrowser.open('http://www.python.org') >> True >> >>> >> >> It opens firefox as expected, but the url is ... >> >> file:///home/ron/%22http://www.python.org%22 >> >> Which of course doesn't do what is expected. >> >> Any ideas? >> >> Ron > > I don't know. This works for me with Python 2.4 on Windows XP SP2. The > docs don't say much (http://docs.python.org/lib/module- > webbrowser.html). Maybe it would be beneficial to read the module's > code? Or use the "register" command manually? It works for me on python 2.4 also, but not on later versions. Looks like I'll need to try to test the url at the point where it calls the browser from webbrowser.py. Can someone else test this on python 2.5? Ron From S.Mientki-nospam at mailbox.kun.nl Thu May 24 17:59:36 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Thu, 24 May 2007 23:59:36 +0200 Subject: Can I reference 1 instance of an object by more names ? rephrase In-Reply-To: References: <4654289a$0$2326$426a74cc@news.free.fr> <3dc25$4655ebd1$d443bb3a$31378@news.speedlinq.nl> Message-ID: Peter Otten wrote: > Stef Mientki wrote: > >> Maric Michaud wrote: > > def bit(index): >>> def fset(self, value): > >>> value = ( value & 1L ) << index >>> mask = ( 1L ) << index >>> self._d = ( self._d & ~mask ) | value >>> def fget(self): > >>> return ( self._d >> index ) & 1 >>> return property(**locals()) >>> >>> >>> class cpu_ports(object) : > > p1 = bit(1) > p2 = bit(2) > p3 = bit(3) > p4 = bit(4) > p5 = bit(5) > >> Looks good, but I miss the index :-( > > No more. agreed, but Python doesn't like it, and I don't understand why def bit(index): def fset(self, value): #index = 5 value = ( value & 1L ) << index mask = ( 1L ) << index self._d = ( self._d & ~mask ) | value def fget(self): #index = 5 return ( self._d >> index ) & 1 return property(**locals()) class cpu_ports(object) : p1 = bit(1) p2 = bit(2) p3 = bit(3) p4 = bit(4) p5 = bit(5) Traceback (most recent call last): File "", line 209, in run_nodebug File "D:\data_to_test\rapid_prototyping_board_16F877.py", line 168, in ? class cpu_ports(object) : File "D:\data_to_test\rapid_prototyping_board_16F877.py", line 169, in cpu_ports p1 = bit(1) File "D:\data_to_test\rapid_prototyping_board_16F877.py", line 166, in bit return property(**locals()) TypeError: 'index' is an invalid keyword argument for this function but anyway thanks Stef > > Peter From jzgoda at o2.usun.pl Fri May 18 06:22:40 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 18 May 2007 12:22:40 +0200 Subject: Python Web Programming - looking for examples of solid high-traffic sites In-Reply-To: References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> <1hy9yf9.1nnsttj139za6bN%aleax@mac.com> Message-ID: Daniel Nogradi napisa?(a): >> For example, it HAS been published elsewhere that YouTube uses lighttpd, >> not Apache: . > > How do you explain these, then: > > http://www.youtube.com/results.xxx > http://www.youtube.com/results.php > http://www.youtube.com/results.py Server signature is usually configurable. -- Jarek Zgoda "We read Knuth so you don't have to." From sjmachin at lexicon.net Sun May 13 20:13:30 2007 From: sjmachin at lexicon.net (John Machin) Date: 13 May 2007 17:13:30 -0700 Subject: Finally started on python.. In-Reply-To: References: Message-ID: <1179101609.995787.175550@y80g2000hsf.googlegroups.com> On May 13, 3:09 am, Roger Gammans wrote: > 2) > I've ended up coding a new wrapper for reading in data structures > from XML files (it wraps xml.sax) so that ctor are call on each end > tag with the XML Objects contents. > > is there already something there taht does this Check out ElementTree at http://www.effbot.org/ ... it may be similar From martin at v.loewis.de Thu May 3 17:54:52 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 03 May 2007 23:54:52 +0200 Subject: hp 11.11 64 bit python 2.5 build gets error "import site failed" In-Reply-To: <1178197261.294121.157120@h2g2000hsg.googlegroups.com> References: <1178131203.719353.91360@y80g2000hsf.googlegroups.com> <4638fe11$0$1098$9b622d9e@news.freenet.de> <1178197261.294121.157120@h2g2000hsg.googlegroups.com> Message-ID: <463a5a2c$0$6904$9b622d9e@news.freenet.de> >>> "import site failed" >>> OverflowError: signed integer is greater than the maximum. >> - what is the value of ival? > ival: 4294967295 I see. This is 0xFFFFFFFF, which would be -1 if it were of type int. So perhaps some value got cast incorrectly at some point, breaking subsequent computations > >> - where does that number come from? > > It is coming from the call to PyInt_AsLong. In that function there is > a call to: > PyInt_AS_LONG((PyIntObject*)op) > which returns the value of ival. That was not my question, really. I wanted to know where the object whose AsLong value was taken came from. And before you say "it's in the arg parameter" of convertsimple() - sure it is. However, how did it get there? It's in an argument tuple - and where came that from? IOW, you really need to know who the caller of convertsimple is, and what line of Python code precisely was triggering that call. Regards, Martin From ptmcg at austin.rr.com Fri May 4 12:04:10 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 4 May 2007 09:04:10 -0700 Subject: How safe is a set of floats? In-Reply-To: <1hxkw5d.1ipc1zfocmqm9N%aleax@mac.com> References: <1178288509.067493.5140@e65g2000hsc.googlegroups.com> <1hxkw5d.1ipc1zfocmqm9N%aleax@mac.com> Message-ID: <1178294650.738576.205690@q75g2000hsh.googlegroups.com> On May 4, 9:50 am, a... at mac.com (Alex Martelli) wrote: > Thomas Nelson wrote: > > I want to generate all the fractions between 1 and limit (with > > limit>1) in an orderly fashion, without duplicates. > > > def all_ratios(limit): > > s = set() > > hi = 1.0 > > lo = 1.0 > > while True: > > if hi/lo not in s: > > s.add(hi/lo) > > yield (hi,lo) > > hi += 1 > > if hi/lo > limit: > > lo += 1 > > hi = lo > > > I use a set to keep from giving duplicates; but is this safe? In C > > they always tell you not to trust floating point equality comparisons, > > since they may not work as you expect. My code seems fine for the > > limited amount I've tested, but I'm curious: is there a gaurantee > > about sets of floats? Or a warning? > > sets of floats work exactly like sets of anything else and thus in > particular they DO intrinsically rely on == comparisons, i.e., exact > equality checks (just like dicts whose keys are floats, etc). > > In your code, some "fractions" that actually differ from others you're > previously seen will in fact be skipped because they don't differ _by > enough_ -- i.e. they do compare == to within the limited precision of > floating-point computations. But if you do want to be yielding floats, > and never want to yield the (num, denom) tuples for two items that *as > float* compare ==, there's nothing you can do about that issue. > > My main suggestion to you actually would be to compute hi/lo ONCE per > iteration rather than 3 times -- I detest repetition in principle and > here it may be costing you a few nanoseconds' speed:-) > > [[If you don't truly care about whether the fractions you yield do > compare as == "as floats", you might e.g. use gmpy.mpq rather than > division to perform your checks]] > > Alex- Hide quoted text - > > - Show quoted text - Does set membership test for equality ("==") or identity ("is")? I just did some simple class tests, and it looks like sets test for identity. So if I were to create a Rational class in which Rational(1,2) and Rational(2,4) both evaluate to 0.5, such that Rational(1,2) == Rational(2,4) evaluates to True, a set of such Rationals would still hold both instances. -- Paul From caseyhHAMMER_TIME at istar.ca Wed May 2 14:50:29 2007 From: caseyhHAMMER_TIME at istar.ca (Casey Hawthorne) Date: Wed, 02 May 2007 18:50:29 GMT Subject: [ANN] Update to Python Quick Reference Card (for Python 2.4) (v0.67) References: Message-ID: <4bnh33pb644j9qsvij3citqrpb2bmqlsu4@4ax.com> PC-cillin flagged this as a dangerous web site. Laurent Pointal wrote: >PQRC (Python Quick Reference Card) is a condensed documentation for >Python and its main libraries, targetting production of printed quick >http://www.limsi.fr/Individu/pointal/python/pqrc/ > -- Regards, Casey From martinvilu at gmail.com Thu May 24 13:03:46 2007 From: martinvilu at gmail.com (Mauler) Date: 24 May 2007 10:03:46 -0700 Subject: Bootstrapping In-Reply-To: <1180020318.432768.170850@w5g2000hsg.googlegroups.com> References: <1180018414.715769.142750@p77g2000hsh.googlegroups.com> <1180020318.432768.170850@w5g2000hsg.googlegroups.com> Message-ID: <1180026226.799536.258450@q66g2000hsg.googlegroups.com> I've seen it, but its different, the idea behind pyinstaller is to bundle python for a specific application, my idea is to modularize and compact the core of python and reuse the egg concept for extensions. The thing is that refuses to load the site-packages when the core is compressed. thanks again! On 24 mayo, 12:25, ici wrote: > On May 24, 5:53 pm, Mauler wrote: > > > I need some help with adding bootstrap code to the core of python, the > > idea is to leave a super base core inside a zip file (python25.zip > > works right out of the box) and leave the rest in separate zip > > modules. Making it more friendly with pendrives and more practical as > > a standalone runtime (ie, without install) and fully modular. The > > thing is that i need to modify the base importer to add this special > > "site-packages" . > > Any hints? > > thanks in advance (and a lot!) > > > Martin Rene Vilugron > > Patagonia Argentina > > http://pyinstaller.python-hosting.com/? From bdesth.quelquechose at free.quelquepart.fr Sun May 13 09:40:39 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 13 May 2007 15:40:39 +0200 Subject: __dict__ for instances? In-Reply-To: References: <1179029071.282774.116050@h2g2000hsg.googlegroups.com> Message-ID: <46470b33$0$4276$426a74cc@news.free.fr> Ivan Voras a ?crit : > half.italian at gmail.com wrote: > > >>I think you want "dir(instance)" __dict__ returns the instance > > > Part of the problem is that dir(instance) returns a list of strings, so > iterating the dir(instance) gets me strings, not methods. Alternatively, > is there a way to get a "bound" instance by its name - some > introspection function perhaps? getattr(obj, name) > >>variables and values as a dictionary, but doesn't return methods. > > > It does on a Class :( > Usually, methods are attributes of the class, not of the instance. From aisaac at american.edu Sun May 20 15:05:46 2007 From: aisaac at american.edu (Alan Isaac) Date: Sun, 20 May 2007 19:05:46 GMT Subject: docs patch: dicts and sets References: <1178934092.773288.31830@o5g2000hsb.googlegroups.com> <1179100338.610239.299180@k79g2000hse.googlegroups.com> <1179652368.412078.303890@k79g2000hse.googlegroups.com> Message-ID: "Raymond Hettinger" wrote in message news:1179652368.412078.303890 at k79g2000hse.googlegroups.com... > Another way to put it is that the docs are sufficient > when they say that set ordering is arbitrary. That should be a cue to > not have *any* expectations about the internal ordering of sets and > dicts. You are usually more careful. 1. Please do not conflate two issues here. It confuses people like Richard T. Did *anyone* who participated in the initial conversation express an expectation that set ordering is not arbitrary? No. Not one. What surprised people was that this ordering could vary between two *sequential* executions of an *unchanged* source. Martin dismisses this by simply asserting (on what basis?) that anyone who was surprised lacks Python experience, and that to address this in any way would make the reference library assume the role of a tutorial. Not very plausible, IMO, given the rest of the library documentation. 2. You say it the existing docs "should be a cue", and yet they clearly did not provide enough guidance to an ordinary user (me) and some more sophisticated users. So the docs "should be a cue" to people who do not need a cue. Do I understand you correctly? 3. Finally, please do not claim that the docs say that set ordering is arbitrary. At least not the docs we have benn talking about: http://docs.python.org/lib/types-set.html It is fascinating that you would confuse this, since it is the core of the proposed documentation patch (although the proposed language was "indeterminate" rather than arbitrary). So it also seems you are now claiming that the patch should not be in because of the presence of language that is in fact not there. Look, I was just trying to help other users who might be as surprised as I was. As I said, I am not attached to any language, and in fact I just used the proposals of others. I just wanted there to be some clue for users who read the docs. If you prefer to leave such users baffled, so be it. My effort is exhausted. Cheers, Alan Isaac From chris.arndt at web.de Mon May 21 13:16:28 2007 From: chris.arndt at web.de (Christopher Arndt) Date: 21 May 2007 10:16:28 -0700 Subject: customary way of keeping your own Python and module directory in $HOME In-Reply-To: <1179190528.707235.324010@e65g2000hsc.googlegroups.com> References: <1179175513.896546.313500@y80g2000hsf.googlegroups.com> <1179190528.707235.324010@e65g2000hsc.googlegroups.com> Message-ID: <1179767786.608222.39910@y2g2000prf.googlegroups.com> On 15 Mai, 02:55, jmg3... at gmail.com wrote: > My issues have been with keeping a ~/pylib directory for extra > modules, and reconciling that with setuptools / Easy Install. I'm > curious to hear how other folks manage their own local module > directory. For Python libraries, I use the workingenv.py (search Cheeseshop) for keeping a separate environment for every application with all the libraries it needs. This is great to dodge problems with two apps requiring different, uncompatible versions of the same library, for having different staging and production environments, and so on. Once you activate an environment (in a shell or in your Python script), the PYTHONPATH and the installation directories for distutils and easy_install will be adapted automatically. Chris From xah at xahlee.org Wed May 2 11:33:39 2007 From: xah at xahlee.org (Xah Lee) Date: 2 May 2007 08:33:39 -0700 Subject: ignorance and intolerance in computing communties Message-ID: <1178120019.271716.299590@e65g2000hsc.googlegroups.com> Today, a motherfucker Christophe Rhodes (aka Xof in irc://chat.freenode.net/lisp ) kicked banned me. Here's the few relevant excerpt. (full, unedited excerpt will be published if there is a public interest) Begin excerpt: [5:31am] k, here is a simple problem but rather tedious to do it correctly. ... [5:32am] given a unit vector A={a1,a2}, write a function AngleA, such that it returns the positive angle from {1,0} to A. [5:33am] mathematically this is simple, but to implement it is rather cumbersome, with many if statements. [5:34am] also, anyone who has implemented this will know trig well. [5:34am] i wonder if there's already in some library in lisp. (i doubt it) [5:36am] xahlee: (acos (scalar-product A #(1 0))) ... [6:34am] can anyone show me the source code of a function that convert a complex number (a1 b2) to it's polar representation? [6:35am] (defun polarize (complex) (values (abs complex) (phase complex))) [6:35am] wait, why am I replying to the troll? [6:36am] :/ [6:36am] even the mighty Xof is not immune! [6:36am] Xach: you were right, he HAS turned into mary poppins. [6:36am] well... what is the source code for your ?phase?? [6:36am] xahlee: it is, as kmp once said, given from god [6:36am] clhs phase [6:36am] http://www.lispworks.com/reference/HyperSpec/Body/f_phase.htm [6:36am] LiamH joined the chat room. [6:36am] xahlee: you know enough maths to write an impllementation [6:36am] piso: ah...hmmm [6:37am] xahlee: if its a CLHS function, then how its actually written will be implementation specific [6:37am] er CL not CLHS [6:37am] as i described, i'm interested in the algorithm of the implementation, not what it means. [6:37am] ?can anyone show me the source code of a function that convert a complex number (a1 b2) to it's polar representation?? [6:37am] all of that is true, but there's quite a good suggestion for how to implement it on the page I got from specbot [6:37am] xahlee: afaik there is no way to calculate it without conditionals [6:38am] xahlee: and that's what you got [6:38am] you can do 4 dot products, or atan.. however you do it you have to handle cases [6:38am] fax: thanks fax! only you come thru understand the question and not being a troll. [6:38am] (atan y x) [6:38am] the others so far, e.g. xof and pjb in particular, just wanted to troll. [6:38am] look, ma, no conditionals [6:38am] xahlee: more than just me gave you some info.. [6:39am] Xof was promoted to operator by ChanServ. [6:39am] Xof set a ban on *! *n=xahlee at adsl-69-236-77-194.dsl.pltn13.pacbell.net. [6:39am] You were kicked from the chat room by Xof. (now go away, please) ------------------ Christophe Rhodes has unjustly kicked banned me about 3 times in the past year in #lisp. Basically, making it impossible for me to use the service provided by freenode.net in way. Today's incident, is actually the most lenient. In the past ~3 times, he simply kick banned me within few minutes i joined the #lisp channel. Christophe Rhodes is one example of a power-struggling tech geeker in the computing industry. Incidents like this, happens frequently in just about all computer forums where almost all members are exclusively male. I want to bring this to the public attention (in this case, in the lisp community). Because, it is motherfuckers like these, that does society harm, and they all pretent to be saints and justice holders. ------------------- Some notes about the math problem discussed in the topic: As i have indicated in my post, it is non-trivial to implement a function that returns the positive angle of a vector. For example, it can be done with sign checking of the coordinate components (in total 4 cases, which can be done as 2 levels of nesting if, or simply 4 if.), and or the evaluation of Min[Abs[ArcCos[x],Abs[ArcSin[x]]], or use clever ways with dot product, or ArcTan. It is not a trivial to know which algorithm is in general more efficient. (this is important, since finding the angle of a vector is a basic function, that may needs to be called millions times directly or indirectly) Further, consider the inverse trig function, it is likely 99.99% of people with a PH D in math wouldn't know how these are actually implemented. So, the question of whether calling one of the inverse trig function is more robust or efficient than another is a open question. And, besides the algorithmic level, the question also entails how the language actually implement the inverse trig functions. Besides efficiency concerns, there's also robustness concerns. For example, if the 2 vectors are {1,0} and {0,1}, a simplistic implementation will result in division by 0 or similar errors. Checking whether one of them lies on the x or y axis means more if statements, as well the non-trivial problem of determining if two numbers are equal. (e.g. is 0.000001 considered equal to 0.0001 ) My interest in bringing this up for discussion, is because i'm writing a program in Linden Scripting Language to generate a architecture of a given polyhedral symmetry in Second Life (see http://xahlee.org/sl/index.html ), and i need to write a function that returns the positive angle of 2 given vectors from A to B. I have implemented solution to this problem a few times in Mathematica since about 1993. Being a efficiency and perfection nerd with some leisure at the moment, i thought i'd like to know more details about his problem. A optimal implementation with respect to the algorithm level, or see how languages implement the function that convert complex numbers to polar form, or some general understanding and learning with regards to this problem. In a person's computing career, concrete and specialized questions like these abound, and the answers or knowledge about them are scarce. Due to the general ignorance of technical knowledge, and the power- struggling nature of males, and the habit of intolerance and ?troll- crying? in computing communities, made it difficult to have any sensible discussion of original questions that doesn't fit into some elementary level of FAQs and concepts. Asides from complainting about the person who unjustly kicked banned me many times in the past year (which has happened to me in other irc channels (in particular, #perl, #python, #emacs,...), mailing lists, forums, as well happens all the time to many many others (every day in just about every irc channel).), i hope that in general, tech geekers be more tolerant and knoweledgable. In particular, aquire understanding and communication from persons in society who are not in the computing community. For example, in newsgroups everyone is all concerned and involved about the phenomenon of troll all day. To understand this more seriously, study psychology, sociology, anhtropology, ethnology, history. I do not mean getting interested and excited with a slashdot news article then start to discuss it in your forum. But do, take a class in community colleges, or if suitable, spare a reading of your favorite science fiction for a text book on the these subjects. The so- called ?troll? (whatever it means), is a social, behavior phenomenon. So, understanding social sciences is the proper way to understand it, if necessary, learn how to remedy the situation. Not, for example, by tech geeking with other tech geekers. If you are, for example, interested in the comparative superiority of computer languages that almost every tech geekers seem to know so much about, then, try to take a course on the great many specific branches of philosophy, the great branches and depths of (non-computer- language) lingusitics, or the great depth and branches and specialties and even philosophies of mathematical logic, or its history. Various branches or trainings in philosophy will help you in critical thinking, as well as aid you in seeing perspectives, philosophies, or how to approach a problem with a good definition. Similarly, linguistics will help you, in general, understand the concept or theories of semantics or meaning and syntax and grammar, in a way that can give you a independent and original thinking on the questions of judging computing languages. Similarly, mathematical logic gives you a extremely modern technical tool in evaluating or accessing the problem. Spare a tech-geeking on a techincal book on your favorite languages or computer language design book or latest computer engineering practice guide or forum argumentation or wiki or Open Sourcing zeitgeist fuck, to read a text book or learn on the above topics. Xah xah at xahlee.org ? http://xahlee.org/ From kyosohma at gmail.com Mon May 14 13:12:13 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 14 May 2007 10:12:13 -0700 Subject: deployment scripts In-Reply-To: <1179153152.824262.146460@k79g2000hse.googlegroups.com> References: <1179153152.824262.146460@k79g2000hse.googlegroups.com> Message-ID: <1179162733.835593.211410@e51g2000hsg.googlegroups.com> On May 14, 9:32 am, Erin wrote: > Does anyone have experience developing deployment scripts with Jython? What do you mean by "deployment scripts"? What do you want to deploy? Jython? A different program from Jython? Or do you mean packaging a Jython program you wrote? We need more info to be more helpful! Mike From bbxx789_05ss at yahoo.com Fri May 4 18:49:32 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 4 May 2007 15:49:32 -0700 Subject: Further adventures in array slicing. In-Reply-To: References: Message-ID: <1178318972.064626.299190@y80g2000hsf.googlegroups.com> > A second question is: When can you use += vs .append(). > Are the two always the same? They are never the same unless you only add one item to the list. append() will only increase the length of a list by 1. la = [1,2] lb = [3, 4, 5] la += lb print la lc = [1,2] lc.append(lb) print lc --output:-- [1, 2, 3, 4, 5] [1, 2, [3, 4, 5]] print la[2] print lc[2] --output:-- 3 [3, 4, 5] From eric.brunel at pragmadev.com Tue May 15 05:51:20 2007 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Tue, 15 May 2007 11:51:20 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> <4648294F.2000704@web.de> <46487a6c$0$2400$426a74cc@news.free.fr> Message-ID: On Tue, 15 May 2007 11:25:50 +0200, Thorsten Kampe wrote: > * Eric Brunel (Tue, 15 May 2007 10:52:21 +0200) >> On Tue, 15 May 2007 09:38:38 +0200, Duncan Booth >> wrote: >> > Recently there has been quite a bit of publicity about the One Laptop >> Per >> > Child project. The XO laptop is just beginning rollout to children and >> > provides two main programming environments: Squeak and Python. It is >> an >> > exciting thought that that soon there will be millions of children in >> > countries such as Nigeria, Brazil, Uruguay or Nepal[*] who have the >> > potential to learn to program, but tragic if the Python community is >> too >> > arrogant to consider it acceptable to use anything but English and >> ASCII. >> >> You could say the same about Python standard library and keywords then. > > You're mixing apples and peaches: identifiers (variable names) are > part of the user interface for the programmer and free to his > diposition. So what? Does it mean that it's acceptable for the standard library and keywords to be in English only, but the very same restriction on user-defined identifiers is out of the question? Why? If I can use my own language in my identifiers, why can't I write: classe MaClasse: d?finir __init__(moi_m?me, maListe): moi_m?me.monDictionnaire = {} pour i dans maListe: moi_m?me.monDictionnaire[i] = Rien For a French-speaking person, this is far more readable than: class MaClasse: def __init__(self, maListe): self.monDictionnaire = {} for i in maListe: self.monDictionnaire[i] = None Now, *this* is mixing apples and peaches... And this would look even weirder with a non-indo-european language... -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From Maria.Reinhammar at accalon.com Mon May 21 01:43:10 2007 From: Maria.Reinhammar at accalon.com (Maria R) Date: 20 May 2007 22:43:10 -0700 Subject: What is deployment? In-Reply-To: <7x8xbkjc6c.fsf@ruckus.brouhaha.com> References: <68m4i4-9a4.ln1@lairds.us> <7x4pm8tf6v.fsf@ruckus.brouhaha.com> <87646o3yrb.fsf@benfinney.id.au> <7x8xbkjc6c.fsf@ruckus.brouhaha.com> Message-ID: <1179726190.740400.272740@u36g2000prd.googlegroups.com> On May 20, 7:28 am, Paul Rubin wrote: > Ben Finney writes: > > Agreed. I usually discuss "deployment" as meaning "everything required > > to take something from the point of working in a vendor's lab > > environment, to an actual working installation in a production > > environment". > > I'd go beyond that. It includes putting the people and procedures in > place for keeping the production system operating, upgrading it as > needed, customer support, the whole bit. It's all the stuff that > happens on the other side of the line separating "development" from > "operations". I would suggest a somewhat more limited view. That is, deployment is the process after development is finished (or the product system is purchased) up until it is in full operation (including establishing support organisation etc). The exact point of time is, of course, not very clear cut. Upgrading the product, adding more users, extending the use etc. is not, as I see it, *deployment*. But then again, one could say that an upgrade is deployed. However, I prefer to view that as a separate project with its own process. From castironpi at gmail.com Wed May 9 19:23:39 2007 From: castironpi at gmail.com (castironpi at gmail.com) Date: 9 May 2007 16:23:39 -0700 Subject: Behavior of mutable class variables In-Reply-To: <1178750989.107897.260360@y80g2000hsf.googlegroups.com> References: <1178744257.369030.95310@w5g2000hsg.googlegroups.com> <1178745918.395377.282470@u30g2000hsc.googlegroups.com> <1178748332.766271.86950@e51g2000hsg.googlegroups.com> <1178750989.107897.260360@y80g2000hsf.googlegroups.com> Message-ID: <1178753019.454306.101800@e51g2000hsg.googlegroups.com> On May 9, 5:49 pm, tkp... at hotmail.com wrote: > Thanks for the insights. I solved the problem as follows: I created a > new class method called cleanUp, which resets NStocks to an empty list > and N1 to 0. Works like a charm - it's the first time I've used a > class method, and I immediately see its utility. Thanks again > > class Stock(object): > NStocks = [] #Class variables > N1 = 0 > > @classmethod > def cleanUp(cls): > Stocks.NStocks = [] > Stocks.N1 = 0 > > def simulation(N, par1, par2, idList, returnHistoryDir): > > Stock.cleanUp() > results = ...... > print results. class A: b= 0 A.b a= A() a.b a.b+= 1 a.b A.b A.b=20 a.b A.b a1= A() a1.b a.b A.b a1.b+=10 a1.b a.b A.b It looks like an instance gets its own copy of A's dictionary upon creation, and -can- no longer affect A's dictionary, though both can be changed elsewhere. Doesn't seem prudent to -obscure- a class by an instance, but if that's not what goes on, then I'm missing something. From apardon at forel.vub.ac.be Wed May 9 08:47:33 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 9 May 2007 12:47:33 GMT Subject: Boolean confusion References: Message-ID: On 2007-05-09, Greg Corradini wrote: > > Hello all, > I'm having trouble understanding why the following code evaluates as it > does: > >>>> string.find('0200000914A','.') and len('0200000914A') > 10 > True >>>> len('0200000914A') > 10 and string.find('0200000914A','.') > -1 > > In the 2.4 Python Reference Manual, I get the following explanation for the > 'and' operator in 5.10 Boolean operations: > " The expression x and y first evaluates x; if x is false, its value is > returned; otherwise, y is evaluated and the resulting value is returned." > > Based on what is said above, shouldn't my first expression ( > string.find('0200000914A','.') and len('0200000914A') > 10) evaluate to > false b/c my 'x' is false? And shouldn't the second expression evaluate to > True? The find method doesn't return a boolean, but returns the index where the substring was found with -1 indicating it wasn't found. If you just want to check wether one string is a substring of an other, use the in operator. >>> '.' in '0200000914A' and len('0200000914A') > 10 False >>> len('0200000914A') > 10 and '.' in '0200000914A' False -- Antoon Pardon From michael at jedimindworks.com Thu May 17 07:38:52 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Thu, 17 May 2007 06:38:52 -0500 Subject: Code Explanation In-Reply-To: <005f01c79863$74e8b320$5eba1960$@rawlins@thinkbluemedia.co.uk> References: <005f01c79863$74e8b320$5eba1960$@rawlins@thinkbluemedia.co.uk> Message-ID: <1D314B23-72EF-442E-8426-27BD012A9BB7@jedimindworks.com> On May 17, 2007, at 4:12 AM, Robert Rawlins - Think Blue wrote: > I?m currently working on a non-python project, and I?m trying to > overcome a task of parsing a text file into a database and/or xml > file. I?ve managed to find a parser example written in python, and > I?m hoping to deconstruct the code methodology a bit so I can write > it in another language. So I?m hoping someone can explain to me > what these following bits of code are doing. > > > > lines = range(data.count("\n")) > > lined_data = data.split("\n") > > print "Read %i vendors, now processing" % data.count("(hex)") > > > > I?ve not used the split() function before, but it partly makes > sense to me. What is that piece of code doing? ?Data? is the > content of the text file, presumably the first line there is > counting the number of lines in the file, but I don?t get the rest > of it. > > > > The rest of the code seems like a relatively simple set of loops, > but it?s just this splitting stuff that?s got me confused. http://docs.python.org/lib/string-methods.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From joshusdog at gmail.com Thu May 17 15:37:53 2007 From: joshusdog at gmail.com (joshusdog at gmail.com) Date: 17 May 2007 12:37:53 -0700 Subject: newbie question: retrieving values of variables through C API Message-ID: <1179430673.372668.217350@h2g2000hsg.googlegroups.com> I've got an application that embeds the Python interpreter. I have the following command in my code: PyRun_SimpleString("a = \"hello\""); My question is, what is the C API function call for retrieving the value of the variable "a"? From kay.schluehr at gmx.net Fri May 4 00:13:50 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 3 May 2007 21:13:50 -0700 Subject: New EasyExtend release is out Message-ID: <1178252030.354372.249260@c35g2000hsg.googlegroups.com> Hi folks, EasyExtend is a grammar based preprocessor generator and metaprogramming system for Python written in Python. After reworking an initial release for 11 months (!) it's time to present now EasyExtend 2.0-alpha1. You find EasyExtend on the projects homepage: http://www.fiber-space.de/EasyExtend/doc/EE.html The EasyExtend package is also uploaded to the cheeseshop: http://www.python.org/pypi/EasyExtend/2.0-alpha1 To make yourself familiar with EE there is now also an introductory level tutorial: http://www.fiber-space.de/EasyExtend/doc/tutorial/EETutorial.html Have fun! Kay From robert.kern at gmail.com Thu May 10 12:29:43 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 10 May 2007 11:29:43 -0500 Subject: change of random state when pyc created?? In-Reply-To: References: <5ae25fF2oggbqU1@mid.uni-berlin.de> Message-ID: Alan Isaac wrote: > "Carsten Haese" wrote in message > news:mailman.7500.1178771660.32031.python-list at python.org... >> I was simply pointing out all the ways in which you made it difficult for > the >> community to explain your problem. > > And without that community, I would still not have a clue. > Thanks to all! > >> Please feel free to suggest specific wording changes to make the > documentation >> more useful. > > I'm sure my first pass will be flawed, but here goes: > > http://docs.python.org/lib/typesmapping.html: > to footnote (3), add phrase "which may depend on the memory location of the > keys" to get: > > Keys and values are listed in an arbitrary order, > which may depend on the memory location of the keys. > This order is non-random, varies across Python implementations, > and depends on the dictionary's history of insertions and deletions. > > http://docs.python.org/lib/types-set.html: append a new sentence to 2nd > paragraph > > Iteration over a set returns elements in an arbitrary order, > which may depend on the memory location of the elements. It's misleading. It only depends on the memory location of the elements if __hash__() is implemented as id() (the default). How about this? """Never rely on the order of dictionaries and sets.""" -- 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 gagsl-py2 at yahoo.com.ar Tue May 1 19:24:54 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 01 May 2007 20:24:54 -0300 Subject: Read and Write the same file References: <1178060601.700099.263240@y5g2000hsa.googlegroups.com> Message-ID: En Tue, 01 May 2007 20:03:28 -0300, JonathanB escribi?: > Ok, so this is the scenario. I need to create a simple, no-frills XML > editor for non-technical users. It doesn't have to do anything fancy, > what I want is a series of text boxes with the text contents of the > elements pre-printed. Then the users can type their changes into the > text boxes and click submit and it will load the changes in. So here > is the problem, this means I need to open the same file as both read > and write. How do I do this? I'm slowly learning the DOM stuff that I > need to know to do this, but this file thing I haven't been able to > find anywhere. Open the file for reading; read and parse the document; close the file. Build form and show to the user. Get data after user clicks OK. Build document, open file for writing, write document, close file. Reading and writing happen on two separate stages, and you dont have to keep the file open all the time. -- Gabriel Genellina From bvukov at teletrader.com Thu May 31 16:06:07 2007 From: bvukov at teletrader.com (bvukov at teletrader.com) Date: 31 May 2007 13:06:07 -0700 Subject: Adding tuples to a dictionary In-Reply-To: <1180636210.328300.298850@p77g2000hsh.googlegroups.com> References: <1180636210.328300.298850@p77g2000hsh.googlegroups.com> Message-ID: <1180641967.412397.93090@w5g2000hsg.googlegroups.com> On May 31, 8:30 pm, Maciej Blizi?ski wrote: > Hi Pythonistas! > > I've got a question about storing tuples in a dictionary. First, a > small test case which creates a list of dictionaries: > > import time > > list_of_dicts = [] > keys = [str(x) for x in range(200000)] > prev_clk = time.clock() > for i in range(20): > my_dict = {} > for key in keys: > my_dict[key] = key > list_of_dicts.append(my_dict) > new_clk = time.clock() > print i, new_clk - prev_clk > prev_clk = new_clk > > It creates dictionaries and stores them in a list, printing out > execution times. The size of each dictionary is constant, so is the > execution time for each iteration. > > 0 0.1 > 1 0.1 > 2 0.1 > 3 0.08 > 4 0.09 > > ...and so on. > > Then, just one line is changed: > my_dict[key] = key > into: > my_dict[key] = (key, key) > > Full code: > > list_of_dicts = [] > keys = [str(x) for x in range(200000)] > prev_clk = time.clock() > for i in range(20): > my_dict = {} > for key in keys: > my_dict[key] = (key, key) > list_of_dicts.append(my_dict) > new_clk = time.clock() > print i, new_clk - prev_clk > prev_clk = new_clk > > The difference is that instead of single values, tuples are added to > the dictionary instead. When the program is run again: > > 0 0.27 > 1 0.37 > 2 0.49 > 3 0.6 > ... > 16 2.32 > 17 2.45 > 18 2.54 > 19 2.68 > > The execution time is rising linearly with every new dictionary > created. > > Next experiment: dictionaries are not stored in a list, they are just > left out when an iteration has finished. It's done by removing two > lines: > > list_of_dicts = [] > > and > > list_of_dicts.append(my_dict) > > Full code: > > keys = [str(x) for x in range(200000)] > prev_clk = time.clock() > for i in range(20): > my_dict = {} > for key in keys: > my_dict[key] = (key, key) > new_clk = time.clock() > print i, new_clk - prev_clk > prev_clk = new_clk > > The time is constant again: > > 0 0.28 > 1 0.28 > 2 0.28 > 3 0.26 > 4 0.26 > > I see no reason for this kind of performance problem, really. It > happens when both things are true: dictionaries are kept in a list (or > more generally, in memory) and they store tuples. > > As this goes beyond my understanding of Python internals, I would like > to kindly ask, if anyone has an idea about how to create this data > structure (list of dictionaries of tuples, assuming that size of all > dictionaries is the same), in constant time? > > Regards, > Maciej Let me comment on what happens in you're code: The place where you create new objects is keys = [str(x) for x in range(200000)] # here you create 200000 strings which will be reused ( by reference ) and my_dict[key] = (key, key) # here you create a new tuple with 2 elements ( both are key, so you're taking a reference of existing key object twice ) The tricky part is where you wrote: for key in keys: my_dict[key] = (key, key) list_of_dicts.append(my_dict) # note that list_of_dicts.append is in the loop! check upstairs! This means that my_dict reference will be stored 200000 times, and it won't be released. statement my_dict = {} will always create new my_dict ( 20 times means 20 new dictionaries ) and start over. Since python caches free dictionaries ( after delete - they're used everywhere ), reuse won't happen, and memory will have to be allocated again. Lists are internally like arrays, when there is not enough space for next element, pointer array is doubled, so there is no huge penalty in the append function. Lists are also reused from some internal cache. Dictionaries also have a some growth function. When there is no space for next key, internal hash map doubles. The reason why you have a growing time comes from the fact that memory allocation takes place instead of object being used by reference. Check the memory usage, and you'll see that test time is pretty much proportional to overall memory usage. Regards, Bosko From python.leojay at gmail.com Fri May 4 08:16:00 2007 From: python.leojay at gmail.com (Leo Jay) Date: Fri, 4 May 2007 20:16:00 +0800 Subject: anyone has experience on cross-compile python 2.5.1? In-Reply-To: <4e307e0f0704300225t691e1ba3g436af126de63cef3@mail.gmail.com> References: <4e307e0f0704300225t691e1ba3g436af126de63cef3@mail.gmail.com> Message-ID: <4e307e0f0705040516keebf61fk6e51f0f9a14ace27@mail.gmail.com> On 4/30/07, Leo Jay wrote: > i have a development board based on s3c2410 arm cpu. and i want to > port python on it. > after googling some threads, i successfully cross compiled python. > but i still encountered a weird issue that when i ran > /lib/python2.5/test/testall.py, > the process stuck at test_asynchat.py, i located the stuck point here: > > def test_numeric_terminator(self): > # Try reading a fixed number of bytes > s = echo_server() > s.start()?????????# <----- stuck here !!! > time.sleep(1) # Give server time to initialize > c = echo_client(6L) > c.push("hello ") > c.push("world\n") > asyncore.loop() > s.join() > > > but the weirdest thing is, if i run python test_asynchat.py directly, > everything is ok. > anybody could help me? > > thanks in advance. > > ps, my linux box is an ubuntu 6.10. > hello, anybody could help me? thanks. -- Best Regards, Leo Jay From steve at REMOVEME.cybersource.com.au Wed May 2 22:04:11 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Thu, 03 May 2007 12:04:11 +1000 Subject: How to check if a string is empty in python? References: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> <1178154290.811928.208900@h2g2000hsg.googlegroups.com> Message-ID: On Wed, 02 May 2007 21:19:54 -0400, Roy Smith wrote: > for c in s: > raise "it's not empty" String exceptions are depreciated and shouldn't be used. http://docs.python.org/api/node16.html -- Steven D'Aprano From warren at muse.com Thu May 31 12:37:30 2007 From: warren at muse.com (Warren Stringer) Date: Thu, 31 May 2007 09:37:30 -0700 Subject: c[:]() In-Reply-To: <135tru124pie2b3@corp.supernews.com> References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com><1180554872.3356.30.camel@dot.uniqsys.com><465DF3DE.40404@cc.umanitoba.ca><1180566831.239580.199300@m36g2000hse.googlegroups.com><005401c7a31a$136f7fe0$240110ac@Muse><135tobve86qj808@corp.supernews.com> <135tru124pie2b3@corp.supernews.com> Message-ID: <002e01c7a3a1$fb4a6f50$240110ac@Muse> > How is it more expressive? In the context you're concerned > with, c[:] is the exactly same thing as c. You seem to be > worried about saving keystrokes, yet you use c[:] instead of c. > > It's like having an integer variable i and using ((i+0)*1) > instead of i. Nope, different. c[:] holds many behaviors that change dynamically. So c[:]() -- or the more recent go(c)() -- executes all those behaviors. This is very useful for many performers. The real world example that I'm working one is a collaborative visual music performance. So c can contain wrapped MIDI events or sequencer behaviors. c may get passed to a scheduler to execute those events, or c may get passed to a pickler to persist the performance. From ptmcg at austin.rr.com Fri May 11 22:34:09 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 11 May 2007 19:34:09 -0700 Subject: need help with python In-Reply-To: <1178934447.719778.197150@h2g2000hsg.googlegroups.com> References: <1178934447.719778.197150@h2g2000hsg.googlegroups.com> Message-ID: <1178937249.263856.191460@p77g2000hsh.googlegroups.com> On May 11, 8:47 pm, adamur... at hotmail.com wrote: > ya so im pretty much a newb to this whole python thing... its pretty > cool but i just started today and im already having trouble. i > started to use a tutorial that i found somewhere and i followed the > instructions and couldnt get the correct results. heres the code > stuff... > > temperature=input("what is the temperature of the spam?") > if temperature>50: > print "the salad is properly cooked." > else: > print "cook the salad some more." > > ya i was trying to do that but when i told it what the spams > temperature was, it just turned off... well it wasnt working at all at > first until i realized that i hadnt been following the instructions > completely correctly and that i was supposed to type that code up in a > notepad then save and open with python... so ya thats when it asked me > what temperature the spam was and i typed a number then it just closed > itself... im not really sure what went wrong... itd be real nice if > someone would be like a mentor or something... Well, this list has a varying level of mentoring and newbie-tolerance, with more latitude for people who have made some effort to start with before posting things like "here's my homework problem, please send me the working code so I can hand it in." I just ran your code interactively at the Python prompt, and it runs just fine. See? >>> temperature=input("what is the temperature of the spam?") what is the temperature of the spam?55 >>> if temperature>50: ... print "the salad is properly cooked." ... else: ... print "the salad is properly cooked." ... the salad is properly cooked. I think the problem you are having is that, when you run your program by double-clicking on the xyz.py file in a file browser, the OS (Windows, I assume?) opens a separate console window, and runs the program, and then at the end of the program, CLOSES the window. I think your code is running just fine, I think your "the salad is whatever" messages get printed out, but afterward, your program ends, so the window closes before you can see how your salad turned out. A simple workaround you can do is to add to the end of your program this statement: input("") This will cause the process to stop and wait for you to press the RETURN key, giving you time to stop and admire your salad results before closing the window. One final note: many people post in a "write like I talk" style. This is okay while telling your story ("well it wasn't working at all at first..."), and the ee cummings all-lower-case is passable, but please drop the "ya"s. They are a verbal tic that may be okay in person, but do not translate at all to written posts. At least you don't say "like" every other word, and I thank you for that! :) You can get a sense of other writing styles by reading through the comp.lang.python archives. I would also recommend that you might find more folks in the "just getting started" phase posting to the python- tutor mailing list (go to http://mail.python.org/mailman/listinfo/tutor), and you can skim through posts there for many introductory topics. Good luck to you, and welcome to Python! -- Paul From toby at tobiah.org Tue May 1 16:45:00 2007 From: toby at tobiah.org (Tobiah) Date: Tue, 01 May 2007 13:45:00 -0700 Subject: I wish that [].append(x) returned [x] Message-ID: <46379a41$0$25252$88260bb3@free.teranews.com> I wanted to do: query = "query text" % tuple(rec[1:-1].append(extra)) but the append() method returns none, so I did this: fields = rec[1:-1] fields.append(extra) query = "query text" % tuple(fields) -- Posted via a free Usenet account from http://www.teranews.com From gagsl-py2 at yahoo.com.ar Wed May 16 19:15:59 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 16 May 2007 20:15:59 -0300 Subject: refcount differences in 2.5 Message-ID: Hi With Python 2.5, there is a change on the reference count of objects compared with previous versions (as reported by sys.getrefcount). All Python versions from 2.1 thru 2.4 gave these same results: Python 2.1.3 (#35, Apr 8 2002, 17:47:50) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. >>> import sys >>> sys.getrefcount(11111111) 2 >>> sys.getrefcount(11111111+1) 1 >>> x=22222222 >>> sys.getrefcount(x) 2 >>> sys.getrefcount(x+1) 1 >>> sys.getrefcount("A unique *str-ing*") 2 >>> sys.getrefcount("A unique *str-ing*".upper()) 1 >>> sys.getrefcount(3+2j) 1 >>> class W: pass ... >>> x=W() >>> sys.getrefcount(x) 2 >>> sys.getrefcount(W()) 1 >>> But Python 2.5 (2.5.1 not tested yet) gives different results: Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win 32 >>> import sys >>> sys.getrefcount(11111111) 3 >>> sys.getrefcount(11111111+1) 2 >>> x=22222222 >>> sys.getrefcount(x) 2 >>> sys.getrefcount(x+1) 1 >>> sys.getrefcount("A unique *str-ing*") 3 >>> sys.getrefcount("A unique *str-ing*".upper()) 1 >>> sys.getrefcount(3+2j) 2 >>> class W: pass ... >>> x=W() >>> sys.getrefcount(x) 2 >>> sys.getrefcount(W()) 1 >>> In particular, I wonder why getrefcount(12341234) returns 3 instead of 2 - who is holding the extra reference? My main two concerns are: - is there a reference leak somewhere? - it's a bit harder to debug my own references since I don't know beforehand the value I should expect from sys.getrefcount() -- Gabriel Genellina From thorsten at thorstenkampe.de Tue May 15 08:42:39 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 15 May 2007 13:42:39 +0100 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <1hy2qg3.iqfvwnrvr9kjN%aleax@mac.com> <46482624.6050507@web.de> <7xd512onsx.fsf@ruckus.brouhaha.com> <464951EF.7030900@web.de> <464997a5$0$10193$9b4e6d93@newsspool4.arcor-online.net> <4649a561$0$10187$9b4e6d93@newsspool4.arcor-online.net> <4649a914$0$10186$9b4e6d93@newsspool4.arcor-online.net> Message-ID: * Ren? Fleschenberg (Tue, 15 May 2007 14:35:33 +0200) > Thorsten Kampe schrieb: > >> It is impossible to write Python in a native language other than English > >> even with the implementation of this PEP. All you get is a weird mixture > >> of English identifiers from various libraries and identifiers in your > >> native language. > > > > You have a few English keywords that are not meant to be understood > > but can be learned. > > I am talking about the stdlib, not about the very few keywords Python > has. Are you going to re-write the standard library in your native > language so you can have a consistent use of natural language among your > code? Why would I want to do that? It's not my code. Identifier names are mine. If I use modules from standard library I use some "foreign words". There's no problem in that. From __peter__ at web.de Sat May 26 02:16:22 2007 From: __peter__ at web.de (Peter Otten) Date: Sat, 26 May 2007 08:16:22 +0200 Subject: csv.reader length? References: <1180118981.024036.163590@p47g2000hsd.googlegroups.com> <1180122583.282729.275840@p47g2000hsd.googlegroups.com> Message-ID: Larry Bates wrote: > Did you try: > > import crystal_ball > > num_lines=crystal_ball(reader) Yes. The answer was a little more comprehensive than I had asked for. >>> print num_lines 42 Peter From castironpi at gmail.com Thu May 10 03:43:34 2007 From: castironpi at gmail.com (castironpi at gmail.com) Date: 10 May 2007 00:43:34 -0700 Subject: the inspect thing Message-ID: <1178783014.146762.259420@q75g2000hsh.googlegroups.com> -----the code: class A: b=2 import inspect print inspect.getsource(A) class A: c=2 print inspect.getsource(A) -----unavailable from the console, but gets you: class A: b=2 class A: b=2 One thought is, in inspect, could at least: def findsource(object): #snip if candidates: # this will sort by whitespace, and by line number, # less whitespace first candidates.sort() return lines, candidates[0][1] be return lines, candidates[-1][1] to get the most recent? Why no cl_firstlineno in the object for the class, or access to the code?-acb From sjmachin at lexicon.net Thu May 24 08:14:22 2007 From: sjmachin at lexicon.net (John Machin) Date: 24 May 2007 05:14:22 -0700 Subject: Changing Unicode object to Tuple Type In-Reply-To: <1180007132.103030.149770@q66g2000hsg.googlegroups.com> References: <1180007132.103030.149770@q66g2000hsg.googlegroups.com> Message-ID: <1180008862.478576.191850@u30g2000hsc.googlegroups.com> On May 24, 9:45 pm, laxmikiran.ba... at gmail.com wrote: > Can we have change a unicode string Type object to a Tuple type > object.. If so how ???? >>> x = u'fubar' >>> y = tuple(x) >>> y (u'f', u'u', u'b', u'a', u'r') >>> type(x) >>> type(y) >>> But I'm quite sure that's not the question you should be asking :-) From john at datavoiceint.com Tue May 8 16:11:20 2007 From: john at datavoiceint.com (HMS Surprise) Date: 8 May 2007 13:11:20 -0700 Subject: chdir() In-Reply-To: References: <1178652809.436141.176900@u30g2000hsc.googlegroups.com> Message-ID: <1178655080.685389.33640@q75g2000hsh.googlegroups.com> On May 8, 3:06 pm, Carsten Haese wrote: > On Tue, 2007-05-08 at 12:54 -0700, HMS Surprise wrote: > > Tried executing os.chdir("c:\twill") from a python Tk shell and got > > the error message: > > > WindowsError: [Error 123] The filename, directory name, or volume > > label syntax is incorrect: 'c:\twill'. > > Backslash-t is a tab character, so you're trying to chdir to > C:will, which is not a valid path name. Use a forward slash, double > up the backslash, or use a raw string literal: > > os.chdir("c:/twill") > os.chdir("c:\\twill") > os.chdir(r"c:\twill") > > HTH, > > -- > Carsten Haesehttp://informixdb.sourceforge.net Thanks all. Windows bytes me again. I know better just wasn't thinking. \n From cbmeeks at gmail.com Mon May 21 08:54:40 2007 From: cbmeeks at gmail.com (cbmeeks) Date: 21 May 2007 05:54:40 -0700 Subject: Simple web apps....mod_python or framework? Message-ID: <1179752080.489657.102310@a26g2000pre.googlegroups.com> If you guys where going to do a simple web-app (as in, 4-5 tables with 99% being simple CRUD), would you use a framework (Django, CodeIgniter, whatever...) or would you do it using maybe mod_python and Python code? Just curious. I'm trying to learn Python but some of the frameworks make CRUD super easy (not that Python is hard for that...lol) Thanks http://www.signaldev.com From ruoyu0088 at gmail.com Wed May 16 06:17:56 2007 From: ruoyu0088 at gmail.com (HYRY) Date: 16 May 2007 03:17:56 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179226183.215907.140450@q75g2000hsh.googlegroups.com> Message-ID: <1179310676.874677.22450@e65g2000hsc.googlegroups.com> > How do you feel about the mix of English keywords and Chinese? > How does the English - like "sentences " look to a Chinese? > > Would you support the extension of this PEP to include Chinese > Keywords? > > Would that be a lesser or greater gift? > Because the students can remember some English words, Mixing characters is not a problem. But it's difficult to express their own thought or logic in English or Pinyin(only mark the pronunciation of the Chinese character). As my experience, I found mixing identifiers of Chinese characters and keywords of English is very easy for reading. Because the large difference between Chinese characters and ASCII characters, I can distinguish my identifiers with keywords and library words quickly. From nagle at animats.com Fri May 4 12:19:57 2007 From: nagle at animats.com (John Nagle) Date: Fri, 04 May 2007 16:19:57 GMT Subject: Why are functions atomic? In-Reply-To: <1178260571.160570.299160@p77g2000hsh.googlegroups.com> References: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> <1178044821.864741.235260@o5g2000hsb.googlegroups.com> <1178063341.779617.289690@o5g2000hsb.googlegroups.com> <1178065685.161372.81790@y80g2000hsf.googlegroups.com> <1178083318.404304.76100@q75g2000hsh.googlegroups.com> <1178260571.160570.299160@p77g2000hsh.googlegroups.com> Message-ID: Michael wrote: > On May 2, 6:08 am, Carsten Haese wrote: > >>On Tue, 2007-05-01 at 22:21 -0700, Michael wrote: > I agree the performance gains are minimal. Using function defaults > rather than closures, however, seemed much cleaner an more explicit to > me. For example, I have been bitten by the following before: > >>>>def f(x): > > ... def g(): > ... x = x + 1 Too cute. Don't nest functions in Python; the scoping model isn't really designed for it. >>An overriding theme in this thread is that you are greatly concerned >>with the speed of your solution rather than the structure and >>readability of your code. ... > > @define_options(first_option='abs_tol') > def step(f,x,J,abs_tol=1e-12,rel_tol=1e-8,**kwargs): > """Take a step to minimize f(x) using the jacobian J. > Return (new_x,converged) where converged is true if the tolerance > has been met. > """ Python probably isn't the right language for N-dimensional optimization if performance is a major concern. That's a very compute-intensive operation. I've done it in C++, with heavy use of inlines, and had to work hard to get the performance up. (I was one of the first to do physics engines for games and animation, which is a rather compute-intensive problem.) If you're doing number-crunching in Python, it's essential to use NumPy or some other C library for matrix operations, or it's going to take way too long. John Nagle From R.Brodie at rl.ac.uk Fri May 25 09:15:03 2007 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Fri, 25 May 2007 14:15:03 +0100 Subject: just a bug (was: xml.dom.minidom: how to preserve CRLF's inside CDATA?) References: <1179841504.782279.86490@u36g2000prd.googlegroups.com> <1180082137.329142.45350@p77g2000hsh.googlegroups.com> Message-ID: "Neil Cerutti" wrote in message news:slrnf5do1c.1g8.horpner at FIAD06.norwich.edu... > Web browsers are in the very business of reasonably rendering > ill-formed mark-up. It's one of the things that makes > implementing a browser take forever. ;) For HTML, yes. it accepts all sorts of garbage, like most browsers; I've never, before now, seen it accept an invalid XML document though. From steven.bethard at gmail.com Sat May 19 15:17:22 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 19 May 2007 13:17:22 -0600 Subject: docs patch: dicts and sets In-Reply-To: <1179593927.503393.127350@u30g2000hsc.googlegroups.com> References: <_5-dnU7aIN73j9LbnZ2dnUVZ_uCinZ2d@comcast.com> <1179593927.503393.127350@u30g2000hsc.googlegroups.com> Message-ID: 7stud wrote: > On May 19, 9:06 am, Steven Bethard wrote: >> Alan Isaac wrote: >>> I submitted the language based on Bill and Carsten's proposals: >>> https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1721372&... >>> That language has been rejected. >>> You many want to read the discussion and see if >>> acceptible language still seems discoverable. >> Seems to me that you're focusing on the wrong part of the docs. The >> source of this "bug" is not sets or dicts, but the default __hash__ >> method implementation. Why don't you propose adding something like: >> >> The default __hash__ method is based on an object's id(), and can >> therefore change between different iterations of the same program. >> >> to the docs for __hash__: >> >> http://docs.python.org/ref/customization.html >> >> Then if you really feel you need to add something for sets and dicts, >> you can add a cross-reference to the __hash__ docs. > > Here's an idea--add All the proposed changes to the docs. Why not > allow user's to add any explanations to the docs that they want? Then > readers can choose the explanations that make the most sense to them. > It would eliminate endless, petty discussions about what minutiae are > more important, and it would allow people to spend their time on more > productive efforts. Actually, it would just move the "endless, petty discussions about what minutiae are more important" into the docs. I don't see how that's an improvement. STeVe From grante at visi.com Thu May 24 10:14:37 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 24 May 2007 14:14:37 -0000 Subject: 0 == False but [] != False? References: <1179982400.412340.178710@g4g2000hsf.googlegroups.com> <1rda53hphn117k5scvcqrc7c2e37utfhgu@4ax.com> Message-ID: <135b7edigd80j18@corp.supernews.com> On 2007-05-24, Rex Turnbull wrote: > Steven D'Aprano : >> On Thu, 24 May 2007 06:59:32 +0000, Tim Roberts wrote: >> >>> As a general rule, I've found code like "if x == False" to be a bad idea in >>> ANY language. >> >> >> Surely that should be written as "if (x == False) == True"? > > Why compare to False? That's a joke... I say, that's a joke, son! He was being sarcastic. -- Grant Edwards grante Yow! The FALAFEL SANDWICH at lands on my HEAD and I visi.com become a VEGETARIAN ... From grante at visi.com Tue May 15 12:03:08 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 15 May 2007 16:03:08 -0000 Subject: File record separators. References: <1179241525.667682.112220@y80g2000hsf.googlegroups.com> Message-ID: <134jmdssitvrp94@corp.supernews.com> On 2007-05-15, HMS Surprise wrote: > I need to write 2 member lists to a file. For each record the number > of these lists can be different. I think a good way to handle that may > be to make each record a list of lists. I am restricted to using > version 2.2. That being the case what is a good standard record > separator to use to ensure that I read in one record (list of lists) > at a time, '\n'? I want to try to stay with what is considered > standard python idioms. Your description is a bit vague, but if I'm guessing your task correctly, the standard idiom is to use the pickle module: http://www.python.org/doc/2.2.3/lib/module-pickle.html You can use it to write pretty much any python object to a file. -- Grant Edwards grante Yow! Nipples, dimples, at knuckles, NICKLES, visi.com wrinkles, pimples!! From zefria at gmail.com Wed May 30 22:54:59 2007 From: zefria at gmail.com (Daniel Gee) Date: 30 May 2007 19:54:59 -0700 Subject: paste text with newlines into raw_input? In-Reply-To: <1180559052.806975.154890@h2g2000hsg.googlegroups.com> References: <1180559052.806975.154890@h2g2000hsg.googlegroups.com> Message-ID: <1180580099.457332.269320@q19g2000prn.googlegroups.com> #!/usr/bin/python print "paste quote:" emptycount = 0 lines = [] while emptycount < 2: t = raw_input() if len(t) == 0: emptycount +=1 else: emptycount=0 lines.append(t) lines.append("\n") quote = " ".join(lines[:-3]) print "Quote was this:" print "===============" print quote print "===============" From hq4ever at gmail.com Sun May 6 10:00:18 2007 From: hq4ever at gmail.com (Maxim Veksler) Date: Sun, 6 May 2007 17:00:18 +0300 Subject: Init style output with python? In-Reply-To: <1cqdnYjjQ7YH6aDbRVnzvQA@telenor.com> References: <1cqdnYjjQ7YH6aDbRVnzvQA@telenor.com> Message-ID: On 5/6/07, Tina I wrote: > Maxim Veksler wrote: > > > Is there are frame work or something in python that would allow me to > > do this (quickly) ? > > If not, ideas how I should I be getting this boring task of: > > 1. get screen width > > You can look into the 'curses' module and do something like: > > screen = curses.initscreen() > maxheight, maxwith = screen.getmaxyx() > > In my experience curses can be a bit tricky to work with but the online > tutorials have some nice examples that help you avoid some of the > pitfalls (like messing up your terminal) > > Tina > -- > http://mail.python.org/mailman/listinfo/python-list > Fine! Thank you. curses is very helpful, I'm attaching the code. I see it has support for colors as well, but I haven't found any tutorial that would explain how to use them. Please note that this is just a draft, I'm not catching any KeyboardInterrupt nor nothing. """#!/usr/bin/env python class ColorTerm: def __init__(self, Mono = False): pass def __get_tput_color_value__(colorcode): from commands import getoutput return getoutput('tput setaf ' + colorcode) BLACK_FG = __get_tput_color_value__('0') RED_FG = __get_tput_color_value__('1') GREEN_FG = __get_tput_color_value__('2') YELLOW_FG = __get_tput_color_value__('3') BLUE_FG = __get_tput_color_value__('4') MAGENTA_FG = __get_tput_color_value__('5') CYAN_FG = __get_tput_color_value__('6') WHITE_FG = __get_tput_color_value__('7') def black(self, msg): return self.BLACK_FG + msg + self.BLACK_FG def red(self, msg): return self.RED_FG + msg + self.BLACK_FG def green(self, msg): return self.GREEN_FG + msg + self.BLACK_FG def yellow(self, msg): return self.YELLOW_FG + msg + self.BLACK_FG def blue(self, msg): return self.BLUE_FG + msg + self.BLACK_FG def magenta(self, msg): return self.MAGENTA_FG + msg + self.BLACK_FG def cyan(self, msg): return self.CYAN_FG + msg + self.BLACK_FG def white(self, msg): return self.WHITE_FG + msg + self.BLACK_FG class StatusWriter(ColorTerm): import curses def __init__(self, report_type = None): pass def initstyle_message(self, msg, status = True): screen = self.curses.initscr(); self.curses.endwin() if status: status_msg = '[' + self.green('OK') + ']' else: status_msg = '[' + self.red('FAIL') + ']' spaces_count = ( screen.getmaxyx()[1] - (len(msg)+len(status_msg)) ) return msg + ' '*spaces_count + status_msg cc = StatusWriter() while 1: print cc.initstyle_message('The end is at hand') print cc.initstyle_message('Lets party', False) print cc.initstyle_message('Why like this?', True) """ -- Cheers, Maxim Veksler "Free as in Freedom" - Do u GNU ? From iltchevi at gmail.com Thu May 24 11:25:18 2007 From: iltchevi at gmail.com (ici) Date: 24 May 2007 08:25:18 -0700 Subject: Bootstrapping In-Reply-To: <1180018414.715769.142750@p77g2000hsh.googlegroups.com> References: <1180018414.715769.142750@p77g2000hsh.googlegroups.com> Message-ID: <1180020318.432768.170850@w5g2000hsg.googlegroups.com> On May 24, 5:53 pm, Mauler wrote: > I need some help with adding bootstrap code to the core of python, the > idea is to leave a super base core inside a zip file (python25.zip > works right out of the box) and leave the rest in separate zip > modules. Making it more friendly with pendrives and more practical as > a standalone runtime (ie, without install) and fully modular. The > thing is that i need to modify the base importer to add this special > "site-packages" . > Any hints? > thanks in advance (and a lot!) > > Martin Rene Vilugron > Patagonia Argentina http://pyinstaller.python-hosting.com/ ? From rw at smsnet.pl Tue May 1 17:36:43 2007 From: rw at smsnet.pl (Rob Wolfe) Date: Tue, 01 May 2007 23:36:43 +0200 Subject: read list of dirnames and search for filenames References: <1178051721.935868.194700@o5g2000hsb.googlegroups.com> <87d51kgs4l.fsf@smsnet.pl> Message-ID: <878xc8gr9w.fsf@smsnet.pl> Rob Wolfe writes: > fscked writes: > >> I cannot seem to get this to work. I am hyst trying to read in a list >> of paths and see if the directory or any sub has a filename pattern. >> Here is the code: >> >> import os, sys >> from path import path >> >> myfile = open("boxids.txt", "r") >> for line in myfile.readlines(): And you don't need to use ``readlines`` at all. This is enough: for line in myfile: -- HTH, Rob From revuesbio at gmail.com Mon May 7 08:00:02 2007 From: revuesbio at gmail.com (revuesbio) Date: 7 May 2007 05:00:02 -0700 Subject: msbin to ieee In-Reply-To: <1178536910.566119.6650@o5g2000hsb.googlegroups.com> References: <1178487847.671199.108140@h2g2000hsg.googlegroups.com> <1178502738.104124.3840@h2g2000hsg.googlegroups.com> <1178525916.145819.264070@n59g2000hsh.googlegroups.com> <1178536910.566119.6650@o5g2000hsb.googlegroups.com> Message-ID: <1178539202.316506.199940@p77g2000hsh.googlegroups.com> On 7 mai, 13:21, John Machin wrote: > On May 7, 6:18 pm, revuesbio wrote: > > > > > On 7 mai, 03:52, John Machin wrote: > > > > On May 7, 7:44 am, revuesbio wrote: > > > > > Hi > > > > Does anyone have the python version of the conversion from msbin to > > > > ieee? > > > > Thank u > > > > Yes, Google has it. Google is your friend. Ask Google. It will lead > > > you to such as: > > > >http://mail.python.org/pipermail/python-list/2005-August/337817.html > > > > HTH, > > > John > > > Thank you, > > > I've already read it but the problem is always present. this script is > > for double precision MBF format ( 8 bytes). > > It would have been somewhat more helpful had you said what you had > done so far, even posted your code ... > > > I try to adapt this script for single precision MBF format ( 4 bytes) > > but i don't find the right float value. > > > for example : 'P\xad\x02\x95' will return '0.00024924660101532936' > > If you know what the *correct* value is, you might like to consider > shifting left by log2(correct_value/erroneous_value) :-) > > Do you have any known correct pairs of (mbf4 string, decimal_float > value)? My attempt is below -- this is based on a couple of > descriptive sources that my friend Google found, with no test data. I > believe the correct answer for the above input is 1070506.0 i.e. you > are out by a factor of 2 ** 32 > > def mbf4_as_float(s): > m0, m1, m2, m3 = [ord(c) for c in s] > exponent = m3 > if not exponent: > return 0.0 > sign = m2 & 0x80 > m2 |= 0x80 > mant = (((m2 << 8) | m1) << 8) | m0 > adj = 24 + 128 > num = mant * 2.0 ** (exponent - adj) > if sign: > return -num > return num > > HTH, > John well done ! it's exactly what i'm waiting for !! my code was: >>> from struct import * >>> x = list(unpack('BBBB','P\xad\x02\x95')) >>> x [80, 173, 2, 149] >>> def conversion1(bytes): b=bytes[:] sign = bytes[-2] & 0x80 b[-2] |= 0x80 exp = bytes[-1] - 0x80 - 56 acc = 0L for i,byte in enumerate(b[:-1]): acc |= (long(byte)<<(i*8)) return (float(acc)*2.0**exp)*((1.,-1.)[sign!=0]) >>> conversion1(x) 0.00024924660101532936 this script come from google groups but i don't understand bit-string manipulation (I'm a newbie). informations about bit-string manipulation with python is too poor on the net. thank you very much for your script. A. From __peter__ at web.de Mon May 28 08:10:40 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 28 May 2007 14:10:40 +0200 Subject: Issue of redirecting the stdout to both file and screen References: <1180343858.903251.182490@x35g2000prf.googlegroups.com> Message-ID: Gabriel Genellina wrote: > En Mon, 28 May 2007 06:17:39 -0300, ??????????????? > escribi?: > >> I wanna print the log to both the screen and file, so I simulatered a >> 'tee' >> >> class Tee(file): >> >> def __init__(self, name, mode): >> file.__init__(self, name, mode) >> self.stdout = sys.stdout >> sys.stdout = self >> >> def __del__(self): >> sys.stdout = self.stdout >> self.close() >> >> def write(self, data): >> file.write(self, data) >> self.stdout.write(data) >> >> Tee('logfile', 'w') >> print >>sys.stdout, 'abcdefg' >> >> I found that it only output to the file, nothing to screen. Why? >> It seems the 'write' function was not called when I *print* something. > > You create a Tee instance and it is immediately garbage collected. It is not garbage collected until the next assignment to sys.stdout. Peter From showell30 at yahoo.com Sun May 27 18:10:34 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 27 May 2007 15:10:34 -0700 (PDT) Subject: Newbie question - better way to do this? In-Reply-To: <1180302942.215945.58090@a26g2000pre.googlegroups.com> Message-ID: <270332.28899.qm@web33507.mail.mud.yahoo.com> --- John Machin wrote: (And you can > > > ignore the fact that > > > it won't find a sequence at the very end of > words, that is fine for my > > > purposes). > > [...] > > Bzzzt. Needs the following code at the end: > if accumulator: > doSomething(accumulator) > FWIW the OP already conceded that bug, but you're right that it's a common anti-pattern, which is just a nice word for bug. :) The itertools.groupby() function is a well-intended attempt to steer folks away from this anti-pattern, although I think it has usability issues, mostly related to the docs (see other thread). ____________________________________________________________________________________Building a website is a piece of cake. Yahoo! Small Business gives you all the tools to get online. http://smallbusiness.yahoo.com/webhosting From gagsl-py2 at yahoo.com.ar Mon May 28 12:23:39 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 28 May 2007 13:23:39 -0300 Subject: Good idea to use a class as function with __new__? References: <1180354650.472117.144430@p77g2000hsh.googlegroups.com> Message-ID: En Mon, 28 May 2007 09:17:30 -0300, glomde escribi?: > I am implementing som code generation and want to to use some variant > of the template method pattern. > > What I came up with is to have a class with the common part > in a method and the subclasses can then override the Customize methods > to do their own special part. > > Now to the question I use the __new__ to return the result instead > of the instance. So that the class is used as an function. It works, and I don't see any big problems, but I don't *like* that. I'd use __call__ instead; that is, write __new__ and __init__ normally -if you need them at all- and move the magic to __call__: def __call__(self, *args, **kwds): return self.__TemplateMethod(*args, **kwds) x = Template()(prefix="foo") or perhaps: x = Template(prefix="foo")() I think the extra () improves readability - it's clear that x comes from a function call, it's not a Template instance as one would expect from your original code. And depending on the application, you could keep the instances and call them with different arguments - with the original code you always create a new instance just to discard it immediately. -- Gabriel Genellina From sjmachin at lexicon.net Wed May 9 08:54:42 2007 From: sjmachin at lexicon.net (John Machin) Date: 9 May 2007 05:54:42 -0700 Subject: error in the if, elif, else statement ? In-Reply-To: <1178696786.705128.320750@l77g2000hsb.googlegroups.com> References: <1178696786.705128.320750@l77g2000hsb.googlegroups.com> Message-ID: <1178715282.772588.23710@p77g2000hsh.googlegroups.com> On May 9, 5:46 pm, juan-manuel.behre... at siemens.com wrote: > Hello together, > > I wrote a script for the engineering software abaqus/CAE. It worked > well until I implemented a selection in order to variate the variable > "lGwU" through an if elif, else statement. I am going to post the > first 82 lines of the script, since the error message points at line > 80: > > from abaqusConstants import * > from abaqus import * > > def CreateSchraube(name, l, flag=None, flag2=None): > import part > vp = session.currentViewportName > model = session.sessionState[vp]['modelName'] > m = mdb.models[model] > s = m.ConstrainedSketch(name='__profile__', sheetSize=1000.0) > s.ConstructionLine(point1=(0.0, -500.0), point2=(0.0, 500.0)) > > if flag==1: > > dh = 15.0 > z = 15.0 > dz = 60.0 > d = 72.0 > f = 1.0 > dD = f*62.0 > lGwO = 110.0 > > if flag2==11: # here appears the > beginning of the new impletation in order to variate lGwU > lGwU = 0.8*d # you can see these inner > if, elif, else statement 4 times, because > elif flag2==12: # the outer if, elif, > else statement (which works!) has 4 cases You have an error in your code (flag instead of flag2). Your coding style is not conducive to ease of maintenance and avoidance of errors. Here are some suggestions: Rip out the three-fold repetition of the same code, replace that code by: assert 11 <= flag2 <= 13 lGwU = (flag2 * 0.2 - 1.4) * d and move it down the end. Also get rid of any remaining instances of "else: pass". Then consider replacing all those tedious assignments ... data = ( (15., 15., 60, ..........), (.........), etc, etc, ) assert 1 <= flag <= len(data) == 4 dh, z, dz, ...... = data[flag-1] Then chose some meaningful names instead of flag and flag2. From bscrivener42 at gmail.com Tue May 15 08:22:58 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: 15 May 2007 05:22:58 -0700 Subject: Iron Python In-Reply-To: <1179224521.550517.271820@e51g2000hsg.googlegroups.com> References: <464981fa$0$8759$ed2619ec@ptn-nntp-reader02.plus.net> <1179224521.550517.271820@e51g2000hsg.googlegroups.com> Message-ID: <1179231778.899533.78590@u30g2000hsc.googlegroups.com> On May 15, 5:22 am, John Machin wrote: > > > Anybody tried it? > > > Me. > > Me too. Anybody like it? rd From carsten at uniqsys.com Sun May 27 20:31:28 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sun, 27 May 2007 20:31:28 -0400 Subject: itertools.groupby In-Reply-To: <969509.18645.qm@web33508.mail.mud.yahoo.com> References: <969509.18645.qm@web33508.mail.mud.yahoo.com> Message-ID: <1180312288.3155.19.camel@localhost.localdomain> On Sun, 2007-05-27 at 14:59 -0700, Steve Howell wrote: > Huh? How is code that uses itertools.groupby not an > actual example of using itertools.groupby? Here's how: """ The returned group is itself an iterator that shares the underlying iterable with groupby(). Because the source is shared, when the groupby object is advanced, the previous group is no longer visible. So, if that data is needed later, it should be stored as a list: groups = [] uniquekeys = [] for k, g in groupby(data, keyfunc): groups.append(list(g)) # Store group iterator as a list uniquekeys.append(k) """ It does not say "Here is an example for how to use itertools.groupby." It's an abstract code pattern for an abstract use case. There is an example on the following page, called Examples! > These docs need work. Please do not defend them; The docs do their job in specifying what groupby does. Providing code snippets is not the job of the documentation. There are plenty of other resources with code snippets. To name just one, there's an example of itertools.groupby in the last code snippet at http://informixdb.blogspot.com/2007/04/power-of-generators-part-two.html > please suggest improvements. Why should I? The docs suit my needs just fine. Of course, that shouldn't stop you from suggesting improvements. Best regards, -- Carsten Haese http://informixdb.sourceforge.net From jscrerar at compuserve.com Sun May 13 09:28:17 2007 From: jscrerar at compuserve.com (Jim) Date: 13 May 2007 06:28:17 -0700 Subject: Video: Professor of Physics Phd at Cal Tech says: 911 Inside Job In-Reply-To: References: <1177467203.719625.93920@u32g2000prd.googlegroups.com> <1177780530.539758.275660@c35g2000hsg.googlegroups.com> <1177788032.971421.65550@c35g2000hsg.googlegroups.com> Message-ID: <1179062897.070612.309910@k79g2000hse.googlegroups.com> On Apr 29, 4:19 pm, Mitchell Jones wrote: > In article <1177788032.971421.65... at c35g2000hsg.googlegroups.com>, > War Office <911falsef... at gmail.com> wrote: > > > On 28 abr, 14:15, Eric Gisse wrote: > > > On Apr 24, 6:13 pm, stj... at rock.com wrote: > > [snip] > > > > I love how folks like you ask for intellectual honesty when every > > > effort is made to ignore evidence that doesn't agree with your > > > presupposed findings. > > > Which evidence would that be? > > ***{I'm not a fan of the Bush administration, and would not put it past > them to carry out an event such as 911, to create an excuse to jettison > the Constitution and Bill of Rights. What is certain in any case is > that, in fact, the Bush administration has used the events of 911 as an > excuse to toss out the Constitution and Bill of Rights. There are, > however, at least three possible scenarios regarding 911 itself: > > (1) The plane crashes were planned and executed by terrorists. The > towers fell because of the impacts. Building 7 fell because of the > impact of debris from the north tower. > > (2) The plane crashes were planned and executed by the Bush > administration. The towers fell because of the impacts. Building 7 fell > because of the impact of debris from the north tower. > > (3) The plane crashes were planned and executed by the Bush > administration. The towers fell because of the impacts, plus the effects > of pre-planted demolition charges. Building 7 fell because of the impact > of debris from the north tower, plus the effects of pre-planted > explosive charges. > > I analyzed (3), above, in great detail a month or so back, in a > sci.physics thread entitled "The amazing denial of what "conspiracy > kooks" really means...." If you are really interested in a reasoned > response to those arguments, you can probably still find that thread on > Google. > > My conclusion at the time was that possibility (3), above, fails because > pre-planted explosives are not needed to explain why the towers fell, or > why building 7 fell. Possibilities (1) and (2), therefore, are all that > remains. > > This post is for informational purposes only, and is not to be taken as > an indication that I am interesting in slogging my way through all this > stuff again. Once is more than enough, and so I am killfiling this > thread after making this post. > > --Mitchell Jones}*** > > ***************************************************************** > If I seem to be ignoring you, consider the possibility > that you are in my killfile. --MJ What has all this got to do with Python? From walterbyrd at iname.com Sat May 19 02:24:15 2007 From: walterbyrd at iname.com (walterbyrd) Date: 18 May 2007 23:24:15 -0700 Subject: Python compared to other language In-Reply-To: References: <1179540061.598417.13870@y80g2000hsf.googlegroups.com> Message-ID: <1179555855.410877.51390@k79g2000hse.googlegroups.com> On May 18, 8:28 pm, Steve Holden wrote: > Surely the fact that Python is available on so many platforms implies > that C is a fairly portable language. Unless it's the same C code, I don't see how that means anything. If I write an app on Windows with C, and I rewrite the same app on UNIX with C - that doesn't mean the C code has been ported. My guess is that some of the C code used to develop Python is the same between the different Python distros, but much of the code is unique to the particular platform. If that is the case, then the C code may not be very portable. But, I can often take the same python code, and run it on MacOS, Linux, FreeBSD, and Windows. Often I can do this even if the app has a gui interface. From stefan.sonnenberg at pythonmeister.com Fri May 11 05:14:22 2007 From: stefan.sonnenberg at pythonmeister.com (Stefan Sonnenberg-Carstens) Date: Fri, 11 May 2007 11:14:22 +0200 (CEST) Subject: Simple Tkinter Progress Bar In-Reply-To: <890234.75240.qm@web62008.mail.re1.yahoo.com> References: <890234.75240.qm@web62008.mail.re1.yahoo.com> Message-ID: <1068189.60418.BlRUCl8VTQA=.1178874862.squirrel@webmailer.hosteurope.de> On Fr, 11.05.2007, 08:42, Gurpreet Singh wrote: > Hi > > I am a newbie in Python > > I am creating a simple Tkinter based application. > I have written Tkinter GUI source code and the > programme logic in the same .py file. > > I am searching for a way to implement a simple > Progress bar for my application. > > Are there any simple ways of doin it. > > > > > > ____________________________________________________________________________________Yahoo! > oneSearch: Finally, mobile search > that gives answers, not web links. > http://mobile.yahoo.com/mobileweb/onesearch?refer=1ONXIC > -- > http://mail.python.org/mailman/listinfo/python-list > > Please see this: http://tkinter.unpythonic.net/wiki/ProgressBar From sjmachin at lexicon.net Thu May 17 17:06:03 2007 From: sjmachin at lexicon.net (John Machin) Date: 17 May 2007 14:06:03 -0700 Subject: Regexes: How to handle escaped characters In-Reply-To: <87irarqkz7.fsf@wilson.homeunix.com> References: <87tzubqniq.fsf@wilson.homeunix.com> <87irarqkz7.fsf@wilson.homeunix.com> Message-ID: <1179435962.962404.191600@y80g2000hsf.googlegroups.com> On May 18, 6:00 am, Torsten Bronger wrote: > Hall?chen! > > James Stroud writes: > > Torsten Bronger wrote: > > >> I need some help with finding matches in a string that has some > >> characters which are marked as escaped (in a separate list of > >> indices). Escaped means that they must not be part of any match. > > >> [...] > > > You should probably provide examples of what you are trying to do > > or you will likely get a lot of irrelevant answers. > > Example string: u"Hollo", escaped positions: [4]. Thus, the second > "o" is escaped and must not be found be the regexp searches. > > Instead of re.search, I call the function guarded_search(pattern, > text, offset) which takes care of escaped caracters. Thus, while > > re.search("o$", string) > > will find the second "o", > > guarded_search("o$", string, 0) Huh? Did you mean 4 instead of zero? > > won't find anything. Quite apart from the confusing use of "escape", your requirements are still as clear as mud. Try writing up docs for your "guarded_search" function. Supply test cases showing what you expect to match and what you don't expect to match. Is "offset" the offset in the text? If so, don't you really want a set of "forbidden" offsets, not just one? > But how to program "guarded_search"? > Actually, it is about changing the semantics of the regexp syntax: > "." doesn't mean anymore "any character except newline" but "any > character except newline and characters marked as escaped". Make up your mind whether you are "escaping" characters [likely to be interpreted by many people as position-independent] or "escaping" positions within the text. > And so > on, for all syntax elements of regular expressions. Escaped > characters must spoil any match, however, the regexp machine should > continue to search for other matches. > Whatever your exact requirement, it would seem unlikely to be so wildly popularly demanded as to warrant inclusion in the "regexp machine". You would have to write your own wrapper, something like the following totally-untested example of one possible implementation of one possible guess at what you mean: import re def guarded_search(pattern, text, forbidden_offsets, overlap=False): regex = re.compile(pattern) pos = 0 while True: m = regex.search(text, pos) if not m: return start, end = m.span() for bad_pos in forbidden_offsets: if start <= bad_pos < end: break else: yield m if overlap: pos = start + 1 else: pos = end 8<------- HTH, John From kyosohma at gmail.com Thu May 10 15:09:42 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 10 May 2007 12:09:42 -0700 Subject: Comparing dates problem In-Reply-To: References: <1178746479.776908.319930@p77g2000hsh.googlegroups.com> Message-ID: <1178824182.509201.234240@y5g2000hsa.googlegroups.com> On May 10, 2:37 am, Tim Golden wrote: > kyoso... at gmail.com wrote: > > I am writing a reminder program for our Zimbra email client. One of > > the requirements I was given was to automatically increment or > > decrement the display to show something like the following: > > > 5 minutes until appointment > > > or > > > 10 minutes past your appointment > > > Either way, as each minute goes by, I need to increment it or > > decrement it. I am having trouble finding a coherent way to take the > > same date and compare just the number of minutes between them to find > > the difference. Like if I have an appointment at 9:30 a.m. and the app > > is loaded at 8 a.m., I need to know the number of minutes or hours and > > minutes until the appointment. > > Not the most elegant piece of code on earth, > but this piece of code works for me (cut-and-pasted > directly from a working project, so doesn't > *exactly* match your requirement). > > > def deltastamp (now, then): > > def pluralise (base, n): > if n > 1: > return "%d %ss" % (n, base) > else: > return "%d %s" % (n, base) > > if now > then: > output_format = "%s ago" > delta = now - then > else: > output_format = "in %s" > delta = then - now > > days = delta.days > if days <> 0: > wks, days = divmod (days, 7) > if wks > 0: > output = pluralise ("wk", wks) > else: > output = pluralise ("day", days) > else: > mins, secs = divmod (delta.seconds, 60) > hrs, mins = divmod (mins, 60) > if hrs > 0: > output = pluralise ("hr", hrs) > elif mins > 0: > output = pluralise ("min", mins) > else: > output = pluralise ("sec", secs) > > return output_format % output > > > > TJG Thanks for the advice. I think this will work for me with some minor tweaking. If not, I will post again. Mike From hardcoded.software at gmail.com Thu May 31 06:45:25 2007 From: hardcoded.software at gmail.com (Virgil Dupras) Date: 31 May 2007 03:45:25 -0700 Subject: Good Python style? In-Reply-To: References: Message-ID: <1180608325.283295.170040@p77g2000hsh.googlegroups.com> On May 31, 3:59 am, Andreas Beyer wrote: > Hi, > > I found the following quite cryptic code, which basically reads the > first column of some_file into a set. > In Python I am used to seeing much more verbose/explicit code. However, > the example below _may_ actually be faster than the usual "for line in ..." > Do you consider this code good Python style? Or would you recommend to > refrain from such complex single-line code?? > > Thanks! > Andreas > > inp = resource(some_file) > # read first entries of all non-empty lines into a set > some_set = frozenset([line.split()[0] for line in \ > filter(None, [ln.strip() for ln in inp])]) I think it would be more readable if you would take the filter out of the list comprehension, and the list comprehension out of the set. inp = resource(some_file) stripped_lines = (ln.strip() for ln in inp) splitted_lines = (line.split()[0] for line in stripped_lines if line) some_set = frozenset(splitted_lines) From http Sun May 27 16:13:10 2007 From: http (Paul Rubin) Date: 27 May 2007 13:13:10 -0700 Subject: ten small Python programs References: Message-ID: <7xd50m2fft.fsf@ruckus.brouhaha.com> Steven Bethard writes: > I think I would rewrite the current unit-testing example to use the > standard library unittest module:: I think these days we're supposed to like doctest better than unittest. From gagsl-py2 at yahoo.com.ar Sun May 13 20:43:50 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 13 May 2007 21:43:50 -0300 Subject: Basic question References: <1178986686.510137.195490@p77g2000hsh.googlegroups.com> <1178991933.421386.58500@u30g2000hsc.googlegroups.com> <1178992910.318929.77790@e51g2000hsg.googlegroups.com> <1178995630.925969.207740@w5g2000hsg.googlegroups.com> <1hy0cy8.eg6p1p135hbo3N%aleax@mac.com> Message-ID: En Sat, 12 May 2007 20:13:48 -0300, Alex Martelli escribi?: > Cesar G. Miguel wrote: >> ------------------- >> L = [] >> file = ['5,1378,1,9', '2,1,4,5'] >> str='' >> for item in file: >> L.append([float(n) for n in item.split(',')]) > > The assignment to str is useless (in fact potentially damaging because > you're hiding a built-in name). > > L = [float(n) for item in file for n in item.split(',')] > > is what I'd call Pythonic, personally (yes, the two for clauses need to > be in this order, that of their nesting). But that's not the same as requested - you get a plain list, and the original was a list of lists: L = [[float(n) for n in item.split(',')] for item in file] And thanks for my "new English word of the day": supererogatory :) -- Gabriel Genellina From michael at jedimindworks.com Fri May 11 05:06:38 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Fri, 11 May 2007 04:06:38 -0500 Subject: searching algorithm In-Reply-To: <7dydnfjNWbo9H97bnZ2dnUVZ_oupnZ2d@comcast.com> References: <7dydnfjNWbo9H97bnZ2dnUVZ_oupnZ2d@comcast.com> Message-ID: > > Call me dense, but how does one do this in Python - which doesn't have > pointers? Dictionaries with dictionaries within dictionaries... (with > each letter as the key and the its children as values) is going to be > extremely space inefficient, right? Isn't *everything* in python essentially a pointer? Dictionaries with dictionaries within dictionaries... My gut feeling (which means I have not measured it, so I don't actually know) is that it would not be space inefficient. Perhaps someone who knows more about this will speak up? From michael at jedimindworks.com Wed May 16 03:32:43 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Wed, 16 May 2007 02:32:43 -0500 Subject: url question - extracting (2 types of) domains In-Reply-To: <1179281042.229172.246760@k79g2000hse.googlegroups.com> References: <1179281042.229172.246760@k79g2000hse.googlegroups.com> Message-ID: <213A0C2B-1914-453C-861C-49ECE6E26C02@jedimindworks.com> On May 15, 2007, at 9:04 PM, lazy wrote: > Hi, > Im trying to extract the domain name from an url. lets say I call > it full_domain and significant_domain(which is the homepage domain) > > Eg: url=http://en.wikipedia.org/wiki/IPod , > full_domain=en.wikipedia.org ,significant_domain=wikipedia.org > > Using urlsplit (of urlparse module), I will be able to get the > full_domain, but Im wondering how to get significant_domain. I will > not be able to use like counting the number of dots. etc > > Some domains maybe like foo.bar.co.in (where significant_domain= > bar.co.in) > I have around 40M url list. Its ok, if I fallout in few(< 1%) cases. > Although I agree that measuring this error rate itself is not clear, > maybe just based on ituition. > > Anybody have clues about existing url parsers in python to do this. > Searching online couldnt help me much other than > the urlparse/urllib module. > > Worst case is to try to build a table of domain > categories(like .com, .co.il etc and look for it in the suffix rather > than counting dots and just extract the part till the preceding dot), > but Im afraid if I do this, I might miss some domain category. The best way I know to get an *authoritive* answer is to start with the full_domain and try a whois lookup. If it returns no records, drop everything before the first dot and try again. Repeat until you get a good answer -- this is the significant_domain. hth, Michael From jek-gmane at kleckner.net Sun May 20 22:54:15 2007 From: jek-gmane at kleckner.net (Jim Kleckner) Date: Sun, 20 May 2007 19:54:15 -0700 Subject: Cycle detection and object memory usage? Message-ID: cycles: I understand from the documentation that types with a finalizer method that participate in cycles can't be collected. What is the best way to go about finding these cycles? Googling gives a variety of methods none of which seem terribly mainstream for such a common problem. Object memory usage: Has anyone written a function to sweep out an object to discover how much memory it and all the objects it references is using? This would be great for performance tuning. Thanks. From shanugulati at gmail.com Sat May 5 10:55:47 2007 From: shanugulati at gmail.com (Shaine) Date: 5 May 2007 07:55:47 -0700 Subject: Ezanb.com New Technology Forums - Register Now and Win!!! Message-ID: <1178376947.591295.312970@e65g2000hsc.googlegroups.com> Hi there, We have just launched a new Technology Forums - http://www.ezanb.com. Our aim is to create such a knowledge base where anybody can find the solution to any 'technology related problems'. So, in this regard we are seeking your co-operation. We want you to share your valuable knowledge with the whole world and also use the knowledge of thousands of other technical experts. We want to make ezanb.com A Technology Forum as "Technology Knowledge Sharing Hub" and with the help of your support we can achieve this aim easily. Sharing your knowledge online will increase your credibility in Cyberspace. You can also share your achievements with others by using ezanb.com. For example if you have written some complex code snippet then you can share that code snippet with others. Besides the benefits mentioned above we also want to encourage you by running a contest "POST and WIN". In this contest we will distribute a gadgets to each member on every 50th Post on ezanb.com. So Go Ahead and Register now at http://www.ezanb.com Thank you very much Administrator http://www.ezanb.com From python-url at phaseit.net Wed May 16 14:45:13 2007 From: python-url at phaseit.net (Cameron Laird) Date: Wed, 16 May 2007 18:45:13 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (May 16) Message-ID: QOTW: "Sometimes you just have to take the path of least distaste". - Grant Edwards "I want to choose my words carefully here, so I'm not misunderstood. They're a bunch of fucking idiots." - Charles Wang, billionaire chairman of software giant Computer Associates, asked to assess the quality of Gartner's researchers Even if you can't make it to the Mountain Zone this week, you deserve to know what great topics turn up in in local interest group sessions: http://lists.community.tummy.com/pipermail/frpythoneers/2007-May/001356.html http://wiki.python.org/moin/LocalUserGroups Formation of identifiers with characters beyond the basic latin codepage is a thorny issue: http://groups.google.com/group/comp.lang.python/browse_thread/thread/ebb6bbb9cc833422/ While calldll (mostly?) compiles "out of the box", it's time to move to ctypes: http://groups.google.com/group/comp.lang.python/browse_thread/thread/49c3762e57ef3a06/ Well-styled object orientation involves more than just inheritance--delegation, for example: http://groups.google.com/group/comp.lang.python/msg/7bdd844a547d0f11 ======================================================================== 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. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, Planet Python indexes much of the universe of Pybloggers. http://www.planetpython.org/ The Python Papers aims to publish "the efforts of Python enthusiats". http://pythonpapers.org/ 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 tom at finland.com Thu May 10 10:46:18 2007 From: tom at finland.com (tom at finland.com) Date: Thu, 10 May 2007 14:46:18 GMT Subject: keyword checker - keyword.kwlist In-Reply-To: <1178806246.179950.147750@l77g2000hsb.googlegroups.com> References: <1178806246.179950.147750@l77g2000hsb.googlegroups.com> Message-ID: <_eG0i.142$Hb2.138@read3.inet.fi> > > Hmm... I tried, and identify it. > Try to change the 'input' variable name with other... > Changed input variable to myInput, but the result is still the same. for example, 'else' isn't identified as a keyword by the script though it exists in keyword.kwlist. From byte8bits at gmail.com Mon May 21 14:28:11 2007 From: byte8bits at gmail.com (brad) Date: Mon, 21 May 2007 14:28:11 -0400 Subject: Python and GUI In-Reply-To: <38a37$4651e295$4275d90a$15861@FUSE.NET> References: <1179761984.704369.116310@b40g2000prd.googlegroups.com> <38a37$4651e295$4275d90a$15861@FUSE.NET> Message-ID: Kevin Walzer wrote: > 2. wxPython is big, harder to learn than Tkinter, but looks good on Mac, > Windows, and *Nix. It will require users to install a lot of extra stuff > (or you'll have to bundle the extra stuff). PyInstaller builds binaries beautifully from raw py source. No need to bundle the wx stuff. I develop on Linux, build on Windows (with PyInstaller) and it works great. The source runs on any platform, the Windows binaries is neat for the point and click users. Brad From deets at nospam.web.de Thu May 24 09:19:22 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 24 May 2007 15:19:22 +0200 Subject: Changing Unicode object to Tuple Type In-Reply-To: <1180010621.001281.268800@g4g2000hsf.googlegroups.com> References: <1180007144.514744.188090@q75g2000hsh.googlegroups.com> <5bldo8F2tlcqfU1@mid.uni-berlin.de> <1180010621.001281.268800@g4g2000hsf.googlegroups.com> Message-ID: <5blhn0F2u4ii7U2@mid.uni-berlin.de> laxmikiran.bachu at gmail.com schrieb: > On May 24, 5:11 pm, "Diez B. Roggisch" wrote: >> laxmikiran.ba... at gmail.com schrieb: >> >>> Can we have change a unicode string Type object to a Tuple type >>> object.. If so how ???? >> Why? Are you getting an error that makes you think that's a good idea? >> >> Tuples are basically structs, unicode objects are strings. There is no >> canonical way to convert them. Tell us more about the problem you want >> to be solved, and we might help you better. >> >> diez > > ********** > > I have to get few strings from an application(strings of different > languages..ex: korean,japanese,french etc.,). The data returned by the > application was in the format of the xml. > Hence I was using pyRXP to get the data. I was not able to get all the > strigs in different languages. Now I wanted to use pyRXPU to get all > the strings of that application.When Iam using pyRXPU iam getting the > following error. > > Traceback (most recent call last): > File "D:\LanguageScripts\Screens.py", line 106, in > test_1_01_DoSomething > TitlenSoftkeyfn() > File "D:\LanguageScripts\EventLog_Screens.py", line 66, in > TitlenSoftkeyfn > titleBar = root.TitleBar.currentText > File "D:\LanguageScripts\XmlWrapper.py", line 35, in __getattr__ > tagName, attrs, children, spare = child > ValueError: need more than 1 value to unpack > > > Here the child is of the format unicode.. > > When pyRXP is used it was of the format tuple... I was just trying to > find out if there is some way that I make this code work. I don't know pyRXP and pyRXPU, and especially not how you use them. Who's responsible for writing that "XmlWrapper.py"? He or she obviously expected a tuple returned that was basically a DOM-tree (tag, attrs, childs and something called spare) But changing to pyRXPU seems to break the protocol here. But I can't judge that without seeing more code. diez From ivoras at __fer.hr__ Sun May 13 13:21:19 2007 From: ivoras at __fer.hr__ (Ivan Voras) Date: Sun, 13 May 2007 19:21:19 +0200 Subject: __dict__ for instances? In-Reply-To: <46470dff$0$19237$426a74cc@news.free.fr> References: <46470dff$0$19237$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > You're not doing anything wrong, that's just how Python works. "methods" > are wrapper objects around function objects attributes. The wrapping > only happens at lookup time, and returns different kind of "method" > wrapper (resp. unbound or bound methods) if the attribute is looked up > on an instance or a class (there are also the staticmethod/classmethod > things, but that's not your problem here). Got it, thanks for the explanation! -- (\__/) (O.o) (> < ) This is Bunny. Copy Bunny into your signature to help him on his way to world domination! -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 258 bytes Desc: OpenPGP digital signature URL: From kay.schluehr at gmx.net Sat May 19 01:08:47 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 18 May 2007 22:08:47 -0700 Subject: List Moderator In-Reply-To: <1179510688.186622.250760@e65g2000hsc.googlegroups.com> References: <880dece00705172218n71123b55q531ec0c5e500f208@mail.gmail.com> <1179494546.468892.49460@l77g2000hsb.googlegroups.com> <1179510688.186622.250760@e65g2000hsc.googlegroups.com> Message-ID: <1179551327.337079.17140@q75g2000hsh.googlegroups.com> On May 19, 3:51 am, Beliavsky wrote: > On May 18, 9:22 am, kyoso... at gmail.com wrote: > > > > > You're probably right, but this week has been pretty bad. Every few > > posts there's another porn or boob related link. Sheesh! > > > Mike > > I wish Google Groups were enhanced to let users block messages > according to > > (1) "keywords" > (2) average ranking of the message on Google groups. > (3) sender name > > There are Python experts who work at Google ... Google groups enables reporting usenet abuse. I tried it once pointing to a spam mail. But since nothing happened it indicates more willingness to admit there could be a problem instead of taking it seriously. From JHoover at fbi.gov Tue May 15 01:24:49 2007 From: JHoover at fbi.gov (Gordon Airporte) Date: Tue, 15 May 2007 01:24:49 -0400 Subject: ClientForm .click() oddity Message-ID: I've written a script using ClientForm to automate opening and closing ports on my Linksys router. It works, but I wonder if there isn't a better way to do it. The problem is that the list of arguments in the request generated by .click()ing the form is incomplete and I have to edit it manually. The Submit button on the form is created with the following code: Which calls this function in the form source: function to_submit(F) { F.submit_button.value = "Forward"; F.action.value = "Apply"; F.submit(); } Simply .click()ing on the form does not properly fill in submit_button=Forward&action=apply, however. The arguments are there but with no values. Is this because ClientForm doesn't run javascript, or is there a way to determine and fix these values without manually editing the .data string of the Request with values I have to find on my own? From per9000 at gmail.com Thu May 3 03:30:16 2007 From: per9000 at gmail.com (per9000) Date: 3 May 2007 00:30:16 -0700 Subject: test In-Reply-To: References: Message-ID: <1178177416.036004.265890@u30g2000hsc.googlegroups.com> On 2 Maj, 05:19, "Robert Rawlins - Think Blue" wrote: [...] I like comp.lang.python - it is a friendly place. See this post on the C-list and compare: http://groups.google.se/group/comp.lang.c/browse_thread/thread/0a4e2e194a6da45b [:)]-|--< /Per -- Per Erik Strandberg .NET Architect - Optimization Tomlab Optimization Inc. http://tomopt.com/tomnet/ From mikeminer53 at hotmail.com Wed May 23 12:43:09 2007 From: mikeminer53 at hotmail.com (mkPyVS) Date: 23 May 2007 09:43:09 -0700 Subject: Resizing listbook's listview pane In-Reply-To: <1179932659.180278.72990@w5g2000hsg.googlegroups.com> Message-ID: <1179938589.526357.96950@q69g2000hsb.googlegroups.com> Sorry, copied from wxpython submit as well.. I'm using wxpython 2.8... Primariy I want the resize to happen programatically during object creation/post creation... I can worry about app size changes later. Thanks, Mike From deepbroke7 at gmail.com Tue May 22 16:32:17 2007 From: deepbroke7 at gmail.com (deepbroke7 at gmail.com) Date: 22 May 2007 13:32:17 -0700 Subject: ^ Blondes Take it on the face! Message-ID: <1179865936.920900.117650@z24g2000prd.googlegroups.com> http://goofythroat.info - Must see this blonde take 3 loads on the face! From stefan.behnel-n05pAM at web.de Wed May 16 07:10:10 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 16 May 2007 13:10:10 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464add30$0$6401$9b4e6d93@newsspool2.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649dd55$0$23144$9b4e6d93@newsspool1.arcor-online.net> <464a25e9$0$10188$9b4e6d93@newsspool4.arcor-online.net> <1179291296.561359.286230@h2g2000hsg.googlegroups.com> <464ab64f$0$10185$9b4e6d93@newsspool4.arcor-online.net> <464AB9F2.60906@web.de> <464ac189$0$20297$9b4e6d93@newsspool3.arcor-online.net> <464ac493$0$6394$9b4e6d93@newsspool2.arcor-online.net> <464add30$0$6401$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <464ae692$0$10186$9b4e6d93@newsspool4.arcor-online.net> Ren? Fleschenberg wrote: > Stefan Behnel schrieb: >>> Now, very special environments (what I called "rare and isolated" >>> earlier) like special learning environments for children are a different >>> matter. It should be ok if you have to use a specially patched Python >>> branch there, or have to use an interpreter option that enables the >>> suggested behaviour. For general programming, it IMO is a bad idea. >> Ok, let me put it differently. >> >> You *do not* design Python's keywords. You *do not* design the stdlib. You *do >> not* design the concepts behind all that. You *use* them as they are. So you >> can simply take the identifiers they define and use them the way the docs say. >> You do not have to understand these names, they don't have to be words, they >> don't have to mean anything to you. They are just tools. Even if you do not >> understand English, they will not get in your way. You just learn them. > > I claim that this is *completely unrealistic*. When learning Python, you > *do* learn the actual meanings of English terms like "open", Fine, then go ahead and learn their actual meaning in two languages (Python and English). My point is: you don't have to. You only need to understand their meaning in Python. Whether or not English can help here or can be useful in your later life is completely off-topic. >> But you *do* design your own software. You *do* design its concepts. You *do* >> design its APIs. You *do* choose its identifiers. And you want them to be >> clear and telling. You want them to match your (or your clients) view of the >> application. You do not care about the naming of the tools you use inside. But >> you do care about clarity and readability in *your own software*. > > I do care about the naming of my tools. I care alot. Part of why I like > Python is that it resisted the temptation to clutter the syntax up with > strange symbols like Perl. And I do dislike the decorator syntax, for > example. > > Also, your distinction between "inside" and "your own" is nonsense, > because the "inside" does heavily leak into the "own". It is impossible > to write "your own software" with clarity and readability by your > definition (i.e. in your native language). Any real Python program is a > mix of identifiers you designed yourself and identifiers you did not > design yourself. And I think the ones chosen by yourself are even often > in the minority. It is not feasible in practice to just learn what the > "other" identifiers do without understanding their names. Not for > general programming. The standard library is already too big for that, > and most real programs use not only the standard library, but also third > party libraries that have English APIs. Ok, I think the difference here is that I have practical experience with developing that way and I am missing native identifiers in my daily work. You don't have that experience and therefore do not feel that need. And you know what? That's perfectly fine. I'm not criticising that at all. All I'm criticising is that people without need for this feature are trying to prevent those who need it and want to use it *where it is appropriate* from actually getting this feature into the language. Stefan From nagle at animats.com Tue May 1 02:30:13 2007 From: nagle at animats.com (John Nagle) Date: Mon, 30 Apr 2007 23:30:13 -0700 Subject: re-importing modules In-Reply-To: <1178000214.802269.267260@n76g2000hsh.googlegroups.com> References: <8%pZh.18192$Kd3.76@newssvr27.news.prodigy.net> <1177962288.575008.48490@q75g2000hsh.googlegroups.com> <1177967919.968338.3300@l77g2000hsb.googlegroups.com> <1177997329.701861.143290@e65g2000hsc.googlegroups.com> <7xejm1w0pw.fsf@ruckus.brouhaha.com> <1178000214.802269.267260@n76g2000hsh.googlegroups.com> Message-ID: Graham Dumpleton wrote: > On May 1, 3:51 pm, Paul Rubin wrote: > >>Graham Dumpleton writes: >> >>>That it doesn't reload a parent when a child changes may be fine in an >>>interactive debugger, but can cause problems if not done where >>>automatic reloading is being done in a long running web application >>>where you want to avoid server restarts. >> >>Oh that sounds horrid. Er, yes. > It may sound horrible but mod_python's original module importer had > lots of problems because of things not being reloaded when they should > have in a consistent manner. People weren't going to want to give up > the reload feature altogether as restarting Apache all the time is > viewed as a worse solution, so the only practical solution was at > least make it reliable and this is one of the things that was required > to do it. The number of complaints against mod_python module importing > and reloading problems has basically vanished now with mod_python 3.3 > and the whole thing is so much more stable now. > > Do note that this reloading mechanism isn't applied across all Python > modules, only mod_python handler and associated modules which are used > within the context of URL/document space of your web server. Thus it > is quite specialised and has quite specific use case scenarios which > are well understood. In that context the whole mechanism works fine. > Thus, please try not to pass judgment on it without full understanding > the problem space it operates in and how it internally works. :-) Ouch. This is one of those things where you start out with what looks like a simple idea, but scaling it up introduces excessive complexity. I'm impressed that somebody worked through that mess. Could be worse, though. Imagine reloading, mod_python, and Twisted all interacting during a software upgrade. There's something to be said for the FastCGI approach. Restarts and upgrades are handled in a straightforward manner. You're just running a program over and over, without reloading, and every N minutes, or when it's asked to do so, the program exits and is replaced by a freshly loaded version. There's no reloading, just loading. John Nagle From aaronwmail-usenet at yahoo.com Sat May 12 14:00:29 2007 From: aaronwmail-usenet at yahoo.com (aaronwmail-usenet at yahoo.com) Date: 12 May 2007 11:00:29 -0700 Subject: searching algorithm In-Reply-To: References: Message-ID: <1178992829.717254.85520@u30g2000hsc.googlegroups.com> On May 10, 1:26 pm, Gigs_ wrote: > Hi all! > > I have text file (english-croatian dictionary) with words in it in alphabetical > order. > This file contains 179999 words in this format: > english word: croatian word Let's assume it's okay to have all the data in memory. In my experience the very fastest way to do what you want is to store the strings in a sorted list and use the binary search library module bisect. I once compared this with doing something similar with tries and it was much faster. It's also the most simple way to do it, which is nice too :). -- Aaron Watters === never eat anything bigger than your head -- kliban From robert.kern at gmail.com Sun May 6 17:00:08 2007 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 06 May 2007 16:00:08 -0500 Subject: howto make Python list from numpy.array? In-Reply-To: <1178482016.071308.235520@l77g2000hsb.googlegroups.com> References: <1178480447.245977.293010@n59g2000hsh.googlegroups.com> <1178482016.071308.235520@l77g2000hsb.googlegroups.com> Message-ID: dmitrey wrote: > Thanks all. > I tried all the approaches but they don't work in my situation > I have a variable x that can be > x = 1 > x = [1, 2, 3] > x = numpy.array([1,2,3]) > so all troubles are with 1st case >>>> x=1 >>>> list(x) > Traceback (most recent call last): > File "", line 1, in > TypeError: iteration over non-sequence >>>> list(array(1)) > Traceback (most recent call last): > File "", line 1, in > ValueError: Rank-0 array has no length. >>>> array(1).tolist() > Traceback (most recent call last): > File "", line 1, in > ValueError: rank-0 arrays don't convert to lists. > > Here I used Python 2.4.3, numpy 1.02 All of these results are entirely correct. A scalar (or rank-0 array) is not a sequence. If you have a need to transform a scalar into a sequence (e.g. transform 1 to [1]), then you can use numpy.atleast_1d(x).tolist(). -- 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 openopt at ukr.net Fri May 11 18:44:38 2007 From: openopt at ukr.net (dmitrey) Date: 11 May 2007 15:44:38 -0700 Subject: matplotlib: howto set title of whole window? Message-ID: <1178923478.087792.101170@n59g2000hsh.googlegroups.com> hi all, does anyone know howto set title of whole window? (I mean not just area above plot but string in the same line where buttons 'close', 'iconify', 'fullscreen' are situated) Thx, D. From facundo at taniquetil.com.ar Thu May 17 08:49:34 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Thu, 17 May 2007 12:49:34 +0000 (UTC) Subject: A bug in cPickle? References: <1179335180.786851.209900@y80g2000hsf.googlegroups.com> Message-ID: Victor Kryukov wrote: > The following behavior is completely unexpected. Is it a bug or a by- > design feature? > > ... > > from pickle import dumps > from cPickle import dumps as cdumps > > print dumps('1001799')==dumps(str(1001799)) > print cdumps('1001799')==cdumps(str(1001799)) It's a feature, the behaviour is described in the documentation: """ Since the pickle data format is actually a tiny stack-oriented programming language, and some freedom is taken in the encodings of certain objects, it is possible that the two modules produce different data streams for the same input objects. However it is guaranteed that they will always be able to read each other's data streams """ >>> from pickle import dumps, loads >>> from cPickle import dumps as cdumps, loads as cloads >>> s = '1001799' >>> s == cloads(dumps(s)) True >>> s == loads(cdumps(s)) True Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From grante at visi.com Thu May 10 10:48:24 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 10 May 2007 14:48:24 -0000 Subject: How to make Python poll a PYTHON METHOD References: <1178590029.225298.195430@y80g2000hsf.googlegroups.com> <1178592128.327658.212000@p77g2000hsh.googlegroups.com> <1178594341.680457.192440@q75g2000hsh.googlegroups.com> <1178806483.999546.74050@u30g2000hsc.googlegroups.com> Message-ID: <1346c5ot6sveu77@corp.supernews.com> On 2007-05-10, johnny wrote: > Is it possible to call threads inside another thread (nested threads)? No. It's not possible to call threads because they're not callable objects. (I'm assuming you're talking about Thread objects from the threading module.) If you're asking if you can create and start threads from a non-main thread, the answer is yes. > The example above creates a thread to call a function "eat" > every time based on a specified interval. Now for example, if > I make the called function "eat" to spawn threads to do the > work in a queue and when all jobs are done, spawned threads > join. When the next interval is up this process repeat > itself. OK. -- Grant Edwards grante Yow! I demand IMPUNITY! at visi.com From steve at holdenweb.com Sun May 27 15:53:31 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 27 May 2007 15:53:31 -0400 Subject: Why isn't this query working in python? In-Reply-To: <37732.54938.qm@web33510.mail.mud.yahoo.com> References: <1180279833.131269.136770@w5g2000hsg.googlegroups.com> <37732.54938.qm@web33510.mail.mud.yahoo.com> Message-ID: Steve Howell wrote: > --- erikcw wrote: >>>> ('SELECT payment_id FROM amember_payments WHERE >> member_id=%s AND >>>> expire_date > NOW() AND completed=1 AND >> (product_id >11 AND product_id >>>> <21)', (1608L,)) >>>> () >> Here is a copy of the table schema and the first 2 >> rows. >> > > Does your table actually contain any rows that meet > the criteria that expire_date is in the future, > completed is 1, product id is between 11 and 21, etc.? > > Have you tried debugging the SQL outside of Python? > This thread all started because a manual query was claimed to succeed when a Python-based one was claimed not to. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From miki.tebeka at gmail.com Wed May 16 21:01:54 2007 From: miki.tebeka at gmail.com (Miki) Date: 16 May 2007 18:01:54 -0700 Subject: Typed named groups in regular expression In-Reply-To: References: Message-ID: <1179363714.241505.153330@l77g2000hsb.googlegroups.com> Hello Hugo, > Is it possible to "automagically" coerce the named groups to python types? e.g.: Not that I know of, however I use the following idiom: match = my_regexp.find(some_string) def t(name, convert=str): return convert(match.group(name)) myint = t("field1", int) HTH, -- Miki http://pythonwise.blogspot.com From eric.brunel at pragmadev.com Mon May 14 04:38:28 2007 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Mon, 14 May 2007 10:38:28 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> Message-ID: On Sun, 13 May 2007 21:10:46 +0200, Stefan Behnel wrote: [snip] > Now, I am not a strong supporter (most public code will use English > identifiers anyway) How will you guarantee that? I'm quite convinced that most of the public code today started its life as private code earlier... > So, introducing non-ASCII identifiers is just a > small step further. Disallowing this does *not* guarantee in any way that > identifiers are understandable for English native speakers. It only > guarantees > that identifiers are always *typable* by people who have access to latin > characters on their keyboard. A rather small advantage, I'd say. I would certainly not qualify that as "rather small". There have been quite a few times where I had to change some public code. If this code had been written in a character set that did not exist on my keyboard, the only possibility would have been to copy/paste every identifier I had to type. Have you ever tried to do that? It's actually quite simple to test it: just remove on your keyboard a quite frequent letter ('E' is a good candidate), and try to update some code you have at hand. You'll see that it takes 4 to 5 times longer than writing the code directly, because you always have to switch between keyboard and mouse far too often. In addition to the unnecessary movements, it also completely breaks your concentration. Typing foreign words transliterated to english actually does take longer than typing "proper" english words, but at least, it can be done, and it's still faster than having to copy/paste everything. So I'd say that it would be a major drawback for code sharing, which - if I'm not mistaken - is the basis for the whole open-source philosophy. -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From jstroud at mbi.ucla.edu Sun May 20 07:59:58 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 20 May 2007 04:59:58 -0700 Subject: converting strings to most their efficient types '1' --> 1, 'A' ---> 'A', '1.2'---> 1.2 In-Reply-To: <465017A0.1030901@lexicon.net> References: <1179529661.555196.13070@k79g2000hse.googlegroups.com> <464E6F32.7070200@lexicon.net> <61B3i.6880$H_.138@newssvr21.news.prodigy.net> <464F93C1.8030305@lexicon.net> <42T3i.29504$Um6.11611@newssvr12.news.prodigy.net> <465017A0.1030901@lexicon.net> Message-ID: <3LW3i.1216$C96.305@newssvr23.news.prodigy.net> John Machin wrote: > The model would have to be a lot more complicated than that. There is a > base number of required columns. The kind suppliers of the data randomly > add extra columns, randomly permute the order in which the columns > appear, and, for date columns I'm going to ignore this because these things have absolutely no affect on the analysis whatsoever. Random order of columns? How could this influence any statistics, counting, Bayesian, or otherwise? randomly choose the day-month-year order, > how much punctuation to sprinkle between the digits, and whether to > append some bonus extra bytes like " 00:00:00". I absolutely do not understand how bonus bytes or any of the above would selectively adversely affect any single type of statistics--if your converter doesn't recognize it then your converter doesn't recognize it and so it will fail under every circumstance and influence any and all statistical analysis. Under such conditions, I want very robust analysis--probably more robust than simple counting statistics. And I definitely want something more efficient. > Past stats on failure to cast are no guide to the future Not true when using Bayesian statistics (and any type of inference for that matter). For example, where did you get 90% cutoff? From experience? I thought that past stats are no guide to future expectations? ... a sudden > change in the failure rate can be caused by the kind folk introducing a > new null designator i.e. outside the list ['', 'NULL', 'NA', 'N/A', > '#N/A!', 'UNK', 'UNKNOWN', 'NOT GIVEN', etc etc etc] Using the rough model and having no idea that they threw in a few weird designators so that you might suspect a 20% failure (instead of the 2% I modeled previously), the *low probabilities of false positives* (say 5% of the non-Int columns evaluate to integer--after you've eliminated dates because you remembered to test more restrictive types first) would still *drive the statistics*. Remember, the posteriors become priors after the first test. P_1(H) = 0.2 (Just a guess, it'll wash after about 3 tests.) P(D|H) = 0.8 (Are you sure they have it together enough to pay you?) P(D|H') = 0.05 (5% of the names, salaries, etc., evaluate to float?) Lets model failures since the companies you work with have bad typists. We have to reverse the probabilities for this: Pf_1(H) = 0.2 (Only if this is round 1.) Pf(D|H) = 0.2 (We *guess* a 20% chance by random any column is Int.) Pf(D|H') = 0.80 (80% of Ints fail because of carpel tunnel, ennui, etc.) You might take issue with Pf(D|H) = 0.2. I encourage you to try a range of values here to see what the posteriors look like. You'll find that this is not as important as the *low false positive rate*. For example, lets not stop until we are 99.9% sure one way or the other. With this cutoff, lets suppose this deplorable display of typing integers: pass-fail-fail-pass-pass-pass which might be expected from the above very pessimistic priors (maybe you got data from the _Apathy_Coalition_ or the _Bad_Typists_Union_ or the _Put_a_Quote_Around_Every_5th_Integer_League_): P_1(H|D) = 0.800 (pass) P_2(H|D) = 0.500 (fail) P_3(H|D) = 0.200 (fail--don't stop, not 99.9% sure) P_4(H|D) = 0.800 (pass) P_6(H|D) = 0.9846153 (pass--not there yet) P_7(H|D) = 0.9990243 (pass--got it!) Now this is with 5% all salaries, names of people, addresses, favorite colors, etc., evaluating to integers. (Pausing while I remember fondly Uncle 41572--such a nice guy...funny name, though.) > There is also the problem of first-time-participating organisations -- > in police parlance, they have no priors :-) Yes, because they teleported from Alpha Centauri where organizations are fundamentally different from here on Earth and we can not make any reasonable assumptions about them--like that they will indeed cough up money when the time comes or that they speak a dialect of an earth language or that they even generate spreadsheets for us to parse. James From chris.atlee at gmail.com Wed May 30 13:25:12 2007 From: chris.atlee at gmail.com (chris.atlee at gmail.com) Date: 30 May 2007 10:25:12 -0700 Subject: Help with ctypes and PAM Message-ID: <1180545912.093839.150450@p77g2000hsh.googlegroups.com> Hello, I've been trying to write a PAM module using ctypes. In the conversation function (my_conv in the script below), you're passed in a pam_response** pointer. You're supposed to allocate an array of pam_response's and set the pointer's value to the new array. Then you fill in the array with appropriate data. I can't seem to get it working in python...The authenticate function always returns PAM_AUTHTOK_RECOVER_ERR (21), which I think means the response doesn't make any sense. I've tried saving the response array outside of my_conv to make sure it doesn't get garbage collected, but that doesn't seem to help. Any pointers would be appreciated! Cheers, Chris from ctypes import * libpam = CDLL("libpam.so") class pam_handle(Structure): _fields_ = [ ("handle", c_void_p) ] def __init__(self): self.handle = 0 class pam_message(Structure): _fields_ = [ ("msg_style", c_int), ("msg", c_char_p), ] def __repr__(self): return "" % (self.msg_style, self.msg) class pam_response(Structure): _fields_ = [ ("resp", c_char_p), ("resp_retcode", c_int), ] def __repr__(self): return "" % (self.resp_retcode, self.resp) conv_func = CFUNCTYPE(c_int, c_int, POINTER(POINTER(pam_message)), POINTER(POINTER(pam_response)), c_void_p) class pam_conv(Structure): _fields_ = [ ("conv", conv_func), ("appdata_ptr", c_void_p) ] pam_start = libpam.pam_start pam_start.restype = c_int pam_start.argtypes = [c_char_p, c_char_p, POINTER(pam_conv), POINTER(pam_handle)] pam_authenticate = libpam.pam_authenticate pam_authenticate.restype = c_int pam_authenticate.argtypes = [pam_handle, c_int] if __name__ == "__main__": import getpass, os, sys @conv_func def my_conv(nMessages, messages, pResponse, appData): # Create an array of nMessages response objects # Does r get GC'ed after we're all done? r = (pam_response * nMessages)() pResponse.contents = cast(r, POINTER(pam_response)) for i in range(nMessages): if messages[i].contents.msg == "Password: ": p = getpass.getpass() pResponse.contents[0].resp_retcode = 0 pResponse.contents[0].resp = p return 0 handle = pam_handle() c = pam_conv(my_conv, 0) retval = pam_start("login", os.getlogin(), pointer(c), pointer(handle)) if retval != 0: print "Couldn't start pam session" sys.exit(-1) retval = pam_authenticate(handle, 0) if retval == 21: print "Authentication information cannot be recovered" sys.exit(-1) print retval From bj_666 at gmx.net Fri May 11 04:34:20 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 11 May 2007 10:34:20 +0200 Subject: how to refer to partial list, slice is too slow? References: <1178862631.470437.134180@h2g2000hsg.googlegroups.com> <1178862971.447773.21760@o5g2000hsb.googlegroups.com> Message-ID: In <1178862971.447773.21760 at o5g2000hsb.googlegroups.com>, ??????????????? wrote: > I make a sample here for the more clearly explanation > > s = " ..... - this is a large string data - ......." > > def parser1(data) > # do some parser > ... > # pass the remainder to next parser > parser2(data[100:]) > > def parser2(data) > # do some parser > ... > # pass the remainder to next parser > parser3(data[100:]) > > def parser3(data) > # do some parser > ... > # pass the remainder to next parser > parser4(data[100:]) > > ... Do you need the remainder within the parser functions? If not you could split the data into chunks of 100 bytes and pass an iterator from function to function. Untested: def iter_chunks(data, chunksize): offset = chunksize while True: result = data[offset:offset + chunksize] if not result: break yield result def parser1(data): chunk = data.next() # ... parser2(data) def parser2(data): chunk = data.next() # ... parser3(data) # ... def main(): # Read or create data. # ... parser1(iter_chunks(data, 100)) Ciao, Marc 'BlackJack' Rintsch From manatlan at gmail.com Sun May 13 04:04:03 2007 From: manatlan at gmail.com (manatlan) Date: 13 May 2007 01:04:03 -0700 Subject: Dynamic subclassing ? In-Reply-To: References: <1178976888.443891.116090@y80g2000hsf.googlegroups.com> Message-ID: <1179043443.193791.255510@p77g2000hsh.googlegroups.com> On 12 mai, 18:57, Karlo Lozovina <_karlo_ at _mosor.net> wrote: > manatlan wrote: > > I can't find the trick, but i'm pretty sure it's possible in an easy > > way. > > It's somewhat easy, boot looks ugly to me. Maybe someone has a more > elegant solution: > > In [6]: import new > > In [13]: class Button: > ....: def buttonFunc(self): > ....: pass > > In [14]: class ExtensionClass: > ....: def extendedMethod(self): > ....: pass > > In [15]: hybrid = new.instance(Button, > Button.__dict__.update(ExtensionClass.__dict__)) > > In [17]: dir(hybrid) > Out[17]: ['__doc__', '__module__', 'buttonFunc', 'extendedMethod'] > > Seems to do what you want it to do. > > HTH, > Karlo. yes, i think it's the only solution ... it's weird but it seems to be the only one ... i will try that ... From eiwot at hotmail.com Tue May 29 01:22:38 2007 From: eiwot at hotmail.com (Eiwot) Date: Tue, 29 May 2007 05:22:38 +0000 Subject: gui application on cross platform Message-ID: Yes, Python can develop cross platform application. I'm using PyGTK which is a binding between GTK and Python. Check it out at http://pyarticles.blogspot.com Cheers> Date: Mon, 28 May 2007 18:52:08 +1000> From: matt at exemail.com.au> Subject: Re: gui application on cross platform> To: python-list at python.org> > james_027 wrote:> > Hi,> > > > I am using delphi to develop gui application, and wish to make a shift> > to python. here are some of my question/concern...> > > > 1. is python develop gui application a cross platform? just like java> > swing?> > 2. delphi makes things easy for me like coding for a specific event on> > a specific component, could it be the same for python?> > 3. are there cool library of component like in delphi available for> > python that will make database application more usesable?> > 4. where do I start the learning curve? I did some research and I> > don't know which one to take among wxwdiget, pygtk, and etc.> > > > > > I'm also going down this path, and have decided on python + wxWidgets + > boa as the RAD tool. From the tutorial, it seems pretty easy to use, > except for some minor annoyances on both windows and linux platforms.> > Under windows, for some inexplicable reason the "dialogs" tab is not > present, while under linux, I can't seem to drag components around the > frame after placement.> > Cheers,> mvdw> -- > http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ Change is good. See what?s different about Windows Live Hotmail. http://www.windowslive-hotmail.com/learnmore/default.html?locale=en-us&ocid=RMT_TAGLM_HMWL_reten_changegood_0507 -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Sat May 19 03:33:36 2007 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sat, 19 May 2007 09:33:36 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179537992.586692.94630@e65g2000hsc.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179537992.586692.94630@e65g2000hsc.googlegroups.com> Message-ID: <464ea851$0$32050$9b622d9e@news.freenet.de> > Providing a method that would translate an arbitrary string into a > valid Python identifier would be helpful. It would be even more > helpful if it could provide a way of converting untranslatable > characters. However, I suspect that the translate (normalize?) routine > in the unicode module will do. Not at all. Unicode normalization only unifies different "spellings" of the same character. For transliteration, no simple algorithm exists, as it generally depends on the language. However, if you just want any kind of ASCII string, you can use the Unicode error handlers (PEP 293). For example, the program import unicodedata, codecs def namereplace(exc): if isinstance(exc, (UnicodeEncodeError, UnicodeTranslateError)): s = u"" for c in exc.object[exc.start:exc.end]: s += "N_"+unicode(unicodedata.name(c).replace(" ","_"))+"_" return (s, exc.end) else: raise TypeError("can't handle %s" % exc.__name__) codecs.register_error("namereplace", namereplace) print u"Schl\xfcssel".encode("ascii", "namereplace") prints SchlN_LATIN_SMALL_LETTER_U_WITH_DIAERESIS_ssel. HTH, Martin From http Mon May 14 21:53:02 2007 From: http (Paul Rubin) Date: 14 May 2007 18:53:02 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <1hy2qg3.iqfvwnrvr9kjN%aleax@mac.com> <46482624.6050507@web.de> Message-ID: <7xd512onsx.fsf@ruckus.brouhaha.com> Stefan Behnel writes: > But then, where's the problem? Just stick to accepting only patches that are > plain ASCII *for your particular project*. There is no feature that has ever been proposed for Python, that cannot be supported with this argument. If you don't like having a "go to" statement added to Python, where's the problem? Just don't use it in your particular project. From carsten at uniqsys.com Thu May 10 10:32:29 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 10 May 2007 10:32:29 -0400 Subject: Read binary data from MySQL database In-Reply-To: <1178806756.509611.192130@e51g2000hsg.googlegroups.com> References: <1178806756.509611.192130@e51g2000hsg.googlegroups.com> Message-ID: <1178807549.3367.65.camel@dot.uniqsys.com> On Thu, 2007-05-10 at 07:19 -0700, Christoph Krammer wrote: > Hello, > > I try to write a python application with wx that shows images from a > MySQL database. I use the following code to connect and get data when > some event was triggered: > > dbconn = MySQLdb.connect(host="localhost", user="...", passwd="...", > db="images") > dbcurs = dbconn.cursor() > dbcurs.execute("""SELECT imgdata FROM images LIMIT 1""") > imgstring = dbcurs.fetchone()[0] > frame.showImage(imgstring) > > Within my frame, the following method is defined: > > def showImage(self, imgstring): > imgdata = StringIO.StringIO() > imgdata.write(imgstring) > print imgdata.getvalue() > wx.ImageFromStream(imgdata, wx.BITMAP_TYPE_GIF) > panel = wx.Panel(self, -1) > self.panel = panel > > But this does not work. The converter says that the data is not valid > GIF. When I print the content of imgstring after the database select > statement, it contains something like this: > > array('c', 'GIF89aL\x01=\x01\x85\x00\x00\x00\x00\x00\xff\xff\xff > \x00\xff\xff\xff[...]\x00\x00;') That means that imgstring is not a string, it's an array of characters. Observe: >>> import array >>> a = array.array('c', 'Blahblahblah') >>> print a array('c', 'Blahblahblah') >>> str(a) "array('c', 'Blahblahblah')" >>> a.tostring() 'Blahblahblah' Calling write() with an object that's not a string will implicitly call str() on that object and write the result of that call to the file. Try imgdata.write(imgstring.tostring()) to extract the string data from the array. Hope this helps, -- Carsten Haese http://informixdb.sourceforge.net From kefeer at netangels.ru Mon May 21 13:39:49 2007 From: kefeer at netangels.ru (Ivan Tikhonov) Date: 21 May 2007 10:39:49 -0700 Subject: Python Web Programming - looking for examples of solid high-traffic sites In-Reply-To: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> Message-ID: <1179769189.351376.151440@z24g2000prd.googlegroups.com> Use php. I am lead programmer/maintainer of big website with a lot of interactive stuff in user's backoffice and with a lot of interraction to our non-web apps. PHP is a crap, but programming for web in python is a pain in the ass. And php programmers are cheaper. Especialy avoid mod_python. IMHO. From __peter__ at web.de Mon May 14 14:01:17 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 14 May 2007 20:01:17 +0200 Subject: tkinter button state = DISABLED References: <1179163831.016938.79840@w5g2000hsg.googlegroups.com> Message-ID: rahulnag22 at yahoo.com wrote: > I have created a button widget with a button click binding. The button > initially has a state=disabled. I can see the greyed out version of > the button in the GUI. But If I click on the button it still invokes > the callback/binding function. > > Any suggestions as to why the callback is being invoked even though > the button has a disabled state. It looks like- > > b=Button(frame, text = "Button", state = 'disabled') > > b.bind("", > lambda > event : > function() > ) Well, the /mouse/ button /was/ released. Do you know about the alternative? b = Button(..., command=function) # no bind(), no lambda It behaves like you expect. Peter From ludovic.danigo at gmail.com Thu May 10 04:54:32 2007 From: ludovic.danigo at gmail.com (ldng) Date: 10 May 2007 01:54:32 -0700 Subject: How to convert Unicode string to raw string escaped with HTML Entities Message-ID: <1178787272.922167.79480@q75g2000hsh.googlegroups.com> Hi, I'm looking for a way to convert en unicode string encoded in UTF-8 to a raw string escaped with HTML Entities. I can't seem to find an easy way to do it. Quote from urllib will only work on ascii (which kind of defeat the purpose imho) and escape from cgi doesn't seems to do anything with my string. Any suggestion ? From irmen.NOSPAM at xs4all.nl Thu May 17 06:35:43 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Thu, 17 May 2007 12:35:43 +0200 Subject: Problem with socket.recv() In-Reply-To: <1179388275.768789.49320@p77g2000hsh.googlegroups.com> References: <1179388275.768789.49320@p77g2000hsh.googlegroups.com> Message-ID: <464c3004$0$324$e4fe514c@news.xs4all.nl> xreload wrote: > Hello ! > > So, lets do : > sock.py "http://forums.childrenwithdiabetes.com/showthread.php?t=5030" > - it not ok , only some part of document. > wget "http://forums.childrenwithdiabetes.com/showthread.php?t=5030" - > it ok ! > sock.py "http://www.google.com/" - it ok ! > > Why i got only some part of document ? This is some bug in sockets > module or i do something wrong in my code? You have a bug in your code: > def get_body(self): > body = self.response.split("\r\n\r\n", 2) > try: > return body[1] > except: > return self.response The split is breaking up the response in 2 splits, that is, three parts. You meant to have it split up in TWO parts. So change the argument 2 to the split call, to 1. Also, why not just use httplib/urllib etc? Just curious. --Irmen From knipknap at gmail.com Tue May 22 10:29:08 2007 From: knipknap at gmail.com (Samuel) Date: 22 May 2007 07:29:08 -0700 Subject: Simple omniORBpy example throws exception with error 0x41540002 In-Reply-To: <5bg40hF2moliaU1@mid.uni-berlin.de> References: <1179833680.255391.198490@x18g2000prd.googlegroups.com> <5bg40hF2moliaU1@mid.uni-berlin.de> Message-ID: <1179839420.414340.148850@z28g2000prd.googlegroups.com> On May 22, 1:54 pm, "Diez B. Roggisch" wrote: > It indeed does open a connection - because it wants to register with a > NameServer. Ah, I see now how this works. I happen to run Ubuntu here, so I tried the following: - sudo apt-get install orbit-name-server-2 - orbit-name-server-2 & - Add to /etc/omniORB4.cfg: InitRef = NameService=IOR:010000002b000000... (where everything starting from "IOR:" is the output given by orbit- name-server-2. However, this does not seem to change the behavior. Any hints? Thanks, -Samuel From mike4ty4 at yahoo.com Fri May 4 04:28:00 2007 From: mike4ty4 at yahoo.com (mike3) Date: 4 May 2007 01:28:00 -0700 Subject: Firefighters at the site of WTC7 "Move away the building is going to blow up, get back the building is going to blow up." In-Reply-To: <1178161820.731367.264500@y80g2000hsf.googlegroups.com> References: <1178161820.731367.264500@y80g2000hsf.googlegroups.com> Message-ID: <1178267280.329328.133650@u30g2000hsc.googlegroups.com> On May 2, 9:10 pm, Midex wrote: > 100% EVIDENCE - SEE THE TRUTH FINALLY - ON THE GROUND VIDEO WITNESSEShttp://www.youtube.com/watch?v=YNN6apj5B2U > > In order to appreciate just what Truthers are talking about when they > cry Treason over WTC7, you would want to see this History Channel > documentary on what they claim happened to WTC7:http://www.youtube.com/watch?v=TVSxeJH_RCY > > Ben Chertoff can't get his story straighthttp://www.youtube.com/watch?v=9YND7XocMocj > > LIES LIES LIES LIES LIES > > 9/11 Truth Focoist Revolution. "When peaceful revolution is made > impossible, violent revolution is inevitable" - Martin Luther King. > How long shall they kill our prophets? Look up Focoism. Write about > it. Spread the method. It will be how this revolution will take shape. Maybe they were just speaking in the heat of the moment... or does this mean that the FIREFIGHTERS were in on the conspiracy too? Did you know that a conspiracy becomes more and more difficult to do the bigger it gets? Do you also know that every structural engineer, every scientist, all of NIST, everyone would have to be "in" on this conspiracy? From mensanator at aol.com Wed May 2 19:46:42 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 2 May 2007 16:46:42 -0700 Subject: How to check if a string is empty in python? In-Reply-To: <463917d1$0$2415$426a74cc@news.free.fr> References: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> <1178138964.503290.254060@o5g2000hsb.googlegroups.com> <1178139155.260722.153750@n59g2000hsh.googlegroups.com> <463917d1$0$2415$426a74cc@news.free.fr> Message-ID: <1178149602.018706.309200@o5g2000hsb.googlegroups.com> On May 2, 6:41 pm, Bruno Desthuilliers wrote: > mensana... at aol.com a ?crit : > > > On May 2, 3:49 pm, Basilisk96 wrote: > > >>A simple > > >>if s: > >> print "not empty" > >>else: > >> print "empty" > > >>will do. > > > How do you know that s is a string? > > Why do you want to know if it's a string ? >>> import gmpy >>> gmpy.mpz(11) mpz(11) >>> gmpy.mpz('11',10) mpz(11) >>> gmpy.mpz(11,10) Traceback (most recent call last): File "", line 1, in gmpy.mpz(11,10) TypeError: gmpy.mpz() with numeric argument needs exactly 1 argument The mpz conversion takes two arguments if and only if s is a string, else it takes 1 argument. So being non-empty is insufficient. From tutufan at gmail.com Wed May 9 11:42:24 2007 From: tutufan at gmail.com (tutufan at gmail.com) Date: 9 May 2007 08:42:24 -0700 Subject: Getting some element from sets.Set In-Reply-To: <1178316417.371855.63170@p77g2000hsh.googlegroups.com> References: <1178258913.095438.173020@h2g2000hsg.googlegroups.com> <1178267029.258868.219800@h2g2000hsg.googlegroups.com> <1178316417.371855.63170@p77g2000hsh.googlegroups.com> Message-ID: <1178725344.400736.210280@n59g2000hsh.googlegroups.com> On May 4, 5:06 pm, John Machin wrote: > Errmm, union and intersection operations each apply to two (or more) > sets, not to the elements of a set. > You have n sets set0, set1, .... > > Let u be the number of unique somevalues (1 <= u <= n) > > If u > 1, then after setn = union(set0, set1), setn may not conform to > the rule -- does this matter? I've also previously run into the same need as the original poster. I no longer recall the details, but I think maybe I was implementing a union/find type algorithm. This basically involves partitioning a universe set into partitions, where any element of a partition can be used as a name/handle/etc for the partition in question. Sets are the obvious representation for these partitions, esp since they implement union efficiently. And given this representation, it's very obvious to want to generate a "name" when you have a set in hand. Since any element of the set serves as a name (and you know the sets are all non- empty), it'd be very nice to have a .element() method, or some such. I guess "iter(s).next()" works okay, but it's not very readable, and I wonder if it's efficient. This is at least the second time this has come up, so maybe there is a need. From elventear at gmail.com Wed May 2 10:46:29 2007 From: elventear at gmail.com (elventear) Date: 2 May 2007 07:46:29 -0700 Subject: Problem with inspect.getfile In-Reply-To: References: <1178041715.206440.134530@y80g2000hsf.googlegroups.com> <1178085235.386994.258310@e65g2000hsc.googlegroups.com> Message-ID: <1178117189.070192.318610@o5g2000hsb.googlegroups.com> On May 2, 1:12 am, "Gabriel Genellina" wrote: > En Wed, 02 May 2007 02:53:55 -0300, elventear > escribi?: > > > Found the offending code. I was importing between files that were at > > the same level of the hierarchy without using absolute references. > > Coded worked fine, but inspect didn't. Was this gaffe on my part? Or > > was inspect supposed to handle it? > > Could you provide an example? Simple example My PYTHONPATH points to /python I have the following: /python/packages __init.py__ /containers __init.py__ module1.py module2.py So basically module2 depends on module1. So within module2.py I was I was doing "import module1" instead of import "packages.containers.module1". My code ran ok, but the functions in the inspect module weren't able to handle it (getfile was the source of the problem). Thanks. From S.Mientki-nospam at mailbox.kun.nl Mon May 7 17:01:20 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Mon, 07 May 2007 23:01:20 +0200 Subject: Simulating simple electric circuits In-Reply-To: <5a9838F2nlbanU1@mid.individual.net> References: <5a9838F2nlbanU1@mid.individual.net> Message-ID: hi Bjoern, Bjoern Schliessmann wrote: > Hello all, > > I'm trying to simulate simple electric logic (asynchronous) > circuits. By "simple" I mean that I only want to know if I > have "current" or "no current" (it's quite digital) and the only > elements need to be (with some level of abstraction to my specific > problem) > > - sources (here begin currents) > - ground (here end currents) that doesn't bring you anywhere ;-) Current doesn't start or end at some location, current flows through a closed circuit. And that's the first law you need: Kirchoff's current law: the total current in every node is ZERO !! The second formula you need: Kirchoff's voltage law, the sum of all voltages following any closed loop is ZERO. That's all you need, it gives you a set of linear equations, enough to let them solve by SciPy / NumPy. And let's forget about capacitors, inductors and semi-conductors for this moment ! Here is a simulation package, although designed for MatLab, it might give you a good idea of what your need. http://www.swarthmore.edu/NatSci/echeeve1/Ref/mna/MNA6.html There are few simulation related packages, but not directly suited for electronics http://www.mcs.vuw.ac.nz/cgi-bin/wiki/SimPy http://www.linuxjournal.com/article/7542 http://pyastra.sourceforge.net/ http://www.nelsim.com/scriptsim/python_man.html As an little test I wrote a PIC simulator (only core) in Python, it's very rough code (generated in a few evenings), if you're interested I could look it up. cheers, Stef Mientki From timr at probo.com Sat May 5 18:40:21 2007 From: timr at probo.com (Tim Roberts) Date: Sat, 05 May 2007 22:40:21 GMT Subject: Cannot execute Windows commands via Python in 64-bit References: <1178143060.952025.85520@h2g2000hsg.googlegroups.com> <1178145527.014102.11480@l77g2000hsb.googlegroups.com> <1178147703.568351.95740@e65g2000hsc.googlegroups.com> <1178306678.251676.230370@p77g2000hsh.googlegroups.com> Message-ID: minitotoro wrote: > >Upon further investigation it turned out to be a windohs 64-bit issue >(which is what I was afraid of). I did however find an asinine work >around. > >Make a copy of defrag.exe from the system32 folder and paste it in the >same directory as the python script. Voila! It now works. Piece of >junk windohs... :-S If you are using a 32-bit Python, then all references you make to \windows\system32 are automatically rewritten to \windows\syswow64. If defrag.exe is not present in \windows\syswow64, that could explain it. Unbelievable but true. Although we were all smart enough to handle the transition from \windows\system in Win16 to \windows\system32 in Win32, Microsoft apparently believes programmers have all grown too stupid to handle the transition to Win64 on our own. Some registry references are also silently rewritten. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From bignose+hates-spam at benfinney.id.au Sun May 27 07:17:55 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 27 May 2007 21:17:55 +1000 Subject: Is PEP-8 a Code or More of a Guideline? References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> Message-ID: <87ejl2plb0.fsf@benfinney.id.au> "OKB (not okblacke)" writes: > Underscores are harder to type than any alphanumeric character. I know of no keyboard layout in common use where it's more complicated than +, exactly the same as a single uppercase letter. Care to enlighten me? -- \ "Conscience is the inner voice that warns us somebody is | `\ looking." -- Henry L. Mencken | _o__) | Ben Finney From aleax at mac.com Mon May 7 23:04:35 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 7 May 2007 20:04:35 -0700 Subject: getmtime differs between Py2.5 and Py2.4 References: <463FA51D.1060600@v.loewis.de> <463fb305$0$326$e4fe514c@news.xs4all.nl> <1178585991.924458.154570@l77g2000hsb.googlegroups.com> Message-ID: <1hxrebv.5tn2pnql23q7N%aleax@mac.com> John Machin wrote: > > [E:\Projects]c:\Python24\python.exe -c "import os; print os.path.getmtime('p64.py')" > > 1164470381 > > > > [E:\Projects]c:\Python25\python.exe -c "import os; print os.path.getmtime('p64.py')" > > 1164466781.28 > > > > This is python 2.4.4 and Python 2.5.1 on windows XP. > > The reported time clearly differs. > > > > --Irmen > > Well nitpicked, but irrelevant to the OP's perceptual problem. > > The reported time clearly differs due to the result being (as > documented) now a float instead of an int. The OP is complaining about > an alleged difference of time-zone magnitude (i.e. at least 30 > minutes, not 0.28 seconds). Somehow he has got the idea that Python > 2.4 & earlier returned local time, not UTC. Please look at those number again, beyond the float/int distinction. >>> 1164466781.28 - 1164470381 -3599.7200000286102 the difference (rounding to an int number of seconds) is just about one hour; in certain parts of the world (Europe and Africa), that could indeed be a timezone issue. Alex From MMM at disney.com Sun May 13 12:16:51 2007 From: MMM at disney.com (MMM at disney.com) Date: Sun, 13 May 2007 11:16:51 -0500 Subject: OMG BRITNEYS AT IT AGAIN AGAIN!!!!!! You stupid fucks! Can't you figger out why we white boys ain't fucking these white trash bitches? References: <1178920641.280005.221690@p77g2000hsh.googlegroups.com> Message-ID: <84ee43dic3dg4ur70la37d7ufgbhdob8ck@4ax.com> On 11 May 2007 14:57:21 -0700, wise.of.clean789 at gmail.com wrote: >http://britneyboobs.blogspot.com/2007/05/britney-spears-slips-up-again-exposes.html >- Exclusive pics of Britney Spears...... Stoopid dog fuckers!We crackers went to school with these bitches for at least 6 grades and decided they are so ignorant that they do not need to reproduce because of their offsprings damage to the social order of the working class. Now here you come and think you have found hidden "gold" and give these dumbass whores your shit and they get preg and spew out a dozen kids like a bitch dog. Leave them bitches alone you dumbass!Take a hint..don't breed the trash hoes dude! Get it now? From fw3 at hotmail.co.jp Mon May 21 21:49:31 2007 From: fw3 at hotmail.co.jp (wang frank) Date: Tue, 22 May 2007 01:49:31 +0000 Subject: how to use private method in a class In-Reply-To: Message-ID: Hi, I am trying to write a python class with a new data type such as: class Cc14: def __init__(self, realpart, imagpart): self.r=realart self.i=imagpart def __saturator(x): return x+1 def out(self,x): return Cc14(__saturator(x.r), __saturator(x,i)) When I use the method out such as: z.out Python complains: global name '_Cc14_saturator' is not defined. Is the way put two underscore in front of the definitio making the method becomes private? Why in the same clase, I could not use the __saturator method? Thanks Frank >From: "wang frank" >To: python-list at python.org >Subject: A newbie question >Date: Mon, 21 May 2007 23:04:06 +0000 > >Hi, > >I am trying to write a python class with a new data type such as: >class Cc14: > def __init__(self, realpart, imagpart): > self.r=realart > self.i=imagpart > > def __add__(self,x): > return self.r+x,r, self.i+x.i > >If I have >x=Cc14(4,5) >y=Cc14(4,5) >z=x+y > >z will be a tuple instead of Cc14. How can I return a Cc14 class? > >Thanks >Frank > >_________________________________________________________________ >????????????????????????? MSN?IE7 ???? >http://promotion.msn.co.jp/ie7/ > >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ ??????????????????????????????? http://chizumaga.jp/ From dejanews at email.com Wed May 30 06:05:05 2007 From: dejanews at email.com (samwyse) Date: Wed, 30 May 2007 10:05:05 GMT Subject: Rats! vararg assignments don't work In-Reply-To: References: Message-ID: Gary Herron wrote: > samwyse wrote: > >>I'm a relative newbie to Python, so please bear with me. After seeing >>how varargs work in parameter lists, like this: >> def func(x, *arglist): >>and this: >> x = func(1, *moreargs) >>I thought that I'd try this: >> first, *rest = arglist >>Needless to say, it didn't work. That leaves me with two questions. >> >>First, is there a good way to do this? For now, I'm using this: >> first, rest = arglist[0], arglist[1:] >>but it leaves a bad taste in my mouth. >> > > Well, your moreargs parameter is a tuple, and there are innumerable ways > to process a tuple. (And even more if you convert it to a list.) My use-case is (roughtly) this: first, *rest = f.readline().split() return dispatch_table{first}(*rest) From larry.bates at websafe.com Tue May 22 13:08:44 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 22 May 2007 12:08:44 -0500 Subject: drag and drop with wxPython ? In-Reply-To: References: Message-ID: stef wrote: > hello, > > I'm trying to move from Delphi to Python > (move from MatLab to Python already succeeded, also thanks to this > discussion group). > From the discussions in this list about "the best" GUI for Python, > it now seems to me that wxPython is th? choice for my kind of applications. > > I've no experience with wxPython yet, > I just run a few examples and indeed it looks good (as expected from the > discussions in this list). > > What I really need at this moment for a new project, > (and I coulnd't find any example, lot of broken links ;-) > is how to implement some drag & drop facilities, > both to drag and drop normal button, > but also to drag and drop some dynamically created objects. > Just like a CAD program, but far more simpler. > > Does anyone has an example how to drag & drop components with wxPython ? > > thanks, > Stef Mientki The demo that comes with wxWindows has good examples of this. -Larry From Josef.Dalcolmo at gmx.net Tue May 8 10:07:37 2007 From: Josef.Dalcolmo at gmx.net (Josef Dalcolmo) Date: Tue, 08 May 2007 16:07:37 +0200 Subject: getmtime differs between Py2.5 and Py2.4 In-Reply-To: <46401FDC.4010705@v.loewis.de> References: <463FA51D.1060600@v.loewis.de> <463fb305$0$326$e4fe514c@news.xs4all.nl> <1178585991.924458.154570@l77g2000hsb.googlegroups.com> <1hxrebv.5tn2pnql23q7N%aleax@mac.com> <46401FDC.4010705@v.loewis.de> Message-ID: Martin v. L?wis wrote: >> the difference (rounding to an int number of seconds) is just about one >> hour; in certain parts of the world (Europe and Africa), that could >> indeed be a timezone issue. > > With the help of Tony Meyer, we rediscovered the explanation: because > of a bug in the Microsoft C run-time library, the UTC time reported by > 2.4 may have been off by one hour (it wasn't local time - just off > by one hour). This was due to DST issues. They have been fixed in 2.5, > which now reports the correct UTC value. > > Regards, > Martin Well, indeed I got only a 1 hour difference, on my machine (local time here is +1 hour). But when I temporarily set the local time of my machine to GMT I the difference became 0, therefore I assumed wrongly it had something to do with the local time difference. Thanks to everyone helping to clarify this. My response was slow, because I have been experiencing problems with my newsreader setup. - Josef From yhvh2000 at googlemail.com Tue May 22 17:11:55 2007 From: yhvh2000 at googlemail.com (will) Date: 22 May 2007 14:11:55 -0700 Subject: Python on Vista installation issues In-Reply-To: References: Message-ID: <1179868315.458709.114000@p47g2000hsd.googlegroups.com> Vista is a 64 bit OS and there is no port of pywin32 for either Vista or 64-bit XP From clodoaldo.pinto at gmail.com Wed May 30 08:53:31 2007 From: clodoaldo.pinto at gmail.com (Clodoaldo) Date: 30 May 2007 05:53:31 -0700 Subject: Unicode to HTML entities In-Reply-To: References: <1180453921.357081.89500@n15g2000prd.googlegroups.com> <1180455075.419150.166050@r19g2000prf.googlegroups.com> Message-ID: <1180529611.452887.218850@q75g2000hsh.googlegroups.com> On May 30, 4:25 am, Duncan Booth wrote: > Clodoaldo wrote: > > On May 29, 12:57 pm, "Richard Brodie" wrote: > >> "Clodoaldo" wrote in message > > >>news:1180453921.357081.89500 at n15g2000prd.googlegroups.com... > > >> >I was looking for a function to transform a unicode string into > >> >htmlentities. > >> >>> u'S?o Paulo'.encode('ascii', 'xmlcharrefreplace') > > >> 'São Paulo' > > > That was a fast answer. I would never find that myself. > > You might actually want: > > >>> cgi.escape(u'S?o Paulo & Esp?rito Santo').encode('ascii', 'xmlcharrefreplace') > > 'São Paulo & Espírito Santo' > > as you have to be sure to escape any ampersands in your unicode > string before doing the encode. I will do it. Thanks. Regards, Clodoaldo. From jadestar at idiom.com Mon May 14 22:46:38 2007 From: jadestar at idiom.com (James T. Dennis) Date: Tue, 15 May 2007 02:46:38 -0000 Subject: How to do basic CRUD apps with Python References: <1179098458.333666.307750@e65g2000hsc.googlegroups.com> <464848fa$0$465$426a74cc@news.free.fr> Message-ID: <1179197198.513508@smirk> Bruno Desthuilliers wrote: > walterbyrd a ?crit : >> With PHP, libraries, apps, etc. to do basic CRUD are everywhere. Ajax >> and non-Ajax solutions abound. >> With Python, finding such library, or apps. seems to be much more >> difficult to find. >> I thought django might be a good way, but I can not seem to get an >> answer on that board. >> I would like to put together a CRUD grid with editable/deletable/ >> addable fields, click on the headers to sort. Something that would >> sort-of looks like an online spreadsheet. It would be nice if the >> fields could be edited in-line, but it's not entirely necessary. >> Are there any Python libraries to do that sort of thing? Can it be >> done with django or cherrypy? > You may want to have a look at turbogears's widgets. Admittedly I had to look up the meaning of CRUD in this context: (http://en.wikipedia.org/wiki/Create%2C_read%2C_update_and_delete create, read, update, and delete). I'm looking at Turbogears' Widgets in another window as I type this ... but it will be awhile before I can comment on how they might apply to the OP's needs. Actually I'm wholly unqualified to comment on his or her needs ... but I can comment on how I interpreted the question. Even with the SQLAlchemy SQLSoup examples there's still an annoying about of boilerplate coding that has to be done in order to create a web application for doing CRUD on a database. The missing element seems to be the ability to autogenerate web forms and reports with the requisite controls in them. Imagine, for a moment, being able to do something like: >>> import sqlalchemy.ext.webcrud as crud >>> db = crud.open(....) >>> db.displayTopForm() '' ... and having a default "top level" web page generated with options to query the database (or some specific table in the database to be more specific, add new entries, etc). I'm thinking of some sort of class/module that would generate various sorts of HTML forms by default, but also allow one to sub-class each of the form/query types to customize the contents. It would use introspection on the database columns and constraints to automatically generate input fields for each of the columns and even fields for required foreign keys (or links to the CRUD for those tables?). Ideally it would also automatically hide autogenerated (index/key) fields, and map the table column IDs to form names (with gettext support for l10n of those). I think that's the sort of thing the OP was looking for. Not the ORM ... the the glue between the web framework and the ORM. -- Jim Dennis, Starshine: Signed, Sealed, Delivered From akurucak at epdk.org.tr Wed May 23 03:23:40 2007 From: akurucak at epdk.org.tr (Abdurrahman Kurucak) Date: Wed, 23 May 2007 10:23:40 +0300 Subject: CGIHTTPServer and XML Message-ID: <7EEA4852922071468F5E2C81AB8E9BCD026CAC7A@epdkexc.epdk.org.tr> I am trying to write an CGI script that writes in an XML file. I am fairly new at all programming, cgi and python. I am using CGIHTTPServer that is bundled in python. When I try to open the created xml file directly from the directory, there is no problem. But when i try to open it within the server it gives an 403 error. What should i do to avoid this. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bytter at gmail.com Tue May 15 23:39:20 2007 From: bytter at gmail.com (Hugo Ferreira) Date: Wed, 16 May 2007 04:39:20 +0100 Subject: Python Dijkstra Shortest Path Message-ID: <4e8efcf50705152039g2234cc2cl236b0cde644549c0@mail.gmail.com> While trying to optimize this: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/119466 ... and still have a fast edge lookup, I've done the following tweaks: class PathFind(object): def __init__(self): self.G = defaultdict(dict) self.E = defaultdict(dict) def addEdge(self, va, vb, cost, edge, way): if way == -1: (vb, va) = (va, vb) self.G[va][vb] = edge if not way: self.G[vb][va] = edge self.E[edge] = cost def findPath(self, start, end): def flatten(L): # Flatten linked list of form [0,[1,[2,[]]]] while len(L) > 0: yield L[0] L = L[1] q = [(0, start, ())] # Heap of (cost, path_head, path_rest). visited = set() # Visited vertices. # Eliminate the dots pattern push, pop, add = heapq.heappush, heapq.heappop, visited.add G, E = self.G, self.E while True: (cost, v1, path) = pop(q) if v1 not in visited: add(v1) path = (v1, path) if v1 == end: return list(flatten(path))[::-1] for (v2, e) in G[v1].iteritems(): if v2 not in visited: push(q, (cost + E[e], v2, path)) def getEdges(self, path): edges = [] for ix in xrange(len(path) - 1): edges.append(self.G[path[ix]][path[ix + 1]]) return edges addEdge() is used to initialize the Graph. It takes a way param: if -1 then the vertex order is reversed; 0 means it is bidir; 1 vertex order is maintained. This version maintains two Dictionaries: one for pair_of_vertexes->edge and another for edge->cost. findPath() will find the path between two vertexes and getEdges(findPath()) will return this list of edges for that path. The "Eliminate the dots" pattern actually improved performance in about 10%. Still, I'm looking for some way to improve even more the performance, while maintaining the dijkstra intact (I don't want an A*). Psyco gave me about 20% of improvement. I wonder if anyone has any idea to make this faster (maybe map? list comprehension? some python trick?)... Profiling blames the heapq (eheh). On a my CoreDuo T2300, it takes 1.6seconds to find a path of 800 vertexes in an half a million mesh. Greetings! Hugo Ferreira From mail at microcorp.co.za Tue May 22 01:59:28 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 22 May 2007 07:59:28 +0200 Subject: Lists vs tuples (newbie) References: Message-ID: <01ab01c79c3c$812e1440$03000080@hendrik> "Szabolcs" wrote: > > I was wondering about why are there both tuples and lists? Is there > anything I can do with a tuple that I cannot do with a list? > > In what circumstances is it advantageous to use tuples instead of lists? > Is there a difference in performance? > > I am still learning Python, so please be gentle ... On this group you do not have to be afraid - there may be barking, but the bulldogs all have rubber teeth... >From a practical perspective, use lists - they have more methods. When you want to use a list as a key in a dict, then you can't, as keys have to be immutable. So then you convert your list to a tuple and use it as a key. Its the only place I have found where you *have* to use a tuple. You will be told a lot of stuff about lists being for homogenous items, and tuples being records like a C struct. Take note, nod your head, and then ignore it, and put whatever you like into your lists. They are your lists, not someone else's, and you can put in just what you like, and it all works, in spite of whatever the design intention had been. Aside from the hashing issue, there is nothing that a tuple can do that can't be done as well or better by a list. Heretically yours, Hendrik From george.sakkis at gmail.com Sat May 26 13:10:11 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 26 May 2007 10:10:11 -0700 Subject: Newbie: Struggling again 'map' In-Reply-To: References: <1180173252.906992.262570@q75g2000hsh.googlegroups.com> Message-ID: <1180199411.042051.306030@q75g2000hsh.googlegroups.com> On May 26, 7:47 am, Roel Schroeven wrote: > mosscliffe schreef: > > > for x,y in map("N/A", lista, listb): ########## Fails - Can not call a > > 'str' > > print "MAP:", x, "<>", y > > > def fillwith(fillchars): > > return fillchars > > > for x,y in map(fillwith("N/A"), lista, listb): ########## Fails also - > > Can not call a 'str' > > print "MAP:", x, "<>", y > > The first argument to map is a function, which is called with the items > of the argument sequences. If the first argument is None, a default > function is used which returns a tuple of the items. In the case that > two input sequences are provided: > > map(None, lista, listb) > > is equivalent to: > > def maketuple(a, b): > return a, b > map(maketuple, lista, listb) > > So what you want to do can be done with map like this: > > def make_fill_missing(fillchars): > def fill_missing(a, b): > if a is None: > a = fillchars > if b is None: > b = fillchars > return a, b > return fill_missing > > map(make_fill_missing("N/A"), lista, listb)) And here's a generalized iterator-based version: def ifill(default, *iterables): from itertools import repeat nextfuncs = [iter(iterable).next for iterable in iterables] # how many non-exhausted iterators are left num_left = [len(iterables)] # closure for iterating over the next value of each iterator def iter_next_tuple_values(): for i,next in enumerate(nextfuncs): try: yield next() except StopIteration: num_left[0] -= 1 nextfuncs[i] = next = repeat(default).next yield next() while True: t = tuple(iter_next_tuple_values()) if not num_left[0]: break yield t # example lista = ['a1', 'a2'] listb = ['b10', 'b11', 'b12', 'b13'] for iterables in [ (lista, listb), (lista, listb, ()), ((), listb, ()), ((), (), ()) ]: print list(ifill(None, *iterables)) == map(None, *iterables) George From gshatadal at rediffmail.com Sun May 27 17:54:42 2007 From: gshatadal at rediffmail.com (Shatadal) Date: 27 May 2007 14:54:42 -0700 Subject: Error in optparse documentation Message-ID: <1180302882.090651.235860@q75g2000hsh.googlegroups.com> In the python documentation section 14.3.2.6 (http://docs.python.org/ lib/optparse-generating-help.html) in the last line it is written "options that have a default value can include %default in the help string--optparse will replace it with str() of the option's default value. If an option has no default value (or the default value is None), %default expands to none." However this is true only for python 2.4 and newer and not for older versions. Though the documentation for optparse (section 14.3, http://docs.python.org/lib/module-optparse.html) says that the module is new for python 2.3, in this version a help string (default value = intermediate) e.g. help="interaction mode: novice, intermediate, or expert [default: %default]" prints interaction mode: novice, intermediate, or expert [default: %default] and not: interaction mode: novice, intermediate, or expert [default: intermediate] Only in python 2.4 and newer do you see the help string print as interaction mode: novice, intermediate, or expert [default: intermediate] I think the documentation should be modified so that it is made clear that %default in the help string behaves as is claimed only in version 2.4 and higher. O.S. used is RHEL 9 From rridge at caffeine.csclub.uwaterloo.ca Thu May 17 21:10:47 2007 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Thu, 17 May 2007 21:10:47 -0400 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <464C5227.7060804@v.loewis.de> Message-ID: =?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?= wrote: >One possible reason is that the tools processing the program would not >know correctly what encoding the source file is in, and would fail >when they guessed the encoding incorrectly. For comments, that is not >a problem, as an incorrect encoding guess has no impact on the meaning >of the program (if the compiler is able to read over the comment >in the first place). Possibly. One Java program I remember had Japanese comments encoded in Shift-JIS. Will Python be better here? Will it support the source code encodings that programmers around the world expect? >Another possible reason is that the programmers were unsure whether >non-ASCII identifiers are allowed. If that's the case, I'm not sure how you can improve on that in Python. There are lots of possible reasons why all these programmers around the world who want to use non-ASCII identifiers end-up not using them. One is simply that very people ever really want to do so. However, if you're to assume that they do, then you should look the existing practice in other languages to find out what they did right and what they did wrong. You don't have to speculate. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From nospam at invalid.com Mon May 28 02:20:49 2007 From: nospam at invalid.com (Jack) Date: Sun, 27 May 2007 23:20:49 -0700 Subject: What's the best way to iniatilize a function References: <7NmdncRrFaG3WMTbnZ2dnUVZ_gWdnZ2d@comcast.com> Message-ID: Thanks Steven, for the reply. Very helpful. I've got a lot to learn in Python :) Some questions: > (1) Python can automatically free most data structures and close open > files, but if your needs are more sophisticated, this approach may not be > suitable. Since it's a wrapper of a DLL or .so file, I actually need to call mylib_exit() to do whatever cleanup the library needs to do. >> 2. what's the right way to call mylib_exit()? I put it in __del__(self) >> but it is not being called in my simple test. > > instance.__del__ is only called when there are no references to the > instance. I didn't call del explicitly. I'm expecting Python to call it when the program exits. I put a logging line in __del__() but I never see that line printed. It seems that __del__() is not being called even when the program exits. Any idea why? From sturlamolden at yahoo.no Tue May 15 14:39:26 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 15 May 2007 11:39:26 -0700 Subject: Trying to choose between python and java In-Reply-To: <1179250163.596672.321480@o5g2000hsb.googlegroups.com> References: <1179250163.596672.321480@o5g2000hsb.googlegroups.com> Message-ID: <1179254366.023180.69400@e65g2000hsc.googlegroups.com> On May 15, 7:29 pm, Beliavsky wrote: > print "Hello, world." > > a substantial fraction of Python programs in existence, including all > of my programs, will be broken. Draw your own conclusions. In the vent that your Python 2.x install will be fubar and suddenly stop working the day Python 3k is released: how difficult will it be it to make a Python 3k script that corrects your code? From aboudouvas at panafonet.gr Tue May 8 09:55:08 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 8 May 2007 06:55:08 -0700 Subject: Gui thread and async jobs. In-Reply-To: <5abajlF2nk767U1@mid.uni-berlin.de> References: <1178627450.408287.139070@p77g2000hsh.googlegroups.com> <5abajlF2nk767U1@mid.uni-berlin.de> Message-ID: <1178632508.635902.187030@e65g2000hsc.googlegroups.com> On May 8, 4:00 pm, "Diez B. Roggisch" wrote: > king kikapu wrote: > > Hi, i am reading the book "Python Cookbook, 2nd edition" and i > > encountered a very handy recipe, the one that is called "Combining > > GUIs and Asynchronous I/O with Threads" > > > It is talking about retain a main GUI thread, doing async work with > > worker threads and have both talk through a Queue object to dispatch > > their messages, so the main (GUI) thread remain responsive. > > It has a very good example by using Tkinter and Qt that is indeed > > working. The only point that make me wonder is that the QUI thread has > > to use some polling to check for messages in the Queue. > > > Author said that another alternatives exists (by not doing polling) > > but the complexity makes them non-practical for the 90% of ocassions. > > I remember in C# we deal with that sort of things with events/ > > delegates. > > Hos the same thing is possible in Python, has anyone any link(s) to > > have a look ? > > It depends on the toolkit you use. Qt has thread-safe custom events in 3.x, > and afaik signal/slots (and thus events) are generally thread-safe in 4.x. > So, no problems there. > > Diez Aha...So you do not use polling there (in Qt), correct ? From pete.losangeles at gmail.com Wed May 30 03:06:29 2007 From: pete.losangeles at gmail.com (MisterPete) Date: 30 May 2007 00:06:29 -0700 Subject: print bypasses calling write method for objects inheriting from file? Message-ID: <1180508789.556984.204520@o11g2000prd.googlegroups.com> I created an object that inherits from file and was a bit surprised to find that print seems to bypass the write method for objects inheriting from file. An optimization I suppose. Does this surprise anyone else at all or am I missing something? import sys class FromObject(object): def write(self, string): # this works fine, gets called by print sys.stdout.write("FromObject: " + string) class FromFile(file): def __init__(self, name, mode='w'): file.__init__(self, name, mode) def write(self, string): # this does not get called by print sys.stdout.write("FromFile: " + string) a = FromObject() b = FromFile("test.txt") a.write("Foo\n") # works as expected b.write("Bar\n") # works as expected print >> a, "Baz\n" # "FromFile: Baz\nFromFile:\n" written to stdout. That's fine. print >> b, "Qux\n" b.flush() # "Qux\n" written to test.txt. b.write wasn't called :( From b.r.willems at gmail.com Tue May 1 20:14:55 2007 From: b.r.willems at gmail.com (Bart Willems) Date: Tue, 01 May 2007 20:14:55 -0400 Subject: python win32com excel problem In-Reply-To: References: Message-ID: <4KQZh.214$o47.98@newsfe12.lga> Ray wrote: > Hi, > I tried to call "xlApp.Columns.AutoFit=1" the whole program will crash, > but without xlApp.Columns.AutoFit=1, everything just fine. Autofit is a method. Also, columns are a method of a worksheet - try: xlApp.Worksheets.Columns("C:K").Autofit() (or whatever columns you need of course) > 2. How do I set a rows format? I need to set row "F" to "Text", "o","p" > to general, and > "Q", "R", to currency. Same story: you will need to define the range first. xlApp.Worksheets.Rows("10:200").Numberformat = "General" I think that you actually mean columns, and not rows - columns have character designators, rows have numbers. In that case, try something like xlApp.Activesheet.Columns("F") = "@" (text format), or the other appropiate codes for number formatting as required. I usually pick "#,##0.00" to display numbers with two decimals and thousands seperators. Cheers, Bart From paul at boddie.org.uk Fri May 4 18:28:42 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 4 May 2007 15:28:42 -0700 Subject: Microsoft's Dynamic Languages Runtime (DLR) In-Reply-To: <1178315641.763473.168290@h2g2000hsg.googlegroups.com> References: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> <1178151313.421106.43130@o5g2000hsb.googlegroups.com> <1178151574.302703.205560@l77g2000hsb.googlegroups.com> <1178296035.993859.183720@n59g2000hsh.googlegroups.com> <1178313159.059210.97560@y80g2000hsf.googlegroups.com> <1178315641.763473.168290@h2g2000hsg.googlegroups.com> Message-ID: <1178317722.669477.260070@y80g2000hsf.googlegroups.com> Luis M. Gonz?lez wrote: > > Indeed, the subject is absolutely on-topic. > If can't talk about a so called "Dynamic Languages Runtime" in a > pyhton mailing list, I wonder what it takes to be considered on-topic. > Frankly, this on-topic/off-topic fascism I see in this list is pissing > me off a little bit. It's less on-topic for comp.lang.lisp, though, unless you want to perform in a measuring competition with the Lisp crowd whilst hearing how they did the very same thing as way back in the 1950s. Despite the permissive licences - it'd be hard to slap a bad EULA on IronPython now - the whole thing demonstrates Microsoft's disdain for open standards as usual, but it remains on-topic for comp.lang.python, I guess. Paul From phaedrus at gmx.net Fri May 18 14:20:53 2007 From: phaedrus at gmx.net (Alexander Dünisch) Date: Fri, 18 May 2007 20:20:53 +0200 Subject: Anti-Aliasing in wxPython? Message-ID: <0brr43to59ltspg1g7cu32jpgqrbonandj@4ax.com> Hi everybody i'm wondering if there's a way to enable Anti-Aliasing for the Graphics Object in wxPython. in Java i do this: ((Graphics2D)g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); i haven't found anything like this in wxPython yet. Thanks Alex From peter_7003 at yahoo.com Thu May 3 04:35:47 2007 From: peter_7003 at yahoo.com (Peter Fischer) Date: Thu, 3 May 2007 01:35:47 -0700 (PDT) Subject: how to use Dispatch to open an application in win32com.client In-Reply-To: <4638DF2C.4090203@timgolden.me.uk> Message-ID: <289998.57072.qm@web63401.mail.re1.yahoo.com> Hello Tim, Thank you for your answer. I just tried, but it didn't work. The reason seems to be that Google Earth prevents a second instance to run on the same machine. Maybe for licensing reasons (do you know whether it is legal to bypass this and how to do this?). So that is no python/COM problem. However, now I will try to run the two instances on separate machines and to synchronize them via network. Do you know how to start a second instance on a second machine over the network in python/COM (DCOM)? Is this possible directly with the win32com package in python or do I have to install an additional package? You would greatly help me with an answer, best regards, Peter. Tim Golden wrote:Suspect you want win32com.client.DispatchEx which, among other things, starts a separate instance of the app. (Or whatever they call the things in COMspeak). GE_n = win32com.client.DispatchEx ("GoogleEarth.ApplicationGE") TJG -- http://mail.python.org/mailman/listinfo/python-list --------------------------------- Ahhh...imagining that irresistible "new car" smell? Check outnew cars at Yahoo! Autos. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Tue May 22 15:37:28 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 22 May 2007 21:37:28 +0200 Subject: too much memory use References: <1179860235.044137.295080@a26g2000pre.googlegroups.com> Message-ID: In <1179860235.044137.295080 at a26g2000pre.googlegroups.com>, rohit wrote: > i am making a program for desktop search. > in order to make it more effective im implementing the records in the > form of a tree(files starting with 'a','b','c'....have different > trees ..so 26 trees in all) in memory and writing it down in file. > the max size file has 16000 records...now to implement the tree in > list i'm using line no as index ..and empty child nodes are > represented as "\n" > all this work is going on in the memory.. > problem is the system eats up my 512 mb RAM +1gb virtual store n hangs > cant think of an effective way to implement tree in memory(i can > compact it on disk by writing just the index no..along with the record > from which tree in memory can be reconstructed, but i have to > implement tree as previous to implement random access) I'm not quite sure what exactly you have as in-memory data structures and how many "records" -- are you sure you don't keep references to objects you don't really need anymore? Or maybe you have object cycles and implemented the `__del__()` method on those objects? Anyway? If the data doesn't fit into memory anymore it's time to put them into a database. Either a `shelve`, an SQL database like SQLite or maybe an object database like zodb or Durus. Ciao, Marc 'BlackJack' Rintsch From george.sakkis at gmail.com Tue May 29 23:30:14 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 29 May 2007 20:30:14 -0700 Subject: itertools.groupby In-Reply-To: <1180420476.785936.322400@g37g2000prf.googlegroups.com> References: <1180286272.100790.131670@q75g2000hsh.googlegroups.com> <7xveecr5xx.fsf@ruckus.brouhaha.com> <6Y6dnb0mTLsaCsbbnZ2dnUVZ_hCdnZ2d@comcast.com> <1180420476.785936.322400@g37g2000prf.googlegroups.com> Message-ID: <1180495814.669018.93410@h2g2000hsg.googlegroups.com> On May 29, 2:34 am, Raymond Hettinger wrote: > If the posters on this thread have developed an interest > in the subject, I would find it useful to hear their > ideas on new and creative ways to use groupby(). The > analogy to UNIX's uniq filter was found only after the > design was complete. Likewise, the page numbering trick > (shown above by Paul and in the examples in the docs) > was found afterwards. I have a sense that there are entire > classes of undiscovered use cases which would emerge > if serious creative effort where focused on new and > interesting key= functions (the page numbering trick > ought to serve as inspiration in this regard). > > The gauntlet has been thrown down. Any creative thinkers > up to the challenge? Give me cool recipes. Although obfuscated one-liners don't have a large coolness factor in Python, I'll bite: from itertools import groupby from random import randint x = [randint(0,100) for _ in xrange(20)] print x n = 7 # <-- insert fat comments here about the next line --> # reduce(lambda acc,(rem,divs): acc[rem].extend(divs) or acc, groupby(x, key=lambda div: div%n), [[] for _ in xrange(n)]) George From josiah.carlson at sbcglobal.net Mon May 21 21:10:34 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Tue, 22 May 2007 01:10:34 GMT Subject: Components for a client/server architecture In-Reply-To: References: <5bd99qF2s85heU1@mid.uni-berlin.de> Message-ID: Samuel wrote: > On Mon, 21 May 2007 12:06:50 +0200, Diez B. Roggisch wrote: > >> I'm not sure which configuration you want to change how often. But I'm >> not convinced that the python threading limitations really do make a >> difference here. Do you really benefit from multi-core capabilities in >> this scenario? > > The threading issues are not bound to multi cpu systems. The problem is > that some of Python's blocking functions require holding the global lock. > > "Not all built-in functions that may block waiting for I/O allow other > threads to run." > "It is not possible to interrupt the acquire() method on a lock" > http://docs.python.org/lib/module-thread.html You really should read the source. static PyObject * lock_PyThread_acquire_lock(lockobject *self, PyObject *args) { int i = 1; if (!PyArg_ParseTuple(args, "|i:acquire", &i)) return NULL; Py_BEGIN_ALLOW_THREADS i = PyThread_acquire_lock(self->lock_lock, i); Py_END_ALLOW_THREADS return PyBool_FromLong((long)i); } That snippet of code shows that acquiring a lock does release the GIL. Whether or not you are able to interrupt the underlying operating system lock acquisition is platform dependent (on *nix, you can signal anything to die). Now, whether or not some other code does or does not release the GIL depends on its implementation. However, having used threads on Windows and Linux, with files, sockets, databases, etc., I haven't ever experienced a case where the threads did something that wasn't reasonable except in once case*. > I also found that IronPython does not have a global lock, so far it seems > well suited for solving the problems I am trying to avoid. I am still > looking for a good comparison between IronPython, Python, and Jython. From what I've been reading over the last couple years, IronPython is relatively competitive with Python, being faster or slower depending on the things you are doing. Jython is syntactically limited to Python 2.2 at present, so if you want decorators, descriptors, etc., you are out of luck. >> Sounds like CORBA to me. CORBA has a very mature and good implementation >> for Python called OmniORB, and interoperability with other orbs (the >> ones available for e.g. Java) is very good - as CORBA as standard is >> mature. > > I have worked with Bonobo (an implementation of CORBA) before, though not > on the network - it is fairly complex. But I did not think of using it > for this purpose, it might actually make sense. I'll have to look into > the transport protocol more. You should also consider XML-RPC. Setting up and using XML-RPC in Python is quite easy (see the recipes in the Python cookbook), both as a server and client. If you are thinking about running the server in Jython or IronPython anyways, you can always use the standard library XML-RPC libraries from Python, aside from the sockets stuff, it's all in Python. - Josiah * That one case was with mixing a 3rd party library that seemed to have an incomplete Python wrapping that caused values from two thread stacks to be exchanged. The only way I was able to tickle it was with older versions of wxPython + wx.FileConfig + Scintilla + Python's compiler module. From half.italian at gmail.com Tue May 15 02:54:54 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 14 May 2007 23:54:54 -0700 Subject: removing spaces between 2 names In-Reply-To: <1179208842.114189.233060@e65g2000hsc.googlegroups.com> References: <1179208842.114189.233060@e65g2000hsc.googlegroups.com> Message-ID: <1179212094.912104.9170@e65g2000hsc.googlegroups.com> On May 14, 11:00 pm, saif.shak... at gmail.com wrote: > Hi, > Suppose i have a string stored in variable,how do i remove the > space between them,like if i have the name: > "USDT request" in a variable.i need "USDTrequest",without any space . > Thanks s = "jk hij ght" print "".join(s.split(" ")) From duncan.booth at invalid.invalid Fri May 4 03:36:31 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 4 May 2007 07:36:31 GMT Subject: base64 and unicode References: Message-ID: EuGeNe Van den Bulke wrote: > >>> import base64 > >>> base64.decode(file("hebrew.b64","r"),file("hebrew.lang","w")) > > It runs but the result is not correct: some of the lines in hebrew.lang > are correct but not all of them (hebrew.expected.lang is the correct > file). I guess it is a unicode problem but can't seem to find out how to > fix it. My guess would be that your problem is that you wrote the file in text mode, so (assuming you are on windows) all newline characters in the output are converted to carriage return/linefeed pairs. However, the decoded text looks as though it is utf16 encoded so it should be written as binary. i.e. the output mode should be "wb". Simpler than using the base64 module you can just use the base64 codec. This will decode a string to a byte sequence and you can then decode that to get the unicode string: with file("hebrew.b64","r") as f: text = f.read().decode('base64').decode('utf16') You can then write the text to a file through any desired codec or process it first. BTW, you may just have shortened your example too much, but depending on python to close files for you is risky behaviour. If you get an exception thrown before the file goes out of scope it may not get closed when you expect and that can lead to some fairly hard to track problems. It is much better to either call the close method explicitly or to use Python 2.5's 'with' statement. From mail at microcorp.co.za Wed May 30 02:47:05 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 30 May 2007 08:47:05 +0200 Subject: Tkinter Listbox - Different Text colors in one listbox References: <1180458123.139727.182500@d30g2000prg.googlegroups.com> Message-ID: <00fa01c7a289$8dd1baa0$03000080@hendrik> wrote: > Hi, > Is it possible to have different items in a listbox in different > colors? Or is it just one color for all items in a listbox? > Thanks > Rahul You specify text and foreground colour when you make the box, so I don't think its possible. - Hendrik From mad.vijay at gmail.com Tue May 22 06:52:23 2007 From: mad.vijay at gmail.com (SamG) Date: 22 May 2007 03:52:23 -0700 Subject: OSError[Error 5] Message-ID: <1179831143.709611.61580@b40g2000prd.googlegroups.com> Hi, I do this on PowerPC.. >>> import os >>> os.listdir('/usr/bin') And endup getting this ... OSError: [Error 5] Input/output error:/usr/bin I use python 2.4.4 (Framework edition) Could anybody help PS: I have clean listing with python 2.3.5 but my requirement is for python 2.4.4. Thanx in advance. From nikbaer at gmail.com Tue May 1 19:38:44 2007 From: nikbaer at gmail.com (nik) Date: 1 May 2007 16:38:44 -0700 Subject: ScrolledText? In-Reply-To: <1178058162.274969.117340@o5g2000hsb.googlegroups.com> References: <1178057529.486757.154860@y5g2000hsa.googlegroups.com> <1178058162.274969.117340@o5g2000hsb.googlegroups.com> Message-ID: <1178062724.003188.56080@q75g2000hsh.googlegroups.com> Thank you, but I am not sure. What is wx in this case? I should have mentioned that I am using Tkinter, am pretty new to python and had previously tried just a plain text box with a scrollbar without success. The scrollbar always works manually, nothing I've tried yet has scrolled down automatically. Thanks From daniel.gadenne at caramail.fr Fri May 25 11:17:25 2007 From: daniel.gadenne at caramail.fr (daniel gadenne) Date: Fri, 25 May 2007 17:17:25 +0200 Subject: dabo framework dependancies In-Reply-To: References: <1179761984.704369.116310@b40g2000prd.googlegroups.com> <46532f57$0$32303$426a34cc@news.free.fr> Message-ID: <4656fe07$0$30852$426a74cc@news.free.fr> Hi Paul, Peter, Uwe Thank to the three of you for your clear answers :) From facundo at taniquetil.com.ar Fri May 18 13:03:34 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Fri, 18 May 2007 17:03:34 +0000 (UTC) Subject: A best approach to a creating specified http post body References: <1179486210.398916.251970@o5g2000hsb.googlegroups.com> <1179497660.462525.26110@o5g2000hsb.googlegroups.com> Message-ID: dzawer at gmail.com wrote: > Hmm, I guess I meant something different by using "body"- I meant > request data part and not the thing sent in ulr string. You should specify better what you need yes. See, to send POST information in an http request, you can do the following... >>> urllib2.urlopen(myurl, data=postbody) ...being postbody a string with the information you want to send, for example "Hello world", "a=5&no=yes", or "\n\n\r\tMMalichorhoh829dh9ho2" So, you need help building a post body, or you need building a string? Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From steve at REMOVE.THIS.cybersource.com.au Sun May 6 19:05:52 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 07 May 2007 09:05:52 +1000 Subject: unable to construct tuple with one item References: <271115400705060523t2f1c23e4ndc87e612384d4951@mail.gmail.com> <1178486806.743481.24580@y5g2000hsa.googlegroups.com> Message-ID: On Sun, 06 May 2007 14:26:46 -0700, MRAB wrote: > If it's the comma that makes the tuple, then wouldn't [1, 2] make a 2- > tuple in a list, ie == [(1, 2)]? Hmm... Yes, Python creates the tuple 1,2 and then the square brackets turn it into a list. I doubt the Python compiler is actually so inefficient that it constructs an actual tuple before duplicating the data to create the list, but conceptually you can think of it that way. Likewise for {3:4, 5:9}. What people mean is that the Python parser uses () for _grouping_ (with the sole exception of an empty set of parentheses, which is special-cased as an empty tuple. Commas separate items. If there is a pair of [ ] surrounding the items, they are items of a list; if there is a pair of { } surrounding them, they are items of a dictionary (and must be of the form key:value); otherwise they are a tuple, _regardless_ of whether or not there is a pair of ( ) around the group or not. -- Steven. From carsten at uniqsys.com Thu May 10 12:55:28 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 10 May 2007 12:55:28 -0400 Subject: change of random state when pyc created?? In-Reply-To: References: <5ae25fF2oggbqU1@mid.uni-berlin.de> Message-ID: <1178816128.3367.100.camel@dot.uniqsys.com> On Thu, 2007-05-10 at 11:29 -0500, Robert Kern wrote: > """Never rely on the order of dictionaries and sets.""" Easy, Robert, there's a baby in that bathwater. I think it's useful to note that the arbitrary ordering returned by dict.keys() et al. is locally stable in the absence of intervening modifications, as long as the guarantee is worded in a way that prevents overly optimistic reliance on that ordering. -Carsten From aahz at pythoncraft.com Wed May 16 11:01:30 2007 From: aahz at pythoncraft.com (Aahz) Date: 16 May 2007 08:01:30 -0700 Subject: Trying to choose between python and java References: Message-ID: In article , Aahz wrote: >In article , >Anthony Irwin wrote: >> >>#5 someone said that they used to use python but stopped because the >>language changed or made stuff depreciated (I can fully remember >>which) and old code stopped working. Is code written today likely to >>still work in 5+ years or do they depreciate stuff and you have to update? > >You're probably thinking of >http://www.gbch.net/gjb/blog/software/discuss/python-sucks.html > >Thing is, while he has a point, I don't think it's a very good one. For >example, just yesterday in upgrading from Java 1.4.2 to Java 5.0, I had >to fix a bunch of instances of "package foo.bar.baz;" to "package baz;" >because apparently the latter is now "correct". Bugfixes happen, and >sometimes they break working code. Update: I was wrong about the package thing -- turned out that someone had made a backup copy of our code inside the source tree, and so ant merrily went along and gave nice "duplicate class" errors... -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Look, it's your affair if you want to play with five people, but don't go calling it doubles." --John Cleese anticipates Usenet From vatamane at gmail.com Mon May 7 07:14:20 2007 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 7 May 2007 04:14:20 -0700 Subject: assisging multiple values to a element in dictionary In-Reply-To: <1178535831.870912.44220@p77g2000hsh.googlegroups.com> References: <1178535831.870912.44220@p77g2000hsh.googlegroups.com> Message-ID: <1178536460.436283.312910@o5g2000hsb.googlegroups.com> On May 7, 7:03 am, saif.shak... at gmail.com wrote: > Hi, > I have a dictionary which is something like this: > id_lookup={ > 16:'subfunction', > 26:'dataId', > 34:'parameterId', > 39:'subfunction', > 44:'dataPackageId', > 45:'parameterId', > 54:'subfunction', > 59:'dataId', > 165:'subfunction', > 169:'subfunction', > 170:'dataPackageId', > 174:'controlParameterId'} > > How do i assign multiple values to the key here.Like i want the > key 170 to take either the name 'dataPackageID' or the name > 'LocalId'.I use this in my code,and hence if either comes it should > work . > Can someone help me. > Thanks id_lookup[170]=('dataPackageID', 'LocallId') -Nick V. From raffaele.salmaso at gmail.com Wed May 16 03:46:24 2007 From: raffaele.salmaso at gmail.com (Raffaele Salmaso) Date: Wed, 16 May 2007 09:46:24 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46473267$0$31532$9b622d9e@news.freenet.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: After reading all thread, and based on my experience (I'm italian, english is not my native language) Martin v. L?wis wrote: > - should non-ASCII identifiers be supported? yes > - why? Years ago I've read C code written by a turkish guy, and all identifiers were transliteration of arab (persian? don't know) words. What I've understand of this code? Nothing. 0 (zero ;) ). Not a word. It would have been different if it was used unicode identifiers? Not at all. > - would you use them if it was possible to do so? yes -- ()_() | NN KAPISCO XK' CELLHAVETE T'ANNTO CN ME SL | +---- (o.o) | XK' SKRIVO 1 P'HO VELLOCE MA HALL'ORA DITTELO | +---+ 'm m' | KE SIETE VOI K CI HAVVETE PROBBLEMI NO PENSATECI | O | (___) | HE SENZA RANKORI CIAOOOO | raffaele punto salmaso at gmail punto com From gregory.miller at kodak.com Fri May 18 09:20:04 2007 From: gregory.miller at kodak.com (gregory.miller at kodak.com) Date: Fri, 18 May 2007 09:20:04 -0400 Subject: Greg Miller/NexPress is out of the office. Message-ID: I will be out of the office starting 05/17/2007 and will not return until 05/21/2007. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Tue May 15 01:57:35 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 15 May 2007 02:57:35 -0300 Subject: Generators in C code References: <1179205960.354310.20490@l77g2000hsb.googlegroups.com> Message-ID: En Tue, 15 May 2007 02:12:40 -0300, Raymond Hettinger escribi?: >> I feel I'm out of luck, but if someone could point some way to write a >> generator in C, I'be very grateful! > > Perhaps the code in the itertools module will provide a good example > -- they behave like generators in many respects except that you are > responsible for tracking state and jumping to an appropriate resume > point. Being C, it won't be as convenient as Python generators, but > should be able to translate any generator into equivalent C. Oh, thanks for pointing that! (I didn't know the itertools module was written in C - I supposed it was a Python module). After a brief reading, I think I'll use something similar to how tee and teedataobject store current state. -- Gabriel Genellina From kw at codebykevin.com Wed May 16 09:39:15 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Wed, 16 May 2007 09:39:15 -0400 Subject: Distributing programs depending on third party modules. In-Reply-To: <464ac306$0$802$426a74cc@news.free.fr> References: <53357$4649c4a6$4275d90a$20775@FUSE.NET> <464a1617$0$14328$426a74cc@news.free.fr> <62bee$464a1c4a$4275d90a$14962@FUSE.NET> <464ac306$0$802$426a74cc@news.free.fr> Message-ID: <3f1cb$464b0984$4275d90a$22300@FUSE.NET> Bruno Desthuilliers wrote: > Kevin Walzer a ?crit : > > Note that if you go that way, neither Windows nor MacOS X are actually > able to cleanly manage such dependencies (which is why the usual > solution on these platforms - or at least on Windows - is to just bundle > everything in a single big package). FWIW, I sure had much more trouble > with "DLHell" on Windows than on Gentoo or Ubuntu. I target Mac OS X only with my Python application. py2app wraps up Python, Tcl/Tk, and the related items into a single application bundle, which the user can then install via drag-and-drop. The resulting package is big, but hard drive space is cheap these days. > > I'm already impressed by the whole setuptools package. > In general, I agree with this statement. It's very simple to do sudo easy_install mypythonextension--even easier than grabbing a tarball myself and doing python setup.py, because it downloads the bits for you. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From ruiligc at earthlink.net Wed May 2 18:37:02 2007 From: ruiligc at earthlink.net (Ray) Date: Wed, 02 May 2007 22:37:02 GMT Subject: win32com.client Excel Color Porblem Message-ID: Hi, I need to use cell's background color. when I record a macro from excel, it shows: Rows("7:7").Select With Selection.Interior .ColorIndex = 8 .Pattern = xlSolid how do I run it from python win32com ? xlApp.ActiveSheet.Rows("7:7").ColorIndex won't work. Thanks for any Help. Ray PS: where or how to find a win32com reference? From mailme.gurpreet at yahoo.com Wed May 2 07:27:43 2007 From: mailme.gurpreet at yahoo.com (Gurpreet Singh) Date: Wed, 2 May 2007 04:27:43 -0700 (PDT) Subject: Leaving Python List Message-ID: <628848.41595.qm@web62002.mail.re1.yahoo.com> This mail is to confirm that i want to leave the python list. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From erikwickstrom at gmail.com Fri May 25 10:39:06 2007 From: erikwickstrom at gmail.com (erikcw) Date: 25 May 2007 07:39:06 -0700 Subject: Why isn't this query working in python? Message-ID: <1180103946.552760.239200@p47g2000hsd.googlegroups.com> Hi all, I'm trying to run the following query: amember_db = MySQLdb.connect(host="localhost", user="**********", passwd="*****", db="*******") # create a cursor self.amember_cursor = amember_db.cursor() # execute SQL statement sql = """SELECT payment_id FROM amember_payments WHERE member_id=%s AND expire_date > NOW() AND completed=1 AND (product_id >11 AND product_id <21)""", (self.uid) print sql self.amember_cursor.execute(*sql) amember_result = self.cursor.fetchall() print amember_result When I manually run the SQL query in mysql, I get a result, but for some reason I get an empty result in python. Here are some notes that may be of importance. -I have 2 connections open to MySQL in this script (they are both in seperate objects of course) - self.uid = 1972L -print amember_result = () Any ideas? Thanks! Erik From sjmachin at lexicon.net Thu May 17 20:18:29 2007 From: sjmachin at lexicon.net (John Machin) Date: 17 May 2007 17:18:29 -0700 Subject: Regexes: How to handle escaped characters In-Reply-To: <1179445577.034717.216870@l77g2000hsb.googlegroups.com> References: <87tzubqniq.fsf@wilson.homeunix.com> <87irarqkz7.fsf@wilson.homeunix.com> <1179435962.962404.191600@y80g2000hsf.googlegroups.com> <1179440203.534490.66510@u30g2000hsc.googlegroups.com> <1179443573.565202.217410@p77g2000hsh.googlegroups.com> <1179445577.034717.216870@l77g2000hsb.googlegroups.com> Message-ID: <1179447509.128104.93900@o5g2000hsb.googlegroups.com> On May 18, 9:46 am, Paul McGuire wrote: > On May 17, 6:12 pm, John Machin wrote: > > > Note: "must not be *part of* any match" [my emphasis] > > > > While we're waiting for clarification from the OP, there's a chicken- > > and-egg thought that's been nagging me: if the OP knows so much about > > the searched string that he can specify offsets which search patterns > > should not span, why does he still need to search it? > > I suspect that this is column/tabular data (a log file perhaps?), and > some columns are not interesting, but produce many false hits for the > search pattern. > If so, why not split the record into fields and look only at the interesting fields? Smells to me of yet another case of re abuse/ misuse ... From jmg3000 at gmail.com Mon May 14 16:45:14 2007 From: jmg3000 at gmail.com (jmg3000 at gmail.com) Date: 14 May 2007 13:45:14 -0700 Subject: customary way of keeping your own Python and module directory in $HOME Message-ID: <1179175513.896546.313500@y80g2000hsf.googlegroups.com> What's the customary way to keep your own local Python and package directory? For example, when you're on a server where you don't have root access, and everything must go in your home directory. * What directories do you create? * What environment variables do you set? * What config files do you keep? * Does that setup work with distutils and setuptools? What special options do you need to pass to these tools when installing modules for everything to work right? Please, share your tips. From michael at jedimindworks.com Thu May 17 19:58:16 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Thu, 17 May 2007 18:58:16 -0500 Subject: How to convert a number to binary? In-Reply-To: <1179445546.307017.275850@p77g2000hsh.googlegroups.com> References: <1179444832.775573.55830@y80g2000hsf.googlegroups.com> <1179445546.307017.275850@p77g2000hsh.googlegroups.com> Message-ID: On May 17, 2007, at 6:45 PM, Lyosha wrote: > On May 17, 4:40 pm, Michael Bentley wrote: >> On May 17, 2007, at 6:33 PM, Lyosha wrote: >> >>> Converting binary to base 10 is easy: >>>>>> int('11111111', 2) >>> 255 >> >>> Converting base 10 number to hex or octal is easy: >>>>>> oct(100) >>> '0144' >>>>>> hex(100) >>> '0x64' >> >>> Is there an *easy* way to convert a number to binary? >> >> def to_base(number, base): >> 'converts base 10 integer to another base' >> >> number = int(number) >> base = int(base) >> if base < 2 or base > 36: >> raise ValueError, "Base must be between 2 and 36" >> if not number: >> return 0 >> >> symbols = string.digits + string.lowercase[:26] >> answer = [] >> while number: >> number, remainder = divmod(number, base) >> answer.append(symbols[remainder]) >> return ''.join(reversed(answer)) >> >> Hope this helps, >> Michael > > That's way too complicated... Is there any way to convert it to a > one- > liner so that I can remember it? Mine is quite ugly: > "".join(str((n/base**i) % base) for i in range(20) if n>=base**i) > [::-1].zfill(1) to_base(number, 2) is too complicated? From scanepa at gmail.com Tue May 29 06:26:02 2007 From: scanepa at gmail.com (Stefano Canepa) Date: 29 May 2007 03:26:02 -0700 Subject: gui application on cross platform In-Reply-To: <1180337330.434010.42210@z28g2000prd.googlegroups.com> References: <1180332092.551838.258440@z28g2000prd.googlegroups.com> <1180335978.008908.51990@q69g2000hsb.googlegroups.com> <1180337330.434010.42210@z28g2000prd.googlegroups.com> Message-ID: <1180434362.171766.299470@w5g2000hsg.googlegroups.com> On 28 Mag, 09:28, james_027 wrote: > On May 28, 3:06 pm, Stefano Canepa wrote: > > > > > On 28 Mag, 08:01, james_027 wrote: > > > > Hi, > > > > I am using delphi to develop gui application, and wish to make a shift > > > to python. here are some of my question/concern... > > > > 1. is python develop gui application a cross platform? just like java > > > swing? > > > Yes. Qt, wxwidgets and pygtk run on Linux and Windows, don't know > > about Macs. > > > > 2. delphi makes things easy for me like coding for a specific event on > > > a specific component, could it be the same for python? > > > Not in the Delphi way but glade/gazpacho are good GUI designer for > > gtk. > > I have no experience with qtdesigner or the wx equivalent app. > > > > 3. are there cool library of component like in delphi available for > > > python that will make database application more usesable? > > > python has dbapi, all DBs look the same, python can also use ORM like > > SQLObjects and SQLALchemy > > > > 4. where do I start the learning curve? I did some research and I > > > don't know which one to take among wxwdiget, pygtk, and etc. > > > I tried wxwidgets and pygtk, then I decided to use pygtk but it > > could be I'll change my mind in the future. > > > Bye > > sc > > Thanks sc, > > What do you mean when you say .."all DBs look the same" That via dbapi you can use different DBs using the same API. > what is the difference between pygtk and wxwidgets? pygtk uses GTK wxwidget use a different gui toolkit on different platform. It is probably the best crossplatform GUI. I used pyGTK simply becouse my GUI apps runs only on gnome. Bye sc From gagsl-py2 at yahoo.com.ar Sun May 13 20:27:54 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 13 May 2007 21:27:54 -0300 Subject: design question References: <1178992981.143066.279690@o5g2000hsb.googlegroups.com> <5amj6gF2pbeeuU1@mid.individual.net> <1179002502.146058.90860@n59g2000hsh.googlegroups.com> <4647192c$0$2346$426a74cc@news.free.fr> Message-ID: En Sun, 13 May 2007 11:40:16 -0300, Bruno Desthuilliers escribi?: > It's alas pretty common to see OO taught by persons who'd rather do some > other job - preferably not related to computers. If I had to name my worst class at university, it was the first one about OO. The teacher really had no idea of what he was talking about - and you didn't have to be a genius to notice it. After a few weeks I moved on to an alternate class. Next semester there was a different teacher. -- Gabriel Genellina From parvini_navid at yahoo.com Tue May 8 09:36:28 2007 From: parvini_navid at yahoo.com (Navid Parvini) Date: Tue, 8 May 2007 06:36:28 -0700 (PDT) Subject: CPU usage Message-ID: <480063.86498.qm@web54508.mail.yahoo.com> Dear All, I want to get the CPU usage in my code. Is there any module in Python to get it? Would you please help me? Thank you in advance. Navid --------------------------------- Bored stiff? Loosen up... Download and play hundreds of games for free on Yahoo! Games. -------------- next part -------------- An HTML attachment was scrubbed... URL: From nicholas.petrella at gmail.com Tue May 8 19:52:14 2007 From: nicholas.petrella at gmail.com (nicholas.petrella at gmail.com) Date: 8 May 2007 16:52:14 -0700 Subject: RotatingFileHandler bugs/errors and a general logging question. Message-ID: <1178668334.588946.256490@e51g2000hsg.googlegroups.com> I am currently trying to use the python logging system as a core enterprise level logging solution for our development and production environments. The rotating file handler seems to be what I am looking for as I want the ability to have control over the number and size of log files that are written out for each of our tools. I have noticed a few problems with this handler and wanted to post here to get your impressions and possibly some ideas about whether these issues can be resolved. The first issue is with multiple copies of the same tool trying to log to the same location. This should not be an issue as the libraries are supposed to be thread safe and therefore also should be safe for multiple instances of a tool. I have run into two problems with this... 1. When a log file is rolled over, occasionally we see the following traceback in the other instance or instances of the tool: Traceback (most recent call last): File "/usr/local/lib/python2.4/logging/handlers.py", line 62, in emit if self.shouldRollover(record): File "/usr/local/lib/python2.4/logging/handlers.py", line 132, in shouldRollover self.stream.seek(0, 2) #due to non-posix-compliant Windows feature ValueError: I/O operation on closed file As best I can tell this seems to be caused by instance A closing the log file and rolling it over and instance B is still trying to use it's file handle to that log file. Except that A has replaced the file during rollover. It seems that a likely solution would be to handle the exception and reopen the log file. It seems that the newer WatchedFileHandler (http://www.trentm.com/python/dailyhtml/lib/ node414.html) provides the functionality that is needed, but I think it would be helpful to have the functionality included with the RotaingFileHandler to prevent these errors. 2. I am seeing that at times when two instances of a tool are logging, the log will be rotated twice. It seems that ass app.log approaches the size limeit (10 MB in my case), the rollover is triggered in both instances of the application causing a small log file to be created. >ls -l -rw-rw-rw- 1 petrella user 10485641 May 8 16:23 app.log -rw-rw-rw- 1 petrella user 2758383 May 8 16:22 app.log.1 <---- Small log -rw-rw-rw- 1 petrella user 10485903 May 8 16:22 app.log.2 -rw-rw-rw- 1 petrella user 2436167 May 8 16:21 app.log.3 It seems that the rollover should also be protected so that the log file is not rolled twice. I also wanted to ask for anyone's thoughts on maybe a better way to implement python logging to meet our needs. The infrastructure in which I am work needs the ability to have log files written to from multiple instances of the same script and potentially from hundreds or more different machines. I know that the documentation suggests using a network logging server but I wanted to know if anyone had any other solutions to allow us to build off of the current python logging packages. Thanks in advance for any of your responses. -Nick From danb_83 at yahoo.com Sat May 26 05:19:38 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: 26 May 2007 02:19:38 -0700 Subject: conditionally creating functions within a class? In-Reply-To: References: Message-ID: <1180171178.397332.272420@m36g2000hse.googlegroups.com> On May 25, 7:44 pm, kaens wrote: > So, I have a class that has to retrieve some data from either xml or > an sql database. > This isn't a problem, but I was thinking "hey, it would be cool if I > could just not define the functions for say xml if I'm using sql", so > I did some fiddling around with the interpreter. > > First, I try conditionally creating a function, period: > > a = 'a' > > if(a == 'a') > def b: > print "hello" > else: > def c: > print "goodbye" > > this works fine. b is defined, c is not. change the value of a and b > gets defined and not c (sorry for the one-letter variables here, but > for these little examples I don't think they detract much) > > then I try doing this within a function: > > class test: > def __init__(self,which): > self.which = which > > if(self.which == 'a'): > def b: > print "hello" > else: > def c: > print "goodbye" > > tester = test('a') > tester.b() > ... class Test: def __init__(self, which): self.which = which if which == 'a': self.__class__ = TestB else: self.__class__ = TestC class TestB(Test): def b(self): print "hello" class TestC(Test): def c(self): print "goodbye" From jim.hefferon at gmail.com Wed May 2 12:45:58 2007 From: jim.hefferon at gmail.com (Jim) Date: 2 May 2007 09:45:58 -0700 Subject: Need Help in Preparing for Study of Python by Forrester Research In-Reply-To: References: Message-ID: <1178124358.203746.290210@c35g2000hsg.googlegroups.com> What does it pay? From apatheticagnostic at gmail.com Tue May 22 23:06:49 2007 From: apatheticagnostic at gmail.com (kaens) Date: Tue, 22 May 2007 23:06:49 -0400 Subject: OSError[Error 5] In-Reply-To: <1179831143.709611.61580@b40g2000prd.googlegroups.com> References: <1179831143.709611.61580@b40g2000prd.googlegroups.com> Message-ID: <163f0ce20705222006s472067eak75f2733baaadbb59@mail.gmail.com> Try adding a trailing slash? On 22 May 2007 03:52:23 -0700, SamG wrote: > Hi, > > I do this on PowerPC.. > > >>> import os > >>> os.listdir('/usr/bin') > > And endup getting this ... > > OSError: [Error 5] Input/output error:/usr/bin > > I use python 2.4.4 (Framework edition) > > Could anybody help > > PS: I have clean listing with python 2.3.5 but my requirement is for > python 2.4.4. > > Thanx in advance. > > -- > http://mail.python.org/mailman/listinfo/python-list > From aleax at mac.com Sat May 19 11:36:29 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 19 May 2007 08:36:29 -0700 Subject: Python compared to other language References: <1179540061.598417.13870@y80g2000hsf.googlegroups.com> <1hybvdz.1qnlesglcv0vcN%aleax@mac.com> <1179556574.341550.229190@q23g2000hsg.googlegroups.com> Message-ID: <1hycp1k.1g93oj9ezbinxN%aleax@mac.com> walterbyrd wrote: > On May 18, 10:24 pm, a... at mac.com (Alex Martelli) wrote: > > > > > I think that Ruby, which roughly speaking sits somewhere between Python > > and Perl, is closer to Python than Perl is. > > I don't know much about Ruby, but it does not seem to be commonly used > for anything other than web-development. It may be that Ruby could be > used for other purposes, but I don't seem to see it happen much. > > I know that PHP can used at the command line, and could be used for > the same sort of sys-admin tasks for which, Perl and Python are often > used, but I don't seem to see that happening either. > > I'm not sure if Ruby, or PHP, are as general purpose as Perl or Python. PHP was definitely born _for_ webpages; Ruby wasn't, just like Perl or Python weren't, it just became very popular for webpages when Rails appeared. so i tried search queries for [ intitle:X intitle:Y ] where X is each of various languages and Y one of two words connected with non-web traditional application programming, and these are the number of hits I saw: Y==scientific: perl 334 python 703 ruby 452 php 423 java 2370 c++ 3340 fortran 3200 Y==payroll: perl 81 python 1 ruby 8 php 176 java 382 c++ 101 fortran 1 >From these numbers it would seem that Ruby (and PHP) aren't really more web-specific than Perl (and Python). In general, these days, when you're interested in how popular each of a certain set of technologies / subjects is, search engines can come in handy (with due precautions, of course: for example, "php" appears in SO many web pages (2.5 billion, vs e.g. 282 million for java) that you need to restrict it cleverly (e.g., I used the intitle: attribute -- that gives 20.1 million for php vs 21.4 million for Java, and biases numbers towards pages that in some sense are "about" that technology rather than just happening to mention it as an aside, a part of an URL, etc:-). "c" is very hard to search for because many occurrences of that single letter have nothing to do with the language (here you may try quoted sentences such as "c programming": without precautions, "c" has 2.86 billion hits, but "c programming" 1.22 million vs 1.09 million for "java programming", which again puts things in better perspective). I say "technology" because this doesn't apply to just programming languages: e.g., "COM", a classic Microsoft technology for component interconnection, is swamped by the homonimous occurrence of ".com" in URLs, so you need the intitle: trick or something like that. An interesting alternative would be to use search engines which do semantic annotation, but I'm not very familiar with those, myself; I'd be interested in details if anybody does try that. Anyway, if you're interested in popularity issues, I believe these techniques, for all their defects, will work better than asking a few people or trying to generalize from unsystematic observations. Alex From laxmikiran.bachu at gmail.com Thu May 24 07:45:32 2007 From: laxmikiran.bachu at gmail.com (laxmikiran.bachu at gmail.com) Date: 24 May 2007 04:45:32 -0700 Subject: Changing Unicode object to Tuple Type Message-ID: <1180007132.103030.149770@q66g2000hsg.googlegroups.com> Can we have change a unicode string Type object to a Tuple type object.. If so how ???? From horpner at yahoo.com Wed May 23 08:34:14 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 23 May 2007 12:34:14 GMT Subject: Lists vs tuples (newbie) References: Message-ID: On 2007-05-22, Duncan Booth wrote: > "Hendrik van Rooyen" wrote: > >> Aside from the hashing issue, there is nothing that a tuple can do >> that can't be done as well or better by a list. > > There are a few other cases where you have to use a tuple, for > example in a try..except statement the exception specification > must be an exception to be caught or a tuple of exception > specifications: a list won't work to catch multiple exceptions. I use tuples simply because of their mellifluous appellation. -- Neil Cerutti From stefan.behnel-n05pAM at web.de Mon May 7 11:47:39 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 07 May 2007 17:47:39 +0200 Subject: Recommended validating XML parser? In-Reply-To: References: Message-ID: <463F4A1B.1030408@web.de> Kirk Strauser wrote: > We're looking for a current, supported, validating XML parser. Since it > seems like there are a few thousand out there, I though we'd see what > everyone else is using. You are asking for lxml, right? http://codespeak.net/lxml/ > Bonus points if it can do something like: > > >>> foo = XMLParser(""" > > 3000 > > """, dtd=file('/etc/weightfile.dtd')) > > >>> print foo.weight > 3000 > > ...or some variant on that theme. Not currently supported, only document internal DTD references are used. But you can always validate the document *after* parsing, be it with DTD, XMLSchema or RNG. BTW, adding this would be straight forward. The implementation is there, it's just not available at the API level (and I'm not sure enough how it should look like...) Stefan From farksimmons at yahoo.com Wed May 30 11:25:48 2007 From: farksimmons at yahoo.com (farksimmons at yahoo.com) Date: 30 May 2007 08:25:48 -0700 Subject: Creating a distro of python... What would you include in it? Message-ID: <1180538748.448426.182820@g4g2000hsf.googlegroups.com> I am creating a distro of Python to be licensed as GPL.... am wondering, what would anyone suggest as to 3rd party modules being put into it (non-commercial of course!)? I know I'd put MySQLdb into it at the very least. Any suggestions? Thanks, Fark Simmons [insert clever tagline here /] From python at rcn.com Tue May 15 01:12:40 2007 From: python at rcn.com (Raymond Hettinger) Date: 14 May 2007 22:12:40 -0700 Subject: Generators in C code In-Reply-To: References: Message-ID: <1179205960.354310.20490@l77g2000hsb.googlegroups.com> On May 14, 9:55 pm, "Gabriel Genellina" wrote: > I feel I'm out of luck, but if someone could point some way to write a > generator in C, I'be very grateful! Perhaps the code in the itertools module will provide a good example -- they behave like generators in many respects except that you are responsible for tracking state and jumping to an appropriate resume point. Being C, it won't be as convenient as Python generators, but should be able to translate any generator into equivalent C. Raymond Hettinger From ruiligc at earthlink.net Thu May 3 07:42:33 2007 From: ruiligc at earthlink.net (Ray) Date: Thu, 03 May 2007 11:42:33 GMT Subject: win32com.client Excel Color Porblem In-Reply-To: <1178148936.556908.189210@n59g2000hsh.googlegroups.com> References: <1178148936.556908.189210@n59g2000hsh.googlegroups.com> Message-ID: Thanks a lot!! ici wrote: > My Excel Template :) + Rows > > # -*- encoding:utf-8 -*- > import win32com.client > > try: import psyco; psyco.full() > except ImportError: pass > > try: > app = win32com.client.Dispatch("Excel.Application.11") # Excel > 2003 > except com_error: > try: > app = win32com.client.Dispatch("Excel.Application.10") # Excel > XP > except com_error: > try: > app = win32com.client.Dispatch("Excel.Application.9") # > Excel 2000 > except com_error: > try: > app = win32com.client.Dispatch("Excel.Application.8") > # Excel 97 > except com_error: > app = win32com.client.Dispatch("Excel.Application") # > Excel 5.0? > # Or raise "No Office ..." > > app.Visible = True > wbk = app.Workbooks.Add() > app.DisplayAlerts = False > while wbk.Worksheets.Count > 1: > wbk.Worksheets[0].Delete() > wbk.Worksheets[0].Name = "SHIT" > sht = wbk.Worksheets[0] # Containers starts with 0! > sht.Name += "$" > > # Rows > rng = sht.Rows(7) > rng.Interior.ColorIndex = 6 > sht.Rows(8).Interior.ColorIndex = 8 > # Rows End > > app.DisplayAlerts = True > wbk.SaveAs(r"c:\temp\test.xls") > app.Quit() > From schoenfeld.one at gmail.com Mon May 7 00:23:36 2007 From: schoenfeld.one at gmail.com (schoenfeld.one at gmail.com) Date: 6 May 2007 21:23:36 -0700 Subject: Firefighters at the site of WTC7 "Move away the building is going to blow up, get back the building is going to blow up." In-Reply-To: <1178172877.755445.101340@q75g2000hsh.googlegroups.com> References: <1178161820.731367.264500@y80g2000hsf.googlegroups.com> <1178163974.007362.13870@c35g2000hsg.googlegroups.com> <1178172877.755445.101340@q75g2000hsh.googlegroups.com> Message-ID: <1178511816.034753.301680@h2g2000hsg.googlegroups.com> On May 3, 4:14 pm, malibu wrote: > On May 2, 9:46 pm, Eric Gisse wrote: > > > On May 2, 7:10 pm, Midex wrote: > > > [...] > > > I guess the explanation that people were looking at the building and > > watching its' structure deform is too rational. > > Also, that was a Larry Silverstein impostor who > said they were going to 'pull it'. > And the only reason he took out huge amounts > of extra insurance on the buildings two months > before this happened was because of global > warming, because we all know a little bit of heat > will bring down steel buildings. And don't forget the hijackers. "OH MY GOD HE'S GOT A PLASTIC KNIFE.... FROM BREAKFAST" Fearing being scratched a little bit, the pilots handed over full control and these antisemite fanatics proceeded to perform an aviation miracle. In the meanwhile, the cave-dweller mastermind, from an afghanistan cave, hacked into NORAD and disabled the entire US defence apparatus. From http Sat May 5 10:53:35 2007 From: http (Paul Rubin) Date: 05 May 2007 07:53:35 -0700 Subject: Looping over lists References: <1hxlsky.tgi88sj7tfrN%aleax@mac.com> <1178363220.575060.219310@y5g2000hsa.googlegroups.com> Message-ID: <7xbqgzcoeo.fsf@ruckus.brouhaha.com> Dustan writes: > > I think the for i in range() is more readable (Maybe because I'm > > coming from a c-style syntax language background) - but what would > > the benefits of using enumerate be (other that being more . . . > > pythonesque?) > > It doesn't create a whole new list just for iterating. That's what xrange is for. From maney at two14.net Wed May 16 11:18:35 2007 From: maney at two14.net (Martin Maney) Date: Wed, 16 May 2007 15:18:35 +0000 (UTC) Subject: zipfile stupidly broken Message-ID: To quote from zipfile.py (2.4 library): # Search the last END_BLOCK bytes of the file for the record signature. # The comment is appended to the ZIP file and has a 16 bit length. # So the comment may be up to 64K long. We limit the search for the # signature to a few Kbytes at the end of the file for efficiency. # also, the signature must not appear in the comment. END_BLOCK = min(filesize, 1024 * 4) So the author knows that there's a hard limit of 64K on the comment size, but feels it's more important to fail a little more quickly when fed something that's not a zipfile - or a perfectly legitimate zipfile that doesn't observe his ad-hoc 4K limitation. I don't have time to find a gentler way to say it because I have to find a work around for this arbitrary limit (1): this is stupid. (1) the leading candidate is to copy and paste the whole frigging zipfile module so I can patch it, but that's even uglier than it is stupid. "This battery is pining for the fjords!" Normally I despise being CC'd on a reply to list or group traffic, but in this case it's probably necessary, as I haven't had time to keep up with this place for several years. :-/ -- To be alive, is that not to be again and again surprised? -- Nicholas van Rijn From jzgoda at o2.usun.pl Fri May 18 03:28:11 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 18 May 2007 09:28:11 +0200 Subject: alternative to eclipse [ python ide AND cvs ] In-Reply-To: References: Message-ID: Stargaming napisa?(a): > Well, basically any editor that features plugins IMO. Although this > sounds much like a "which editor is the best?" question (what will > enrage us even more than non-ASCII identifiers ), I'd suggest Vim. The IDE which embeds Vim is PIDA: http://www.pida.co.uk/. Looks promising. -- Jarek Zgoda "We read Knuth so you don't have to." From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri May 18 08:50:21 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 18 May 2007 14:50:21 +0200 Subject: Python Web Programming - looking for examples of solid high-traffic sites In-Reply-To: <1179411025.269221.72210@k79g2000hse.googlegroups.com> References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> <1179411025.269221.72210@k79g2000hse.googlegroups.com> Message-ID: <464da10a$0$25891$426a74cc@news.free.fr> Istvan Albert a ?crit : > On May 16, 5:04 pm, Victor Kryukov wrote: > >> Our main requirement for tools we're going to use is rock-solid >> stability. As one of our team-members puts it, "We want to use tools >> that are stable, has many developer-years and thousands of user-years >> behind them, and that we shouldn't worry about their _versions_." The >> main reason for that is that we want to debug our own bugs, but not >> the bugs in our tools. > > I think this is a requirement that is pretty much impossible to > satisfy. Only dead frameworks stay the same. I have yet to see a > framework that did not have incompatible versions. > > Django has a very large user base, great documentation and is deployed > for several online new and media sites. It is fast, it's efficient and > is simple to use. Few modern frameworks (in any language) are > comparable, and I have yet to see one that is better, Then have a look at Pylons. From cam.ac.uk at mh391.invalid Sun May 20 06:46:47 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 20 May 2007 11:46:47 +0100 Subject: questions about programming styles In-Reply-To: References: Message-ID: fdu.xiaojf at gmail.com wrote: > (1) > which is the better way to calculate the value of attributes of a class ? > for example: > > (A) > def cal_attr(self, args): > #do some calculations > self.attr = calculated_value > and then if the vlue of attribute is needed, > self.cal_attr(args) > some_var = self.attr > or I can define cal_attr() as follows: > (B) > def cal_attr(self, args): > #do some calculations > return calculated_value > and then, if the value of attribute is needed, > self.attr = self.cal_attr(args) > some_var = self.attr In many cases (I would really have to see the context to be sure) would prefer something like: def get_attr(self, args): # calculations here return calculated_value Don't have a self.attr, just return the results of get_attr(). -- Michael Hoffman From zefria at gmail.com Sun May 20 16:24:39 2007 From: zefria at gmail.com (Daniel Gee) Date: 20 May 2007 13:24:39 -0700 Subject: Translating some Java to Python Message-ID: <1179692679.422164.27700@r3g2000prh.googlegroups.com> A while ago I wrote a class in Java for all kinds of dice rolling methods, as many sides as you want, as many dice as you want, only count values above or below some number in the total, things like that. Now I'm writing a project in Python that needs to be able to make use of that kind of a class. The Java version has static methods for common roll styles (XdY and XdY +Z) for classes that just want a result but don't want to bother keeping an object around for later. So the question is, assuming that I wanted to keep the static method behavior (which I'm not really sure I do), how does one format the method header on a 'static' method in Python? Is it just something like: class Foo: def statAdd(self,a): return a+5 or do you drop the 'self' bit and just use a 1 variable parameter list? From Wiseman1024 at gmail.com Sat May 5 21:57:45 2007 From: Wiseman1024 at gmail.com (Wiseman) Date: 5 May 2007 18:57:45 -0700 Subject: Python regular expressions just ain't PCRE In-Reply-To: <1178401499.480169.140940@e65g2000hsc.googlegroups.com> References: <1178323901.381993.47170@e65g2000hsc.googlegroups.com> <1178380335.646708.260540@h2g2000hsg.googlegroups.com> <1178401499.480169.140940@e65g2000hsc.googlegroups.com> Message-ID: <1178416665.895916.299360@p77g2000hsh.googlegroups.com> On May 5, 10:44 pm, John Machin wrote: > "UTF-8 Unicode" is meaningless. Python has internal unicode string > objects, with comprehensive support for converting to/from str (8-bit) > string objects. The re module supports unicode patterns and strings. > PCRE "supports" patterns and strings which are encoded in UTF-8. This > is quite different, a kludge, incomparable. Operations which inspect/ > modify UTF-8-encoded data are of interest only to folk who are > constrained to use a language which has nothing resembling a proper > unicode datatype. Sure, I know it's a mediocre support for Unicode for an application, but we're not talking an application here. If I get the PCRE module done, I'll just PyArg_ParseTuple(args, "et#", "utf-8", &str, &len), which will be fine for Python's Unicode support and what PCRE does, and I won't have to deal with this string at all so I couldn't care less how it's encoded and if I have proper Unicode support in C or not. (I'm unsure of how Pyrex or SWIG would treat this so I'll just hand-craft it. It's not like it would be complex; most of the magic will be pure C, dealing with PCRE's API.) > There's also the YAGNI factor; most folk would restrict using regular > expressions to simple grep-like functionality and data validation -- > e.g. re.match("[A-Z][A-Z]?[0-9]{6}[0-9A]$", idno). The few who want to > recognise yet another little language tend to reach for parsers, using > regular expressions only in the lexing phase. Well, I find these features very useful. I've used a complex, LALR parser to parse complex grammars, but I've solved many problems with just the PCRE lib. Either way seeing nobody's interested on these features, I'll see if I can expose PCRE to Python myself; it sounds like the fairest solution because it doesn't even deal with the re module - you can do whatever you want with it (though I'd rather have it stay as it is or enhance it), and I'll still have PCRE. That's if I find the time to do it though, even having no life. From aleax at mac.com Sat May 19 00:24:54 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 18 May 2007 21:24:54 -0700 Subject: Python compared to other language References: <1179540061.598417.13870@y80g2000hsf.googlegroups.com> Message-ID: <1hybvdz.1qnlesglcv0vcN%aleax@mac.com> walterbyrd wrote: > - IMO: the most comparable language to Python, is Perl. Both are > scripting languages. Both are free, multi-platform, and multi-purpose. > Both are also very popular. I think that Ruby, which roughly speaking sits somewhere between Python and Perl, is closer to Python than Perl is. Judging popularity strictly by the number of hits on search engines, it seems to be in the same ballpark as Python and Perl. Alex From showell30 at yahoo.com Thu May 31 20:46:47 2007 From: showell30 at yahoo.com (Steve Howell) Date: Thu, 31 May 2007 17:46:47 -0700 (PDT) Subject: file reading by record separator (not line by line) In-Reply-To: Message-ID: <244624.66856.qm@web33508.mail.mud.yahoo.com> --- Marc 'BlackJack' Rintsch wrote: > There was just recently a thread with a > `itertools.groupby()` solution. Yes, indeed. I think it's a very common coding problem (with plenty of mostly analogous variations) that has these very common pitfalls: 1) People often forget to handle the last block. This is not quite exactly an OBOE (off-by-one-error) in the classic sense, but it's an OBOE-like thing waiting to happen. 2) Even folks who solve this correctly won't always solve it idiomatically. 3) The problem oftens comes up with the added complication of a non-finite data stream (snooping on syslog, etc.). I think itertools.groupby() is usually the key batteries-included component in elegant solutions to this problem, but I wonder if the Python community couldn't help a lot of newbies (or insufficiently caffeinated non-newbies) by any of the following: 1) Add a function to some Python module (maybe not itertools?) that implements something to the effect of group_blocks(identify_block_start_method). 2) Address this in the cookbook. 3) Promote this problem as a classic use case of itertools.groupby() (despite the function's advancedness), and provide helpful examples in the itertools docs. Thoughts? ____________________________________________________________________________________ Moody friends. Drama queens. Your life? Nope! - their life, your story. Play Sims Stories at Yahoo! Games. http://sims.yahoo.com/ From steve at REMOVEME.cybersource.com.au Wed May 2 02:19:56 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 02 May 2007 16:19:56 +1000 Subject: While we're talking about annoyances References: <1177837565.317999.244420@c35g2000hsg.googlegroups.com> <8oag339eh56tnpbl8mk3lqlf6avkmusvdm@4ax.com> Message-ID: On Wed, 02 May 2007 06:10:54 +0000, Tim Roberts wrote: > Michael Hoffman wrote: >> >>Hint: if you find yourself using a decorate-sort-undecorate pattern, >>sorted(key=func) or sequence.sort(key=func) might be a better idea. > > Is it? I thought I remember reading on this very list some years ago that > the performance of sequence.sort became much, much worse when a key > function was supplied. You're probably thinking of a comparison function: sequence.sort(cmp=lambda x, y: cmp(y, x)) is a slow way of sorting a sequence in reverse order. The fast way is the two liner: sequence.sort() sequence.reverse() Faster(?) still is: sequence.sort(reverse=True) > I've tended to favor the "Schwarzian transform" (decorate-sort-undecorate) > because of that. That's what the key= argument does. cmp= is slow because the comparison function is called for EVERY comparison. The key= function is only called once per element. -- Steven D'Aprano From rene at korteklippe.de Tue May 15 06:17:09 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 15 May 2007 12:17:09 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <46478694$0$1412$426a34cc@news.free.fr> <1hy252p.1anf7sr1p4yp12N%aleax@mac.com> Message-ID: <464988a4$0$20289$9b4e6d93@newsspool3.arcor-online.net> Steven D'Aprano schrieb: > How is that different from misreading "disk_burnt = True" as "disk_bumt = > True"? In the right (or perhaps wrong) font, like the ever-popular Arial, > the two can be visually indistinguishable. Or "call" versus "cal1"? That is the wrong question. The right question is: Why do you want to introduce *more* possibilities to do such mistakes? Does this PEP solve an actual problem, and if so, is that problem big enough to be worth the introduction of these new risks and problems? I think it is not. I think that the problem only really applies to very isolated use-cases. So isolated that they do not justify a change to mainline Python. If someone thinks that non-ASCII identifiers are really needed, he could maintain a special Python branch that supports them. I doubt that there would be alot of demand for it. -- Ren? From duncan.booth at invalid.invalid Wed May 30 15:21:47 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 30 May 2007 19:21:47 GMT Subject: is there a standard way to "install" egg-files under windows ? References: <4c205$465dbe2b$d443bb3a$17537@news.speedlinq.nl> <5c5u7lF2v1pm3U1@mid.uni-berlin.de> Message-ID: "Diez B. Roggisch" wrote: > setuptools - which you install using the ez_setup.py - will install a > script called easy_install. Under unix, this is installed in /usr/bin, > I'm not sure where it is installed under windows - go use a search. It puts easy_install.exe (and variations on it) in C:\Python25\Scripts (replace C:\Python25 with the path to your python installation). From grante at visi.com Wed May 9 21:29:42 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 10 May 2007 01:29:42 -0000 Subject: Single precision floating point calcs? References: <1343v0emvdjr545@corp.supernews.com> Message-ID: <1344tc6t0hejoac@corp.supernews.com> On 2007-05-09, Robert Kern wrote: > Grant Edwards wrote: >> I'm pretty sure the answer is "no", but before I give up on the >> idea, I thought I'd ask... >> >> Is there any way to do single-precision floating point >> calculations in Python? >> >> I know the various array modules generally support arrays of >> single-precision floats. I suppose I could turn all my >> variables into single-element arrays, but that would be way >> ugly... > > We also have scalar types of varying precisions in numpy: > > In [9]: from numpy import * > > In [10]: float32(1.0) + float32(1e-8) == float32(1.0) > Out[10]: True Very interesting. Converting a few key variables and intermediate values to float32 and then back to CPython floats each time through the loop would probably be more than sufficient. So far as I know, I haven't run into any cases where the differences between 64-bit prototype calculations in Python and 32-bit production calculations in C have been significant. I certainly try to design the algorithms so that it won't make any difference, but it's a nagging worry... > In [11]: 1.0 + 1e-8 == 1.0 > Out[11]: False > > If you can afford to be slow, Yes, I can afford to be slow. I'm not sure I can afford the decrease in readability. > I believe there is an ASPN Python Cookbook recipe for > simulating floating point arithmetic of any precision. Thanks, I'll go take a look. -- Grant Edwards grante Yow! It's the RINSE at CYCLE!! They've ALL IGNORED visi.com the RINSE CYCLE!! From john at datavoiceint.com Wed May 2 13:03:20 2007 From: john at datavoiceint.com (HMS Surprise) Date: 2 May 2007 10:03:20 -0700 Subject: Time functions In-Reply-To: <1178125256.640115.26480@o5g2000hsb.googlegroups.com> References: <1178125256.640115.26480@o5g2000hsb.googlegroups.com> Message-ID: <1178125400.794972.164150@y80g2000hsf.googlegroups.com> On May 2, 12:00 pm, HMS Surprise wrote: > I wish to generate a datetime string that has the following format. > '05/02/2007 12:46'. The leading zeros are required. > > I found '14.2 time' in the library reference and have pulled in > localtime. Are there any formatting functions available or do I need > to make my own? Perhaps there is something similar to C's printf > formatting. > > Thanks, > > jvh (whose newbieism is most glaring) Oops, it appears I overlooked strftime. Regrets, jvh From rene at korteklippe.de Tue May 15 07:54:56 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 15 May 2007 13:54:56 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464997E5.4050105@web.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> <4648294F.2000704@web.de> <46487a6c$0$2400$426a74cc@news.free.fr> <464977D3.6010703@web.de> <464993e7$0$23148$9b4e6d93@newsspool1.arcor-online.net> <464997E5.4050105@web.de> Message-ID: <46499f8f$0$20294$9b4e6d93@newsspool3.arcor-online.net> Stefan Behnel schrieb: > Ren? Fleschenberg wrote: >> Programming is such an English-dominated culture that I even "think" in >> English about it. > > That's sad. I don't think so. It enables me to communicate about that topic with a very broad range of other people, which is A Good Thing. >> My experience is: If you know so little "technical" English that you >> cannot come up with well chosen English identifiers, you need to learn >> it. > > :) This is not about "technical" English, this is about domain specific > English. How big is your knowledge about, say, biological terms or banking > terms in English? Would you say you're capable of modelling an application > from the domain of biology, well specified in a large German document, in > perfect English terms? As I have said, I don't need to be able to do that (model the application in perfect English terms). It is better to model it in non-perfect English terms than to model it in perfect German terms. Yes, I do sometimes use a dictionary to look up the correct English term for a domain-specific German word when programming. It is rarely necessary, but when it is, I usually prefer to take that effort over writing a mixture of German and English. > And: why would you want to do that? 1) To get the broadest possible range of coworkers and maintenance programmers. 2) To be consistent. The code is more beautiful if it does not continously jump from one language to another. And the only way to achieve that is to write it all in English, since the standard library and alot of other stuff is in English. -- Ren? From rahulnag22 at yahoo.com Thu May 3 23:26:56 2007 From: rahulnag22 at yahoo.com (rahulnag22 at yahoo.com) Date: 3 May 2007 20:26:56 -0700 Subject: tkinter listboxes Message-ID: <1178249216.774940.141950@p77g2000hsh.googlegroups.com> I will give a simplified example of the problem at hand -- I have a case in which I have two listboxes - listbox1 and listbox2, if I click on an item in listbox1 the item gets highlighted as expected. Now if I click on an item in listbox2 the selected item in listbox1 loses its highlight. My question is how do I keep the listbox1 item from losing its highlight if I select an item in listbox2 or to that matter any other widget. Thanks Rahul From joel.granados at gmail.com Tue May 22 11:00:48 2007 From: joel.granados at gmail.com (Joel Andres Granados) Date: Tue, 22 May 2007 17:00:48 +0200 Subject: The use of universal_newlines in subprocess Message-ID: <465305A0.5010201@gmail.com> Hi list: I have been working with the universal_newlines option that can be specified while using the subprocess module. I'm calling an app that uses sys.stdout.write('\r'+' '*80) to manage its stdout. The situation that I encountered was that when I wanted to log this output into a file it looked rather freaky, so I needed to change the way the output was logged. I found the answer in the universal_newlines option (it basically changed all the \r for \n, which is a good idea in my case). When I read the documentation for the universal_newline it stated that "Also, the newlines attribute of the file objects stdout, stdin and stderr are not updated by the communicate() method.". So I did not use the communicate method thinking that it could not be used for my purpose. After some hours of trying to make it work without the communicate method I decide to use it and to my surprise it worked. So my question is what does " are not updated by the communicate() method " mean in the documentation. Thanx in advance. -------------- next part -------------- A non-text attachment was scrubbed... Name: joel.granados.vcf Type: text/x-vcard Size: 150 bytes Desc: not available URL: From kyosohma at gmail.com Thu May 3 10:37:32 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 3 May 2007 07:37:32 -0700 Subject: How to replace the last (and only last) character in a string? In-Reply-To: <1178202464.201578.211150@c35g2000hsg.googlegroups.com> References: <1178202464.201578.211150@c35g2000hsg.googlegroups.com> Message-ID: <1178203052.794524.223790@o5g2000hsb.googlegroups.com> On May 3, 9:27 am, Johny wrote: > Let's suppose > s='12345 4343 454' > How can I replace the last '4' character? > I tried > string.replace(s,s[len(s)-1],'r') > where 'r' should replace the last '4'. > But it doesn't work. > Can anyone explain why? > > Thanks > L. I think the reason it's not working is because you're doing it kind of backwards. For one thing, the "string" module is deprecated. I would do it like this: s = s.replace(s[len(s)-1], 'r') Although that is kind of hard to read. But it works. Mike From carsten at uniqsys.com Sun May 27 15:47:01 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sun, 27 May 2007 15:47:01 -0400 Subject: itertools.groupby In-Reply-To: <1180286272.100790.131670@q75g2000hsh.googlegroups.com> References: <1180286272.100790.131670@q75g2000hsh.googlegroups.com> Message-ID: <1180295221.3163.9.camel@localhost.localdomain> On Sun, 2007-05-27 at 10:17 -0700, 7stud wrote: > Bejeezus. The description of groupby in the docs is a poster child > for why the docs need user comments. Can someone explain to me in > what sense the name 'uniquekeys' is used this example: > > > import itertools > > mylist = ['a', 1, 'b', 2, 3, 'c'] > > def isString(x): > s = str(x) > if s == x: > return True > else: > return False > > uniquekeys = [] > groups = [] > for k, g in itertools.groupby(mylist, isString): > uniquekeys.append(k) > groups.append(list(g)) > > print uniquekeys > print groups > > --output:-- > [True, False, True, False, True] > [['a'], [1], ['b'], [2, 3], ['c']] The so-called example you're quoting from the docs is not an actual example of using itertools.groupby, but suggested code for how you can store the grouping if you need to iterate over it twice, since iterators are in general not repeatable. As such, 'uniquekeys' lists the key values that correspond to each group in 'groups'. groups[0] is the list of elements grouped under uniquekeys[0], groups[1] is the list of elements grouped under uniquekeys[1], etc. You are getting surprising results because your data is not sorted by the group key. Your group key alternates between True and False. Maybe you need to explain to us what you're actually trying to do. User-supplied comments to the documentation won't help with that. Regards, -- Carsten Haese http://informixdb.sourceforge.net From kib2 at free.fr Wed May 9 18:01:04 2007 From: kib2 at free.fr (tool69) Date: Thu, 10 May 2007 00:01:04 +0200 Subject: preferred windows text editor? In-Reply-To: <464222d8$0$30508$c3e8da3@news.astraweb.com> References: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> <464222d8$0$30508$c3e8da3@news.astraweb.com> Message-ID: <46424523$0$3276$426a74cc@news.free.fr> Notepad++ with NppExec plugin and you can launch your scripts inside Np++. some others, very Powerfull : http://e-texteditor.com/ http://intype.info/home/index.php From bbxx789_05ss at yahoo.com Sat May 26 20:32:44 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 26 May 2007 17:32:44 -0700 Subject: Newbie: Struggling again 'map' In-Reply-To: <1180181743.879140.304010@p47g2000hsd.googlegroups.com> References: <1180173252.906992.262570@q75g2000hsh.googlegroups.com> <1180181743.879140.304010@p47g2000hsd.googlegroups.com> Message-ID: <1180225964.929880.90430@p47g2000hsd.googlegroups.com> 1) If you write (...) after a function name, it executes the function(except when defining a function). And when you write (...) after a function name it's known as a "function call": def calc(): return 3.5 result = calc() + 2 2) Function calls are replaced in the code by the function's return value: result = calc() + 2 becomes: result = 3.5 + 2 3) map() and zip() perform two different tasks. zip() takes two(or more) sequences, and it returns a list of tuples, where each tuple consists of one element from each of the sequences: s1 = [1, 2, 3] s2 = [10, 20, 30, 40] print zip(s1, s2) --->[(1, 10), (2, 20), (3, 30)] If one sequence is shorter than the other, zip() stops when it reaches the end of the shorter sequence. On the other hand, map() applies a given function to each member of a sequence and returns a list that contains the return values of the function: s1 = [1, 2, 3] def f(x): return x*2 result = map(f, s1) print result ---->[2, 4, 6] If you call map() with a function and two sequences, e.g.: map(f, s1, s2) then the specified function will be called with two arguments--using one element from each sequence for the arguments: s1 = [1, 2, 3] s2 = [10, 20, 30] def f(x,y): return x + y result = map(f, s1, s2) print result ----->[11, 22, 33] If one sequence is shorter than the other, then unlike zip() which stops at the end of the shorter sequence, map() continues on until it reaches the end of the longer sequence. In that case, since the shorter sequence won't have any more values to provide, map() uses None. In other words, map() calls the specified function with one argument from the longer sequence and the other argument being None: s1 = [1, 2, 3] s2 = [10, 20, 30, 40, 50] def f(x,y): return x + y result = map(f, s1, s2) print result Traceback (most recent call last): File "2pythontest.py", line 7, in ? result = map(f, s1, s2) File "2pythontest.py", line 5, in f return x + y TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' The error results from the attempt inside the function f to add the value 40 from the second sequence to None(which is used in lieu of a value from the first sequence). So if you want to use map() with sequences of different lengths, before you perform any calculations in the specified function, you have to first check to see if one of the values is None. If one of the values is None, then you have to take some special action: s1 = [1, 2, 3] s2 = [10, 20, 30, 40, 50] def f(x,y): if x==None or y==None: return "N/A" return x + y result = map(f, s1, s2) print result ---->[11, 22, 33, 'N/A', 'N/A'] > for x,y in map(None, lista, listb): # Also fine - extends as > expected > print "MAP:", x, "<>", y That is not expected at all--at least not by me. You have to decipher the fine print of the map() description to expect that result. My expectation is the code will fail since None is not a function, and the first argument to map() is supposed to be a function. In any case, that should be considered aberrant behavior--not the normal way map() works. > for x,y in map("N/A", lista, listb): ########## Fails - Can not call a > 'str' > print "MAP:", x, "<>", y That is as expected since "N/A" is not a function. After all, how can you call a string? s = "hello world" print s(10) Obviously, that's nonsensical. > def fillwith(fillchars): > return fillchars > > for x,y in map(fillwith("N/A"), lista, listb): ########## Fails also - > Can not call a 'str' In the last line of code, the function call is replaced in the code by the function's return value(see point 2 above--at the very top of the post). Since the return value of the function call fillwith("N/A") is "N/A", the last line of your code becomes: for x,y in map("N/A", lista, listb) and once again map() is unable to call a string: s = "N/A" print s(lista[0], listb[0]) In conclusion, zip() returns a list of tuples (where each tuple contains one element from each sequence). map() returns a list (where each element of the list is the return value of a function). From martin at v.loewis.de Thu May 17 12:46:00 2007 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Thu, 17 May 2007 18:46:00 +0200 Subject: A bug in cPickle? In-Reply-To: References: <1179335180.786851.209900@y80g2000hsf.googlegroups.com> Message-ID: <464c86c9$0$6874$9b622d9e@news.freenet.de> > This does seem odd, at the very least. The differences between the pn codes comes from this comment in cPickle.c: /* Make sure memo keys are positive! */ /* XXX Why? * XXX And does "positive" really mean non-negative? * XXX pickle.py starts with PUT index 0, not 1. This makes for * XXX gratuitous differences between the pickling modules. */ p++; The second difference (where sometimes p1 is written and sometimes not) comes from this block in put: if (ob->ob_refcnt < 2 || self->fast) return 0; Here, a reference to the object is only marshalled if the object has more than one reference to it. The string literal does; the dynamically computed string does not. If there is only one reference to an object, there is no need to store it in the memo, as it can't possibly be referenced later on. Regards, Martin From antroy at gmail.com Wed May 9 11:06:23 2007 From: antroy at gmail.com (Ant) Date: 9 May 2007 08:06:23 -0700 Subject: N00b question on Py modules In-Reply-To: References: <1178521238.333095.111370@h2g2000hsg.googlegroups.com> <1178535840.526299.126700@e65g2000hsc.googlegroups.com> Message-ID: <1178723183.621515.235600@e65g2000hsc.googlegroups.com> On May 9, 2:47 pm, Sion Arrowsmith wrote: ... > How so? Python style gurus discourage use of global variables. So > does all the C++ (and to a lesser extent C) advice I've ever > encountered. And Java outright forbids the concept. Class variables (public static), are the equivalent of global variables in Java, and can be an equal pain. Singleton objects can cause similar problems, since they are essentially global objects, and changing the values of any of their members can cause wierd behaviour in otherwise unrelated parts of the code. So Java isn't by any means immune to the global variable problem, it just has different names for them! From bj_666 at gmx.net Sat May 19 13:57:02 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 19 May 2007 19:57:02 +0200 Subject: regex matching question References: <1179595319.239229.262160@l77g2000hsb.googlegroups.com> Message-ID: In <1179595319.239229.262160 at l77g2000hsb.googlegroups.com>, bullockbefriending bard wrote: > first, regex part: > > I am new to regexes and have come up with the following expression: > ((1[0-4]|[1-9]),(1[0-4]|[1-9])/){5}(1[0-4]|[1-9]),(1[0-4]|[1-9]) > > to exactly match strings which look like this: > > 1,2/3,4/5,6/7,8/9,10/11,12 > > i.e. 6 comma-delimited pairs of integer numbers separated by the > backslash character + constraint that numbers must be in range 1-14. > > i should add that i am only interested in finding exact matches (doing > some kind of command line validation). > > [?] > > the idea in the above code being that i want to use the regex match as > a test of whether or not the input string (results) is correctly > formatted. if the string results is not exactly matched by the regex, > i want my program to barf an exception and bail out. apart from > whether or not the regex is good idiom, is my approach suitably > pythonic? I would use a simple regular expression to extract "candidates" and a Python function to split the candidate and check for the extra constraints. Especially the "all pairs different" constraint is something I would not even attempt to put in a regex. For searching candidates this should be good enough:: r'(\d+,\d+/){5}\d+,\d+' Ciao, Marc 'BlackJack' Rintsch From alessiogiovanni.baroni at gmail.com Thu May 10 10:10:46 2007 From: alessiogiovanni.baroni at gmail.com (alessiogiovanni.baroni at gmail.com) Date: 10 May 2007 07:10:46 -0700 Subject: keyword checker - keyword.kwlist In-Reply-To: References: Message-ID: <1178806246.179950.147750@l77g2000hsb.googlegroups.com> On 10 Mag, 15:38, t... at finland.com wrote: > Hi > > I try to check whether a given input is keyword or not. However this > script won't identify keyword input as a keyword. How should I modify it > to make it work? > > #!usr/bin/env python > import keyword > > input = raw_input('Enter identifier to check >> ') > if input in keyword.kwlist: > print input + "is keyword" > > else: > print input + "is not keyword" Hmm... I tried, and identify it. Try to change the 'input' variable name with other... From carl at personnelware.com Thu May 24 10:41:58 2007 From: carl at personnelware.com (Carl K) Date: Thu, 24 May 2007 09:41:58 -0500 Subject: installing cx_Oracle. In-Reply-To: References: Message-ID: Bill Scherer wrote: > Carl K wrote: >> Getting closer, thanks Bill and Diez. >> >> $ export ORACLE_HOME >> $ ORACLE_HOME=/usr/lib/oracle/xe/app/oracle/product/10.2.0/client >> $ python setup.py build >> $ sudo python setup.py install >> >> $ python -c "import cx_Oracle" >> Traceback (most recent call last): >> File "", line 1, in ? >> ImportError: libclntsh.so.10.1: cannot open shared object file: No >> such file or directory >> >> guessing I need to add >> /usr/lib/oracle/xe/app/oracle/product/10.2.0/client/lib/ >> to some path? >> > You can `export > LD_LIBRARY_PATH=/usr/lib/oracle/xe/app/oracle/product/10.2.0/client/lib` > > or (assuming a recent RedHat linux (or similar) now), put that path in a > file, /etc/ld.so.conf.d/oracle.conf > > and run /sbin/ldconfig > > You'll find the latter operation to be persistent, and the former is not. >> btw - anyone know of a .deb that will install this? >> >> Carl K >> bingo. carl at dell17:~/a/cx_Oracle-4.3.1$ python Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02) [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import cx_Oracle >>> connection = cx_Oracle.connect('testuserA', 'pw', 'nf55') >>> cursor = connection.cursor() >>> cursor.execute("select * from tbl1") [, , ] >>> rows=cursor.fetchall() >>> rows [(1, 'a ', 1.01), (2, 'a ', 1.02), (3, 'a ', 1.03)] Thanks - now I can get to the real problem: client side join/order by :) But I have already done it in MySql, so this should be the easy part... Thanks again. Carl K From anton.vredegoor at gmail.com Mon May 14 05:29:55 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Mon, 14 May 2007 11:29:55 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: In article , nyamatongwe+thunder at gmail.com says... > Martin v. L?wis: > > > This PEP suggests to support non-ASCII letters (such as accented > > characters, Cyrillic, Greek, Kanji, etc.) in Python identifiers. > > I support this to ease integration with other languages and > platforms that allow non-ASCII letters to be used in identifiers. Python > has a strong heritage as a glue language and this has been enabled by > adapting to the features of various environments rather than trying to > assert a Pythonic view of how things should work. > > Neil > Ouch! Now I seem to be disagreeing with the one who writes my editor. What will become of me now? A. From robert.kern at gmail.com Fri May 25 18:52:24 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 25 May 2007 17:52:24 -0500 Subject: Long double in Python In-Reply-To: <200705252140.34353.charles.vejnar@isb-sib.ch> References: <200705252140.34353.charles.vejnar@isb-sib.ch> Message-ID: Charles Vejnar wrote: > Hi, > > I have a C library using "long double" numbers. I would like to be able to > keep this precision in Python (even if it's not portable) : for the moment I > have to cast the "long double" numbers to "double" numbers. > > 1st solution . Is it possible that by re-compiling Python, Python Float object > becomes "long double" C type instead of "double" ? It might be possible, but I recommend against it. > 2nd solution : Numpy. In memory, a "numpy.longdouble" is a C "long double" or > a string ? Well, it's always a sequence of bytes, but yes, it is a C "long double," whatever that happens to be on your platform. On my Intel MacBook: In [55]: import numpy In [56]: x = numpy.longdouble(1e200) In [57]: x Out[57]: 9.99999999999999969733e+199 In [58]: x * x Out[58]: 9.99999999999999939489e+399 In [59]: x * x * x Out[59]: 9.99999999999999909194e+599 In [60]: 1e200 * 1e200 * 1e200 Out[60]: inf -- 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 gagsl-py2 at yahoo.com.ar Mon May 28 01:36:08 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 28 May 2007 02:36:08 -0300 Subject: os.path.walk not pruning descent tree (and I'm not happy with that behavior?) References: <1180316372.126765.213530@r19g2000prf.googlegroups.com> Message-ID: En Sun, 27 May 2007 22:39:32 -0300, Joe Ardent escribi?: > Good day, everybody! From what I can tell from the archives, this is > everyone's favorite method from the standard lib, and everyone loves > answering questions about it. Right? :) Well, in fact, the preferred (and easier) way is to use os.walk - but os.path.walk is fine too. > Anyway, my question regards the way that the visit callback modifies > the names list. Basically, my simple example is: > > ############################## > def listUndottedDirs( d ): > dots = re.compile( '\.' ) > > def visit( arg, dirname, names ): > for f in names: > if dots.match( f ): > i = names.index( f ) > del names[i] > else: > print "%s: %s" % ( dirname, f ) > > os.path.walk( d, visit, None ) > ############################### There is nothing wrong with os.walk - you are iterating over the names list *and* removing elements from it at the same time, and that's not good... Some ways to avoid it: - iterate over a copy (the [:] is important): for fname in names[:]: if fname[:1]=='.': names.remove(fname) - iterate backwards: for i in range(len(names)-1, -1, -1): fname = names[i] if fname[:1]=='.': names.remove(fname) - collect first and remove later: to_be_deleted = [fname for fname in names if fname[:1]=='.'] for fname in to_be_deleted: names.remove[fname] - filter and reassign in place (the [:] is important): names[:] = [fname for fname in names if fname[:1]!='.'] (Notice that I haven't used a regular expression, and the remove method) -- Gabriel Genellina From Pavel.Stefanovic at gmail.com Tue May 29 14:21:50 2007 From: Pavel.Stefanovic at gmail.com (no`name`) Date: 29 May 2007 11:21:50 -0700 Subject: Connection acception with confirmation Message-ID: <1180462910.584445.256400@j4g2000prf.googlegroups.com> Hi, i'm new in Python and i'm trying to write some server which can confirm connection from client. Here is a part of code: import sys import threading from socket import * class TelGUI(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): s = socket(AF_INET, SOCK_STREAM) s.bind(('',8900)) s.listen(5) while 1: client,addr = s.accept() print addr print "Or u want to accept connection from this host? [y/n]" opt = sys.stdin.read(1) if opt == 'y': #establish else: s.close() #reject def main(): app = TelGUI() app.start() print "Menu" while 1: #some menu operations op = sys.stdin.read(1) if op == 'x': break if __name__ == "__main__": main() maybe someone have some ideas how to block first stdin in main function and get stdin from the thread when here is a new connection? Thanks From paul at boddie.org.uk Fri May 11 12:35:49 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 11 May 2007 09:35:49 -0700 Subject: Towards faster Python implementations - theory In-Reply-To: References: <1210i.7468$2v1.2505@newssvr14.news.prodigy.net> <1178804728.527486.196400@y80g2000hsf.googlegroups.com> Message-ID: <1178901348.978990.307950@e51g2000hsg.googlegroups.com> On 11 May, 18:04, John Nagle wrote: > > Another problem is that if the language is defined as > "whatever gets put in CPython", that discourages other > implementations. The language needs to be standards-based. Indeed. This was suggested by one of the speakers at last year's EuroPython with reference to the various proposals to remove map, reduce, lambda and so on from the language. The opinion was that if Python implementations change and leave the users either on unsupported releases or with the work of migrating their code continuously and/or to features that they don't find as intuitive or appropriate, some people would rather migrate their code to a language which is standardised and which can remain agreeable for the foreseeable future. Paul From bdesth.quelquechose at free.quelquepart.fr Thu May 10 18:38:17 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 11 May 2007 00:38:17 +0200 Subject: Newbie question about string(passing by ref) In-Reply-To: <1178833397.076720.279940@l77g2000hsb.googlegroups.com> References: <1178833397.076720.279940@l77g2000hsb.googlegroups.com> Message-ID: <464394cb$0$27196$426a74cc@news.free.fr> lazy a ?crit : > Hi, > > I want to pass a string by reference. I understand that strings are > immutable, but Im not > going to change the string in the function, just to aviod the overhead > of copying(when pass-by-value) because the > strings are long and this function will be called over and over > again. Once again : in Python, "variables" are just name=>ref pairs in a namespace. The concepts of "pass by ref" or pass by val" are meaningless here. Args passed to a function *are* references to objects - Python doesn't copy objects unless explicitelly asked to. > I initially thought of breaking the strings into list and passing the > list instead, but I think there should be an efficient way. A typical case of premature "optimization" !-) > So is there a way to pass a const reference to a string? Yes : be lazy, and don't worry about that. From showell30 at yahoo.com Sun May 27 17:59:43 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 27 May 2007 14:59:43 -0700 (PDT) Subject: itertools.groupby In-Reply-To: <1180295221.3163.9.camel@localhost.localdomain> Message-ID: <969509.18645.qm@web33508.mail.mud.yahoo.com> --- Carsten Haese wrote: > On Sun, 2007-05-27 at 10:17 -0700, 7stud wrote: > > Bejeezus. The description of groupby in the docs > is a poster child > > for why the docs need user comments. Can someone > explain to me in > > what sense the name 'uniquekeys' is used this > example: > > > > > > import itertools > > > > mylist = ['a', 1, 'b', 2, 3, 'c'] > > > > def isString(x): > > s = str(x) > > if s == x: > > return True > > else: > > return False > > > > uniquekeys = [] > > groups = [] > > for k, g in itertools.groupby(mylist, isString): > > uniquekeys.append(k) > > groups.append(list(g)) > > > > print uniquekeys > > print groups > > > > --output:-- > > [True, False, True, False, True] > > [['a'], [1], ['b'], [2, 3], ['c']] > > The so-called example you're quoting from the docs > is not an actual > example of using itertools.groupby [...] Huh? How is code that uses itertools.groupby not an actual example of using itertools.groupby? These docs need work. Please do not defend them; please suggest improvements. ____________________________________________________________________________________Take the Internet to Go: Yahoo!Go puts the Internet in your pocket: mail, news, photos & more. http://mobile.yahoo.com/go?refer=1GNXIC From nogradi at gmail.com Thu May 10 17:27:01 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Thu, 10 May 2007 23:27:01 +0200 Subject: File modes In-Reply-To: <1178830039.962239.245800@e51g2000hsg.googlegroups.com> References: <1178830039.962239.245800@e51g2000hsg.googlegroups.com> Message-ID: <5f56302b0705101427w3272361fh3d5a26122d7a4189@mail.gmail.com> > After reading a file is it possible to write to it without first > closing it? I tried opening with 'rw' access and re-winding. This does > not seem to work unless comments are removed. > > > Also, does close force a flush? > > Thanks, > > jh > > #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > f = open('c:\\tempMaxq\\incidents.txt', 'rw') > s = f.read() > lst = s.split() > incId = [] > incId.extend([lst.pop(), lst.pop()]) > #f.close() > #f = open('c:\\tempMaxq\\incidents.txt', 'w') > #f.seek(0) > for el in lst: > f.write(el + ' ') > f.close() Please see the documentation of the function open( ): http://python.org/doc/lib/built-in-funcs.html It says that the modes can only be 'r', 'w', 'a', 'r+', 'w+', 'a+' and possibly a 'b' or 'U' appended to these. So if you open it with 'rw' it will be interpreted as 'r'. For example this will not work: f = open( 'myfile', 'rw' ) f.write( 'hello' ) f.close( ) because python thinks you want to open 'myfile' in 'r' mode. I guess I agree that the thrown exception IOError: [Errno 9] Bad file descriptor is not very informative in this case. HTH, Daniel From bill.scherer at verizonwireless.com Thu May 24 09:20:08 2007 From: bill.scherer at verizonwireless.com (Bill Scherer) Date: Thu, 24 May 2007 09:20:08 -0400 Subject: installing cx_Oracle. In-Reply-To: References: Message-ID: <46559108.4010704@verizonwireless.com> Bill Scherer wrote: > Carl K wrote: > >> I am trying to use this: >> http://python.net/crew/atuining/cx_Oracle/html/cx_Oracle.html >> it is a real module, right? >> >> > It is indeed. > >> sudo easy_install cx_Oracle did not easy_install cx_Oracle. >> >> http://www.python.org/pypi/cx_Oracle/4.3.1 doesn't give me any clue. >> >> I got the source from >> http://prdownloads.sourceforge.net/cx-oracle/cx_Oracle-4.3.1.tar.gz?download >> >> carl at dell17:~/a/cx_Oracle-4.3.1$ python setup.py build >> Traceback (most recent call last): >> File "setup.py", line 36, in ? >> oracleHome = os.environ["ORACLE_HOME"] >> File "/usr/lib/python2.4/UserDict.py", line 17, in __getitem__ >> def __getitem__(self, key): return self.data[key] >> KeyError: 'ORACLE_HOME' >> >> > You have an oracle client installed, right? If not, go get an Instant > Client: > > http://www.*oracle*.com/technology/software/tech/oci/*instant**client*/index.html > muh. Sorry for the mangled url. try this one instead: http://www.oracle.com/technology/software/tech/oci/instantclient/index.html > > Then you need to set an environment variable, ORACLE_HOME, to point to > the root of the oracle client installation so that the cx_Oracle > installer can find the oracle libraries to build with. > > >> Now I don't really know whos problem this is. >> >> Carl K >> >> From herman_slagman at placid-dash-sky-dot-org Mon May 21 04:26:36 2007 From: herman_slagman at placid-dash-sky-dot-org (Herman Slagman) Date: Mon, 21 May 2007 10:26:36 +0200 Subject: Translating some Java to Python In-Reply-To: <1179692679.422164.27700@r3g2000prh.googlegroups.com> References: <1179692679.422164.27700@r3g2000prh.googlegroups.com> Message-ID: <465157bd$0$333$e4fe514c@news.xs4all.nl> "Daniel Gee" schreef in bericht news:1179692679.422164.27700 at r3g2000prh.googlegroups.com... > class Foo: > def statAdd(self,a): > return a+5 > > or do you drop the 'self' bit and just use a 1 variable parameter list? class Foo: @staticmethod def statAdd(a): return a+5 HTH Herman From carsten at uniqsys.com Tue May 8 10:18:34 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 08 May 2007 10:18:34 -0400 Subject: changing a var by reference of a list In-Reply-To: <11e49df10705080640pa19e535va4c21e41040b7dcc@mail.gmail.com> References: <5abcj4F2nv0p0U1@mid.uni-berlin.de> <11e49df10705080640pa19e535va4c21e41040b7dcc@mail.gmail.com> Message-ID: <1178633914.3357.45.camel@dot.uniqsys.com> On Tue, 2007-05-08 at 15:40 +0200, Jorgen Bodde wrote: > Ok thanks, > > I will try this approach. The idea was that I could give a list to the > SQL execute command, so that the results coming back would > automatically be assigned to variables. It's not possible to do that exactly as stated. A function can not modify its caller's namespace. (There is probably some dirty trick that can do this anyway, but you don't want to use dirty tricks.) Also, I'm not sure I'd want a function to pollute my local namespace with any variables of its choice. How would I know that it won't overwrite any variable whose contents I need? (Don't try to answer, this is a rhetorical question!) Most DB-API implementations have a facility to return query results as dictionaries or "a bag full of attributes"-type objects. The syntax for achieving this varies between implementations, because this is a non-standard addition outside the DB-API spec. With InformixDB for example, it would look something like this: import informixdb conn = informixdb.connect("stores_demo") cur = conn.cursor(rowformat=informixdb.ROW_AS_OBJECT) cur.execute("select * from customer") for row in cur: print row.customer_num, row.company This allows accessing the result columns as attributes of a row object, which is 99% as convenient as having local variables assigned to the results, and its 15000% cleaner. I strongly suggest you find an equivalent mechanism to use with whatever database module you're using, since it's a fairly safe bet that you're not using Informix. We could help you find that mechanism if you told us what database and what DB-API module you're using. Best regards, -- Carsten Haese http://informixdb.sourceforge.net From mailmaverick666 at gmail.com Thu May 3 03:50:43 2007 From: mailmaverick666 at gmail.com (rishi pathak) Date: Thu, 3 May 2007 13:20:43 +0530 Subject: Searching for a piece of string In-Reply-To: <1178177757.536983.277330@u30g2000hsc.googlegroups.com> References: <1178177757.536983.277330@u30g2000hsc.googlegroups.com> Message-ID: <180b672e0705030050h67bda4b6x3c1eeddf8da06d9f@mail.gmail.com> s="CastinTime" if s.find("Time") != -1: print "found" else: print "not found" On 3 May 2007 00:35:57 -0700, saif.shakeel at gmail.com wrote: > > Hi, > How can i match a part of string and branch to some part of code. > Ex If there is a string like "Timeout" and i want to search only > whether the word "Time" is present in it(which is valid in this > case).so if i have "CastinTime",still this should hold. > I need to use this in a "if" statement and code.Can someone help me > in this. > Thanks . > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Regards-- Rishi Pathak National PARAM Supercomputing Facility Center for Development of Advanced Computing(C-DAC) Pune University Campus,Ganesh Khind Road Pune-Maharastra -------------- next part -------------- An HTML attachment was scrubbed... URL: From AchatesAVC at gmail.com Sun May 20 21:54:05 2007 From: AchatesAVC at gmail.com (AchatesAVC) Date: 20 May 2007 18:54:05 -0700 Subject: list modification subclassing In-Reply-To: <1179708952.464667.47020@y18g2000prd.googlegroups.com> References: <1179708952.464667.47020@y18g2000prd.googlegroups.com> Message-ID: <1179712445.062126.278090@x18g2000prd.googlegroups.com> On May 20, 8:55 pm, manstey wrote: > Hi, > > I have a simple subclass of a list: > > class CaListOfObj(list): > """ subclass of list """ > def __init__(self, *args, **kwargs): > list.__init__(self, *args, **kwargs) > > a= CaListOfObj([1,2,3]) > > How do I write a method that does something EVERY time a is modified? > > Thanks You could overridge the __setitem__ and __setslice__ methods like so. def somefunc(): print 'Hello There' class CaListOfObj(list): """ subclass of list """ def __init__(self, *args, **kwargs): list.__init__(self, *args, **kwargs) def __setitem__(self,i,y): list.__setitem__(self,i,y) somefunc() def __setslice__(self,i,j,y): list.__setslice__(self,i,j,y) somefunc() >>> a= CaListOfObj([1,2,3]) >>> a[0]=2 Hello There >>> a[1:2]=[4,5] Hello There Is that anything like what you're trying to do? If you want this to work with append and extend you'll have to do the same sort of thing with those. From sjmachin at lexicon.net Mon May 21 17:35:42 2007 From: sjmachin at lexicon.net (John Machin) Date: Tue, 22 May 2007 07:35:42 +1000 Subject: re.compile for names In-Reply-To: References: Message-ID: <465210AE.6040803@lexicon.net> On 21/05/2007 11:46 PM, brad wrote: > I am developing a list of 3 character strings like this: > > and > bra > cam > dom > emi > mar > smi > ... > > The goal of the list is to have enough strings to identify files that > may contain the names of people. Missing a name in a file is unacceptable. The constraint that you have been given (no false negatives) is utterly unrealistic. Given that constraint, forget the 3-letter substring approach. There are many two-letter names. I have seen a genuine instance of a one-letter surname ("O"). In jurisdictions which don't disallow it, people can change their name to a string of digits. These days you can't even rely on names starting with a capital letter ("i think paris hilton is do u 2"). > > For example, the string 'mar' would get marc, mark, mary, maria... 'smi' > would get smith, smiley, smit, etc. False positives are OK (getting > common words instead of people's names is OK). > > I may end up with a thousand or so of these 3 character strings. If you get a large file of names and take every possible 3-letter substring that you find, you would expect to get well over a thousand. > Is that > too much for an re.compile to handle? Suck it and see. I'd guess that re.compile("mar|smi|jon|bro|wil....) is *NOT* the way to go. > Also, is this a bad way to > approach this problem? Yes. At the very least I'd suggest that you need to break up your file into "words" and then consider whether each word is part of a "name". Much depends on context, if you want to cut down on false positives -- "we went 2 paris n staid at the hilton", "the bill from the smith was too high". > Any ideas for improvement are welcome! 1. Get the PHB to come up with a more realistic constraint. 2. http://en.wikipedia.org/wiki/Named_entity_recognition HTH, John From kyosohma at gmail.com Wed May 9 17:34:39 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 9 May 2007 14:34:39 -0700 Subject: Comparing dates problem Message-ID: <1178746479.776908.319930@p77g2000hsh.googlegroups.com> Hi, I am writing a reminder program for our Zimbra email client. One of the requirements I was given was to automatically increment or decrement the display to show something like the following: 5 minutes until appointment or 10 minutes past your appointment Either way, as each minute goes by, I need to increment it or decrement it. I am having trouble finding a coherent way to take the same date and compare just the number of minutes between them to find the difference. Like if I have an appointment at 9:30 a.m. and the app is loaded at 8 a.m., I need to know the number of minutes or hours and minutes until the appointment. I have looked at the dateutils module and it has many comparison methods, but they seem to only return the number of days or seconds. Any ideas would be great! Mike From fdu.xiaojf at gmail.com Mon May 21 04:55:25 2007 From: fdu.xiaojf at gmail.com (fdu.xiaojf at gmail.com) Date: Mon, 21 May 2007 16:55:25 +0800 Subject: questions about programming styles In-Reply-To: References: <46501710.6090904@gmail.com> Message-ID: <46515E7D.5010103@gmail.com> Arvind Singh wrote: > On 5/20/07, fdu.xiaojf at gmail.com wrote: >> which is the better way to calculate the value of attributes of a >> class ? >> for example: >> >> (A) >> def cal_attr(self, args): >> #do some calculations >> self.attr = calculated_value >> and then if the vlue of attribute is needed, >> self.cal_attr(args) >> some_var = self.attr >> or I can define cal_attr() as follows: >> (B) >> def cal_attr(self, args): >> #do some calculations >> return calculated_value >> and then, if the value of attribute is needed, >> self.attr = self.cal_attr(args) >> some_var = self.attr > > The way, I get it: you are trying to *cache* the value of an > *expensive* calculation. You should worry about it if only if: > a. It is *really* expensive to calculate the value. > b. The value is read more often then it can change. > > Otherwise, just don't bother with it (i.e.use some_var = > obj.cal_value(*args) ). > > But if you really want to cache the value, maybe you should keep track > if the value is valid: > > class C(object): > def calc_attr(self, *args): > """Calculates value of "attr". > """ > self._attr = calculated_value > self._attr_valid = True > > def get_attr(self, *args): > """Use this to get values.""" > self._attr_valid or self.calc_attr(*args) > return self._attr > > def another_method(self, *args): > """Does some calculations which invalidate *cached* value of > "attr". > """ > # do something > self._attr_valid = False > >> (2) >> when to use class methods and when to use functions ? >> >> In my opinion, both of class methods and functions have advantages and >> disadvantages. I have to pass many arguments to a function, which is >> annoying. When using class methods, the arguments can be stored as >> attributes of the class, which is convenient for later use. But I have >> to create an object in advance. > > > I hope you know about all of it, but here it is, anyway: > > - In Python, *everything* is an object. > - Whenever Python finds a class definition, it creates a *class object*. > - A class objects acts as a *template* to create new objects called > *instances* (of that class). > - The template and the instance can both have *attributes* (to store > data). > - *Class attributes* can be accessed by both -- class as well as its > instances. > - *Instance attributes* can only be accesses by instances (because > class doesn't have to know about these). > - All the class attributes are shared among all the instances. If you > change an attribute of a class, all the instances of that class > (irrespective of when they were instantiated) will see the change. > > That gives us: > - *Instance methods* (or simply, "methods") can access: class > attributes, instance attributes, class methods, and instance methods. > (And are accessible via an instance only.) > - *Class methods* can ONLY access class attributes or other class > methods. (And are accessible via the class or its instance.) > - The first argument to instance methods is traditionally called > "self" (which is an *instance object*) and that of class methods is > called "cls" (which is a *class object*). > > > Design choices: > - The data which is to be shared by all the instances (and is mostly > immutable) should be kept as class attribute (to minimize memory > consumption). > - The methods which should produce same result for all instances (and > don't need to access instance attributes) should be declared as class > methods. > - Class attributes are also useful to *share state* among various > instances (so that they can co-operate). Such "sharing functionality" > is mostly implemented as class methods. > > > It's just whatever I could recollect and thought might be relevant. I > hope it helps. > > Arvind > > > PS: Defining something as "property" suggests (to the class users) > that it is inexpensive to access that value -- just a matter of style. > Thanks a lot for all kind replies! I think I need a systematic learning of design patterns. I have found some tutorials about design pattern about python, but can somebody point me which is the best to start with ? Regrads, xiaojf From nsjmetzger at gmail.com Fri May 4 15:24:38 2007 From: nsjmetzger at gmail.com (minitotoro) Date: 4 May 2007 12:24:38 -0700 Subject: Cannot execute Windows commands via Python in 64-bit In-Reply-To: <1178147703.568351.95740@e65g2000hsc.googlegroups.com> References: <1178143060.952025.85520@h2g2000hsg.googlegroups.com> <1178145527.014102.11480@l77g2000hsb.googlegroups.com> <1178147703.568351.95740@e65g2000hsc.googlegroups.com> Message-ID: <1178306678.251676.230370@p77g2000hsh.googlegroups.com> On May 2, 4:15 pm, minitotoro wrote: > On May 2, 3:46 pm, Larry Bates wrote: > > > > > minitotoro wrote: > > > On May 2, 3:07 pm, Larry Bates wrote: > > >> nsjmetz... at gmail.com wrote: > > >>> I have a script that runs fine in Windows 2003 (32-bit). It basically > > >>> calls the Windows defrag command. When I try the exact same code on > > >>> Windows 2003 (64-bit) I get the following message: > > >>> C:\Scripts>autodefrag.py > > >>> Starting defragment: defrag -v C: >>c:/Scripts/DEFRAG20070502.log > > >>> 'defrag' is not recognized as an internal or external command, > > >>> operable program or batch file. > > >>> I have tried defrag.exe and even giving it the full path to > > >>> defrag.exe. Always the same result. Here is the python code that is > > >>> generating this error: > > >>> cmd = "defrag -v C: >>c:/Scripts/DEFRAG20070502.log" > > >>> print "Starting defragment: ", cmd > > >>> errorlevel = os.system(cmd) > > >>> Anyone know what the heck is going on and how to fix it? This code > > >>> works fine on my 32-bit windows machines. > > >>> Thanks. > > >> Sounds like system can't find defrag. Usually this is because of a path > > >> issue. Are you running the script in the foreground or scheduled? Can > > >> you open a command prompt and enter the command and have it work? If > > >> you give full path, this shouldn't be the problem. > > > >> -Larry > > > > I have tried foreground and scheduled (neither works). I can run > > > defrag from the command prompt with no problem. If I give it the full > > > path in the script it still fails. I am completely befuddled. Help. > > > Copy and paste the traceback here for us. > > > -Larry > > I'm sorry, but I'm not familiar with traceback. How do I use it? > Thanks. Upon further investigation it turned out to be a windohs 64-bit issue (which is what I was afraid of). I did however find an asinine work around. Make a copy of defrag.exe from the system32 folder and paste it in the same directory as the python script. Voila! It now works. Piece of junk windohs... :-S From steve at holdenweb.com Mon May 7 07:45:48 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 07 May 2007 07:45:48 -0400 Subject: CGI python use "under a curse" In-Reply-To: <1178518223.618267.325710@e51g2000hsg.googlegroups.com> References: <1178512216.246621.38960@p77g2000hsh.googlegroups.com> <1178518223.618267.325710@e51g2000hsg.googlegroups.com> Message-ID: Adrian Smith wrote: > On May 7, 2:30 pm, Steven D'Aprano > wrote: >> On Sun, 06 May 2007 21:30:16 -0700, Adrian Smith wrote: > >> It is NOT the same error. There are NO syntax errors in the script, there >> is a runtime error. The so-called administrator is wrong: you can't use >> Perl to test just any old CGI scripts. They have to be written in Perl. > > Well, I thought that, but you know what happens to newbies who come > out with such opinions forcefully. Maybe they have special magic perl > which parses python. > >> I see from the source code on your page that you have a line: >> >> >> >> You have two lines in your cgi script: >> >> form = cgi.FieldStorage() >> print form["essay"].value >> >> Having never done cgi programming, I'm not sure what the problem is, but >> after reading help(cgi) I'll take a stab in the dark and say try this: >> >> print form.value >> >> It might also help for you to try this: >> >> print form.keys() > > Both give me the same ISE, alas. > >> Good luck with the "admins" at your hosting company. > > Well, it *is* free, and there aren't that many free ones that offer > Python. My paid-for host has sent me a message to say they're > ruminating on my issues, though, so I live in hope. > I'd go to Cornerhost. You can get a cheap account there and the support is friendly and knowledgable. I am no longer a customer and do not stand to gain by this recommendation, but they are a small business that were very helpful to me when I *was* a customer. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From toby at tobiah.org Thu May 3 14:44:22 2007 From: toby at tobiah.org (Tobiah) Date: Thu, 03 May 2007 11:44:22 -0700 Subject: Slicing Arrays in this way In-Reply-To: <1178146865.383519.326430@c35g2000hsg.googlegroups.com> References: <4638fe20$0$16403$88260bb3@free.teranews.com> <1178146865.383519.326430@c35g2000hsg.googlegroups.com> Message-ID: <463a2128$0$16355$88260bb3@free.teranews.com> John Machin wrote: > On May 3, 8:55 am, Steven D'Aprano > wrote: >> On Wed, 02 May 2007 15:03:24 -0700, Tobiah wrote: >> >>> >>> elegant_solution([1,2,3,4,5,6,7,8,9,10]) >>> [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] >> Wow! That's impressive. What version of Python are you using? When I try >> it, I get this: >> >>>>> elegant_solution([1,2,3,4,5,6,7,8,9,10]) >> Traceback (most recent call last): >> File "", line 1, in >> NameError: name 'elegant_solution' is not defined >> > > The OP has already confessed. Don't rub it in. > Well, my first post made perfect sense. My 'confession' involved noticing that I had replied to one respondent saying that I wanted something more concise, while praising the aptness of the same solution to the next poster. Lack of oxygen, I think. -- Posted via a free Usenet account from http://www.teranews.com From hq4ever at gmail.com Sat May 5 08:37:31 2007 From: hq4ever at gmail.com (Maxim Veksler) Date: Sat, 5 May 2007 15:37:31 +0300 Subject: Non blocking sockets with select.poll() ? In-Reply-To: <20070504125645.19381.772631055.divmod.quotient.8302@ohm> References: <20070504125645.19381.772631055.divmod.quotient.8302@ohm> Message-ID: On 5/4/07, Jean-Paul Calderone wrote: > >""" > >#!/usr/bin/env python > >import socket > >import select > > > >class PollingSocket(socket.socket): > > > > > > def __init__(self, port_number): > > self.__poll = select.poll() > > self.tcp_port_number = port_number > > > > socket.socket.__init__(self, socket.AF_INET, socket.SOCK_STREAM) > > self.setblocking(0) > > self.bind(('0.0.0.0', self.tcp_port_number)) > > self.listen(5) > > self.__poll.register(self) > > > > def poll(self, timeout = 0): > > return self.__poll.poll(timeout) > > > >def debugPollingSocket(port_num): > > print "BIND TO PORT: ", port_num > > return PollingSocket(port_num) > > > >all_sockets = map(debugPollingSocket, xrange(10000, 19169)) > > > >print "We have this in stock:" > >for nb_active_socket in all_sockets: > > print nb_active_socket.tcp_port_number > > > >while 1: > > for nb_active_socket in all_sockets: > > print "Asking", nb_active_socket.tcp_port_number > > if nb_active_socket.poll(0): > > print "Found", nb_active_socket.tcp_port_number > > conn, addr = nb_active_socket.accept() > > while 1: > > data = conn.recv(1024) > > if not data: break > > conn.send(data) > > conn.close() > >""" > > > > This will only handle one connection at a time, of course. The polling > it does is also somewhat inefficient. Perhaps that's fine for your use > case. If not, though, I'd suggest this version (untested): > Actually, I'm here to learn. I could have used any number of different approaches to accomplish this; starting from http://docs.python.org/lib/module-asyncore.html to twisted to http://oss.coresecurity.com/projects/pcapy.html. I would appreciate it if you could elaborate on why my loop is inefficient, I will try to improve it then (and post back). Besides, this whole story started from me writing a "quick totalitarian" security testing framework. Once I'm done with the networking part I will start working on the part that kill's all current processes listening on TCP/IP of the machine. Obviously thats not meant for production boxes... The simple idea is having the poller on one side of the firewall connection and the "monster" on the other side replying, a kind of primitive and plain firewall testing utility. > from twisted.internet import pollreactor > pollreactor.install() > > from twisted.internet import reactor > from twisted.protocols.wire import Echo > from twisted.internet.protocol import ServerFactory > > f = ServerFactory() > f.protocol = Echo > for i in range(10000, 19169): > reactor.listenTCP(i, f) > reactor.run() > > This will handle traffic from an arbitrary number of clients at the same > time and do so more efficiently than the loop in your version. You can > also try epollreactor instead of pollreactor, if the version of Linux you > are using supports epoll, for even better performance. > Thanks! > Jean-Paul > -- Cheers, Maxim Veksler "Free as in Freedom" - Do u GNU ? From tkpmep at hotmail.com Wed May 16 18:42:48 2007 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: 16 May 2007 15:42:48 -0700 Subject: pyExcelerator bug? Message-ID: <1179355368.793891.233240@u30g2000hsc.googlegroups.com> My program creates three lists: the first has dates expressed as strings, the second has floats that are strictly positive, and the third has floats that are strictly negative. I have no trouble writing the data in these lists to a .csv file using the csv module using the following code. outfile = file(fn + '.csv','wb') writer = csv.writer(outfile) for i in range(len(dateList)): writer.writerow([dateList[i], posVals[i], negVals[i]]) outfile.close() However, when I try to write to an Excel file using pyExcelerator (see code below), the third list is not always written correctly - my program sometimes writes positive numbers into the third column of the spreadsheet. Is this a known bug? if so, is there a workaround? Is pyExcelerator being developed any longer? My attempts to reach the developer have gone nowhere. w = pyExcelerator.Workbook() ws = w.add_sheet(fn + p) for i,d in enumerate(dateList): ws.write(i+1, 0, dateList[i]) ws.write(i+1, 1, posVals[i]) ws.write(i+1, 2, negVals[i]) w.save(fn+'.xls') Sincerely Thomas Philps From __peter__ at web.de Thu May 24 05:42:31 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 24 May 2007 11:42:31 +0200 Subject: function nested References: Message-ID: Gigs_ wrote: > i have this function. > > def f(start): > stack = [] > def f1(start): > for fname in os.listdir(startDir): > path = os.path.join(startDir, fname) > if os.path.isfile(path): > stack.append(path) > else: > f1(path) > return stack > > > this is returning empty list, why? Because f() doesn't invoke f1(). Peter From jmg3000 at gmail.com Thu May 10 12:45:44 2007 From: jmg3000 at gmail.com (jmg3000 at gmail.com) Date: 10 May 2007 09:45:44 -0700 Subject: Newbie look at Python and OO In-Reply-To: <1178812734.860473.236370@y80g2000hsf.googlegroups.com> References: <1178812734.860473.236370@y80g2000hsf.googlegroups.com> Message-ID: <1178815544.746022.67940@p77g2000hsh.googlegroups.com> On May 10, 11:58 am, walterbyrd wrote: >[snip] > > 2) list assignment handling, pointing two vars to the same list: > > With simple data types:>>> a = 5 > >>> b = a > >>> a = 3 > >>> a,b > > (3, 5) > > Which is what I'd expect, since I have changed a, but not b. > > But with lists:>>> a = list("1234") > >>> b = a > >>> a.append("5") > >>> a,b > > (['1', '2', '3', '4', '5'], ['1', '2', '3', '4', '5']) > > b changes even though I have not touched b. I know why, but this is > not what I would ordinarilly expect, it does not seem intuitive. Well, although it may not be what you expect right now, it *is* quite uniform with the rest of the language. That is: labels refer to objects. Writing ``a = b`` just makes the 'b' label refer to the same thing that the 'a' label refers to. Nice and simple. > And, > IMO, it gets worse: > > >>> a = list("1234") > >>> b = a > >>> a = a + ['5'] > >>> a,b > > (['1', '2', '3', '4', '5'], ['1', '2', '3', '4']) Now here, after you've set 'a' and 'b' to refer to the same object, you went and created a new object (a + ['5']) for a to refer to. ``a + ['5']`` creates a new object, whereas ``a.append('5')`` just modifies the existing object. (By the way, as an aside, '5' is a one-character string, not a number.) > [snip] > > 3) ambiguous use of the form: this.that() > > Sometimes, this.that() means module.funcion() as in: > > >>> os.dirlist(".") > > Other times, "this" is sort of like a parameter to the "that" > function: > > >>> a = list("1234") > >>> "_".join(a) > > '1_2_3_4_5' I think I see what you mean: In Python, there's this convention that you're supposed to name your classes starting with a capital letter (``class HeadCheese(object):``), but for core built-in classes, they start with a lower-case letter (like ``list``, ``dict``, ``set``, ``file``, etc.). So, ``list('foo')`` is actually a constructor call. Also, note that, in Python, "_" is a literal for creating a string object, so you can call methods on that resulting object -- as in ``'_'.join('cheezit')`` -- the same as if you'd said ``foo = "_"; foo.join('cheezit')``. > [snip] > > I'm not complaining. Python is a great language in many respects. But, > I would take some issue with those claiming Python is intuitive and > easy. IMO: there seems to be many ambiguous, unintuitve, and > confusing, aspects to Python. Well, every language has its warts. :) Folks are working to minimize or remove a number of them for Python 3000. ---John From M.Waack at gmx.de Fri May 25 06:09:38 2007 From: M.Waack at gmx.de (Mathias Waack) Date: Fri, 25 May 2007 10:09:38 GMT Subject: Compiling python extension on amd64 for 32 bit Message-ID: After switching my development environment to 64 bit I've got a problem with a python extension for a 32 bit application. Compiling the app under Linux results in the following error: g++ -m32 -Wall -g -O2 -I. -Idb -DPYTHON=25 -o mappy.o -c mappy.cpp In file included from /usr/include/python2.5/Python.h:57, from mappy.cpp:29: /usr/include/python2.5/pyport.h:732:2: error: #error "LONG_BIT definition appears wrong for platform (bad gcc/glibc config?)." My gcc is: Using built-in specs. Target: x86_64-suse-linux Configured with: ../configure --enable-threads=posix --prefix=/usr --with-local-prefix=/usr/local --infodir=/usr/share/info --mandir=/usr/share/man --libdir=/usr/lib64 --libexecdir=/usr/lib64 --enable-languages=c,c++,objc,fortran,obj-c++,java,ada --enable-checking=release --with-gxx-include-dir=/usr/include/c++/4.1.2 --enable-ssp --disable-libssp --disable-libgcj --with-slibdir=/lib64 --with-system-zlib --enable-shared --enable-__cxa_atexit --enable-libstdcxx-allocator=new --program-suffix=-4.1 --enable-version-specific-runtime-libs --without-system-libunwind --with-cpu=generic --host=x86_64-suse-linux Thread model: posix gcc version 4.1.2 20061115 (prerelease) (SUSE Linux) So I've checked this magic LONG_BIT define: #:/tmp cat t.c #include #include int main() { printf("%d\n",sizeof(long)); printf("%d\n",LONG_BIT); return 0; } #:/tmp gcc t.c #:/tmp ./a.out 8 64 #:/tmp gcc -m32 t.c #:/tmp ./a.out 4 32 Ok, thats fine. So why is python complaining? Or even more interesting, what do I have to do to compile the code? Mathias From sturlamolden at yahoo.no Wed May 30 11:15:57 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 30 May 2007 08:15:57 -0700 Subject: writing to a file In-Reply-To: <1180536826.630382.89610@u30g2000hsc.googlegroups.com> References: <1180515758.671628.43200@k79g2000hse.googlegroups.com> <5c5681F2t82noU1@mid.uni-berlin.de> <1180536826.630382.89610@u30g2000hsc.googlegroups.com> Message-ID: <1180538157.062816.136890@u30g2000hsc.googlegroups.com> On May 30, 4:53 pm, sturlamolden wrote: > import numpy > > byte = numpy.uint8 > desc = numpy.dtype({'names':['r','g','b'],'formats':[byte,byte,byte]}) > mm = numpy.memmap('myfile.dat', dtype=desc, offset=4096, > shape=(480,640), order='C') > red = mm['r'] > green = mm['g'] > blue = mm['b'] An other thing you may commonly want to do is coverting between numpy uint8 arrays and raw strings. This is done using the methods numpy.fromstring and numpy.tostring. # reading from file to raw string rstr = mm.tostring() # writing raw string to file mm[:] = numpy.fromstring(rstr, dtype=numpy.uint8) mm.sync() From exarkun at divmod.com Thu May 31 17:17:09 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 31 May 2007 17:17:09 -0400 Subject: Standalone HTTP parser? In-Reply-To: Message-ID: <20070531211709.30678.561999815.divmod.quotient.8256@ohm> On Thu, 31 May 2007 14:07:00 -0400, Christopher Stawarz wrote: >Does anyone know of a standalone module for parsing and generating >HTTP messages? I'm looking for something that will take a string and >return a convenient message object, and vice versa. All the Python >HTTP parsing code I've seen is either intimately bound to the >corresponding socket I/O operations (e.g. httplib, httplib2, >BaseHTTPServer) and/or buried in somebody's framework (e.g. Twisted). > >I want to write some HTTP servers/clients that do asynchronous I/O >using my own engine (multitask), so I need a HTTP package that won't >insist on doing the I/O for me. > Neither of Twisted's HTTP implementations insist on doing the I/O for you. All protocols in Twisted are independent of their transport. You can feed them data any way you like. Jean-Paul From mail at thegoldenaura.com Mon May 21 17:25:45 2007 From: mail at thegoldenaura.com (=?ISO-8859-1?Q?Jo=E3o_Santos?=) Date: Mon, 21 May 2007 23:25:45 +0200 Subject: Python Web Programming - looking for examples of solid high-traffic sites References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> Message-ID: Please have a look at Plone and Zope. "During the month of January 2006, we've had approx. 167 million hits" plone.org On 2007-05-16 23:04:17 +0200, Victor Kryukov said: > Hello list, > > our team is going to rewrite our existing web-site, which has a lot of > dynamic content and was quickly prototyped some time ago. > > Today, as we get better idea of what we need, we're going to re-write > everything from scratch. Python is an obvious candidate for our team: > everybody knows it, everybody likes it, it has *real* objects, nice > clean syntax etc. > > Our main requirement for tools we're going to use is rock-solid > stability. As one of our team-members puts it, "We want to use tools > that are stable, has many developer-years and thousands of user-years > behind them, and that we shouldn't worry about their _versions_." The > main reason for that is that we want to debug our own bugs, but not > the bugs in our tools. > > Our problem is - we yet have to find any example of high-traffic, > scalable web-site written entirely in Python. We know that YouTube is > a suspect, but we don't know what specific python web solution was > used there. > > TurboGears, Django and Pylons are all nice, and provides rich features > - probably too many for us - but, as far as we understand, they don't > satisfy the stability requirement - Pylons and Django hasn't even > reached 1.0 version yet. And their provide too thick layer - we want > something 'closer to metal', probably similar to web.py - > unfortunately, web.py doesn't satisfy the stability requirement > either, or so it seems. > > So the question is: what is a solid way to serve dynamic web pages in > python? Our initial though was something like python + mod_python + > Apache, but we're told that mod_python is 'scary and doesn't work very > well'. > > And although http://www.python.org/about/quotes/ lists many big names > and wonderful examples, be want more details. E.g. our understanding > is that Google uses python mostly for internal web-sites, and > performance is far from perfect their. YouTube is an interesting > example - anybody knows more details about that? > > Your suggestions and comments are highly welcome! > > Best Regards, > Victor. -- Jo?o Santos mail at thegoldenaura.com www.thegoldenaura.com From bj_666 at gmx.net Sat May 5 02:06:14 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 05 May 2007 08:06:14 +0200 Subject: Looping over lists References: <64D2C5F9-2896-47C3-8606-B021DB9D378A@mac.com> Message-ID: In , prad wrote: > On Friday 04 May 2007 18:40:53 Tommy Grav wrote: >> Can anyone help me with the right approach for this >> in python? > > for each in a: > for item in a[a.index(each)+1:]: > print each,item > > will produce > > 1 2 > 1 3 > 1 4 > 1 5 > 2 3 > 2 4 > 2 5 > 3 4 > 3 5 > 4 5 But only if the elements in the list are unique. And the runtime is suboptimal because `index()` is doing a linear search -- the outer loop becomes slower and slower with each iteration. Ciao, Marc 'BlackJack' Rintsch From S.Mientki-nospam at mailbox.kun.nl Sat May 19 05:57:52 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sat, 19 May 2007 11:57:52 +0200 Subject: (Modular-)Application Framework / Rich-Client-Platform in Python In-Reply-To: References: <8ea03$464dc950$d443bb3a$5229@news.speedlinq.nl> <3750e$464e1bda$d443bb3a$11610@news.speedlinq.nl> Message-ID: <96ff9$464ec95a$d443bb3a$8960@news.speedlinq.nl> Jarek Zgoda wrote: > Stef Mientki napisa?(a): > >> I took a look at some of the examples build with eclipse, >> and I might be wrong, but it's just another IDE, >> (like Delphi, Lazarus, Visual Basic, Kylix, Pida, Envisage, VisualWX, >> wxGlade, ...) >> what am I missing ? > > I think you miss the difference between Eclipse IDE and Eclipse > Platform. The IDE is and application built using RCP. As Azureus or > RSSOwl, which aren't IDE-type applications. One of the tutorials > mentioned int the RCP wiki takes user through creating an email client > application, which is not an IDE, definitely. Eclipse RCP allows > building applications as a set of pluggable features over common > runtime. While not a "mark-and-drop" solution yet, it's a great leap > forward in Java desktop applications. > > There's more to Eclipse that just IDE. ;) > Sorry, I don't get the difference between an IDE and RPC. If I look at the demo of the "email client" you mentioned, (and I don't understand a bit of Java), I see a very complex story (at least for me). Is there an easy possibility that I can see the "email client" you mentioned, working on my computer, so I can judge how I would create the same functionality in one of the other IDE's, maybe then I get the picture. thanks, Stef Mientki From turbana at gmail.com Fri May 11 22:11:52 2007 From: turbana at gmail.com (Ian Clark) Date: Fri, 11 May 2007 19:11:52 -0700 Subject: need help with python In-Reply-To: <1178934447.719778.197150@h2g2000hsg.googlegroups.com> References: <1178934447.719778.197150@h2g2000hsg.googlegroups.com> Message-ID: On 11 May 2007 18:47:27 -0700, adamurbas at hotmail.com wrote: > ya so im pretty much a newb to this whole python thing... its pretty > cool but i just started today and im already having trouble. i > started to use a tutorial that i found somewhere and i followed the > instructions and couldnt get the correct results. heres the code > stuff... > > temperature=input("what is the temperature of the spam?") > if temperature>50: > print "the salad is properly cooked." > else: > print "cook the salad some more." > > ya i was trying to do that but when i told it what the spams > temperature was, it just turned off... well it wasnt working at all at > first until i realized that i hadnt been following the instructions > completely correctly and that i was supposed to type that code up in a > notepad then save and open with python... so ya thats when it asked me > what temperature the spam was and i typed a number then it just closed > itself... im not really sure what went wrong... itd be real nice if > someone would be like a mentor or something... > I'm making a couple of assumptions here (correct me if I'm wrong): 1. You're using windows 2. You double clicked on the .py file What this does is open up a new terminal window and start execution of the program. The program will execute to completion and then the window will close automatically without waiting for you to tell it to (lovely isn't it?). To get around this you have a couple options: 1. Run the script from the command line 2. Put this at the end of the .py file: input('Press ENTER to continue') Ian From okyoon at stanford.edu Tue May 1 11:20:41 2007 From: okyoon at stanford.edu (OhKyu Yoon) Date: Tue, 1 May 2007 08:20:41 -0700 Subject: Qustion about struct.unpack In-Reply-To: References: <1178007769.831101.238210@u30g2000hsc.googlegroups.com> Message-ID: Wow, thank you all! "Gabriel Genellina" wrote in message news:op.trm6zrmbx6zn5v at furufufa-ec0e13.cpe.telecentro.com.ar... > En Tue, 01 May 2007 05:22:49 -0300, eC escribi?: > >> On Apr 30, 9:41 am, Steven D'Aprano >> wrote: >>> On Mon, 30 Apr 2007 00:45:22 -0700, OhKyu Yoon wrote: > >>> > I have a really long binary file that I want to read. >>> > The way I am doing it now is: >>> >>> > for i in xrange(N): # N is about 10,000,000 >>> > time = struct.unpack('=HHHH', infile.read(8)) >>> > # do something >>> > tdc = struct.unpack('=LiLiLiLi',self.lmf.read(32)) >>> >>> Disk I/O is slow, so don't read from files in tiny little chunks. Read a >>> bunch of records into memory, then process them. >>> >>> # UNTESTED! >>> rsize = 8 + 32 # record size >>> for i in xrange(N//1000): >>> buffer = infile.read(rsize*1000) # read 1000 records at once >>> for j in xrange(1000): # process each record >>> offset = j*rsize >>> time = struct.unpack('=HHHH', buffer[offset:offset+8]) >>> # do something >>> tdc = struct.unpack('=LiLiLiLi', buffer[offset+8:offset+rsize]) >>> # do something >>> >>> (Now I'm just waiting for somebody to tell me that file.read() already >>> buffers reads...) >> >> I think the file.read() already buffers reads... :) > > Now we need someone to actually measure it, to confirm the expected > behavior... Done. > > --- begin code --- > import struct,timeit,os > > fn = r"c:\temp\delete.me" > fsize = 1000000 > if not os.path.isfile(fn): > f = open(fn, "wb") > f.write("\0" * fsize) > f.close() > os.system("sync") > > def smallreads(fn): > rsize = 40 > N = fsize // rsize > f = open(fn, "rb") > for i in xrange(N): # N is about 10,000,000 > time = struct.unpack('=HHHH', f.read(8)) > tdc = struct.unpack('=LiLiLiLi', f.read(32)) > f.close() > > > def bigreads(fn): > rsize = 40 > N = fsize // rsize > f = open(fn, "rb") > for i in xrange(N//1000): > buffer = f.read(rsize*1000) # read 1000 records at once > for j in xrange(1000): # process each record > offset = j*rsize > time = struct.unpack('=HHHH', buffer[offset:offset+8]) > tdc = struct.unpack('=LiLiLiLi', buffer[offset+8:offset+rsize]) > f.close() > > print "smallreads", timeit.Timer("smallreads(fn)","from __main__ import > fn,smallreads,fsize").repeat(3,1) > print "bigreads", timeit.Timer("bigreads(fn)", "from __main__ import > fn,bigreads,fsize").repeat(3,1) > --- end code --- > > Output: > smallreads [4.2534193777646663, 4.126013885559789, 4.2389176672125458] > bigreads [1.2897319939456011, 1.3076018578892405, 1.2703250635695138] > > So in this sample case, reading in big chunks is about 3 times faster than > reading many tiny pieces. > > -- > Gabriel Genellina From projecktzero at yahoo.com Wed May 30 12:16:59 2007 From: projecktzero at yahoo.com (projecktzero) Date: 30 May 2007 09:16:59 -0700 Subject: Is PEP-8 a Code or More of a Guideline? In-Reply-To: References: <316098.9123.qm@web33510.mail.mud.yahoo.com> <465C3861.8010508@aristote.info> Message-ID: <1180541819.177905.264630@u30g2000hsc.googlegroups.com> On May 30, 12:36 am, "Hendrik van Rooyen" wrote: > "Maric Michaud" wrote: > > Typist is fine, although MCP that I am, I tend to think of > typist as female... > - Hendrik What does being a Microsoft Certified Professional(MCP) have to do with thinking of a typist as female? =) From kevin.bell at slcgov.com Wed May 30 10:36:43 2007 From: kevin.bell at slcgov.com (Bell, Kevin) Date: Wed, 30 May 2007 08:36:43 -0600 Subject: google maps api for py? Message-ID: <2387F0EED10A4545A840B231BBAAC722F11AB7@slcimail1.slcgov.com> I see that the weapon of choice for google maps is javascript... Is there anything for python? Kev -------------- next part -------------- An HTML attachment was scrubbed... URL: From bdesth.quelquechose at free.quelquepart.fr Tue May 22 16:41:49 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 22 May 2007 22:41:49 +0200 Subject: [Fwd: Re: managed lists?] In-Reply-To: References: <4651fe96$0$24671$426a34cc@news.free.fr> <11e49df10705220013q11c35e6axba72cc4227401ac2@mail.gmail.com> Message-ID: <46534b25$0$19922$426a74cc@news.free.fr> Jorgen Bodde a ?crit : (snip) > class ObjListException(Exception): > pass > > class ObjListIterator(object): > def __init__(self, objlist): > self.__objlist = objlist > self.__idx = 0 You should use a single underscore here. From martin at v.loewis.de Thu May 31 17:12:08 2007 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Thu, 31 May 2007 23:12:08 +0200 Subject: non standard path characters In-Reply-To: References: <465ec26a$0$336$e4fe514c@news.xs4all.nl> Message-ID: <465F3A28.9030502@v.loewis.de> > thanks for that. I guess the problem is that when a path is obtained > from such an object the code that gets the path usually has no way of > knowing what the intended use is. That makes storage as simple bytes > hard. I guess the correct way is to always convert to a standard (say > utf8) and then always know the required encoding when the thing is to be > used. Inside the program itself, the best things is to represent path names as Unicode strings as early as possible; later, information about the original encoding may be lost. If you obtain path names from the os module, pass Unicode strings to listdir in order to get back Unicode strings. If they come from environment variables or command line arguments, use locale.getpreferredencoding() to find out what the encoding should be. If they come from a zip file, Tijs already explained what the encoding is. Always expect encoding errors; if they occur, chose to either skip the file name, or report an error to the user. Notice that listdir may return a byte string if decoding fails (this may only happen on Unix). Regards, Martin From jowr.pi at gmail.com Wed May 2 23:46:14 2007 From: jowr.pi at gmail.com (Eric Gisse) Date: 2 May 2007 20:46:14 -0700 Subject: Firefighters at the site of WTC7 "Move away the building is going to blow up, get back the building is going to blow up." In-Reply-To: <1178161820.731367.264500@y80g2000hsf.googlegroups.com> References: <1178161820.731367.264500@y80g2000hsf.googlegroups.com> Message-ID: <1178163974.007362.13870@c35g2000hsg.googlegroups.com> On May 2, 7:10 pm, Midex wrote: [...] I guess the explanation that people were looking at the building and watching its' structure deform is too rational. From ptmcg at austin.rr.com Mon May 21 10:02:02 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 21 May 2007 07:02:02 -0700 Subject: re.compile for names In-Reply-To: References: Message-ID: <1179756122.369462.200260@r3g2000prh.googlegroups.com> On May 21, 8:46 am, brad wrote: > I am developing a list of 3 character strings like this: > > and > bra > cam > dom > emi > mar > smi > ... > > The goal of the list is to have enough strings to identify files that > may contain the names of people. Missing a name in a file is unacceptable. > > For example, the string 'mar' would get marc, mark, mary, maria... 'smi' > would get smith, smiley, smit, etc. False positives are OK (getting > common words instead of people's names is OK). > > I may end up with a thousand or so of these 3 character strings. Is that > too much for an re.compile to handle? Also, is this a bad way to > approach this problem? Any ideas for improvement are welcome! > > I can provide more info off-list for those who would like. > > Thank you for your time, > Brad There are only 17,576 possible 3-letter strings, so you must keep your percentage of this number small for this filter to be of any use. With a list of a dozen or so strings, this may work okay for you. But the more of these strings that you add, the more the number of false positives will frustrate your attempts at making any sense of the results. I suspect that using a thousand or so of these strings will end up matching 95+% of all files. You will also get better results if you constrain the location of the match, for instance, looking for file names that *start* with someone's name, instead of just containing them somewhere. -- Paul From Roka100 at gmail.com Fri May 18 11:49:36 2007 From: Roka100 at gmail.com (Jia Lu) Date: 18 May 2007 08:49:36 -0700 Subject: Why canNOT import from a local directory ? Message-ID: <1179503376.706409.185930@w5g2000hsg.googlegroups.com> Hi all I created a folder named *lib* and put a py file *lib.py* in it. In the upper folder I created a py file as: import lib.lib def main(): """ __doc__ """ lib.lib.test() # //////////////////////////////////////// if __name__ == "__main__": main() But I got an error : #.:python main.py Traceback (most recent call last): File "main.py", line 6, in ? import lib.lib ImportError: No module named lib.lib Why ? From basilisk96 at gmail.com Wed May 2 16:49:24 2007 From: basilisk96 at gmail.com (Basilisk96) Date: 2 May 2007 13:49:24 -0700 Subject: How to check if a string is empty in python? In-Reply-To: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> References: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> Message-ID: <1178138964.503290.254060@o5g2000hsb.googlegroups.com> A simple if s: print "not empty" else: print "empty" will do. -Basilisk96 From orsenthil at gmail.com Fri May 18 19:15:04 2007 From: orsenthil at gmail.com (Phoe6) Date: 18 May 2007 16:15:04 -0700 Subject: RFC - n-puzzle.py Message-ID: <1179530104.645902.135250@p77g2000hsh.googlegroups.com> Hi All, I would like to request a code and design review of one of my program. n-puzzle.py http://sarovar.org/snippet/detail.php?type=snippet&id=83 Its a N-puzzle problem solver ( Wikipedia page and http://norvig.com/ltd/test/n-puzzle.lisp ) I have used OO Python for the above program and would like comments on my approach as I am just starting with OOP. Thanks Senthil From lists at webcrunchers.com Thu May 3 21:49:02 2007 From: lists at webcrunchers.com (John Draper) Date: Thu, 03 May 2007 18:49:02 -0700 Subject: Can I use Python instead of Joomla? In-Reply-To: <1178138925.498663.252920@o5g2000hsb.googlegroups.com> References: <1178138925.498663.252920@o5g2000hsb.googlegroups.com> Message-ID: <463A910E.6000602@webcrunchers.com> walterbyrd wrote: >If I wanted to build a website with forums, news feeds, galleries, >event calander, document managment, etc. I do so in Joomla easily. > >But, I would perfer to use django/python, if that would be at all >practical. > >I suppose I could put python scripts into django, if those scripts >exist. > > > There are at least 3 Python oriented web apps out there. I highly recommend you ditch Joomla as soon as you can. joomla has a lot of security issues, and I've been trying to get my friend off of this POS for the longest time. Her web sites are constantly getting defaced... there are at least 3 Joomla exploits I know of out there. djangoproject.org turbogears.com plone.org Check these out. But get off of Joomla as soon as you can. I admit, Joomla is easy to use I admit, but very easy to vector into a root exploit. John From sjdevnull at yahoo.com Fri May 18 17:18:31 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 18 May 2007 14:18:31 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <464C5382.6080403@v.loewis.de> <1179423799.254286.294930@w5g2000hsg.googlegroups.com> <1179503525.018943.95740@u30g2000hsc.googlegroups.com> <1179508599.868680.177960@e65g2000hsc.googlegroups.com> Message-ID: <1179523111.401781.125660@k79g2000hse.googlegroups.com> On May 18, 1:47 pm, "Javier Bezos" wrote: > >> This question is more or less what a Korean who doesn't > >> speak English would ask if he had to debug a program > >> written in English. > > > Perhaps, but the treatment by your mail/news software plus the > > delightful Google Groups of the original text (which seemed intact in > > the original, although I don't have the fonts for the content) would > > suggest that not just social or cultural issues would be involved. > > The fact my Outlook changed the text is irrelevant > for something related to Python. On the contrary, it cuts to the heart of the problem. There are hundreds of tools out there that programmers use, and mailing lists are certainly an incredibly valuable tool--introducing a change that makes code more likely to be silently mangled seems like a negative. Of course, there are other benefits to the PEP, so I'm only barely opposed. But dismissing the fact that Outlook and other quite common tools may have severe problems with code seems naive (or disingenuous, but I don't think that's the case here). From hg at nospam.org Fri May 4 01:56:21 2007 From: hg at nospam.org (hg) Date: Fri, 04 May 2007 07:56:21 +0200 Subject: Real Time Battle and Python References: <1178224357.498503.206570@h2g2000hsg.googlegroups.com> Message-ID: Matimus wrote: > On May 3, 5:20 am, hg wrote: >> Hi, >> >> I have started to work on a python-based robot, and am interested in your >> feedback: >> >> http://realtimebattle.sourceforge.net/www.snakecard.com/rtb >> >> hg > > This is not necessarily a response to your effort, but just a note > (rant) about realtimebattle. It reminds me more of homework in 300 and > 400 level college engineering classes than a game. Based upon my > previous effort and realizations, I found realtimebattle coding to be, > from a programming perspective, an exercise in protocol implementation > first. Once the protocol work is done you need to implement control > algorithms for movement and enemy tracking. Think PID algorithms > (Proportional, Integral and Differential). Only when the protocol and > control portions are done can you focus on strategy and play the game. > You should also note, however, that the first two tasks are quite > daunting. And the second is difficult to get right. I found the whole > process to be very tiring and not very rewarding. I don't mean to > discourage you, I just think it would be more fun to write my own game > than to 'play' that one. > > A better game, from a programming perspective, would be > "discretetimebattle". Where each player controls their robot with > second order parameters (velocity not force), the world has no third > order effects (friction) and the time is discrete. Discrete time > meaneing that the protocol updates every player at regular intervals > with the same information and, in terms of the simulation, each update > represents a set time delta. > > I would be interested to know if anybody else has played, or tried to > play, realtimebattle and has similar sentiments. > > I do wish you luck though. If you get a robot working you are a far > more dedicated and patient individual than me. > > -Matt I do try to separate the "engine" from the "driver". Yes the engine is a pain to code and the documentation quite skimpy (have to got through C headers to understand the command set) ... still I'll try to finish it. hg From duncan.booth at invalid.invalid Tue May 1 11:17:48 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 May 2007 15:17:48 GMT Subject: Why are functions atomic? References: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> <1178030115.591931.137040@h2g2000hsg.googlegroups.com> Message-ID: 7stud wrote: > Does deepcopy work? It doesn't copy a function. The easiest way to make a modified copy of a function is to use the 'new' module. >>> def f(x=2): print "x=", x >>> g = new.function(f.func_code, f.func_globals, 'g', (3,), f.func_closure) >>> g() x= 3 >>> f() x= 2 From rajarshi.guha at gmail.com Thu May 24 00:53:20 2007 From: rajarshi.guha at gmail.com (Rajarshi) Date: 23 May 2007 21:53:20 -0700 Subject: 0 == False but [] != False? Message-ID: <1179982400.412340.178710@g4g2000hsf.googlegroups.com> This is a slightly naive question, but I know that 0 can be used to represent False. So >>> 0 == False True But, I know I can use [] to represent False as in >>> if not []: print 'empty' ... empty But then doing the following gives a surprising (to me!) result >>> [] == False False Could anybody point out why this is the case? Thanks, Rajarshi From aleax at mac.com Wed May 2 00:02:23 2007 From: aleax at mac.com (Alex Martelli) Date: Tue, 1 May 2007 21:02:23 -0700 Subject: relative import broken? References: <1hxa9x3.c0unyd1jw7vu9N%aleax@mac.com> <1hxcdkq.47p2r6beuctcN%aleax@mac.com> <1hxeg2v.1ct59rv3oyq87N%aleax@mac.com> <7nNZh.4420$st3.1414@trnddc06> Message-ID: <1hxgczf.1l5eh5j1vln0z9N%aleax@mac.com> Alan Isaac wrote: > "Alex Martelli" wrote in message > news:1hxeg2v.1ct59rv3oyq87N%aleax at mac.com... > > I don't know of any "pretty" way -- I'd do it by path manipulation > > (finding mypackage from os.path.abspath(__file__) and inserting its > > _parent_ directory in sys.path). > > > Yes, that seems to be the standard solution. > I find it ugly. Anyway, I suppose my question remains: > why are we constrained from solving this with > a relative import? (And I suppose your answer will be: > well then, relative to *what*? I am having trouble > seeing why that answer cannot be given a clear riposte.) So what do you think the answer should be? Alex From steven at REMOVE.THIS.cybersource.com.au Tue May 15 22:23:33 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 16 May 2007 02:23:33 GMT Subject: Interesting list Validity (True/False) References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> <1178914190.166662.285410@p77g2000hsh.googlegroups.com> <1178915791.584216.293130@l77g2000hsb.googlegroups.com> <1178918808.091358.233740@o5g2000hsb.googlegroups.com> <1179017740.656323.209590@e51g2000hsg.googlegroups.com> <1179020634.130689.171960@o5g2000hsb.googlegroups.com> <1179031812.090768.248750@l77g2000hsb.googlegroups.com> <1179168081.603409.39970@e51g2000hsg.googlegroups.com> Message-ID: On Mon, 14 May 2007 11:41:21 -0700, mensanator at aol.com wrote: > On May 13, 8:24 am, Steven D'Aprano > wrote: >> On Sat, 12 May 2007 21:50:12 -0700, mensana... at aol.com wrote: > > I intended to reply to this yesterday, but circumstances (see timeit > results) prevented it. > >> >> > Actually, it's this statement that's non-sensical. >> >> >> > >> >> > "if arg==True" tests whether the object known as arg is equal to >> >> > the object known as True. >> >> > >> >> >> Not at all, it makes perfect sense. X == Y always tests whether the >> >> argument X is equal to the object Y regardless of what X and Y are. >> >> > Except for the exceptions, that's why the statement is wrong. >> >> But there are no exceptions. > > > Sec 2.2.3: > Objects of different types, *--->except<---* different numeric types and > different string types, never compare equal; Yes, and all swans are white, except for the black swans from Australia, but we're not talking about swans, nor are we talking about objects of different type comparing unequal, we're talking about whether X == Y means X is equal to Y. THERE ARE NO EXCEPTIONS TO THIS, BECAUSE IT IS TRUE BY DEFINITION. In Python, the meaning of "equal" is nothing more and nothing less than "does X == Y return True?". End of story, there is nothing more to discuss. If it returns True, they are equal. If it doesn't, they aren't. If you want to drag in non-Python meanings of "equal", you are wrong to do so. "Lizzie Windsor", "Queen Elizabeth the Second", "the Queen of England" and "Her Royal Majesty, Queen Elizabeth II" are all equal in the sense that they refer to the same person, but it would be crazy to expect Python to compare those strings equal. If you want to complain that lists and tokens should compare equal if their contents are the same, that's a different issue. I don't believe you'll have much support for that. If you want to complain that numeric types shouldn't compare equal, so that 1.0 != 1 != 1L != gmpy.mpz(1), that's also a different issue. I believe you'll have even less support for that suggestion. [snip] >> > No, they are not "equal". >> >> Of course they are. It says so right there: "a equals d" is true. > > Ok, but they are an exception to the rule "different types compare > False". You are only quoting part of the rule. The rule says that numeric types and strings are not included in the "different types" clause. If you quote the full rule, you will see that it is not an exception to the rule, it matches perfectly. Although, the rule as given is actually incomplete, because it only applies to built-in types. It does not apply to classes, because the class designer has complete control over the behaviour of his class. If the designer wants his class to compare equal to lists on Wednesdays and unequal on other days, he can. (That would be a stupid thing to do, but possible.) [snip] >> > The ints >> > ALWAYS have to be coerced to mpzs to perform arithmetic and this >> > takes time...LOTS of it. >> >> Really? Just how much time? > > Can't say, had to abort the following. Returns the count of n/2 and 3n+1 > operations [1531812, 854697]. Maybe you should use a test function that isn't so insane then. Honestly, if you want to time something, time something that actually completes! You don't gain any accuracy by running a program for twenty hours instead of twenty minutes. [snip functions generating the Collatz sequence] >> timeit.Timer("x == y", "import gmpy; x = 1; y = gmpy.mpz(1)").repeat() >> timeit.Timer("x == y", "x = 1; y = 1").repeat() >> >> I don't have gmpy installed here, > > Good Lord! How do you solve a Linear Congruence? :-) In my head of course. Don't you? *wink* >> so I can't time it, but I look forward to seeing the results, if you >> would be so kind. > > I had a lot of trouble with this, but I think I finally got a handle on > it. I had to abort the previous test after 20+ hours and abort a second > test (once I figured out to do your example) on another machine after > 14+ hours. I had forgotten just how significant the difference is. > > import timeit > > ## t = timeit.Timer("a == b", "a = 1; b = 1") ## u = > timeit.Timer("c == d", "import gmpy; c = 1; d = gmpy.mpz(1)") > ## t.repeat() > ## [0.22317417437132372, 0.22519314605627253, 0.22474588250741367] ## > u.repeat() > ## [0.59943819675405763, 0.5962260566636246, 0.60122920650529466] Comparisons between ints take about 0.2 microseconds, compared to about 0.6 microseconds for small gmpy.mpz values. That's an optimization worth considering, but certainly not justifying your claim that one should NEVER compare an int and a mpz "in a loop". If the rest of the loop takes five milliseconds, who cares about a fraction of a microsecond difference? > Unfortunately, this is not a very useful test, since mpz coercion > appears to vary ny the size of the number involved. No, it is a very useful test. It's not an EXHAUSTIVE test. (By the way, you're not testing coercion. You're testing the time it takes to compare the two. There may or may not be any coercion involved.) > Although changing t to > > ## t = timeit.Timer("a == b", "a = 2**177149-1; b = 2**177149-1") > > still produces tractable results > ## t.repeat() > ## [36.323597552202841, 34.727026758987506, 34.574566320579862] About 36 microseconds per comparison, for rather large longints. > the same can't be said for mpz coercion: > > ## u = timeit.Timer("c == d", "import gmpy; c = 2**177149-1; d = > gmpy.mpz(2**177149-1)") > ## u.repeat() > ## *ABORTED after 14 hours* This tells us that a comparison between large longints and large gmpz.mpz vales take a minimum of 14 hours divided by three million, or roughly 17 milliseconds each. That's horribly expensive if you have a lot of them. It isn't clear _why_ the comparison takes so long. [snip] > And, just for laughs, I compared mpzs to mpzs, > > s = 'import gmpy; a = gmpy.mpz(%d); b = gmpy.mpz(%d)' % (n,n) > > which ended up faster than comparing ints to ints. I'm hardly surprised. If speed is critical, gmpy is likely to be faster than anything you can do in pure Python. [snip] >> Even if it is terribly slow, that's just an implementation detail. What >> happens when Python 2.7 comes out (or Python 3.0 or Python 99.78) and >> coercion from int to mpz is lightning fast? Would you then say "Well, >> int(1) and mpz(1) used to be unequal, but now they are equal?". > > Are you saying I should be unconcerned about implementation details? > That it's silly of me to be concerned about implementation side effects > due to mis-matched types? Of course not. But the discussion isn't about optimization, that's just an irrelevant side-track. >> Me, I'd say they always were equal, but previously it used to be slow >> to coerce one to the other. > > So, when you're giving advice to the OP you don't feel any need to point > this out? That's all I'm trying to do, supply some "yes, but you should > be aware of..." commentary. Why on Earth would I need to mention gmpy.mpz()? Does the OP even use gmpy? You were the one who brought gmpy into the discussion, not him. Why not give him a lecture about not repeatedly adding strings together, or using << instead of multiplication by two, or any other completely irrelevant optimization? My favorite, by the way, is that you can save anything up to an hour of driving time by avoiding Hoddle Street during peak hour and using the back-streets through Abbotsford, next to Yarra Bend Park and going under the Eastern Freeway. Perhaps I should have raised that as well? >> In any case, what you describe is a local optimization. Its probably a >> good optimization, but in no way, shape or form does it imply that >> mpz(1) is not equal to 1. > > It's a different type. It is an exception to the "different types > compare False" rule. What does this have to do with your ridiculous claim that mpz(1) is not equal to 1? It clearly is equal. > That exception is not without cost, the type mis-match > causes coercion. Any comparison has a cost. Sometimes its a lot, sometimes a little. That has nothing to do with equality. >> There's nothing false about it. Ask any mathematician, does 1 equal >> 1.0, and they will say "of course". > > And if you ask any mathematician, he'll say that (1,) is equal to [1]. I'd like to find the mathematician who says that. The first thing he'd say is "what is this (1,) notation you are using?" and the second thing he'd ask is "equal in what sense?". Perhaps you should ask a mathematician if the set {1, 2} and the vector [1, 2] are equal, and if either of them are equal to the coordinate pair (1, 2). > That's the difference between a mathematician and a programmer. A > programmer will say "of course not, the int has to be coered." A C programmer maybe. [snip] >> Numeric values are automatically coerced because that's more practical. >> That's a design decision, and it works well. > > And I'm not saying it shouldn't be that way. But when I wrote my Collatz > Functions library, I wasn't aware of the performance issues when doing > millions of loop cycles with numbers having millions of digits. I only > found that out later. Would I have gotten a proper answer on this > newgroup had I asked here? Sure doesn't look like it. If you had asked _what_? Unless you tell me what question you asked, how can anyone guess what answer you would have received? If you had asked a question about optimization, you surely would have received an answer about optimization. If you asked about string concatenation, you would have received a question about string concatenation. If you had asked a question about inheritance, you would have received an answer about inheritance. See the pattern? > BTW, in reviewing my Collatz Functions library, I noticed a coercion I > had overlooked, so as a result of this discussion, my library is now > slightly faster. So some good comes out of this argument after all. > > >> As for gmpy.mpz, since equality tests are completely under the control >> of the class author, the gmpy authors obviously wanted mpz values to >> compare equal with ints. > > And they chose to do a silent coercion rather than raise a type > exception. > It says right in the gmpy documentation that this coercion will be > performed. > What it DOESN'T say is what the implications of this silent coercion > are. OF COURSE a coercion takes time. This is Python, where everything is a rich object, not some other language where a coercion merely tells the compiler to consider bytes to be some other type. If you need your hand- held to the point that you need somebody to tell you that operations take time, maybe you need to think about changing professions. The right way to do this is to measure first, then worry about optimizations. The wrong way is to try to guess the bottlenecks ahead of time. The worse way is to expect other people to tell you were your bottlenecks are ahead of time. > > >> >> Since both lists and tuples are containers, neither are strings or >> >> numeric types, so the earlier rule applies: they are different >> >> types, so they can't be equal. >> >> > But you can't trust a==d returning True to mean a and d are "equal". >> >> What does it mean then? > > It means they are mathematically equivalent, which is not the same as > being programatically equivalent. Mathematical equivalency is what most > people want most of the time. I think that by "most people", you mean you. > Not all of the people all of the time, > however. For example, I can calculate my Hailstone Function parameters > using either a list or a tuple: > >>>> import collatz_functions as cf >>>> print cf.calc_xyz([1,2]) > (mpz(8), mpz(9), mpz(5)) >>>> print cf.calc_xyz((1,2)) > (mpz(8), mpz(9), mpz(5)) > > But [1,2]==(1,2) yields False, so although they are not equal, they ARE > interchangeable in this application because they are mathematically > equivalent. No, they aren't mathematically equivalent, because Python data structures aren't mathematical entities. (They may be _similar to_ mathematical entities, but they aren't the same. Just ask a mathematician about the difference between a Real number and a float.) They are, however, both sequences, and so if your function expects any sequence, they will both work. [snip] >> I never said that there was no efficiency differences. Comparing X with >> Y might take 0.02ms or it could take 2ms depending on how much work >> needs to be done. I just don't understand why you think that has a >> bearing on whether they are equal or not. > > The bearing it has matters when you're writing a function library that > you want to execute efficiently. Which is true, but entirely irrelevant to the question in hand, which is "are they equal?". -- Steven. From gagsl-py2 at yahoo.com.ar Fri May 11 23:58:24 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 12 May 2007 00:58:24 -0300 Subject: path stuff References: <1178734266.858048.311740@y5g2000hsa.googlegroups.com> <1178818879.239014.152210@e65g2000hsc.googlegroups.com> <1178826330.282268.132350@p77g2000hsh.googlegroups.com> <1178829783.996168.48250@u30g2000hsc.googlegroups.com> <1178834670.518728.102920@e65g2000hsc.googlegroups.com> <1178900755.209201.94000@n59g2000hsh.googlegroups.com> Message-ID: En Fri, 11 May 2007 13:25:55 -0300, fscked escribi?: >> import os, sys, os.path, fnmatch >> >> def findinterestingfiles(root_dir): >> for dirpath, dirnames, filenames in os.walk(root_dir): >> if "Archived" in dirnames: >> dirnames.remove("Archived") >> for filename in fnmatch.filter(filenames, '*Config*.xml'): >> fullfn = os.path.join(dirpath, filename) >> print fullfn >> >> myfile = open("boxids.txt", "r") >> for line in myfile: >> dirname = os.path.join('D:\\Dir\\', line.strip()) >> findinterestingfiles(dirname): >> myfile.close() > Should this code work? I get a syntax error and cannot figure out why. Sorry, remove the spurious : after findinterestingfiles(dirname) and it should work fine. -- Gabriel Genellina From aleax at mac.com Mon May 7 00:34:04 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 6 May 2007 21:34:04 -0700 Subject: import conflict References: <1178504177.697440.23740@p77g2000hsh.googlegroups.com> Message-ID: <1hxpnt3.gmhjqv5rm1x8N%aleax@mac.com> wrote: > Hello, > > I have a problem where I need to set up two separate Python projects > that each live under the same package. Once they are distributed, > they will live under the same filesystem path, but during development, > they are separated. > > For example: > proj1/lib/pkg/foo/mod1.py > proj2/lib/pkg/bar/mod2.py > > Furthermore, proj1 is dependent on proj2, so I want to be able to say > things like this, from within proj1: > > import pkg.foo.mod1 > import pkg.bar.mod2 > > Of course this doesn't work, even with a PYTHONPATH configured to see > both projects, because it will find 'pkg' in proj1/lib and so pkg.bar > will be hidden from view. proj1/lib/pkg/__init__.py (and its counterpart under proj2) might set their __path__ as to "merge" the two separate directories when seen as Python packages. A rather contorted "solution" (compared to the simple and obvious one of NOT "separating during development" parts that appear to be so closely entwined) but I think it would work. Alex From ark at acm.org Fri May 11 10:39:38 2007 From: ark at acm.org (Andrew Koenig) Date: Fri, 11 May 2007 14:39:38 GMT Subject: software testing articles References: <1178889267.152525.230420@e65g2000hsc.googlegroups.com> Message-ID: wrote in message news:1178889267.152525.230420 at e65g2000hsc.googlegroups.com... > Have you ever been interested in software testing? Giving you an in > depth analysis/knowledge on software testing!! Looking around the site at random, I saw no "in depth analysis/knowledge" of anything. From rahulnag22 at yahoo.com Tue May 29 13:02:03 2007 From: rahulnag22 at yahoo.com (rahulnag22 at yahoo.com) Date: 29 May 2007 10:02:03 -0700 Subject: Tkinter Listbox - Different Text colors in one listbox Message-ID: <1180458123.139727.182500@d30g2000prg.googlegroups.com> Hi, Is it possible to have different items in a listbox in different colors? Or is it just one color for all items in a listbox? Thanks Rahul From eric.brunel at pragmadev.com Mon May 14 06:02:27 2007 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Mon, 14 May 2007 12:02:27 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <4648252D.5020704@web.de> Message-ID: On Mon, 14 May 2007 11:00:29 +0200, Stefan Behnel wrote: > Eric Brunel wrote: >> On Sun, 13 May 2007 21:10:46 +0200, Stefan Behnel >> wrote: >> [snip] >>> Now, I am not a strong supporter (most public code will use English >>> identifiers anyway) >> >> How will you guarantee that? I'm quite convinced that most of the public >> code today started its life as private code earlier... > > Ok, so we're back to my original example: the problem here is not the > non-ASCII encoding but the non-english identifiers. As I said in the rest of my post, I do recognize that there is a problem with non-english identifiers. I only think that allowing these identifiers to use a non-ASCII encoding will make things worse, and so should be avoided. > If we move the problem to a pure unicode naming problem: > > How likely is it that it's *you* (lacking a native, say, kanji keyboard) > who > ends up with code that uses identifiers written in kanji? And that you > are the > only person who is now left to do the switch to an ASCII transliteration? > > Any chance there are still kanji-enabled programmes around that were not > hit > by the bomb in this scenario? They might still be able to help you get > the > code "public". Contrarily to what one might think seeing the great achievements of open-source software, people willing to maintain public code and/or make it evolve seem to be quite rare. If you add burdens on such people - such as being able to read and write the language of the original code writer, or forcing them to request a translation or transliteration from someone else -, the chances are that they will become even rarer... -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From saif.shakeel at gmail.com Wed May 16 02:17:04 2007 From: saif.shakeel at gmail.com (saif.shakeel at gmail.com) Date: 15 May 2007 23:17:04 -0700 Subject: removing common elemets in a list Message-ID: <1179296224.885877.187200@q23g2000hsg.googlegroups.com> Hi, Suppose i have a list v which collects some numbers,how do i remove the common elements from it ,without using the set() opeartor. Thanks From attn.steven.kuo at gmail.com Wed May 9 14:49:45 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 9 May 2007 11:49:45 -0700 Subject: Inheritance problem In-Reply-To: <5aeigdF2p1oghU1@mid.individual.net> References: <1178734168.255175.248800@e51g2000hsg.googlegroups.com> <5aeigdF2p1oghU1@mid.individual.net> Message-ID: <1178736585.835528.97920@w5g2000hsg.googlegroups.com> On May 9, 11:33 am, Bjoern Schliessmann wrote: > amidzic.bra... at gmail.com wrote: > > class longList(shortList): > > > def __init__(self): > > > shortList.setList() > > > self.setList() > > Addition: Always call the base class __init__ in your constructor if > there exists one, i. e. > > class longList(shortList) > def __init__(self): > shortlist.__init__() > # [...] > Delegating to an ancestor class by calling an unbound method is fine as long as one remembers to pass an instance as the first argument. So, this means: shortList.setList(self) and shortList.__init__(self) for the examples above. -- Regards, Steven From apatheticagnostic at gmail.com Wed May 23 02:07:03 2007 From: apatheticagnostic at gmail.com (kaens) Date: Wed, 23 May 2007 02:07:03 -0400 Subject: xml.parsers.expat loading xml into a dict and whitespace In-Reply-To: <163f0ce20705222253h2d171b1fs61efa448ad86dc8e@mail.gmail.com> References: <163f0ce20705222253h2d171b1fs61efa448ad86dc8e@mail.gmail.com> Message-ID: <163f0ce20705222307n2bc79f44r6099e8e008beb460@mail.gmail.com> Wait. . . it's because the curTag is set to "", thus it sets the whitespace after a tag to that part of the dict. That doesn't explain why it does it on a xml file containing no whitespace, unless it's counting newlines. Is there a way to just ignore whitespace and/or xml comments? On 5/23/07, kaens wrote: > Hey everyone, this may be a stupid question, but I noticed the > following and as I'm pretty new to using xml and python, I was > wondering if I could get an explanation. > > Let's say I write a simple xml parser, for an xml file that just loads > the content of each tag into a dict (the xml file doesn't have > multiple hierarchies in it, it's flat other than the parent node) > > so we have > > foo > bar > . . . > > > (I'm using xml.parsers.expat) > the parser sets a flag that says it's in the parent, and sets the > value of the current tag it's processing in the start tag handler. > The character data handler sets a dictionary value like so: > > dictName[curTag] = data > > after I'm done processing the file, I print out the dict, and the first value is > : > > There are comments in the xml file - is this what is causing this? > There are also blank lines. . .but I don't see how a blank line would > be interpreted as a tag. Comments though, I could see that happening. > > Actually, I just did a test on an xml file that had no comments or > whitespace and got the same behaviour. > > If I feed it the following xml file: > > > hey > bee > eff > > > it prints out: > " : > > three : eff > two : bee > one : hey" > > wtf. > > For reference, here's the handler functions: > > def handleCharacterData(self, data): > if self.inOptions and self.curTag != "options": > self.options[self.curTag] = data > > def handleStartElement(self, name, attributes): > if name == "options": > self.inOptions = True > if self.inOptions: > self.curTag = name > > > def handleEndElement(self, name): > if name == "options": > self.inOptions = False > self.curTag = "" > > Sorry if the whitespace in the code got mangled (fingers crossed...) > From sjmachin at lexicon.net Sun May 20 05:40:48 2007 From: sjmachin at lexicon.net (John Machin) Date: Sun, 20 May 2007 19:40:48 +1000 Subject: converting strings to most their efficient types '1' --> 1, 'A' ---> 'A', '1.2'---> 1.2 In-Reply-To: <42T3i.29504$Um6.11611@newssvr12.news.prodigy.net> References: <1179529661.555196.13070@k79g2000hse.googlegroups.com> <464E6F32.7070200@lexicon.net> <61B3i.6880$H_.138@newssvr21.news.prodigy.net> <464F93C1.8030305@lexicon.net> <42T3i.29504$Um6.11611@newssvr12.news.prodigy.net> Message-ID: <465017A0.1030901@lexicon.net> On 20/05/2007 5:47 PM, James Stroud wrote: > John Machin wrote: >> Against that background, please explain to me how I can use "results >> from previous tables as priors". >> >> Cheers, >> John > > It depends on how you want to model your probabilities, but, as an > example, you might find the following frequencies of columns in all > tables you have parsed from this organization: 35% Strings, 25% Floats, > 20% Ints, 15% Date MMDDYYYY, and 5% Date YYMMDD. The model would have to be a lot more complicated than that. There is a base number of required columns. The kind suppliers of the data randomly add extra columns, randomly permute the order in which the columns appear, and, for date columns, randomly choose the day-month-year order, how much punctuation to sprinkle between the digits, and whether to append some bonus extra bytes like " 00:00:00". > Let's say that you have > also used prior counting statistics to find that there is a 2% error > rate in the columns (2% of the values of a typical Float column fail to > cast to Float, 2% of values in Int columns fail to cast to Int, and > so-on, though these need not all be equal). Lets also say that for > non-Int columns, 1% of cells randomly selected cast to Int. Past stats on failure to cast are no guide to the future ... a sudden change in the failure rate can be caused by the kind folk introducing a new null designator i.e. outside the list ['', 'NULL', 'NA', 'N/A', '#N/A!', 'UNK', 'UNKNOWN', 'NOT GIVEN', etc etc etc] There is also the problem of first-time-participating organisations -- in police parlance, they have no priors :-) So, all in all, Bayesian inference doesn't seem much use in this scenario. > > These percentages could be converted to probabilities and these > probabilities could be used as priors in Bayesian scheme to determine a > column type. Lets say you take one cell randomly and it can be cast to > an Int. What is the probability that the column is an Int? (See > .) That's fancy -- a great improvement on the slide rule and squared paper :-) Cheers, John From openopt at ukr.net Sun May 6 16:06:56 2007 From: openopt at ukr.net (dmitrey) Date: 6 May 2007 13:06:56 -0700 Subject: howto make Python list from numpy.array? In-Reply-To: References: <1178480447.245977.293010@n59g2000hsh.googlegroups.com> Message-ID: <1178482016.071308.235520@l77g2000hsb.googlegroups.com> Thanks all. I tried all the approaches but they don't work in my situation I have a variable x that can be x = 1 x = [1, 2, 3] x = numpy.array([1,2,3]) so all troubles are with 1st case >>> x=1 >>> list(x) Traceback (most recent call last): File "", line 1, in TypeError: iteration over non-sequence >>> list(array(1)) Traceback (most recent call last): File "", line 1, in ValueError: Rank-0 array has no length. >>> array(1).tolist() Traceback (most recent call last): File "", line 1, in ValueError: rank-0 arrays don't convert to lists. >>> Here I used Python 2.4.3, numpy 1.02 From priyank.patel21 at yahoo.com Tue May 15 21:05:18 2007 From: priyank.patel21 at yahoo.com (cvncvbnvbn vbnvbnbn) Date: Tue, 15 May 2007 18:05:18 -0700 (PDT) Subject: /bin/sh: ./python: cannot execute binary file Message-ID: <225135.67691.qm@web59002.mail.re1.yahoo.com> I am very newbie to PYTHON, and cross-compiling python 2.4 with arm-linux. I am getting following error,, CC='/usr/local/openrg/openrg/pkg/build/rg_gcc' LDSHARED='/usr/local/openrg/openrg/pkg/build/rg_gcc -shared' OPT='-DNDEBUG -g -O3 -Wall -Wstrict-prototypes' ./python -E ./setup.py -q build;; \ *) CC='/usr/local/openrg/openrg/pkg/build/rg_gcc' LDSHARED='/usr/local/openrg/openrg/pkg/build/rg_gcc -shared' OPT='-DNDEBUG -g -O3 -Wall -Wstrict-prototypes' ./python -E ./setup.py build;; \ esac /bin/sh: ./python: cannot execute binary file make: *** [sharedmods] Error 126 can anybody help me, how to run this python binaryfile within MAKEFILE.. suggestion will be really appriciated. Regars,, Priyank --------------------------------- Park yourself in front of a world of choices in alternative vehicles. Visit the Yahoo! Auto Green Center. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jon at ffconsultancy.com Tue May 29 01:16:19 2007 From: jon at ffconsultancy.com (Jon Harrop) Date: Tue, 29 May 2007 06:16:19 +0100 Subject: The Concepts and Confusions of Prefix, Infix, Postfix and Fully Functional Notations References: <1179936917.652372.24780@q69g2000hsb.googlegroups.com> <1oveejxwke.fsf@hod.lan.m-e-leypold.de> Message-ID: <465bb872$0$8729$ed2619ec@ptn-nntp-reader02.plus.net> Markus E Leypold wrote: > The answer to your question is very simple: Xah Lee is a troll. In this context, I believe he is marketing/advertising himself as a consultant and some kind of vampiric man-whore according to this page: http://xahlee.org/PageTwo_dir/Personal_dir/xah.html "... I'm technically American. Love me and I can make you American." Xah is perhaps the world's first person to claim to be both a Lisp programmer and "strong at siring". :-) Anyway, are there any libraries to do hardware accelerated vector graphics in Perl, Python, Lisp, Java or any functional language (except OCaml and F# and excluding WPF and Silverlight)? -- Dr Jon D Harrop, Flying Frog Consultancy The F#.NET Journal http://www.ffconsultancy.com/products/fsharp_journal/?u7 From horpner at yahoo.com Thu May 10 13:49:11 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 10 May 2007 17:49:11 GMT Subject: Newbie look at Python and OO References: <1178812734.860473.236370@y80g2000hsf.googlegroups.com> Message-ID: On 2007-05-10, walterbyrd wrote: > I learned to program with Pascal, way back when. Went into software > development for a while, then went into systems admin. Have programmed > in several languages, just learning Python. > > Some things I find odd: > > 1) 5/-2 == -3? Any math implementation has to decide on the convention for division of negative numbers (which most people think they understand) so that it works logically with the implementation of the mod operator (which most people don't clame to understand for negative numbers). C says something complicated to allow differing yet compliant answers, while Python defines it strictly for programmer convenience. > 2) list assignment handling, pointing two vars to the same list: > > With simple data types: >>>> a = 5 >>>> b = a >>>> a = 3 >>>> a,b > (3, 5) > > Which is what I'd expect, since I have changed a, but not b. > > But with lists: >>>> a = list("1234") >>>> b = a >>>> a.append("5") >>>> a,b > (['1', '2', '3', '4', '5'], ['1', '2', '3', '4', '5']) > > b changes even though I have not touched b. I know why, but > this is not what I would ordinarilly expect, it does not seem > intuitive. And, IMO, it gets worse: Actually, binding to numbers works just the same as for lists, it's just that you can't change a number, it is immutable. You just end up rebinding to a new number object. >>> a = 3 Now a is bound to a number object representing 3. >>> b = a b and a are now both bound to the same number object. >>> id(b) == id(a) True A number object cannot be modified, unlike a list. >>> a += 5 A is in fact rebound to a new number object representing 8 by the above line. >>> id(a) == id(b) False >>>> a = list("1234") >>>> b = a >>>> a = a + ['5'] >>>> a,b > (['1', '2', '3', '4', '5'], ['1', '2', '3', '4']) > > Sometimes changing a changes b, and sometimes not. The + operator does not change a list, it produces a new one. > 3) ambiguous use of the form: this.that() > > Sometimes, this.that() means module.funcion() as in: > >>>> os.dirlist(".") > > Other times, "this" is sort of like a parameter to the "that" > function: It's the exact same operation each time (attribute lookup), it's just that it's operating on two different object types. > BTW: it seems a bit odd to that the positions of the string, and the > delimitor, are reversed between the complementory functions join(), > and split(). I suppose if it weren't for OO, we have something > terribly complicated, like: > > split(str, "_") > join(str, "_") "".join is a tiny sore spot for some Python users, I think. No language is perfect. ;) > Again, those who think in Python, will understand right away > that: > > math.count(x) > > is counting the substring "x" in the "math" string. But can you > see where that might be confused to be a function called > count() in the math module? The only thing you know for sure (without tracing backwards) is that count is an attribute of the object bound to the name 'math' (or something masquerading as an attribute. Look under the hood at descriptors for the details). > I'm not complaining. Python is a great language in many > respects. But, I would take some issue with those claiming > Python is intuitive and easy. IMO: there seems to be many > ambiguous, unintuitve, and confusing, aspects to Python. Name binding can seem confusing at first, but it's really the distinction between mutable and immutable objects that's the root of your current confusion. -- Neil Cerutti From john at datavoiceint.com Thu May 3 14:02:27 2007 From: john at datavoiceint.com (HMS Surprise) Date: 3 May 2007 11:02:27 -0700 Subject: cannot import name ..... In-Reply-To: References: <1178209261.189586.95540@p77g2000hsh.googlegroups.com> Message-ID: <1178215347.492858.217280@y5g2000hsa.googlegroups.com> Thanks for posting. pythonpath = .;c:\maxq\bin\testScripts; c:\maxq\bin;c:\maxq\jython Both files are in c:\maxq\bin\testScripts. Also I do not get the message "no module named...: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ File nCreateIncident.py, the importer: from PyHttpTestCase import PyHttpTestCase from com.bitmechanic.maxq import Config global validatorPkg from nBaseTest import nBaseTest # definition of test class class nCreateIncident(nBaseTest): def runTest(self): self.msg('Test started') self.logon() # Code to load and run the test if __name__ == 'main': test = nCreateIncident("nCreateIncident") test.Run() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ File nBaseTest from PyHttpTestCase import PyHttpTestCase from com.bitmechanic.maxq import Config global validatorPkg if __name__ == 'main': validatorPkg = Config.getValidatorPkgName() # Determine the validator for this testcase. exec 'from '+validatorPkg+' import Validator' # definition of test class class nBaseTest(PyHttpTestCase): def logon(self): self.msg('Test started') if __name__ == 'main': t = nBaseTest('nBaseTest') t.logon() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Best Regards, jvh From bj_666 at gmx.net Wed May 2 11:16:56 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 02 May 2007 17:16:56 +0200 Subject: I need help speeding up an app that reads football scores and generates rankings References: <1178118022.865173.266300@h2g2000hsg.googlegroups.com> Message-ID: In <1178118022.865173.266300 at h2g2000hsg.googlegroups.com>, jocknerd wrote: > The biggest difference in my two apps is the C app uses linked lists. > I feel my Python app is doing too many lookups which is causing the > bottleneck. Then replace those linear searches you wrote in Python with a dictionary. Ciao, Marc 'BlackJack' Rintsch From aldo at nullcube.com Sun May 13 19:42:13 2007 From: aldo at nullcube.com (Aldo Cortesi) Date: Mon, 14 May 2007 09:42:13 +1000 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46473267$0$31532$9b622d9e@news.freenet.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <20070513234213.GA23907@nullcube.com> Thus spake "Martin v. L?wis" (martin at v.loewis.de): > - should non-ASCII identifiers be supported? why? No! I believe that: - The security implications have not been sufficiently explored. I don't want to be in a situation where I need to mechanically "clean" code (say, from a submitted patch) with a tool because I can't reliably verify it by eye. We should learn from the plethora of Unicode-related security problems that have cropped up in the last few years. - Non-ASCII identifiers would be a barrier to code exchange. If I know Python I should be able to easily read any piece of code written in it, regardless of the linguistic origin of the author. If PEP 3131 is accepted, this will no longer be the case. A Python project that uses Urdu identifiers throughout is just as useless to me, from a code-exchange point of view, as one written in Perl. - Unicode is harder to work with than ASCII in ways that are more important in code than in human-language text. Humans eyes don't care if two visually indistinguishable characters are used interchangeably. Interpreters do. There is no doubt that people will accidentally introduce mistakes into their code because of this. > - would you use them if it was possible to do so? in what cases? No. Regards, Aldo -- Aldo Cortesi aldo at nullcube.com http://www.nullcube.com Mob: 0419 492 863 From bj_666 at gmx.net Wed May 16 09:22:34 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 16 May 2007 15:22:34 +0200 Subject: Execute commands from file References: <1179320782.594398.67980@u30g2000hsc.googlegroups.com> Message-ID: In <1179320782.594398.67980 at u30g2000hsc.googlegroups.com>, tmp123 wrote: > We have very big files with python commands (more or less, 500000 > commands each file). > > It is possible to execute them command by command, like if the > commands was typed one after the other in a interactive session? Take a look at the `code` module in the standard library: In [31]: code? Type: module Base Class: String Form: Namespace: Interactive File: /usr/lib/python2.4/code.py Docstring: Utilities needed to emulate Python's interactive interpreter. Ciao, Marc 'BlackJack' Rintsch From mblume at socha.net Thu May 17 12:11:05 2007 From: mblume at socha.net (Martin Blume) Date: Thu, 17 May 2007 18:11:05 +0200 Subject: Execute commands from file References: <1179320782.594398.67980@u30g2000hsc.googlegroups.com> <464b370c$0$3808$5402220f@news.sunrise.ch> <1179387023.005808.60670@o5g2000hsb.googlegroups.com> Message-ID: <464c7e99$0$3814$5402220f@news.sunrise.ch> "Steve Holden" schrieb > >> > >> Try it on a file that reads something like > >> > >> xxx = 42 > >> print xxx > >> > >> and you will see NameError raised because the assignment > >> hasn't affected the environment for the print statement. > >> > > [...] > > > No, because there isn't one. Now try adding a function > definition and see how well it works. > C:\temp>more question.py xxx=42 print xxx def sowhat(): print xxx print xxx C:\temp>c:\programme\python\python Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> exec open("question.py").read() 42 42 >>> sowhat() 42 >>> xxx 42 Seems to work great to me. OTOH, this doesn't: >>> inp=open("question.py") >>> for l in inp: ... exec l ... 42 Traceback (most recent call last): File "", line 2, in ? File "", line 1 def sowhat(): ^ SyntaxError: unexpected EOF while parsing So it seems to depend on the way the file is read. Regards Martin From michele.simionato at gmail.com Thu May 17 14:32:08 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 17 May 2007 11:32:08 -0700 Subject: Is wsgi ready for prime time? In-Reply-To: References: Message-ID: <1179426728.846565.51390@h2g2000hsg.googlegroups.com> On May 17, 8:09 pm, Ron Garret wrote: > The wsgiref module in Python 2.5 seems to be empty: > > [ron at mickey:~/Sites/modpy]$ python > Python 2.5 (r25:51908, Mar 1 2007, 10:09:05) > [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin > Type "help", "copyright", "credits" or "license" for more information.>>> import wsgiref > >>> dir(wsgiref) > > ['__builtins__', '__doc__', '__file__', '__name__', '__path__'] > > > > So... is wsgi considered ready for production use, or is it still on the > bleeding edge? And if the former, which implementation should one use? > > rg Try help(wsgiref). I would say that WSGI (the spec) is ready for production use whereas wsgiref (the implementation in the standard library) is intended for easy development and testing purposes, not for industrial strenght deployement. On the other hand Zope 3 uses Twisted via WSGI as a business class server, and I hear that mod_wsgi is slightly more performant than mod_python, so those are the first options I would consider. But you could post on the WSGI list for more. Michele Simionato From grahn+nntp at snipabacken.dyndns.org Mon May 21 18:23:01 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 21 May 2007 22:23:01 GMT Subject: zipfile [module and file format, both] stupidly broken References: Message-ID: On Sat, 19 May 2007 17:00:01 +0000 (UTC), Martin Maney wrote: ... > posted here and had so much fun. Apparently I don't speak for most readers here, but I had fun too. Smart, reasonable people write braindead code all the time. I think it's fine when people whine about that once in a while, as long as it's done in an entertaining manner. Less constructive than writing, testing and submitting a patch, but more constructive than slapping your monitor, cursing and doing nothing at all about it. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From revuesbio at gmail.com Mon May 28 18:51:44 2007 From: revuesbio at gmail.com (revuesbio) Date: 28 May 2007 15:51:44 -0700 Subject: DbiDate object Message-ID: <1180392704.580831.229190@q75g2000hsh.googlegroups.com> Hi all I am using odbc to connect to Microsoft Access DB. When I send a request with a datetime column from the database, odbc returns something called a DbiDate object. ex : >>> x=data[0][2] >>> print x Fri Apr 20 07:27:45 2007 I would like to select columns where datetime ("DbiDate column") is > yesterday date. and i don't understand how to send request with this DbiDate. Could you help me ? thank you From grflanagan at yahoo.co.uk Tue May 29 10:03:26 2007 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 29 May 2007 07:03:26 -0700 Subject: multiline regular expression (replace) In-Reply-To: References: Message-ID: <1180447406.724659.55950@u30g2000hsc.googlegroups.com> On May 29, 11:03 am, Zdenek Maxa wrote: > Hi all, > > I would like to perform regular expression replace (e.g. removing > everything from within tags in a XML file) with multiple-line pattern. > How can I do this? > > where = open("filename").read() > multilinePattern = "^ .... <\/tag>$" > re.search(multilinePattern, where, re.MULTILINE) > If it helps, I have the following function: 8<----------------------------------------------------------- def update_xml(infile, outfile, mapping, deep=False): from xml.etree import cElementTree as ET from utils.elementfilter import ElementFilter doc = ET.parse(infile) efilter = ElementFilter(doc.getroot()) changes = 0 for key, val in mapping.iteritems(): pattern, repl = val efilter.filter = key changes += efilter.sub(pattern, repl, deep=deep) doc.write(outfile, encoding='UTF-8') return changes mapping = { '/portal/content-node[@type=="page"]/@action': ('.*', 'ZZZZ'), '/portal/web-app/portlet-app/portlet/localedata/title': ('Portal', 'Gateway'), } changes = update_xml('c:\\working\\tmp\\test.xml', 'c:\\working\\tmp\ \test2.xml', mapping, True) print 'There were %s changes' % changes 8<----------------------------------------------------------- where utils.elementfilter is this module: http://gflanagan.net/site/python/elementfilter/elementfilter.py It doesn't support `re` flags, but you could change the sub method of elementfilter.ElementFilter to do so, eg.(UNTESTED!): def sub(self, pattern, repl, count=0, deep=False, flags=None): changes = 0 if flags: pattern = re.compile(pattern, flags) for elem in self.filtered: ... [rest of method unchanged] ... Gerard From DustanGroups at gmail.com Mon May 21 08:53:48 2007 From: DustanGroups at gmail.com (Dustan) Date: 21 May 2007 05:53:48 -0700 Subject: NEWBIE: Extending a For Statement. In-Reply-To: References: <1179749446.179064.222990@z28g2000prd.googlegroups.com> Message-ID: <1179752028.224444.99980@a26g2000pre.googlegroups.com> On May 21, 7:22 am, Jean-Paul Calderone wrote: > On 21 May 2007 05:10:46 -0700, mosscliffe wrote: > > > > >I keep seeing examples of statements where it seems conditionals are > >appended to a for statement, but I do not understand them. > > >I would like to use one in the following scenario. > > >I have a dictionary of > > >mydict = { 1: 500, 2:700, 3: 800, 60: 456, 62: 543, 58: 6789} > > >for key in mydict: > > if key in xrange (60,69) or key == 3: > > print key,mydict[key] > > >I would like to have the 'if' statement as part of the 'for' > >statement. > > >I realise it is purely cosmetic, but it would help me understand > >python syntax a little better. > > Only list comprehensions and generator expressions support this extension > to the loop syntax. > > [key, mydict[key] for key in mydict if key in xrange(60, 69) or key == 3] > (key, mydict[key] for key in mydict if key in xrange(60, 69) or key == 3] ack! >>> (key, mydict[key] for key in mydict if key in xrange(60, 69) or key == 3] File "", line 1 (key, mydict[key] for key in mydict if key in xrange(60, 69) or key == 3] ^ SyntaxError: invalid syntax Perhaps you meant that second one to be: (key, mydict[key] for key in mydict if key in xrange(60, 69) or key == 3) > For the statement form of 'for', there is no syntactic way to combine it > with 'if' into a single statement. There is a dumb hack to get it to happen, but I'm not going to it here, because Guido never meant for generator expressions to be used that way. To the OP: I would suggest you just live what might seem like excess indentation; it's good for your eyes. > Jean-Paul From mail at microcorp.co.za Fri May 18 02:49:40 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 18 May 2007 08:49:40 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de><+Yl*xeSKr@news.chiark.greenend.org.uk> Message-ID: <00a801c7991b$2a856360$03000080@hendrik> "Sion Arrowsmith" wrote: Hvr: >>Would not like it at all, for the same reason I don't like re's - >>It looks like random samples out of alphabet soup to me. > >What I meant was, would the use of "foreign" identifiers look so >horrible to you if the core language had fewer English keywords? >(Perhaps Perl, with its line-noise, was a poor choice of example. >Maybe Lisp would be better, but I'm not so sure of my Lisp as to >make such an assertion for it.) I suppose it would jar less - but I avoid such languages, as the whole thing kind of jars - I am not on the python group for nothing.. : - ) - Hendrik From castironpi at gmail.com Wed May 9 18:14:45 2007 From: castironpi at gmail.com (castironpi at gmail.com) Date: 9 May 2007 15:14:45 -0700 Subject: Checking if string inside quotes? In-Reply-To: References: <1178745091.682071.128670@w5g2000hsg.googlegroups.com> Message-ID: <1178748885.208189.123540@l77g2000hsb.googlegroups.com> On May 9, 4:31 pm, "Michael Yanowitz" wrote: > Thanks, but it is a little more complicated than that, > the string could be deep in quotes. > > The problem is in string substitution. > Suppose I have a dictionary with MY_IP : "172.18.51.33" > > I need to replace all instances of MY_IP with "172.18.51.33" > in the file. > It is easy in cases such as: > if (MY_IP == "127.0.0.1"): > > But suppose I encounter:" > ("(size==23) and (MY_IP==127.0.0.1)") > > In this case I do not want: > ("(size==23) and ("172.18.51.33"==127.0.0.1)") > but: > ("(size==23) and (172.18.51.33==127.0.0.1)") > without the internal quotes. > How can I do this? > I presumed that I would have to check to see if the string > was already in quotes and if so remove the quotes. But not > sure how to do that? > Or is there an easier way? > > Thanks in advance: > Michael Yanowitz > > -----Original Message----- > From: python-list-bounces+m.yanowitz=kearfott.... at python.org > > [mailto:python-list-bounces+m.yanowitz=kearfott.... at python.org]On Behalf > Of half.ital... at gmail.com > Sent: Wednesday, May 09, 2007 5:12 PM > To: python-l... at python.org > Subject: Re: Checking if string inside quotes? > > On May 9, 1:39 pm, "Michael Yanowitz" wrote: > > Hello: > > > If I have a long string (such as a Python file). > > I search for a sub-string in that string and find it. > > Is there a way to determine if that found sub-string is > > inside single-quotes or double-quotes or not inside any quotes? > > If so how? > > > Thanks in advance: > > Michael Yanowitz > > I think the .find() method returns the index of the found string. You > could check one char before and then one char after the length of the > string to see. I don't use regular expressions much, but I'm sure > that's a more elegant approach. > > This will work. You'll get in index error if you find the string at > the very end of the file. > > s = """ > foo > "bar" > """ > findme = "foo" > index = s.find(findme) > > if s[index-1] == "'" and s[index+len(findme)] == "'": > print "single quoted" > elif s[index-1] == "\"" and s[index+len(findme)] == "\"": > print "double quoted" > else: > print "unquoted" > > ~Sean > > --http://mail.python.org/mailman/listinfo/python-list In "nearby" quotes or in quotes at all? import re a='abc"def"ghijk' b=re.sub( r'([\'"])[^\1]*\1', '', a ) b.replace( 'ghi', 'the string' ) #fb: 'abcthe stringjk' edit() Here, you get the entire file -in b-, strings omitted entirely, so you can't write it back. I've used `tokenize' to parse a file, but you don't get precisely your original back. Untokenize rearrages your spacings. Equivalent semantically, so if you want to compile immedately afterwords, you're alright with that. Short example: from tokenize import * import token from StringIO import StringIO a= StringIO( 'abc "defghi" ghi jk' ) from collections import deque b= deque() for g in generate_tokens( a.readline ): if g[0]== token.NAME and g[1]== 'ghi': b.append( ( token.STRING, '"uchoose"' ) ) else: b.append( g ) untokenize( b ) #fb: 'abc "defghi""uchoose"jk ' edit() acb From nagle at animats.com Tue May 1 01:24:15 2007 From: nagle at animats.com (John Nagle) Date: Mon, 30 Apr 2007 22:24:15 -0700 Subject: re-importing modules In-Reply-To: References: <8%pZh.18192$Kd3.76@newssvr27.news.prodigy.net> <1177962288.575008.48490@q75g2000hsh.googlegroups.com> <1177967919.968338.3300@l77g2000hsb.googlegroups.com> Message-ID: Steven D'Aprano wrote: > I'd hate for reload to disappear, it is great for interactive > development/debugging, at least under some circumstances. (If you have > complex and tangled class hierarchies, it might not be powerful enough.) > > As for the semantics being awful, I disagree. reload() does exactly > what it claims to do, no more, no less. It's more complicated than that. See http://arcknowledge.com/lang.jython.user/2006-01/msg00017.html Exactly what reloading should do is still an open question for some of the hard cases. "reload" as a debug facility is fine. Trouble comes from production programs which use it as a reinitialization facility. Reloading a module with multiple threads running gets complicated. It works in CPython because CPython doesn't have real concurrency. Insisting that it work like CPython implies an inefficient locking model. John Nagle From tsuraan at gmail.com Tue May 29 15:12:53 2007 From: tsuraan at gmail.com (tsuraan) Date: Tue, 29 May 2007 14:12:53 -0500 Subject: Malformed big5 reading bug Message-ID: <84fb38e30705291212t12e3f668x66927a918926e761@mail.gmail.com> Python enters some sort of infinite loop when attempting to read data from a malformed file that is big5 encoded (using the codecs library). This behaviour can be observed under Linux and FreeBSD, using Python 2.4 and 2.5. A really simple example illustrating the bug follows: Python 2.4.4 (#1, May 15 2007, 13:33:55) [GCC 4.1.1 (Gentoo 4.1.1-r3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import codecs >>> fname='out' >>> outfd=open(fname,'w') >>> outfd.write(chr(243)) >>> outfd.close() >>> >>> infd=codecs.open(fname, encoding='big5') >>> infd.read(1024) And then, it hangs forever. If I instead use the following code: Python 2.5 (r25:51908, Jan 8 2007, 19:09:28) [GCC 3.4.5 (Gentoo 3.4.5-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import codecs, signal >>> fname='out' >>> def handler(*args): ... raise Exception("boo!") ... >>> signal.signal(signal.SIGALRM, handler) 0 >>> outfd=open(fname, 'w') >>> outfd.write(chr(243)) >>> outfd.close() >>> >>> infd=codecs.open(fname, encoding='big5') >>> signal.alarm(5) 0 >>> infd.read(1024) The program still hangs forever. The program can be made to crash if I don't install a signal handler at all, but that's pretty lame. It looks like the entire interpreter is being locked up by this read, so I don't think there's likely to be a pure-python workaround, but I thought it would be a good but to have out there so a future version of python can (hopefully) fix this. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Fri May 25 07:33:09 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 25 May 2007 08:33:09 -0300 Subject: method override inside a module References: <4656A86E.5040602@iriti.cnr.it> Message-ID: En Fri, 25 May 2007 06:12:14 -0300, Fabrizio Pollastri escribi?: > I am trying to override a method of a class defined into an imported > module, but keeping intact the namespace of the imported module. The last part I don't get completely... > For example, let suppose > > import module_X > > and in module_X is defined something like > > class A: > > ... > > def method_1(): > ... > > ... > > I wish to override method_1 with a new function and to call the > overrided method inside my application with the same name of the > original method like > > ... > module_X.method_1() > ... I think you meant to say: someAinstance = module_X.A(...) someAinstance.method_1(...) If you import module_X in a SINGLE module, in THAT module you could use: import module_X class A(module_X.A): def method_1()... and create all your instances using A(). (This is the traditional approach, you modify the original class by inheritance). Notice that the important thing is where you *create* your instances: other modules that import module_X but do not create A instances are unaffected; they will use your modified class anyway. If you import module_X in several places, and you create A instances in several places too, you may "monkey-patch" the A class. Somewhere at the *start* of your application, you can write: def method_1(self, ...): ... new version of method_1 import module_X module_X.A.method_1 = method_1 You are effectively replacing the method_1 with another one. -- Gabriel Genellina From http Tue May 22 12:09:02 2007 From: http (Paul Rubin) Date: 22 May 2007 09:09:02 -0700 Subject: howto check does module 'asdf' exist? (is available for import) References: <1179753436.736228.321400@x35g2000prf.googlegroups.com> <1179818823.916836.226090@r3g2000prh.googlegroups.com> Message-ID: <7xsl9ox2ld.fsf@ruckus.brouhaha.com> Asun Friere writes: > > howto check does module 'asdf' exist (is available for import) or no? > try : > import asdf > del asdf > except ImportError : > print "module asdf not available" > else : > print "module asdf available for loading" But this has a side effect: if asdf is already loaded, it deletes it. From sjmachin at lexicon.net Mon May 21 17:59:42 2007 From: sjmachin at lexicon.net (John Machin) Date: Tue, 22 May 2007 07:59:42 +1000 Subject: re.compile for names In-Reply-To: References: Message-ID: <4652164E.9080403@lexicon.net> On 22/05/2007 12:09 AM, brad wrote: > Marc 'BlackJack' Rintsch wrote: > >> What about names with letters not in the ASCII range? > > Like Asian names? The names we encounter are spelled out in English... > like Xu, Zu, Li-Cheng, Matsumoto, Wantanabee, etc. "spelled out in English"? "English" has nothing to do with it. The first 3 are Chinese, spelled using the Pinyin system, which happens to use "Roman" letters [including non-ASCII ?]. They may appear adorned with tone marks [not ASCII] or tone digits. The 4th and 5th [which is presumably intended to be "Watanabe"] are Japanese, using the Romaji system, which ... you guess the rest :-) Cheers, John From gagsl-py2 at yahoo.com.ar Tue May 15 20:07:52 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 15 May 2007 21:07:52 -0300 Subject: Interesting list Validity (True/False) References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> <1178914190.166662.285410@p77g2000hsh.googlegroups.com> <1178915791.584216.293130@l77g2000hsb.googlegroups.com> <1178918808.091358.233740@o5g2000hsb.googlegroups.com> <1179017740.656323.209590@e51g2000hsg.googlegroups.com> <1179020634.130689.171960@o5g2000hsb.googlegroups.com> <1179031812.090768.248750@l77g2000hsb.googlegroups.com> <1179168081.603409.39970@e51g2000hsg.googlegroups.com> <1179203827.881205.287910@l77g2000hsb.googlegroups.com> <1179248480.350553.4430@n59g2000hsh.googlegroups.com> Message-ID: En Tue, 15 May 2007 14:01:20 -0300, mensanator at aol.com escribi?: > On May 15, 12:30 am, "Gabriel Genellina" > wrote: >> And said section 5.9 should be updated too: "The objects need not have >> the >> same type. If both are numbers or strings, they are converted to a >> common >> type. > > Except when they aren't. I think you don't get the difference between a builtin object, fully under the Python developers' control, and a user defined class that can behave arbitrarily at wish of its writer and for which the Python documentation barely can say a word. The docs say how will the Python interpreter try to compare objects (invoke the rich comparison methods, invoke __cmp__, etc) and how the *builtin* objects behave. For other objects, it's up to the object *writer* to provide such methods, and he can do whatever he wishes: py> class Reversed(int): ... def __lt__(self, other): return cmp(int(self),other)>0 ... def __gt__(self, other): return cmp(int(self),other)<0 ... def __le__(self, other): return cmp(int(self),other)>=0 ... def __ge__(self, other): return cmp(int(self),other)<=0 ... py> py> j=Reversed(6) py> j==6 True py> j>5 False py> j>10 True py> j<=5 True You can't blame Python for this. >>>> import gmpy >>>> a = 2**177149-1 >>>> b = gmpy.mpz(2**177149-1) >>>> a==b > True >>>> print '%d' % (b) > > Traceback (most recent call last): > File "", line 1, in > print '%d' % (b) > TypeError: int argument required > > So although the comparison operator is smart enough to realize > the equivalency of numeric types and do the type conversion, > the print statement isn't so smart. This is up to the gmpy designers/writers/maintainers. Anyone writing a class chooses which features to implement, which ones to omit, how to implement them, etc. The code may contain bugs, may not be efficient, may not behave exactly as the users expect, may not have anticipated all usage scenarios, a long etc. In this case, probably the gmpy writers have chosen not to allow to convert to int, and they may have good reasons to not do that (I don't know what platform are you working in, but I feel that your b object is somewhat larger than sys.maxint...). >> Otherwise, objects of different builtin types always compare >> unequal, and are ordered consistently but arbitrarily. You can control >> comparison behavior of objects of non-builtin types by defining a >> __cmp__ >> method or rich comparison methods like __gt__, described in section >> 3.4." >> >> I hope this helps a bit. Your performance issues don't have to do with >> the >> *definition* of equal or not equal, > > I didn't say that, I said the performance issues were related > to type conversion. Can you explain how the "definition" of > equal does not involve type conversion? There is no type conversion involved for user defined classes, *unless* the class writer chooses to do so. Let's invent some new class Number; they can be added and have basic str/repr support py> class Number(object): ... def __init__(self, value): self.value=value ... def __add__(self, other): return Number(self.value+other.value) ... def __str__(self): return str(self.value) ... def __repr__(self): return 'Number(%s)' % self.value ... py> x = Number(2) py> y = Number(3) py> z = x+y py> z Number(5) py> z == 5 False py> 5 == z False py> z == Number(5) False py> int(z) Traceback (most recent call last): File "", line 1, in ? TypeError: int() argument must be a string or a number py> "%d" % z Traceback (most recent call last): File "", line 1, in ? TypeError: int argument required You can't compare them to anything, convert to integer, still nothing. Let's add "int conversion" first: py> Number.__int__ = lambda self: int(self.value) py> int(z) 5 py> "%d" % z '5' py> z == 5 False py> 5 == z False Ok, a Number knows how to convert itself to integer, but still can't be compared successfully to anything. (Perhaps another language would try to convert automagically z to int, to compare against 5, but not Python). Let's add basic comparison support: py> Number.__cmp__ = lambda self, other: cmp(self.value, other.value) py> z == Number(5) True py> z > Number(7) False py> z == z True py> z == 5 Traceback (most recent call last): File "", line 1, in ? File "", line 1, in AttributeError: 'int' object has no attribute 'value' Now, a Number can be compared to another Number, but still not compared to integers. Let's make the comparison a bit smarter (uhm, I'll write it as a regular function because it's getting long...) py> def NumberCmp(self, other): ... if isinstance(other, Number): return cmp(self.value, other.value) ... else: return cmp(self.value, other) ... py> Number.__cmp__ = NumberCmp py> z == 5 True py> z == 6 False py> 5 == z True As you can see, until I wrote some code explicitely to do the comparison, and allow other types of comparands, Python will not "convert" anything. If you find that some class appears to do a type conversion when comparing instances, it's because the class writer has explicitely coded it that way, not because Python does the conversion automagically. >> only with how someone decided to write the mpz class. > I'm beginning to think there's a problem there. Yes: you don't recognize that gmpy is not a builtin package, it's an external package, and its designers/writers/implementors/coders/whatever decide how it will behave, not Python itself nor the Python developers. -- Gabriel Genellina From parham111 at hotmail.com Mon May 21 06:20:01 2007 From: parham111 at hotmail.com (parham haghighi rad) Date: Mon, 21 May 2007 11:20:01 +0100 Subject: Particle Filter Message-ID: Hi All I have Grid with n number of rows and n number of columns, and there is an agent in the environment which it has to move freely while its avoiding obstacles I am using Particle Filter Algorithm (simplified Markov) with recursive update. My problem is that my virtual agents which i use them to detect the walls and then i filter them, they don't update the information to actual agent. Any suggestion Thanks Parham _________________________________________________________________ Try Live.com - your fast, personalized homepage with all the things you care about in one place. http://www.live.com/getstarted -------------- next part -------------- An HTML attachment was scrubbed... URL: From uzi18 at o2.pl Thu May 10 15:34:28 2007 From: uzi18 at o2.pl (=?UTF-8?Q?Bart.?=) Date: Thu, 10 May 2007 21:34:28 +0200 Subject: =?UTF-8?Q?Re:_Re:_High_resolution_sleep_(Linux)?= In-Reply-To: <1178808104.915724.176100@n59g2000hsh.googlegroups.com> References: <1178274122.142071.91740@y5g2000hsa.googlegroups.com> <8l90i.911$UU.403@newssvr19.news.prodigy.net> <1178808104.915724.176100@n59g2000hsh.googlegroups.com> Message-ID: <5c12d89.219db764.464373c4.a069f@o2.pl> > On 9 Maj, 03:23, John Nagle wrote: > > Hendrik van Rooyen wrote: > > > "Tim Roberts" wrote" > > > It is also possible to keep the timer list sorted by "expiry date", > > > and to reprogram the timer to interrupt at the next expiry time > > > to give arbitrary resolution, instead of implementing a regular 'tick'. > > > > Yes, and that's a common feature in real-time operating systems. > > If you're running QNX, you can expect that if your high priority > > task delays to a given time, you WILL get control back within a > > millisecond of the scheduled time. Even tighter timing control > > is available on some non-x86 processors. > > > > Some CPUs even have hardware support for a sorted event list. > > The Intel 8061, which ran the engines of most Ford cars in the 1980s, > > had that. > > > > But no way are you going to get consistent timing resolution like that > > from Python. It's an interpreter with a garbage collector, after all. > > > > John Nagle > > > The application the original poster (i.e. me) was interested in was a > program that sends ethernet packets at a loosely specified rate. A > loop that sends all packets with no sleep in between will send them at > a too high rate. Using the default sleep in my Python interpreter > sleeps to long, since even a few microseconds add up when you send > hundreds of thousands of packets. > > If the process scheduler deals with another process now and then, it > doesn't matter. If it switches to another application between each > packet is beeing sent, that's a problem. > > Anyways, what I need is high resolution sleep, not high resolution > timing. Installing a real time OS seems like overkill. > > (Yes I know, one can also send, say, 50 packets at a time, and then > sleep, send 50 more packets, and so on.) > > -- > http://mail.python.org/mailman/listinfo/python-list What about C module with usleep,nanosleep? Best regards. Bart. From python at rcn.com Thu May 24 01:09:48 2007 From: python at rcn.com (Raymond Hettinger) Date: 23 May 2007 22:09:48 -0700 Subject: 0 == False but [] != False? In-Reply-To: <1179982400.412340.178710@g4g2000hsf.googlegroups.com> References: <1179982400.412340.178710@g4g2000hsf.googlegroups.com> Message-ID: <1179983387.883994.67580@x18g2000prd.googlegroups.com> > >>> [] == False > False > > Could anybody point out why this is the case? Writing, "if x" is short for writing "if bool(x)". Evaluating bool(x) checks for a x.__nonzero__() and if that method isn't defined, it checks for x.__len__() to see if x is a non-empty container. In your case, writing "if []" translates to "if len([]) != 0", which evaluates to False. True and False are of type bool which is a subclass of int. So, False really is equal to zero and True really is equal to one. In contrast, the empty list is not of type int. So [] != False eventhough bool([]) == False. Raymond From half.italian at gmail.com Wed May 9 21:48:02 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 9 May 2007 18:48:02 -0700 Subject: Checking if string inside quotes? In-Reply-To: References: <1178745091.682071.128670@w5g2000hsg.googlegroups.com> Message-ID: <1178761682.334958.246010@y5g2000hsa.googlegroups.com> On May 9, 2:31 pm, "Michael Yanowitz" wrote: > Thanks, but it is a little more complicated than that, > the string could be deep in quotes. > > The problem is in string substitution. > Suppose I have a dictionary with MY_IP : "172.18.51.33" > > I need to replace all instances of MY_IP with "172.18.51.33" > in the file. > It is easy in cases such as: > if (MY_IP == "127.0.0.1"): > > But suppose I encounter:" > ("(size==23) and (MY_IP==127.0.0.1)") > > In this case I do not want: > ("(size==23) and ("172.18.51.33"==127.0.0.1)") > but: > ("(size==23) and (172.18.51.33==127.0.0.1)") > without the internal quotes. > How can I do this? > I presumed that I would have to check to see if the string > was already in quotes and if so remove the quotes. But not > sure how to do that? > Or is there an easier way? > > Thanks in advance: > Michael Yanowitz > > -----Original Message----- > From: python-list-bounces+m.yanowitz=kearfott.... at python.org > > [mailto:python-list-bounces+m.yanowitz=kearfott.... at python.org]On Behalf > Of half.ital... at gmail.com > Sent: Wednesday, May 09, 2007 5:12 PM > To: python-l... at python.org > Subject: Re: Checking if string inside quotes? > > On May 9, 1:39 pm, "Michael Yanowitz" wrote: > > Hello: > > > If I have a long string (such as a Python file). > > I search for a sub-string in that string and find it. > > Is there a way to determine if that found sub-string is > > inside single-quotes or double-quotes or not inside any quotes? > > If so how? > > > Thanks in advance: > > Michael Yanowitz > > I think the .find() method returns the index of the found string. You > could check one char before and then one char after the length of the > string to see. I don't use regular expressions much, but I'm sure > that's a more elegant approach. > > This will work. You'll get in index error if you find the string at > the very end of the file. > > s = """ > foo > "bar" > """ > findme = "foo" > index = s.find(findme) > > if s[index-1] == "'" and s[index+len(findme)] == "'": > print "single quoted" > elif s[index-1] == "\"" and s[index+len(findme)] == "\"": > print "double quoted" > else: > print "unquoted" > > ~Sean > > --http://mail.python.org/mailman/listinfo/python-list In that case I suppose you'd have to read the file line by line and if you find your string in the line then search for the indexes of any matching quotes. If you find matching quotes, see if your word lies within any of the quote indexes. #!/usr/bin/env python file = open("file", 'r') findme= "foo" for j, line in enumerate(file): found = line.find(findme) if found != -1: quotecount = line.count("'") quoteindexes = [] start = 0 for i in xrange(quotecount): i = line.find("'", start) quoteindexes.append(i) start = i+1 f = False for i in xrange(len(quoteindexes)/2): if findme in line[quoteindexes.pop(0):quoteindexes.pop(0)]: f = True print "Found %s on line %s: Single-Quoted" % (findme, j +1) if not f: print "Found %s on line %s: Not quoted" % (findme, j+1) It's not pretty but it works. ~Sean From daniele.varrazzo at gmail.com Mon May 7 10:26:55 2007 From: daniele.varrazzo at gmail.com (Daniele Varrazzo) Date: 7 May 2007 07:26:55 -0700 Subject: problem with quoted strings while inserting into varchar field of database. In-Reply-To: References: <1178475772.423687.118800@e65g2000hsc.googlegroups.com> <1178526655.933789.294700@h2g2000hsg.googlegroups.com> <1178530363.516882.228380@l77g2000hsb.googlegroups.com> Message-ID: <1178548015.856661.308070@u30g2000hsc.googlegroups.com> > >> >> > cur.execute("INSERT INTO datatable (data) VALUES (%s);", > >> >> > (pickled_data,)) > %s is not a placeholder IMHO. > What happens when using %s is, that the string given will be inserted where > %s is; that is something python does as with every print or such. It is indeed. The behavior you describe would be true if i had used the "%" operator. Read better what i have written: There is no "%" operator. cur.execute() receives 2 parameters: a SQL string with placeholders and a tuple with values: it's not me mangling values into the SQL string. This is the driver responsibility and it has the chance because it receives SQL and values as two distinct parameters. The driver can ask the SQL string to contain placeholders either in qmark "?" or in format "%s" style, but there is no functional difference. Notice that the placeholder is always "%s" and not "%d" or "%f" for integers or float: there is always an escaping phase converting each python object into a properly encoded string and then the placeholders are replaced with the value. This happens into the execute() machinery. > By using the qmark style, it is up the the implementation of the > cursor.execute method to decide what to do. python itself, and it's string > implementation, don't know anything to do with the qmark. > So, IMHO it *makes* a difference: > with %s the execute function sees a string and nothing more as the > parameters are consumed away by the % substitution. > with ?, the execute implementation must do it's best, it gets a string and > a list/tuple with values. Again, this would be true for "cur.execute(sql % data)": what i wrote is "cur.execute(sql, data)". -- Daniele From bj_666 at gmx.net Tue May 8 12:55:18 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 08 May 2007 18:55:18 +0200 Subject: Towards faster Python implementations - theory References: <1210i.7468$2v1.2505@newssvr14.news.prodigy.net> <1178641778.266569.13290@p77g2000hsh.googlegroups.com> Message-ID: In <1178641778.266569.13290 at p77g2000hsh.googlegroups.com>, Paul Boddie wrote: >> On the typing front, the neatest way to express typing is via >> initialization. With the Shed Skin restrictions, if all variables are >> initialized before use (preferably in __init__), there's no need to >> maintain an "undefined" flag for a variable. And, of course, if >> the type of a varaible is simple and can't change, it doesn't have to >> be "boxed", (enclosed in an object) which is a big win. A variable? :-) Maybe that last sentence should start with: And, of course, if the type of objects bound to a name won't change? > I'm fairly sure, although my intuition unfortunately doesn't provide a > ready example right now, that typing via initialisation, whilst an > important tool, may either impose unacceptable restrictions if > enforced too rigidly or limit the precision that one might desire in > determining type information in the resulting system. I often bind a name to `None` first if it is going to be bound to it's "real" value later on. So this initialization doesn't say anything about the type(s) that will be bound to it later. I don't see how this type inference for static types will work unless some of the dynamism of the language will get restricted. But is this really necessary? Isn't a JIT compiler and maybe type hinting good enough? By type hinting I really mean just recommendations from the programmer. So you can say this name should be an `int` and the JIT compiler produces code in advance, but it's okay to pass another object instead. Ciao, Marc 'BlackJack' Rintsch From deets at nospam.web.de Tue May 1 07:38:00 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 01 May 2007 13:38:00 +0200 Subject: Problems with time In-Reply-To: <1178018008.341271.300880@n59g2000hsh.googlegroups.com> References: <1178018008.341271.300880@n59g2000hsh.googlegroups.com> Message-ID: <59on4pF2l1bk2U1@mid.uni-berlin.de> loial schrieb: > I am running on an AIX system with time zone set to BST > > If I run the following, I get the GMT time, i.e an hour less than the > correct time. > > How can I get the correct time > > now = time() > > timeProcessed = strftime("%H:%M",gmtime(now)) > localtime? Diez From byte8bits at gmail.com Mon May 21 11:50:17 2007 From: byte8bits at gmail.com (brad) Date: Mon, 21 May 2007 11:50:17 -0400 Subject: Python and GUI In-Reply-To: <1179761984.704369.116310@b40g2000prd.googlegroups.com> References: <1179761984.704369.116310@b40g2000prd.googlegroups.com> Message-ID: sdoty044 at gmail.com wrote: > Just wondering on what peoples opinions are of the GUIs avaiable for > Python? We have used wxPython with great results. It's cross platform. Can use native OS widgets and is easy to program. Compiles easily to exe binaries for Windows users as well. Best of luck, Brad From afriere at yahoo.co.uk Thu May 10 05:16:06 2007 From: afriere at yahoo.co.uk (Asun Friere) Date: 10 May 2007 02:16:06 -0700 Subject: Newbie (but improving) - Passing a function name with parameters as a parameter In-Reply-To: <1178785638.736644.312970@e51g2000hsg.googlegroups.com> References: <1178785638.736644.312970@e51g2000hsg.googlegroups.com> Message-ID: <1178788566.073321.193530@e65g2000hsc.googlegroups.com> Try again ... Just looking over your code quickly ... the function 'lookup' returns either True or False (a boolean) depending on whether matchcount == pattcount. Then in the declaration of the function 'timeloop' this return value gets bound to 'dofunction.' The subsequent call 'dofunction()' fails, because a boolean is not callable. Asun From sjdevnull at yahoo.com Tue May 1 11:07:23 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 1 May 2007 08:07:23 -0700 Subject: re-importing modules In-Reply-To: References: <8%pZh.18192$Kd3.76@newssvr27.news.prodigy.net> <1177962288.575008.48490@q75g2000hsh.googlegroups.com> <1177967919.968338.3300@l77g2000hsb.googlegroups.com> Message-ID: <1178032043.139028.101170@c35g2000hsg.googlegroups.com> John Nagle wrote: > Steven D'Aprano wrote: > > I'd hate for reload to disappear, it is great for interactive > > development/debugging, at least under some circumstances. (If you have > > complex and tangled class hierarchies, it might not be powerful enough.) > > > > As for the semantics being awful, I disagree. reload() does exactly > > what it claims to do, no more, no less. > > It's more complicated than that. See > > http://arcknowledge.com/lang.jython.user/2006-01/msg00017.html > > Exactly what reloading should do is still an open question for some of > the hard cases. > > "reload" as a debug facility is fine. > Trouble comes from production programs which use it as a > reinitialization facility. I tend to agree with this; our servers do graceful restarts to pick up code changes (which, in addition to avoiding reload also means that it's easier as an admin to control the view of the code than in "automatically pick up new changes" models--in particular, you can wait until all changes are there, send SIGUSR1, and pick up the whole set of changes atomically). > Reloading a module with multiple threads running gets > complicated. It works in CPython because CPython doesn't have > real concurrency. Point of clarity: the CPython interpreter is not concurrent. Concurrency != multithreading, and multiprocess solutions run fine in CPython. From michael at jedimindworks.com Thu May 31 04:53:40 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Thu, 31 May 2007 03:53:40 -0500 Subject: Good Python style? In-Reply-To: <465E804B.9060904@a-beyer.de> References: <465E804B.9060904@a-beyer.de> Message-ID: <1A016DE6-483C-45BA-96B9-7D03BC1654E3@jedimindworks.com> On May 31, 2007, at 2:59 AM, Andreas Beyer wrote: > Hi, > > I found the following quite cryptic code, which basically reads the > first column of some_file into a set. > In Python I am used to seeing much more verbose/explicit code. > However, > the example below _may_ actually be faster than the usual "for line > in ..." > Do you consider this code good Python style? Or would you recommend to > refrain from such complex single-line code?? > > Thanks! > Andreas > > inp = resource(some_file) > # read first entries of all non-empty lines into a set > some_set = frozenset([line.split()[0] for line in \ > filter(None, [ln.strip() for ln in inp])]) I don't know about style, but I find it much harder to read than this: some_set = frozenset(line.split()[0] for line in inp if len(line.strip())) ...which I *think* is equivalent, but less complicated. regards, Michael --- (do (or (do (not '(there is no try))) ())) From aleax at mac.com Thu May 3 01:06:21 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 2 May 2007 22:06:21 -0700 Subject: __dict__s and types and maybe metaclasses... References: <1178140405.468223.146220@l77g2000hsb.googlegroups.com> <1Nadna6BCcEWnKTbnZ2dnUVZ_u_inZ2d@comcast.com> <1178148009.279627.157560@n59g2000hsh.googlegroups.com> Message-ID: <1hxiam1.7hbnbq1ooj87dN%aleax@mac.com> Adam Atlas wrote: > On May 2, 5:24 pm, Larry Bates wrote: > > I think that most people accomplish this by: > > > > class blah: > > __initial_values={'a': 123, 'b': 456} > > > > def __init__(self): > > self.__dict__.update(self.__initialvalues) > > That's not really what I'm talking about... I'm talking about > replacing the __dict__ with a SUBCLASS of dict (not just default > values), and that's at the time of the class declaration (the creation > of `blah` as a `type` instance), not at instance creation. The metaclass only enters the picture AFTER the class body has run (and built a __dict__). As I explained many times: class ic(bases): means: -- run the to create a dictionary D -- identify the metaclass M -- execute: ic = M("ic", bases, D) the body always creates a dictionary -- you can't override that with metaclasses. Maybe some deep bytecode hacks might work, but I have some doubts in the matter (not given it much thought, tho). Alex From python-post at infocentrality.co.uk Mon May 21 11:11:37 2007 From: python-post at infocentrality.co.uk (Trevor Hennion) Date: Mon, 21 May 2007 15:11:37 +0000 (UTC) Subject: Help required with Python App Message-ID: Hi, I am producing a Web based database application for a customer and could do with some help producing pdf documents from the data. The project uses Apache. Postgresql and Python CGI scripts on a Linux server for a company with 20-25 users. I have been looking at the http://www.reportlab.org - ReportLab Toolkit, but am rather busy with the other parts of the project, so if any one located in the UK - Reading/Basingstoke area has the right skills and time available now, please contact me. I have a small budget available for this work. Regards Trevor PS UK/Reading/Basingstoke area is essential. From schoenfeld.one at gmail.com Sat May 12 20:57:38 2007 From: schoenfeld.one at gmail.com (schoenfeld.one at gmail.com) Date: 12 May 2007 17:57:38 -0700 Subject: Video: Professor of Physics Phd at Cal Tech says: 911 Inside Job In-Reply-To: <1177778685.506101.201540@h2g2000hsg.googlegroups.com> References: <1177467203.719625.93920@u32g2000prd.googlegroups.com> <1177778685.506101.201540@h2g2000hsg.googlegroups.com> Message-ID: <1179017858.568924.189700@u30g2000hsc.googlegroups.com> On Apr 29, 2:44 am, War Office <911falsef... at gmail.com> wrote: > Why can't any of you just discuss the fact that free-fall collapse of > this building contradicts the laws of physics? Why do you assume he's even capable of doing so? He's just a crackpot, but he's in the unfortunate majority. > Why do you all have to avoid the topic and rather go on a character > assassination which is totally abhorent to scientific method? That is the new "scientific method". From http Mon May 28 02:34:55 2007 From: http (Paul Rubin) Date: 27 May 2007 23:34:55 -0700 Subject: itertools.groupby References: <1180295221.3163.9.camel@localhost.localdomain> <1180313441.598026.198230@d30g2000prg.googlegroups.com> <7x8xb939ut.fsf@ruckus.brouhaha.com> <1180330198.466144.197620@j4g2000prf.googlegroups.com> Message-ID: <7xveed1mnk.fsf@ruckus.brouhaha.com> Raymond Hettinger writes: > On May 27, 8:28 pm, Paul Rubin wrote: > > I use the module all the time now and it is great. > Thanks for the accolades and the great example. Thank YOU for the great module ;). Feel free to use the example in the docs if you want. The question someone coincidentally posted about finding sequences of capitalized words also made a nice example. Here's yet another example that came up in something I was working on: you are indexing a book and you want to print a list of page numbers for pages that refer to George Washington. If Washington occurs on several consecutive pages you want to print those numbers as a hyphenated range, e.g. Washington, George: 5, 19, 37-45, 82-91, 103 This is easy with groupby (this version not tested but it's pretty close to what I wrote in the real program). Again it works by Bates numbering, but a little more subtly (enumerate generates the Bates numbers): snd = operator.itemgetter(1) # as before def page_ranges(): pages = sorted(filter(contains_washington, all_page_numbers)) for d,g in groupby(enumerate(pages), lambda (i,p): i-p): h = map(snd, g) if len(h) > 1: yield '%d-%d'% (h[0], h[-1]) else: yield '%d'% h[0] print ', '.join(page_ranges()) See what has happened: for a sequence of p's that are consecutive, i-p stays constant, and groupby splits out the clusters where this occurs. > FWIW, I checked in a minor update to the docs: ... The uniq example certainly should be helpful for Unix users. From grante at visi.com Sun May 20 23:35:59 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 21 May 2007 03:35:59 -0000 Subject: List Moderator References: <880dece00705172218n71123b55q531ec0c5e500f208@mail.gmail.com> <880dece00705190012g4f3d3ef6v4e6c87a156708bb0@mail.gmail.com> <880dece00705191305m203bc8ep804d647c17438581@mail.gmail.com> <464F5E42.6090607@holdenweb.com> <880dece00705201305q6944986fj8f77c4b5cac09456@mail.gmail.com> Message-ID: <13524svhtst5dd1@corp.supernews.com> On 2007-05-20, Dennis Lee Bieber wrote: >> It doesn't all go through a central point - users like me who use a news >> server to access the list submit articles through a local news server >> using NNTP. While there *is* a single point of access for articles >> pulled from python.org's news server and gatewayed out as email (and for >> which the filters you mention probably ought to help), articles I see >> have never been processed by this interface. >> > Which doesn't explain why only comp.lang.python, of the several > newsgroups I read, seems to be so spam-filled... Maybe I've got a beter news server, but I don't see much spam at all in c.l.p. -- Grant Edwards grante Yow! Is it 1974? What's at for SUPPER? Can I spend my visi.com COLLEGE FUND in one wild afternoon?? From deets at nospam.web.de Tue May 1 10:49:11 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 01 May 2007 16:49:11 +0200 Subject: Store variable name in another variable In-Reply-To: <1178023417.680239.156910@n59g2000hsh.googlegroups.com> References: <1177592072.498517.139260@b40g2000prd.googlegroups.com> <4631120a$0$27375$ba4acef3@news.orange.fr> <1178023417.680239.156910@n59g2000hsh.googlegroups.com> Message-ID: <59p2b8F2m04ukU1@mid.uni-berlin.de> loial schrieb: > OK, I have it working with dictionaries. > > However I have another scenerio : > > I am reading a file containing records like the following : > > > > > .. > .. > > > I need to substitute MYVARIABLE with the current value of MYVARIABLE > in my python script and write the file out again. > > The file may contain many more lines and many substitution values on > any line > > Assuming that MYVARIABLE is currently set to JOHN then the output > would be > > > > > > Can this be done in Python? Amending the way the variable names are > distinguished in the incoming file is possible if that would help. There are many ways to do so in python. You can use the built-in string interpolation: "" % dict(name=value) Or you can use one of the many available templating engines, like KID, genshi, cheetah and so on. Diez From jkn_gg at nicorp.f9.co.uk Thu May 10 04:03:39 2007 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: 10 May 2007 01:03:39 -0700 Subject: Erlang style processes for Python In-Reply-To: References: <1178759792.268979.206630@p77g2000hsh.googlegroups.com> Message-ID: <1178784219.289832.204770@n59g2000hsh.googlegroups.com> Have you seen Candygram? http://candygram.sourceforge.net/ jon N From grante at visi.com Wed May 9 12:51:26 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 09 May 2007 16:51:26 -0000 Subject: Single precision floating point calcs? Message-ID: <1343v0emvdjr545@corp.supernews.com> I'm pretty sure the answer is "no", but before I give up on the idea, I thought I'd ask... Is there any way to do single-precision floating point calculations in Python? I know the various array modules generally support arrays of single-precision floats. I suppose I could turn all my variables into single-element arrays, but that would be way ugly... -- Grant Edwards grante Yow! -- I have seen the at FUN -- visi.com From arkanes at gmail.com Wed May 2 11:27:24 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 2 May 2007 10:27:24 -0500 Subject: Is it possible to determine what a function needs for parameters - In-Reply-To: <1178118792.289104.212670@l77g2000hsb.googlegroups.com> References: <1178115727.932794.100390@h2g2000hsg.googlegroups.com> <1178118792.289104.212670@l77g2000hsb.googlegroups.com> Message-ID: <4866bea60705020827t3e9e8417wb51e2b13d082d977@mail.gmail.com> On 2 May 2007 08:13:12 -0700, rh0dium wrote: > > This is far more work than you need. Push an (args, kwargs) tuple into > > your arguments queue and call self.function(*args, **kwargs). > > No see I tried that and that won't work. > > I'm assuming what you are referring to is this (effectively) > > Q.put(((),{a:"foo", b:"bar})) > > input = Q.get() > self.function( *input[0], **input[1]) > > This will obviously fail if several conditions aren't met - hence the > kludge. Am I missing something here? > Assuming that the caller correctly pushes arguments, how can this fail? From gagsl-py2 at yahoo.com.ar Tue May 29 13:31:37 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 29 May 2007 14:31:37 -0300 Subject: how to print the GREEK CAPITAL LETTER delta under utf-8 encoding References: <1180414659.066482.236370@i38g2000prf.googlegroups.com> <465BBB49.6000803@v.loewis.de> <1180421212.151587.118020@r19g2000prf.googlegroups.com> <465BD0AA.9080805@v.loewis.de> <1180423455.639315.155990@a26g2000pre.googlegroups.com> Message-ID: En Tue, 29 May 2007 04:24:15 -0300, ??????????????? escribi?: > On 5?29?, ??3?05?, "Martin v. Lo"wis" wrote: >> > yes, it could print to the terminal(cmd.exe), but when I write these >> > string to file. I got the follow error: >> >> > File "E:\Tools\filegen\filegen.py", line 212, in write >> > self.file.write(data) >> > UnicodeEncodeError: 'ascii' codec can't encode character u'\u0394' in >> > position 0 >> > : ordinal not in range(128) >> >> Yes, when writing to a file, you need to define an encoding, e.g. >> >> self.file.write(data.encode("utf-8")) >> >> You can use codecs.open() instead of open(), >> so that you can just use self.file.write(data) >> > Thanks a lot! > I want to just use the utf-8. how could I convert my 'mbcs' encoding > to the utf-8 and write it to the file? > I have replaced the open() to codecs.open() > > but it still can not decode the 'mbcs', the error is as follow: > > File "E:\Tools\filegen\filegen.py", line 213, in write > self.file.write(data) > File "C:\Python25\lib\codecs.py", line 638, in write > return self.writer.write(data) > File "C:\Python25\lib\codecs.py", line 303, in write > data, consumed = self.encode(object, self.errors) > UnicodeDecodeError: 'ascii' codec can't decode byte 0xcc in position > 32: ordinal > not in range(128) Just to provide an example of what MvL already said: py> line = u"Delta=\u0394" py> f = open("data.txt","w") py> f.write(line.encode("utf8")) py> f.close() py> print repr(open("data.txt").read()) 'Delta=\xce\x94' py> import codecs py> f = codecs.open("data2.txt","w","utf8") py> f.write(line) py> f.close() py> print repr(open("data2.txt").read()) 'Delta=\xce\x94' -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Tue May 22 17:48:13 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 22 May 2007 18:48:13 -0300 Subject: trying to gzip uncompress a StringIO References: <1179854545.199999.247590@k79g2000hse.googlegroups.com> Message-ID: En Tue, 22 May 2007 14:22:25 -0300, escribi?: > I'm using the code below to read the zipped, base64 encoded WMF file > saved in an XML file with "Save as XML" from MS Word. As the "At this > point" comment shows, I know that the base64 decoding is going fine, > but unzipping from the decodedVersion StringIO object isn't getting me > anything, because the len(fileContent) call is returning 0. Any > suggestions? Perhaps GzipFile reads from the current position till end (and sees nothing). Try rewinding the file: > decodedVersion = StringIO.StringIO() > base64.decode(open(infile, 'r'),decodedVersion) decodedVersion.seek(0) > fileObj = gzip.GzipFile(fileobj=decodedVersion); > fileContent = fileObj.read() > print len(fileContent) -- Gabriel Genellina From DannyBoy at DannyBoyAds.com Thu May 31 23:12:42 2007 From: DannyBoy at DannyBoyAds.com (DannyBoy Advertising) Date: Thu, 31 May 2007 20:12:42 -0700 Subject: Market Your Business On Search Engines Message-ID: <1180667562.060417.67350@q69g2000hsb.googlegroups.com> Utilize the Internet's search engines to promote your specific business website. Yahoo, Google, MSN, Business, Ask, and many more! If you have a website for your business, take it to the next level! Market locally, regionally, nationally or worldwide! *Promote Events *Produce Leads *Increase Sales *Increase Registrations *Attract specific clientele *and more Contact DannyBoy Advertising today for a free consultation to determine the ideal campaign for your marketing needs. www.DannyBoyAds.com (407)468-9278 Webmaster at ... From aisaac at american.edu Tue May 8 13:59:27 2007 From: aisaac at american.edu (Alan Isaac) Date: Tue, 08 May 2007 17:59:27 GMT Subject: change of random state when pyc created?? References: <1178408359.113807.181570@l77g2000hsb.googlegroups.com> Message-ID: <3U20i.2110$wy2.1466@trnddc03> "Steven D'Aprano" wrote in message news:pan.2007.05.08.07.40.52 at REMOVE.THIS.cybersource.com.au... > My testing suggests the bug is *not* to do with pyc files at all. I'm > getting different results when running the files, even when the directory > is read-only (and therefore no pyc files can be created). > > My results suggest that setting the seed to the same value does NOT give > identical results, *even though* the random number generator is giving > the same results. > > So I think we can discount the issue being anything to do with either > the .pyc files or the random number generator. I do not know how Python handles your use of a readonly directory. What I have seen is: - when a test1.pyc file is present, I always get the same outcome (result1) - when a test1.pyc file is NOT present, I always get the same outcome (result2) - the two outcomes are different (result1 != result2) Do you see something different than this if you run the test as I suggested? If not, how can in not involve the .pyc file (in some sense)? Cheers, Alan Isaac From cam.ac.uk at mh391.invalid Thu May 3 04:49:14 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 03 May 2007 09:49:14 +0100 Subject: Slicing Arrays in this way In-Reply-To: <1178153081.907748.242110@h2g2000hsg.googlegroups.com> References: <4638fe20$0$16403$88260bb3@free.teranews.com> <1178153081.907748.242110@h2g2000hsg.googlegroups.com> Message-ID: John Machin wrote: > On May 3, 10:21 am, Michael Hoffman wrote: >> Tobiah wrote: >> >>> >>> elegant_solution([1,2,3,4,5,6,7,8,9,10]) >>> [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] >> That's not an array, it's a list. See the array module for arrays >> (fixed-length, unlike variable-length lists). > > You must have your very own definitions of "fixed-length" and > "unlike". Sorry, too much time spent with numarray arrays which are documented to have immutable size. -- Michael Hoffman From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun May 13 15:52:44 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 13 May 2007 21:52:44 +0200 Subject: Simulating simple electric circuits References: <5a9838F2nlbanU1@mid.individual.net> <5ae44aF2ku9rtU1@mid.individual.net> <5ak3u9F2odts2U1@mid.individual.net> <1178974027.175679.51130@k79g2000hse.googlegroups.com> Message-ID: <5ap8kcF2pejv7U1@mid.individual.net> Arnaud Delobelle wrote: > I'm interested! I was tempted to have a go at it after your > initial post, it sounded like a nice little project :) Please stand by a day. I'm momentarily facing problems with currents that never end (going in a circle). And my code doesn't look that beatiful and/or clean to me, as is using this framework. But judge yourself (soonest tomorrow). I'm already looking forward to comments and suggestions. :) Regards, Bj?rn -- BOFH excuse #198: Post-it Note Sludge leaked into the monitor. From mccredie at gmail.com Thu May 3 16:32:37 2007 From: mccredie at gmail.com (Matimus) Date: 3 May 2007 13:32:37 -0700 Subject: Real Time Battle and Python In-Reply-To: References: Message-ID: <1178224357.498503.206570@h2g2000hsg.googlegroups.com> On May 3, 5:20 am, hg wrote: > Hi, > > I have started to work on a python-based robot, and am interested in your > feedback: > > http://realtimebattle.sourceforge.net/www.snakecard.com/rtb > > hg This is not necessarily a response to your effort, but just a note (rant) about realtimebattle. It reminds me more of homework in 300 and 400 level college engineering classes than a game. Based upon my previous effort and realizations, I found realtimebattle coding to be, from a programming perspective, an exercise in protocol implementation first. Once the protocol work is done you need to implement control algorithms for movement and enemy tracking. Think PID algorithms (Proportional, Integral and Differential). Only when the protocol and control portions are done can you focus on strategy and play the game. You should also note, however, that the first two tasks are quite daunting. And the second is difficult to get right. I found the whole process to be very tiring and not very rewarding. I don't mean to discourage you, I just think it would be more fun to write my own game than to 'play' that one. A better game, from a programming perspective, would be "discretetimebattle". Where each player controls their robot with second order parameters (velocity not force), the world has no third order effects (friction) and the time is discrete. Discrete time meaneing that the protocol updates every player at regular intervals with the same information and, in terms of the simulation, each update represents a set time delta. I would be interested to know if anybody else has played, or tried to play, realtimebattle and has similar sentiments. I do wish you luck though. If you get a robot working you are a far more dedicated and patient individual than me. -Matt From stefan.behnel-n05pAM at web.de Tue May 15 09:57:32 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 15 May 2007 15:57:32 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179236673.893122.28800@w5g2000hsg.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> Message-ID: <4649BC4C.10200@web.de> George Sakkis wrote: > After 175 replies (and counting), the only thing that is clear is the > controversy around this PEP. Most people are very strong for or > against it, with little middle ground in between. I'm not saying that > every change must meet 100% acceptance, but here there is definitely a > strong opposition to it. Accepting this PEP would upset lots of people > as it seems, and it's interesting that quite a few are not even native > english speakers. But the positions are clear, I think. Open-Source people are against it, as they expect hassle with people sending in code or code being lost as it can't go public as-is. Teachers are for it as they see the advantage of having children express concepts in their native language. In-house developers are rather for this PEP as they see the advantage of expressing concepts in the way the "non-techies" talk about it. That's about all I could extract as arguments. To me, this sounds pretty much like something people and projects could handle on their own once the PEP is accepted. Stefan From horpner at yahoo.com Fri May 11 09:15:01 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Fri, 11 May 2007 13:15:01 GMT Subject: vim e autoindentazione commenti References: Message-ID: On 2007-05-11, Alan Franzoni wrote: > Al contrario con altri tipi di file (es. Java) questa aggiunta > ? automatica e la trovo molto, molto comoda. > > Dovrei andae a intaccare il file di indentazione? o quello di > sintassi? Colto prego nel manuale Vim: :help format-comments (Spiacente per la mia scrittura difettosa. Sto utilizzando il traduttore di altavista.) -- Neil Cerutti You've got to take the sour with the bitter. --Samuel Goldwyn From martinvilu at gmail.com Thu May 24 10:53:34 2007 From: martinvilu at gmail.com (Mauler) Date: 24 May 2007 07:53:34 -0700 Subject: Bootstrapping Message-ID: <1180018414.715769.142750@p77g2000hsh.googlegroups.com> I need some help with adding bootstrap code to the core of python, the idea is to leave a super base core inside a zip file (python25.zip works right out of the box) and leave the rest in separate zip modules. Making it more friendly with pendrives and more practical as a standalone runtime (ie, without install) and fully modular. The thing is that i need to modify the base importer to add this special "site-packages" . Any hints? thanks in advance (and a lot!) Martin Rene Vilugron Patagonia Argentina From __peter__ at web.de Mon May 21 17:17:14 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 21 May 2007 23:17:14 +0200 Subject: doctest environment question References: <1179762737.153434.143030@b40g2000prd.googlegroups.com> <1179775483.685881.236940@x18g2000prd.googlegroups.com> Message-ID: tag wrote: > On 21 May, 18:53, Peter Otten <__pete... at web.de> wrote: >> The doctest code is executed in a module without a __name__, it seems. >> Unfortunately (in this case) the builtin module serves as a fallback >> helping out with its own name: >> >> >>> __name__ >> '__main__' >> >>> del __name__ >> >>> __name__ >> >> '__builtin__' >> >> What to do about it? doctest could be changed to execute code snippets in >> a module with a name and a sys.modules entry though I don't see much >> benefit here. > > Peter, thanks for the quick response, but I don't quite understand > what you're saying. I don't want to change doctest -- I want to find a > way to make my example pass using doctest. The environment that doctest provides is similar to the interactive interpreter but not identical. In particular there is no meaningful __name__. > doctest.testfile comes with lots of parameters, and I suspect if I > knew how to do it I could pass in the correct parameters to make this > example work. It's not what I actually want to document/test, it's a > minimal example which demonstrates the problem. Here are two alternatives: (1) >>> def f(): pass ... >>> del f >>> f() Traceback (most recent call last): File "", line 1, in NameError: name 'f' is not defined (2) >>> def f(): pass ... >>> del globals()["f"] >>> f() Traceback (most recent call last): File "", line 1, in NameError: name 'f' is not defined If these don't work you'll have to give a bit more context. Peter From gordon.chapman at gmail.com Fri May 11 18:22:53 2007 From: gordon.chapman at gmail.com (gordon.chapman at gmail.com) Date: 11 May 2007 15:22:53 -0700 Subject: py2exe LoadLibrary question Message-ID: <1178922172.944048.124430@y80g2000hsf.googlegroups.com> Yep, it's the old LoadLibrary failed problem. I understand that python24.dll is required for the executable to run, but I'm going to be building a few of these executables and I don't want to have to bundle python24 along with each one. We have python24.dll installed in c:/windows/system32, why is loadlibrary not finding it? Is there an option I can specify to add c:/windows/system32 to the loadlibrary search path? Thanks. From laurentszyster at gmail.com Wed May 16 14:52:42 2007 From: laurentszyster at gmail.com (laurentszyster at gmail.com) Date: 16 May 2007 11:52:42 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46473267$0$31532$9b622d9e@news.freenet.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <1179341562.010190.291760@q23g2000hsg.googlegroups.com> On May 13, 5:44 pm, "Martin v. L?wis" wrote: > PEP 1 specifies that PEP authors need to collect feedback from the > community. As the author of PEP 3131, I'd like to encourage comments > to the PEP included below, either here (comp.lang.python), or to > python-3... at python.org > > In summary, this PEP proposes to allow non-ASCII letters as > identifiers in Python. If the PEP is accepted, the following > identifiers would also become valid as class, function, or > variable names: L?ffelstiel, chang?, ??????, or ??? > (hoping that the latter one means "counter"). +1 If only for one simple reason: JSON objects have UNICODE names and it may be convenient from a Python web agent to be able to instanciate/ serialize any such object as-is ... to/from a Python class instead of a dictionnary. Regards, Laurent Szyster From gagsl-py2 at yahoo.com.ar Thu May 17 00:20:07 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 17 May 2007 01:20:07 -0300 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179160242.787344.48060@h2g2000hsg.googlegroups.com> Message-ID: En Mon, 14 May 2007 13:30:42 -0300, escribi?: > Although probably not-sufficient to overcome this built-in > bias, it would be interesting if some bi-lingual readers would > raise this issue in some non-english Python discussion > groups to see if the opposition to this idea is as strong > there as it is here. Survey results from a Spanish-speaking group and a local group from Argentina: Yes: 6 No: 3 Total: 9 Comments summary: - Spanish requires few additional characters in addition to ASCII letters: ???????, so there is no great need of Unicode identifiers by Spanish developers. - Python can be embedded and extended using libraries - in those cases, what matters mostly is the domain specific usage. Letting the final users write their scripts/tasklets/etc using domain-specific and language-specific names would be a great thing. - Would be nice if class attribute names could correspond to table column names directly; would be nice to use the Pi greek symbol, by example, in math formulae. - Others raised already seen concerns: about source code legibility; being unable to type identifiers; risk of keywords being translated; that you can't know in advance whether your code will become widely published so best to use English identifiers from start. - Someone proposed using escape sequences of some kind, supported by editor plugins, so there is no need to modify the parser. - Refactoring tools should let you rename foreign identifiers into ASCII only. -- Gabriel Genellina From steve at holdenweb.com Wed May 30 22:58:35 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 30 May 2007 22:58:35 -0400 Subject: RDFXML Parser For "qualified Dublin Core" Database File In-Reply-To: <465e3522.75fb435e.20b3.5b51@mx.google.com> References: <465e3522.75fb435e.20b3.5b51@mx.google.com> Message-ID: <465E39DB.207@holdenweb.com> Brandon McGinty wrote: > Hi, > Thanks for the info. The speed is fantastic. 58 mb in under 15 sec, just as > shown. > I did notice that in this rdf file, I can't do any sort of find or findall. > I haven't been able to find any documentation on how to search. For > instance, in perl, one can do a search for "/rdf:RDF/pgterms:etext", and > when done in python, with many many variations, find and findall return no > results, either when searching from root or children of root. > ... one thought comes to mind: you will have to actually build the parse tree if you want to be ab le to search it that way. The technique I used, you would need to process the end events to get the data you seem to need! 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From timr at probo.com Wed May 2 02:10:54 2007 From: timr at probo.com (Tim Roberts) Date: Wed, 02 May 2007 06:10:54 GMT Subject: While we're talking about annoyances References: <1177837565.317999.244420@c35g2000hsg.googlegroups.com> Message-ID: <8oag339eh56tnpbl8mk3lqlf6avkmusvdm@4ax.com> Michael Hoffman wrote: > >Hint: if you find yourself using a decorate-sort-undecorate pattern, >sorted(key=func) or sequence.sort(key=func) might be a better idea. Is it? I thought I remember reading on this very list some years ago that the performance of sequence.sort became much, much worse when a key function was supplied. I've tended to favor the "Schwarzian transform" (decorate-sort-undecorate) because of that. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From etxuwig at cbe.ericsson.se Tue May 29 05:13:25 2007 From: etxuwig at cbe.ericsson.se (Ulf Wiger) Date: Tue, 29 May 2007 11:13:25 +0200 Subject: The Concepts and Confusions of Prefix, Infix, Postfix and Fully Functional Notations References: <1179936917.652372.24780@q69g2000hsb.googlegroups.com> <1oveejxwke.fsf@hod.lan.m-e-leypold.de> <465bb872$0$8729$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: >>>>> "Jon" == Jon Harrop writes: Jon> Anyway, are there any libraries to do hardware accelerated Jon> vector graphics in Perl, Python, Lisp, Java or any functional Jon> language (except OCaml and F# and excluding WPF and Jon> Silverlight)? I guess the OpenGL binding for Erlang qualifies. The best exhibit of this would be Wings3D, an Open Source 3D graphics modeller, written in Erlang, and with quite a large user base. http://www.wings3d.com BR, Ulf W -- Ulf Wiger, Senior Specialist, / / / Architecture & Design of Carrier-Class Software / / / Team Leader, Software Characteristics / / / Ericsson AB, IMS Gateways From steven at REMOVE.THIS.cybersource.com.au Mon May 7 04:18:34 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 07 May 2007 08:18:34 -0000 Subject: long lists References: <1178522894.357829.28250@u30g2000hsc.googlegroups.com> Message-ID: On Mon, 07 May 2007 00:28:14 -0700, Merrigan wrote: > 1. I have the script popping all the files that need to be checked into > a list, and have it parsing the list for everything...Now the problem is > this : The sever needs to check (at the moment) 375 files and eliminate > those that don't need reuploading. This number will obviously get bigger > and bigger as more files gets uploaded. Now, the problem that I'm having > is that the script is taking forever to parse the list and give the > final result. How can I speed this up? By writing faster code??? It's really hard to answer this without more information. In particular: - what's the format of the list and how do you parse it? - how does the script decide what files need uploading? -- Steven. From deepns7 at gmail.com Thu May 3 02:37:35 2007 From: deepns7 at gmail.com (pradeep nair) Date: 2 May 2007 23:37:35 -0700 Subject: FInd files with .so extension In-Reply-To: References: <1178168321.581307.284750@y5g2000hsa.googlegroups.com> <180b672e0705022310i3ad709f8w6590e6aaffd884cc@mail.gmail.com> <163f0ce20705022324s5953335v1c5d5337442a36a0@mail.gmail.com> Message-ID: <1178174254.998741.96930@o5g2000hsb.googlegroups.com> On May 3, 11:27 am, kaens wrote: > do YOU mean hit "reply to all" not "reply?" > > On 5/3/07, kaens wrote: > > > do you mean > > filelst.append(i)? > > > On 5/3/07, rishi pathak wrote: > > > May be this would work > > > import os > > > grep="so" > > > dir="." > > > lst = os.listdir(dir) > > > filelst=[] > > > for i in lst: > > > if i.split(".")[len(i.split("."))-1] == grep: > > > lst.append(i) > > > print lst > > > > On 2 May 2007 21:58:41 -0700, pradeep nair wrote: > > > > HI, > > > > > How do i find files with .so extension using python . > > > > > -- > > > >http://mail.python.org/mailman/listinfo/python-list > > > > -- > > > Regards-- > > > Rishi Pathak > > > National PARAM Supercomputing Facility > > > Center for Development of Advanced Computing(C-DAC) > > > Pune University Campus,Ganesh Khind Road > > > Pune-Maharastra > > > -- > > >http://mail.python.org/mailman/listinfo/python-list ???? From nospam at nospam.net Fri May 4 18:31:30 2007 From: nospam at nospam.net (Andrew) Date: Fri, 04 May 2007 15:31:30 -0700 Subject: Problems Drawing Over Network Message-ID: <133nd279g7ob8a2@corp.supernews.com> Hello Everyone I am receiving an error in an application I am working on. The application when its done will be a Dungeons and Dragons Network game. I am having problems with the Networked Canvas basically for drawing the dungeon maps If I initialize two of the Tkinter Canvas widgets with in the same window I can draw across the network, however if I open a second instance of the Application and initialize the canvas, on windows I recv a "Software has caused a connection abort error", on Linux I recv a broken pipe message I am wondering how to go about fixing this I have spent the last 4 days trying to figure it Any ideas would be appreciated Cheers ###CODE### #CLIENT import random import time from Tkinter import * import string import sys import Image import ImageTk import JpegImagePlugin from threading import * import socket import spots import time import thread Image.initialized = 1 HOST = '24.207.81.142' PORT = 8080 PORT2 = 8888 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) PORT2 = 8888 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.connect((HOST, PORT2)) ZSP = spots.ZSP(server) def main(): global hold hold = [] global fill fill = '#000000' connect() root = Tk() root.title('Graphics') root.resizable(False, False) upper = LabelFrame(root, text='Global Canvas') lower = LabelFrame(root, text='Their Canvas') global draw draw = Canvas(upper, bg='#ffffff', width=400, height=300, highlightthickness=0) global look #look = Canvas(lower, bg='#ffffff', width=400, height=300, highlightthickness=0) cursor = Button(upper, text='Cursor Color', command=change_cursor) canvas = Button(upper, text='Canvas Color', command=change_canvas) draw.bind('', motion) draw.bind('', press) draw.bind('', release) draw.bind('', delete) upper.grid(padx=5, pady=5) lower.grid(padx=5, pady=5) draw.grid(row=0, column=0, padx=5, pady=5, columnspan=2) #look.grid(padx=5, pady=5) cursor.grid(row=1, column=0, padx=5, pady=5, sticky=EW) canvas.grid(row=1, column=1, padx=5, pady=5, sticky=EW) root.mainloop() def connect(): thread.start_new_thread(processor, ()) ##def start_server(): ## global ZSP ## server = socket.socket() ## server.bind(('', PORT)) ## server.listen(1) ## ZSP = spots.ZSP(server.accept()[0]) def processor(): while True: (func, args, kwargs) = ZSP.recv() getattr(draw, func)(*args, **kwargs) time.sleep(0.1) def call(func, *args, **kwargs): ZSP.send((func, args, kwargs)) ################################################################################ def change_cursor(): global fill color = tkColorChooser.askcolor(color=fill)[1] if color is not None: fill = color def change_canvas(): color = tkColorChooser.askcolor(color=draw['bg'])[1] if color is not None: draw['bg'] = color draw.config(bg=color) call('config', bg=color) ################################################################################ def motion(event): if hold: hold.extend([event.x, event.y]) event.widget.create_line(hold[-4:], fill=fill, tag='TEMP') call('create_line', hold[-4:], fill=fill, tag='TEMP') def press(event): global hold hold = [event.x, event.y] def release(event): global hold if len(hold) > 2: event.widget.delete('TEMP') event.widget.create_line(hold, fill=fill, smooth=True) call('delete', 'TEMP') call('create_line', hold, fill=fill, smooth=True) hold = [] def delete(event): event.widget.delete(ALL) call('delete', ALL) ################################################################################ class App: def __init__(self, master): #initialize socket variables for theclient self.thread1 = Thread(target=self.run) self.thread1.start() self.frameH = frameH = Frame(master, background="#ffffff") self.labelH = Label(frameH, image=fri) self.labelH.pack(side=TOP) frameH.pack() self.framettext = Frame(master) self.scrollbar = Scrollbar(self.framettext) self.scrollbar.pack(side=RIGHT, fill=Y, expand=TRUE) self.textbox = Text(self.framettext) self.textbox.pack(fill=BOTH, expand=True) self.textbox.config(yscrollcommand=self.scrollbar.set) self.scrollbar.config(command=self.textbox.yview) self.framettext.pack(fill=BOTH, expand=True) self.frame = Frame(master) self.frame.pack(fill=X, expand=True) self.send=Button(self.frame, text='Send Message', command=self.send) self.send.pack(side=LEFT) self.draw=Button(self.frame, text='Dungeon Canvas', command=self.openCanvas) self.draw.pack(side=LEFT) self.d20=Button(self.frame, text='D20', command=self.d20roll) self.d20.pack(side=LEFT) self.sendtext=Entry(self.frame) self.sendtext.pack(side=LEFT, fill=X, expand=True) ################################################################################ def d20roll(self): self.rand = random.randrange(1, 20) rs = str(self.rand) self.d20text = "d20 Roll " + rs s.send(self.d20text) self.textbox.insert(END, self.d20text) def openCanvas(self): main() def send(self): self.sendit = self.sendtext.get() if self.sendit == "": pass else: s.send(self.sendit) self.textbox.insert(END, self.sendit + "\n") self.sendtext.delete(0, END) def run(self): while 1: data=s.recv(1024) app.textbox.insert(END, str(data) + "\n") time.sleep(0.1) ################################# root = Tk() root.wm_resizable(0, 0) root.wm_iconbitmap("shinobi.ico") frmimg = Image.open("banner.jpg") fri = ImageTk.PhotoImage(frmimg) classtitle="Tech Shinobi Chat 1.0" root.option_readfile("optionDB") root.title(classtitle) root.geometry('%dx%d+%d+%d' % (500,380,0,0)) app = App(root) root.mainloop() s.close() ###END CODE### That is the client now here is the server ###CODE### #!/usr/bin/env python #SERVER import socket, traceback, os, sys from threading import * import spots host = '' # Bind to all interfaces port = 8888 def handlechild(): while 1: data = ZSP.recv() if not len(data): break ZSP.send((data)) # Set up the socket. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((host, port)) s.listen(1) while 1: try: ZSP = spots.ZSP(s.accept()[0]) except KeyboardInterrupt: raise except: traceback.print_exc() continue t = Thread(target=handlechild) t.setDaemon(1) t.start() heres is a link to the spots module I am using http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/511435 also the original drawing application I am using http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/511436 Cheers I appreciate any help ty Andrew Evans From nsjmetzger at gmail.com Wed May 2 18:38:47 2007 From: nsjmetzger at gmail.com (minitotoro) Date: 2 May 2007 15:38:47 -0700 Subject: Cannot execute Windows commands via Python in 64-bit In-Reply-To: References: <1178143060.952025.85520@h2g2000hsg.googlegroups.com> Message-ID: <1178145527.014102.11480@l77g2000hsb.googlegroups.com> On May 2, 3:07 pm, Larry Bates wrote: > nsjmetz... at gmail.com wrote: > > I have a script that runs fine in Windows 2003 (32-bit). It basically > > calls the Windows defrag command. When I try the exact same code on > > Windows 2003 (64-bit) I get the following message: > > > C:\Scripts>autodefrag.py > > Starting defragment: defrag -v C: >>c:/Scripts/DEFRAG20070502.log > > 'defrag' is not recognized as an internal or external command, > > operable program or batch file. > > > I have tried defrag.exe and even giving it the full path to > > defrag.exe. Always the same result. Here is the python code that is > > generating this error: > > > cmd = "defrag -v C: >>c:/Scripts/DEFRAG20070502.log" > > print "Starting defragment: ", cmd > > errorlevel = os.system(cmd) > > > Anyone know what the heck is going on and how to fix it? This code > > works fine on my 32-bit windows machines. > > Thanks. > > Sounds like system can't find defrag. Usually this is because of a path > issue. Are you running the script in the foreground or scheduled? Can > you open a command prompt and enter the command and have it work? If > you give full path, this shouldn't be the problem. > > -Larry I have tried foreground and scheduled (neither works). I can run defrag from the command prompt with no problem. If I give it the full path in the script it still fails. I am completely befuddled. Help. From steven.bethard at gmail.com Sun May 27 12:32:21 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 27 May 2007 10:32:21 -0600 Subject: [ANN] argparse 0.8 - Command-line parsing library Message-ID: ======================= Announcing argparse 0.8 ======================= The argparse module is an optparse-inspired command line parser that improves on optparse by supporting: * positional arguments * sub-commands * required options * options with a variable number of args * better usage messages * a much simpler extension mechanism and a number of other improvements on the optparse API. Download argparse ================= argparse home: http://argparse.python-hosting.com/ argparse single module download: http://argparse.python-hosting.com/file/trunk/argparse.py?format=raw argparse bundled downloads at PyPI: http://www.python.org/pypi/argparse/ Example argparse code ===================== Here's a simple program that sums its the command-line arguments and writes them to a file:: parser = argparse.ArgumentParser() parser.add_argument('integers', nargs='+', type=int) parser.add_argument('--log', default=sys.stdout, type=argparse.FileType('w')) args = parser.parse_args() args.log.write('%s\n' % sum(args.integers)) args.log.close() About this release ================== This release adds support for options with different prefix characters, a parser-level default for all arguments, and help messages for subparser commands. The deprecated 'outfile' type was finally removed in this release. Please update your code to use the FileType factory. New features ------------ * Options with different prefix characters, e.g. ``+foo`` or ``/bar``, using the new ``prefix_chars=`` keyword argument to ArgumentParser. * A parser-level argument default using the new ``argument_default=`` keyword argument to ArgumentParser. * Support for ``help=`` in the ``add_parser()`` method of subparsers. Bugs fixed ---------- * ``set_defaults()`` now correctly overrides defaults from ``add_argument()`` calls * ``default=SUPPRESS`` now correctly suppresses the action for positional arguments with ``nargs='?'`` or ``nargs='*'``. From mail at timgolden.me.uk Thu May 31 04:42:44 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 31 May 2007 09:42:44 +0100 Subject: Embedding objects( txt, doc) into excel using python In-Reply-To: <1180599820.017532.45430@d30g2000prg.googlegroups.com> References: <1180599820.017532.45430@d30g2000prg.googlegroups.com> Message-ID: <465E8A84.1070402@timgolden.me.uk> Girish wrote: > I want to embed a txt document into an excel using python. I didn't know people still did that! Still, each to his own ;) > Here is my code, but i get an error message > =================================================== > Traceback (most recent call last): > File "C:\Documents and Settings\kusumap\Desktop\Girish.py", line 7, > in ? > worksheet.OLEObjects.Add(Filename="C:\Documents and Settings > \kusumap\My Documents\desktop.ini", Link=False,DisplayAsIcon=True, > IconFileName="packager.exe", IconIndex=0, IconLabel="C:\Documents and > Settings\kusumap\My Documents\desktop.ini").Select > AttributeError: 'function' object has no attribute 'Add' > =================================================== Well done for providing reproducible code, by the way. It's amazing how many people expect us to deduce code from tracebacks! Two things: 1) You need to use raw strings for your path names or to double-up the slashes. By good fortune, you don't seem to be using any actual special characters (\n, \r, \t etc.) but you won't always be so lucky! 2) As the error suggests, OLEObjects is in fact a method, not an container. Slightly more concise screen dump: 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. >>> import win32com.client >>> xl = win32com.client.Dispatch ("Excel.Application") >>> ws = xl.Workbooks.Add ().ActiveSheet >>> print repr (ws.OLEObjects) > >>> >>> o = ws.OLEObjects () >>> o >>> o.Add > >>> As you can see, the ws.OLEObjects is a bound method, ie a function within the _Worksheet class. It seems to return a value which is an OLEObjects instance, which itself seems to have an .Add method. Although I could forage in the docs, I just tried it out at the interpreter. You can do the same if you want! TJG From thorsten at thorstenkampe.de Sun May 20 10:38:00 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun, 20 May 2007 15:38:00 +0100 Subject: zipfile [module and file format, both] stupidly broken References: Message-ID: * Gabriel Genellina (Sat, 19 May 2007 18:09:06 -0300) > En Sat, 19 May 2007 14:00:01 -0300, Martin Maney > escribi?: > > BTW, thanks for the pointer someone else gave to the proper place for > > posting bugs. I'd had the silly idea that I would be able to find that > > easily at www.python.org, but if I had then I'd not have posted here > > and had so much fun. > > My microwave oven doesn't work very well, it's rather new and I want it > fixed. I take the manual, go to the last pages, and find how to contact > the factory. > A module in the Python Standard Library has a bug. I take the Python > Library Reference manual, go to the last pages (Appendix B), and find how > to properly report a bug. Don't be silly. Where would you look for the URL to report bugs? On the website of the project, of course. It's not that easy to find on python.org (although not as hard as Martin says): Core Development > Links for Developers > Bug Manager or About > Help > Got a Python problem or question? > Python Bug Tracker Both ways are kind of misleading (or non-intuitive) as you do not want to engage in Core Development to report a bug. Lots of good projects have a prominent link on their website (start page) how to report bugs. Python hasn't. Thorsten From gagsl-py2 at yahoo.com.ar Wed May 23 04:32:06 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 23 May 2007 05:32:06 -0300 Subject: Shared Memory Space - Accross Apps & Network References: <003a01c79b8a$8f1f8c30$ad5ea490$@rawlins@thinkbluemedia.co.uk> <4653F57A.2090903@timgolden.me.uk> Message-ID: En Wed, 23 May 2007 05:04:10 -0300, Tim Golden escribi?: > I noticed that the post hadn't appeared on Google > Groups, at least. I read things via the mailing list; > is it possible your post hasn't made it across to > Usenet either? I read this thru the gmane news interfase and the original question never appeared. -- Gabriel Genellina From ptmcg at austin.rr.com Thu May 17 18:16:43 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 17 May 2007 15:16:43 -0700 Subject: Regexes: How to handle escaped characters In-Reply-To: <1179435962.962404.191600@y80g2000hsf.googlegroups.com> References: <87tzubqniq.fsf@wilson.homeunix.com> <87irarqkz7.fsf@wilson.homeunix.com> <1179435962.962404.191600@y80g2000hsf.googlegroups.com> Message-ID: <1179440203.534490.66510@u30g2000hsc.googlegroups.com> On May 17, 4:06 pm, John Machin wrote: > On May 18, 6:00 am, Torsten Bronger > wrote: > > > > > > > Hall?chen! > > > James Stroud writes: > > > Torsten Bronger wrote: > > > >> I need some help with finding matches in a string that has some > > >> characters which are marked as escaped (in a separate list of > > >> indices). Escaped means that they must not be part of any match. > > > >> [...] > > > > You should probably provide examples of what you are trying to do > > > or you will likely get a lot of irrelevant answers. > > > Example string: u"Hollo", escaped positions: [4]. Thus, the second > > "o" is escaped and must not be found be the regexp searches. > > > Instead of re.search, I call the function guarded_search(pattern, > > text, offset) which takes care of escaped caracters. Thus, while > > > re.search("o$", string) > > > will find the second "o", > > > guarded_search("o$", string, 0) > > Huh? Did you mean 4 instead of zero? > > > > > won't find anything. > > Quite apart from the confusing use of "escape", your requirements are > still as clear as mud. Try writing up docs for your "guarded_search" > function. Supply test cases showing what you expect to match and what > you don't expect to match. Is "offset" the offset in the text? If so, > don't you really want a set of "forbidden" offsets, not just one? > > > But how to program "guarded_search"? > > Actually, it is about changing the semantics of the regexp syntax: > > "." doesn't mean anymore "any character except newline" but "any > > character except newline and characters marked as escaped". > > Make up your mind whether you are "escaping" characters [likely to be > interpreted by many people as position-independent] or "escaping" > positions within the text. > > > And so > > on, for all syntax elements of regular expressions. Escaped > > characters must spoil any match, however, the regexp machine should > > continue to search for other matches. > > Whatever your exact requirement, it would seem unlikely to be so > wildly popularly demanded as to warrant inclusion in the "regexp > machine". You would have to write your own wrapper, something like the > following totally-untested example of one possible implementation of > one possible guess at what you mean: > > import re > def guarded_search(pattern, text, forbidden_offsets, overlap=False): > regex = re.compile(pattern) > pos = 0 > while True: > m = regex.search(text, pos) > if not m: > return > start, end = m.span() > for bad_pos in forbidden_offsets: > if start <= bad_pos < end: > break > else: > yield m > if overlap: > pos = start + 1 > else: > pos = end > 8<------- > > HTH, > John- Hide quoted text - > > - Show quoted text - Here are two pyparsing-based routines, guardedSearch and guardedSearchByColumn. The first uses a pyparsing parse action to reject matches at a given string location, and returns a list of tuples containing the string location and matched text. The second uses an enhanced version of guardedSearch that uses the pyparsing built-ins col and lineno to filter matches by column instead of by raw string location, and returns a list of tuples of line and column of the match location, and the matching text. (Note that string locations are zero-based, while line and column numbers are 1-based.) -- Paul from pyparsing import Regex,ParseException,col,lineno def guardedSearch(pattern, text, forbidden_offsets): def offsetValidator(strng,locn,tokens): if locn in forbidden_offsets: raise ParseException, "can't match at offset %d" % locn regex = Regex(pattern).setParseAction(offsetValidator) return [ (tokStart,toks[0]) for toks,tokStart,tokEnd in regex.scanString(text) ] print guardedSearch(u"o", u"Hollo how are you", [4,]) def guardedSearchByColumn(pattern, text, forbidden_columns): def offsetValidator(strng,locn,tokens): if col(locn,strng) in forbidden_columns: raise ParseException, "can't match at offset %d" % locn regex = Regex(pattern).setParseAction(offsetValidator) return [ (lineno(tokStart,text),col(tokStart,text),toks[0]) for toks,tokStart,tokEnd in regex.scanString(text) ] text = """\ alksjdflasjf;sa a;sljflsjlaj ;asjflasfja;sf aslfj;asfj;dsf aslf;lajdf;ajsf aslfj;afsj;sd """ print guardedSearchByColumn(";", text, [1,6,11,]) Prints: [(1, 'o'), (7, 'o'), (15, 'o')] [(1, 13, ';'), (2, 2, ';'), (3, 12, ';'), (5, 5, ';')] From deepns7 at gmail.com Fri May 4 03:07:06 2007 From: deepns7 at gmail.com (pradeep nair) Date: 4 May 2007 00:07:06 -0700 Subject: How to find the present working directory using python. In-Reply-To: <1178262352.837860.59880@e65g2000hsc.googlegroups.com> References: <1178262224.269446.69410@c35g2000hsg.googlegroups.com> <1178262352.837860.59880@e65g2000hsc.googlegroups.com> Message-ID: <1178262426.210040.66220@n76g2000hsh.googlegroups.com> On May 4, 12:05 pm, SamG wrote: > On May 4, 12:03 pm, pradeep nair wrote: > > > how to find out the present working directory using python. > > > os.system('pwd') works good. But i need some specific one in > > python rather than embedding shell command into python. > > os.path.getcwd() Thank u... From aboudouvas at panafonet.gr Tue May 8 11:00:23 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 8 May 2007 08:00:23 -0700 Subject: Gui thread and async jobs. In-Reply-To: <5abh5aF2lth8jU1@mid.uni-berlin.de> References: <1178627450.408287.139070@p77g2000hsh.googlegroups.com> <5abajlF2nk767U1@mid.uni-berlin.de> <1178632508.635902.187030@e65g2000hsc.googlegroups.com> <5abh5aF2lth8jU1@mid.uni-berlin.de> Message-ID: <1178636422.968892.305190@n59g2000hsh.googlegroups.com> On May 8, 5:52 pm, "Diez B. Roggisch" wrote: > >> It depends on the toolkit you use. Qt has thread-safe custom events in > >> 3.x, and afaik signal/slots (and thus events) are generally thread-safe > >> in 4.x. So, no problems there. > > >> Diez > > > Aha...So you do not use polling there (in Qt), correct ? > > You don't need to, no. > > Diez Thanks! From gh at gregor-horvath.com Thu May 17 08:50:32 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Thu, 17 May 2007 14:50:32 +0200 Subject: Sending a JavaScript array to Python script? In-Reply-To: <1179405295.865954.241740@e65g2000hsc.googlegroups.com> References: <1179405295.865954.241740@e65g2000hsc.googlegroups.com> Message-ID: placid schrieb: > Just wondering if there is any way of sending a JavaScript array to a > Python cgi script? A quick Google search didn't turn up anything > useful. http://mochikit.com/doc/html/MochiKit/Base.html#json-serialization http://svn.red-bean.com/bob/simplejson/tags/simplejson-1.3/docs/index.html Gregor From http Fri May 18 03:03:47 2007 From: http (Paul Rubin) Date: 18 May 2007 00:03:47 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <464ab2f9$0$23146$9b4e6d93@newsspool1.arcor-online.net> <464ABA99.8080208@web.de> <464abecb$0$6403$9b4e6d93@newsspool2.arcor-online.net> <464C5185.4060302@v.loewis.de> Message-ID: <7xsl9u1ulo.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > > Integration with existing tools *is* something that a PEP should > > consider. This one does not do that sufficiently, IMO. > What specific tools should be discussed, and what specific problems > do you expect? Emacs, whose unicode support is still pretty weak. From bjornkri at gmail.com Wed May 23 06:46:12 2007 From: bjornkri at gmail.com (beertje) Date: 23 May 2007 03:46:12 -0700 Subject: Printing dots in sequence ('...') In-Reply-To: References: Message-ID: <1179917172.503421.124310@u30g2000hsc.googlegroups.com> On May 23, 3:36 am, rzed wrote: > "Tim Williams" wrote innews:mailman.8029.1179845747.32031.python-list at python.org: > > [...] > > > maybe this: (on Win32, don't know about *nix) > > > for x in range(10): > > print '.\b', > > better: > print '\b.', > > -- > rzed print '.\b' gives a nice and funky output though... Thanks for your suggestions, all! From apardon at forel.vub.ac.be Tue May 15 03:23:34 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 15 May 2007 07:23:34 GMT Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <1hy2qg3.iqfvwnrvr9kjN%aleax@mac.com> <46482624.6050507@web.de> <7xd512onsx.fsf@ruckus.brouhaha.com> Message-ID: On 2007-05-15, Paul Rubin wrote: > Stefan Behnel writes: >> But then, where's the problem? Just stick to accepting only patches that are >> plain ASCII *for your particular project*. > > There is no feature that has ever been proposed for Python, that cannot > be supported with this argument. If you don't like having a "go to" > statement added to Python, where's the problem? Just don't use it in > your particular project. There is no feature that has ever been propose that cannot be rejected by the opposite argument: I don't want to be bothered with something like this and if it is introduced sooner or later I will. And in my experience this argument is used a lot more than the first. -- Antoon Pardon From john at datavoiceint.com Thu May 10 14:41:04 2007 From: john at datavoiceint.com (HMS Surprise) Date: 10 May 2007 11:41:04 -0700 Subject: append In-Reply-To: References: <1178816546.689849.255070@y5g2000hsa.googlegroups.com> Message-ID: <1178822464.683018.164260@y5g2000hsa.googlegroups.com> > > Do you really mean syntax? > Thought so? A few sources I bookmarked to avoid future google two-steps. http://www.diveintopython.org/native_data_types/lists.html http://en.wikibooks.org/wiki/Python_Programming/Lists http://infohost.nmt.edu/tcc/help/pubs/python22.pdf Thank you all. jh From s.steffann at computel.nl Tue May 22 13:10:51 2007 From: s.steffann at computel.nl (Sander Steffann) Date: Tue, 22 May 2007 19:10:51 +0200 Subject: Restart Linux System In-Reply-To: References: <002d01c79b81$aa748d40$ff5da7c0$@rawlins@thinkbluemedia.co.uk> <1179850502.22230.6.camel@contra.chem.byu.edu> Message-ID: <003401c79c94$284398c0$78caca40$@steffann@computel.nl> Hi, > > Probably not. You need to just spawn the "reboot" command, or run > > "init 6." This requires root, though. Without root there's no way > > to reboot a linux system. > > ...unless you run shutdown(8) or reboot(8) setuid root (reboot is > kinda harsh though, btw). It's not that bad. Reboot takes care of unintended consequences itself: from 'man 8 reboot': > If halt or reboot is called when the system is not in runlevel 0 or 6, > in other words when it's running normally, shutdown will be invoked > instead (with the -h or -r flag). Since version 2.74 :) - Sander From wgwigw at gmail.com Wed May 30 08:35:37 2007 From: wgwigw at gmail.com (momobear) Date: 30 May 2007 05:35:37 -0700 Subject: Key Listeners In-Reply-To: <1180491273.446164.281990@q75g2000hsh.googlegroups.com> References: <1180491273.446164.281990@q75g2000hsh.googlegroups.com> Message-ID: <1180528537.628454.266800@i13g2000prf.googlegroups.com> On May 30, 10:14 am, Mike wrote: > Are there key listeners for Python? Either built in or third party? try "pykeylogger", that's maybe u want. From collver at peak.org Fri May 4 10:17:13 2007 From: collver at peak.org (Ben Collver) Date: Fri, 04 May 2007 07:17:13 -0700 Subject: My Python annoyances In-Reply-To: References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> <1178202431.147195.249790@u30g2000hsc.googlegroups.com> Message-ID: Chris Mellon wrote: > #python is one of the most accepting communities around. If the bug > reports here and the way you've presented them in this thread (vs the > way that they appear to an outside observer) are any indication, > though, I'm not surprised that you might have left in a huff. > > Bear in mind that #python has no special status with regards to python > development and is primarily a community of *users*. If you go in with > some sort of thing you consider a problem, you are likely to be shown > a solution. Debate over whether it should be fixed in the core is > likely to be met with "patches accepted". I generally use IRC for idle chat and mulling over problems, and I realize it would be the wrong place to ask for a change. At the time I was talking about XML in the Python library. I was informed that I was unwise to read 3rd party documentation for the Python library. I get "Don't complain about documentation we didn't write" instead of "Yeah it's broken, use pyxml instead." >> It is problem report #1678102. I understand the problem: that a 32 bit >> number looks different in a 32 bit signed int than in a 64 bit signed >> int. However, the workaround of dropping a bit seems to defeat the >> purpose of using a CRC. >> > > That's a valid point. Maybe you should have responded on the tracker > with that viewpoint. Your characterization of what happened in your > original post borders on dishonest - how can you possibly view what > happened there as "bug reports not welcomed"? I made a mistake when I first read the response: it does not drop any bits. In the bug report itself, I saw a diagnosis of my problem's cause, and then I saw the bug report closed as invalid. I did not know why the bug was flagged invalid and closed, because I received no comment from the person who closed it. I assumed that I should not have filed the bug report. Feedback in this newsgroup names my bug report as a "hobby horse", a "wart", and "not a real bug report". I apologize for this noise over such a small issue. It is clear now that real bug reports are welcome. > Code like this is working directly against Python philosophy. You > probably got told this on #python, too. There's hardly any > circumstance where you should need to validate the exact class of an > object, and as long as they have the same interface theres no harm > whatsoever in tempfile changing it's return value between Python > versions. I am unqualified to comment on the Python philosophy, but I would like for my function to do some basic error checking on its arguments. I will read up on the Python philosophy. Ben From aleax at mac.com Wed May 2 10:49:54 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 2 May 2007 07:49:54 -0700 Subject: While we're talking about annoyances References: <1177837565.317999.244420@c35g2000hsg.googlegroups.com> <8oag339eh56tnpbl8mk3lqlf6avkmusvdm@4ax.com> Message-ID: <1hxh6se.iybb3k1qfyxhlN%aleax@mac.com> Michael Hoffman wrote: > Steven D'Aprano wrote: > > On Wed, 02 May 2007 06:10:54 +0000, Tim Roberts wrote: > > >> I've tended to favor the "Schwarzian transform" (decorate-sort-undecorate) > >> because of that. > > > > That's what the key= argument does. cmp= is slow because the comparison > > function is called for EVERY comparison. The key= function is only called > > once per element. > > Right. Using sort(key=keyfunc) is supposed to be faster than > decorate-sort-undecorate. And I think it is clearer too. Right, and speed comparisons are pretty easy (just make sure to copy the list within the loop to compare like with like:-)...: brain:~ alex$ python -mtimeit -s'L=range(-3,5)' 'X=L[:]; X.sort(lambda x, y: cmp(abs(x), abs(y)))' 100000 loops, best of 3: 13 usec per loop brain:~ alex$ python -mtimeit -s'L=range(-3,5)' 'X=[(abs(x),x) for x in L]; X.sort(); X=[x for _,x in X]' 100000 loops, best of 3: 7.85 usec per loop brain:~ alex$ python -mtimeit -s'L=range(-3,5)' 'X=L[:]; X.sort(key=abs)' 100000 loops, best of 3: 4.23 usec per loop The "intrinsic" DSU done by key= is clearly superior on all scores. The semantics are subtly different: it guarantees to never compare anything _except_ the key (because that's typically what one wants), so, make sure they key includes everything you may ever want compared. Alex From kyosohma at gmail.com Fri May 25 10:57:10 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 25 May 2007 07:57:10 -0700 Subject: drag and drop with wxPython ? In-Reply-To: References: <1179863040.585516.155490@k79g2000hse.googlegroups.com> Message-ID: <1180105030.298534.104360@k79g2000hse.googlegroups.com> On May 25, 4:46 am, Stef Mientki wrote: > kyoso... at gmail.com wrote: > > On May 22, 10:00 am, stef wrote: > >> hello, > > >> I'm trying to move from Delphi to Python > >> (move from MatLab to Python already succeeded, also thanks to this > >> discussion group). > >> From the discussions in this list about "the best" GUI for Python, > >> it now seems to me that wxPython is th? choice for my kind of applications. > > >> I've no experience with wxPython yet, > >> I just run a few examples and indeed it looks good (as expected from the > >> discussions in this list). > > >> What I really need at this moment for a new project, > >> (and I coulnd't find any example, lot of broken links ;-) > >> is how to implement some drag & drop facilities, > >> both to drag and drop normal button, > >> but also to drag and drop some dynamically created objects. > >> Just like a CAD program, but far more simpler. > > >> Does anyone has an example how to drag & drop components with wxPython ? > > >> thanks, > >> Stef Mientki > > > Stef, > > > wxPython's wiki has a couple examples: > > >http://wiki.wxpython.org/DragAndDrop?highlight=%28drop%29%7C%28drag%29 > >http://wiki.wxpython.org/DragAndDropWithFolderMovingAndRearranging?hi... > > > I think Larry meant to say that the wxPython demo has an example. It's > > under the "Clipboard and DnD" category. > > > For lots of help from people that create wxPython and its widgets, > > check out the wxPython user's group here:http://www.wxpython.org/maillist.php > > thanks Mike and Larry, > > I didn't succeed in testing (and understand what you both meant), > because I had an old version of wxPython. > After updating to the last version, > WOW,... > ... that demo is really an example how to interatively teach wxPython. > BEAUTIFUL ! > > cheers, > Stef Mientki > > > Mike Just an FYI for future reference. Always mention what Python / wxPython and OS you're using. We probably could have told you that your problem was using the old version of wxPython sooner. Have fun! Mike From larry.bates at websafe.com Mon May 7 09:35:26 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 07 May 2007 08:35:26 -0500 Subject: How do I use the config parser? In-Reply-To: <1178392410.866037.179950@e65g2000hsc.googlegroups.com> References: <1178392410.866037.179950@e65g2000hsc.googlegroups.com> Message-ID: noagbodjivictor at gmail.com wrote: > Hi, > I need a specific example. I have seen the docs, but I don't all the > stuffs there. > > So basically, I need my config file to be created and read by my > script. > > Here is a snippet > > # read old actions > from ConfigParser import ConfigParser > > fp = open(makepath('App\qt_actions.conf')) > configdict = ConfigParser() > configdict.readfp(fp) > > > Now I want to know how to read a section, a section attribute's value, > and to write thoses back after reading. > > Thanks > The best place to start is always: import ConfigParser help(ConfigParser) Example: section='INIT' option='logfile' logfile=configdict.get(section, option) most of the methods are self explanitory. -Larry From jstroud at mbi.ucla.edu Thu May 3 16:21:54 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 03 May 2007 13:21:54 -0700 Subject: adding methods at runtime and lambda In-Reply-To: <1178221975.149008.192410@y5g2000hsa.googlegroups.com> References: <1178221975.149008.192410@y5g2000hsa.googlegroups.com> Message-ID: Mike wrote: > I was messing around with adding methods to a class instance at > runtime and saw the usual code one finds online for this. All the > examples I saw say, of course, to make sure that for your method that > you have 'self' as the first parameter. I got to thinking and thought > "I have a lot of arbitrary methods in several utility files that I > might like to add to things. How would I do that?" And this is what I > came up with: > > > def AddMethod(currObject, method, name = None): > if name is None: name = method.func_name > class newclass(currObject.__class__):pass > setattr(newclass, name, method) > return newclass() > > And lets say I have a utility function that can check if a drive > exists on my windows box called HasDrive. I can add that like this: > > superdict = addm(dict(), lambda self, d: myUtils.HasDrive(d), > "hasdrive") > > and then I can call > > superdict.HasDrive('c') > > lambda makes it possible to add any random function because you can > use it to set self as the first parameter. I've found several real > uses for this already. My big question is, will something like this be > possible in python 3000 if lambda really does go away? I've not heard > much about lambda, reduce, etc. lately but I know Guido wanted them > out of the language. > > Is there a better way to do this today than to use lambda? It seemed > the simplest way to do this that I could find. > You don't absolutely require lambda. def add_self(afun): def _f(self, *args, **kwargs): return afun(*args, **kwargs) return _f superdict = addm(dict(), add_self(myUtils.HasDrive), "hasdrive") James From rene at korteklippe.de Tue May 15 08:08:34 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 15 May 2007 14:08:34 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46499BF9.30209@web.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476081.7080609@web.de> <46498514$0$6402$9b4e6d93@newsspool2.arcor-online.net> <4649882E.3060005@web.de> <46499940$0$10199$9b4e6d93@newsspool4.arcor-online.net> <46499BF9.30209@web.de> Message-ID: <4649a2c1$0$10193$9b4e6d93@newsspool4.arcor-online.net> Stefan Behnel schrieb: >> I think your argument about "isolated projects" is flawed. It is not at >> all unusual for code that was never intended to be public, whose authors >> would have sworn that it will never ever be need to read by anyone >> except themselves, to surprisingly go public at some point in the future. > > Ok, but how is "using non-ASCII identifiers" different from "using mandarin > tranliterated ASCII identifiers" in that case? 1) Transliterated ASCII identifiers do not have problems such as not displaying at all and not being easily possible to type. 2) I consider transliterated ASCII identifiers a bad idea, but it is virtually impossible to prohibit them at the language level. > Please try to understand what the point of this PEP is. Please try to understand that the fact that certain bad practices are possible today is no valid argument for introducing support for more of them! -- Ren? From mattheww at chiark.greenend.org.uk Wed May 16 15:59:22 2007 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 16 May 2007 20:59:22 +0100 (BST) Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: Eric Brunel wrote: > Joke aside, this just means that I won't ever be able to program math in > ADA, because I have absolutely no idea on how to do a 'pi' character on my > keyboard. Just in case it wasn't clear: you could of course continue to use the old name 'Pi' instead. -M- From torriem at chem.byu.edu Sat May 19 13:51:20 2007 From: torriem at chem.byu.edu (Michael Torrie) Date: Sat, 19 May 2007 11:51:20 -0600 Subject: Python compared to other language In-Reply-To: References: <1179540061.598417.13870@y80g2000hsf.googlegroups.com> Message-ID: <1179597080.29334.10.camel@enterprise> On Fri, 2007-05-18 at 22:28 -0400, Steve Holden wrote: > Surely the fact that Python is available on so many platforms implies > that C is a fairly portable language. I realise that you have to take > platform specifics into account much more than you do in Python, but I > do feel you are being somewhat unfair to C. This is now going off-topic. Cross-platform code is a matter of mindset and toolset. It's very possible to write python code that is *not* cross-platform compatible. Perhaps it relies a specific behavioral quirk of the platform. Or maybe it uses modules that only exist on a platform. For example, you can do very low-level COM or even Active X programming using python. That certainly wouldn't run on Linux. The same can be true of some python code that's only intended to run on Posix systems. You may have assumed a certain directory character separator, for example (of course the os module can give you a portable way of not making this assumption). I write cross-platform C code all the time. I do it by carefully choosing my libraries (toolset) and then try to code making as few assumptions as possible. Platform-specific code is generally less than 6% of the total code. I even wrote a cross-platform python module in C. It's no big deal. Recently I wrote a medium-sized C++ application using Qt. The platform-specific code (basically a few minor things Qt doesn't do for me) is 10 lines total, out of many thousands of lines of code. The apps compiles and runs on Linux, OS X, and Windows. I plan to write the next version in Python, but I'm still not sure what GUI toolkit to use. wxWidgets just doesn't sit well with me, Qt's licensing doesn't fit my client (I can't afford the non-GPL version), and GTK isn't there on OS X. Python, like C, can be used easily to make cross-platform programs. Python makes it even easier than C because the entire standard python library of modules is available on every platform, so you don't have to rely on as many third-party abstraction libraries for threads, sockets, etc. I think the original poster will find Python, and may wxPython, satisfies the bulk of his development needs. > > > I'm just learning Python. FWIW: my opinions about 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 your way to fame!! > holdenweb.blogspot.com squidoo.com/pythonology > tagged items: del.icio.us/steve.holden/python > All these services currently offer free registration! > -------------- Thank You for Reading ---------------- > From carsten at uniqsys.com Tue May 22 08:29:42 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 22 May 2007 08:29:42 -0400 Subject: howto check does module 'asdf' exist? (is available for import) In-Reply-To: <1179818823.916836.226090@r3g2000prh.googlegroups.com> References: <1179753436.736228.321400@x35g2000prf.googlegroups.com> <1179818823.916836.226090@r3g2000prh.googlegroups.com> Message-ID: <1179836982.3373.4.camel@dot.uniqsys.com> On Tue, 2007-05-22 at 00:27 -0700, Asun Friere wrote: > You can generalise this, but at the expense of a couple of exec > statements: > def is_module_available (module) : > try : > exec('import %s' % module) > exec('del %s' % module) > except ImportError : > return False > else : > return True You can save the exec statement by using the built-in __import__ function: def is_module_available(modulename): try: mod = __import__(modulename) except ImportError: return False else: return True -- Carsten Haese http://informixdb.sourceforge.net From andre.roberge at gmail.com Sun May 13 12:36:13 2007 From: andre.roberge at gmail.com (=?utf-8?B?QW5kcsOp?=) Date: 13 May 2007 09:36:13 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46473267$0$31532$9b622d9e@news.freenet.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <1179074173.419675.4130@h2g2000hsg.googlegroups.com> On May 13, 12:44 pm, "Martin v. L?wis" wrote: > PEP 1 specifies that PEP authors need to collect feedback from the > community. As the author of PEP 3131, I'd like to encourage comments > to the PEP included below, either here (comp.lang.python), or to > python-3... at python.org > > In summary, this PEP proposes to allow non-ASCII letters as > identifiers in Python. If the PEP is accepted, the following > identifiers would also become valid as class, function, or > variable names: L?ffelstiel, chang?, ??????, or ??? > (hoping that the latter one means "counter"). > > I believe this PEP differs from other Py3k PEPs in that it really > requires feedback from people with different cultural background > to evaluate it fully - most other PEPs are culture-neutral. > > So, please provide feedback, e.g. perhaps by answering these > questions: > - should non-ASCII identifiers be supported? why? I use to think differently. However, I would say a strong YES. They would be extremely useful when teaching programming. > - would you use them if it was possible to do so? in what cases? Only if I was teaching native French speakers. > Policy Specification > ==================== > > As an addition to the Python Coding style, the following policy is > prescribed: All identifiers in the Python standard library MUST use > ASCII-only identifiers, and SHOULD use English words wherever feasible. > I would add something like: Any module released for general use SHOULD use ASCII-only identifiers in the public API. Thanks for this initiative. Andr? From Goofy.throat6 at gmail.com Sat May 19 02:09:56 2007 From: Goofy.throat6 at gmail.com (Goofy.throat6 at gmail.com) Date: 18 May 2007 23:09:56 -0700 Subject: * Sizzling Boobies all new pics and Vidz Message-ID: <1179554996.861465.114600@q75g2000hsh.googlegroups.com> http://nudepicks.blogspot.com/ - Download them often and get them all! From kyosohma at gmail.com Thu May 10 14:52:22 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 10 May 2007 11:52:22 -0700 Subject: Comparing dates problem In-Reply-To: <1178748764.663230.186570@y80g2000hsf.googlegroups.com> References: <1178746479.776908.319930@p77g2000hsh.googlegroups.com> <1178748764.663230.186570@y80g2000hsf.googlegroups.com> Message-ID: <1178823142.101246.220660@l77g2000hsb.googlegroups.com> On May 9, 5:12 pm, John Machin wrote: > On May 10, 7:34 am, kyoso... at gmail.com wrote: > > > > > Hi, > > > I am writing a reminder program for our Zimbra email client. One of > > the requirements I was given was to automatically increment or > > decrement the display to show something like the following: > > > 5 minutes until appointment > > > or > > > 10 minutes past your appointment > > > Either way, as each minute goes by, I need to increment it or > > decrement it. I am having trouble finding a coherent way to take the > > same date and compare just the number of minutes between them to find > > the difference. Like if I have an appointment at 9:30 a.m. and the app > > is loaded at 8 a.m., I need to know the number of minutes or hours and > > minutes until the appointment. > > > I have looked at the dateutils module and it has many comparison > > methods, but they seem to only return the number of days or seconds. > > Ermmm ... what's wrong with > > minutes = seconds / 60.0 > hours = minutes / 60.0 > > ? I'm sure there is a hack for doing something like what you suggest, but it would be messy. The problem is that I get a datetime object returned and division really isn't something you can do to one of those objects. Besides, if I had seconds returned, I would want to multiply by 60, not divide. Maybe I misunderstand you. Mike From bignose+hates-spam at benfinney.id.au Mon May 28 08:13:45 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 28 May 2007 22:13:45 +1000 Subject: Flags of the world References: <1180299312.207986.4340@k79g2000hse.googlegroups.com> <1180299814.129770.93220@o11g2000prd.googlegroups.com> Message-ID: <87tztxno1y.fsf@benfinney.id.au> Tim Churches writes: > http://shaheeilyas.com/flags/ > > Scroll to the bottom to see why this is not entirely off-topic. I fail to see what it has to do with the thread you're replyiing to, which is a discussion of creating a dictionary from a list comprehension. If you want to start a new thread, compose a new message, not a reply to an existing thread. -- \ "If you ever catch on fire, try to avoid seeing yourself in the | `\ mirror, because I bet that's what REALLY throws you into a | _o__) panic." -- Jack Handey | Ben Finney From john at datavoiceint.com Thu May 17 09:02:50 2007 From: john at datavoiceint.com (HMS Surprise) Date: 17 May 2007 06:02:50 -0700 Subject: Declaring variables In-Reply-To: <1179359317.494376.259990@n59g2000hsh.googlegroups.com> References: <1179334649.990688.73320@o5g2000hsb.googlegroups.com> <1179359317.494376.259990@n59g2000hsh.googlegroups.com> Message-ID: <1179406970.776873.144470@o5g2000hsb.googlegroups.com> On May 16, 6:48 pm, Matimus wrote: > On May 16, 9:57 am, HMS Surprise wrote: > > > I looked in the language but did not find a switch for requiring > > variables to be declared before use. > > > Is such an option available? > > > Thanks, > > > jvh > > You do have to declare a variable before use. You do so by assigning > it a value. You can't use a variable before it has been assigned. Yes this is where the problem arises. This is a gross oversimplification , but is where I typically find problems. jh #~~~~~~~~~~~~~~~~~~~~~~ createdIncidentId = 0 . . . #attempt to change varialbe createdIncidentID = 1 . . . if createdIncidentId == 1: ... From hafeliel at yahoo.com Sun May 20 14:19:50 2007 From: hafeliel at yahoo.com (Gre7g Luterman) Date: Sun, 20 May 2007 12:19:50 -0600 Subject: _PyObject_New / PyObject_Init / PyInstance_New / etc? References: Message-ID: > From Python, you create a Noddy object by *calling* its type. Do the same > in C: > > return PyObject_CallObject((PyObject *) &NoddyType, NULL); > > Or any other suitable variant of PyObject_CallXXX. (I've answered this > same question yesterday, when I was not sure about this; then I've tried > it and it appears to be working. But I've not read any docs telling this > is *the* right way to create an object). Many thanks. That seems to work now. It turns out that my previous problems stemmed from defining my type as a static, so I was ending up with multiple copies of it and of course only one type was getting fully initialized when the module was launched! From michele.simionato at gmail.com Fri May 18 14:16:17 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 18 May 2007 11:16:17 -0700 Subject: Python Web Programming - looking for examples of solid high-traffic sites In-Reply-To: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> Message-ID: <1179512177.092027.83960@q23g2000hsg.googlegroups.com> On May 16, 11:04 pm, Victor Kryukov wrote: > > Our main requirement for tools we're going to use is rock-solid > stability. As one of our team-members puts it, "We want to use tools > that are stable, has many developer-years and thousands of user-years > behind them, and that we shouldn't worry about their _versions_." The > main reason for that is that we want to debug our own bugs, but not > the bugs in our tools. > > Our problem is - we yet have to find any example of high-traffic, > scalable web-site written entirely in Python. We know that YouTube is > a suspect, but we don't know what specific python web solution was > used there. > > TurboGears, Django and Pylons are all nice, and provides rich features > - probably too many for us - but, as far as we understand, they don't > satisfy the stability requirement - Pylons and Django hasn't even > reached 1.0 version yet. And their provide too thick layer - we want > something 'closer to metal', probably similar to web.py - > unfortunately, web.py doesn't satisfy the stability requirement > either, or so it seems. > > So the question is: what is a solid way to serve dynamic web pages in > python? Our initial though was something like python + mod_python + > Apache, but we're told that mod_python is 'scary and doesn't work very > well'. AFAIK mod_python is solid and works well, but YMMV of course. If you want rock solid stability, you want a framework where there is little development going on. In that case, I have a perfect match for your requirements: Quixote. It has been around for ages, it is the most bug free framework I have seen and it *very* scalable. For instance http://www.douban.com is a Quixote-powered chinese site with more than 2 millions of pages served per day. To quote from a message on the Quixote mailing list: """ Just to report-in the progress we're making with a real-world Quixote installation: yesterday douban.com celebrated its first 2 million- pageview day. Quixote generated 2,058,207 page views. In addition, there're about 640,000 search-engine requests. These put the combined requests at around 2.7 millions. All of our content pages are dynamic, including the help and about-us pages. We're still wondering if we're the busiest one of all the python/ruby supported websites in the world. Quixote runs on one dual-core home-made server (costed us US$1500). We have three additional servers dedicated to lighttpd and mysql. We use memcached extensively as well. Douban.com is the most visible python establishment on the Chinese web, so there's been quite a few django vs. quixote threads in the Chinese language python user mailing lists. """ Michele Simionato From enleverlesX.XmcX at XmclaveauX.com Tue May 8 02:43:04 2007 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Tue, 8 May 2007 08:43:04 +0200 Subject: Windows, subprocess.Popen & encodage Message-ID: <46401c16$0$5072$ba4acef3@news.orange.fr> Hi! >From long time, I have problems with strings return, in Windows, by subprocess.Popen / stdout.read() Last night, I found, by hazard, than if the second byte equal 0, it's, perhaps, the solution. With a code like this: p=subprocess.Popen(u850("cmd /u/c .... tdata=p.stdout.read() if ord(tdata[1])==0: data=tdata.decode('utf-16') else: data=tdata.decode('cp850') Diffrents scripts seem run OK. I had try with: - common dir - dir on unicode-named-files - ping - various commands But, I don't found anything, in any documentations, on this. Sombody can confirm? Am I misled? Am I right? * sorry for my bad english* @-salutations Michel Claveau From goon12 at gmail.com Wed May 30 12:07:24 2007 From: goon12 at gmail.com (Joe Riopel) Date: Wed, 30 May 2007 12:07:24 -0400 Subject: Is PEP-8 a Code or More of a Guideline? In-Reply-To: <1180539790.654176.26900@q75g2000hsh.googlegroups.com> References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <5c1jpkF2tl0ilU1@mid.individual.net> <1180539790.654176.26900@q75g2000hsh.googlegroups.com> Message-ID: <6a2ccd190705300907w7c0542l4ccc23fc4caca462@mail.gmail.com> Using camel case instead of the under_score means less typing. I am lazy. fooBar foo_bar From gagsl-py2 at yahoo.com.ar Sat May 19 03:11:59 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 19 May 2007 04:11:59 -0300 Subject: Compiling Python code within a module References: <1179528700.031053.307480@k79g2000hse.googlegroups.com> <20070518164933.21bd8b91@opal.pathscale.com> Message-ID: En Fri, 18 May 2007 20:49:33 -0300, Mitko Haralanov escribi?: > On 18 May 2007 15:51:40 -0700 > ici wrote: > >> exec it :) > > Thank you! That works when I compile/exec it in the main body of the > program. However, when I try to do that in a separate module it > doesn't. For example: exec has a long form - see http://docs.python.org/ref/exec.html And forget the compile pass - let Python handle it automatically. Also note that exec is a statement, not a function, so you don't need () To "inject" inside a module a function defined in source_code, do: exec source_code in module.__dict__ To "inject" a function inside a class, it's easier if you use an intermediate dictionary: d = globals().copy() exec source_code in d my_class.method = d['method'] > def register (self, text): > exec (compiler.compile (text, "", > "exec")) > > f.register ("def blah():\n\tprint 'blah'\n") > > In this case, the function 'blah' is nowhere to be found. I've tried > looking in 'f', in the class 'Foo', in the module 'Foo' and it's > nowhere. It existed briefly in the local namespace of the register method - after register is exited, it's gone. -- Gabriel Genellina From half.italian at gmail.com Sat May 5 17:26:16 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 5 May 2007 14:26:16 -0700 Subject: progress In-Reply-To: <1178354814.884102.194790@q75g2000hsh.googlegroups.com> References: <1178354814.884102.194790@q75g2000hsh.googlegroups.com> Message-ID: <1178400376.804319.34490@p77g2000hsh.googlegroups.com> On May 5, 1:46 am, Merrigan wrote: > Hi All, > > I have posted yesterday about an ftplib issue, this has been resolved. > > I actually want to ask something here... > > The script that that ftplib error was from...I was wondering - What do > I need to do to print the stats (speed/s, percentage done) of the > upload that is running on the monitor. > > This script runs on a Fedora Machine. > > Thanx for the help guys! > > -- Merrigan Looks like all you've got on the Python side is the size() method. You could start a timer when the transfer begins, and then compare the size on the server versus the size locally to get progress. ~Sean From half.italian at gmail.com Tue May 15 20:38:31 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 15 May 2007 17:38:31 -0700 Subject: transparent images In-Reply-To: <1179275214.794050.199460@y80g2000hsf.googlegroups.com> References: <1179275214.794050.199460@y80g2000hsf.googlegroups.com> Message-ID: <1179275911.335663.257730@n59g2000hsh.googlegroups.com> On May 15, 5:26 pm, moishyyeh... at gmail.com wrote: > Does any one know how to make a transparent image with specifically > PIL, but any standard python library will do. I need a spacer, and it > has to be transparent. > > Thanks Something like this...not my code...untested... im = Image.open("image.jpg") opacity = .5 if im.mode != 'RGBA': im = im.convert('RGBA') else: im = im.copy() alpha = im.split()[3] alpha = ImageEnhance.Brightness(alpha).enhance(opacity) im.putalpha(alpha) ~Sean From stefan.behnel-n05pAM at web.de Tue May 15 13:48:21 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 15 May 2007 19:48:21 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers - ambiguity issues In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649BC4C.10200@web.de> <1179238847.407605.4620@w5g2000hsg.googlegroups.com> <4649C63C.1030508@web.de> <1179242328.800088.246620@h2g2000hsg.googlegroups.com> <4649D4A5.5060102@web.de> <1179247724.234869.47310@l77g2000hsb.googlegroups.com> <4649E730.9000609@web.de> Message-ID: <4649F265.1050200@web.de> John Nagle wrote: > There are really two issues here, and they're being > confused. > > One is allowing non-English identifiers, which is a political > issuer. The other is homoglyphs, two characters which look the same. > The latter is a real problem in a language like Python with implicit > declarations. If a maintenance programmer sees a variable name > and retypes it, they may silently create a new variable. > > If Unicode characters are allowed, they must be done under some > profile restrictive enough to prohibit homoglyphs. I'm not sure > if UTS-39, profile 2, "Highly Restrictive", solves this problem, > but it's a step in the right direction. This limits mixing of scripts > in a single identifier; you can't mix Hebrew and ASCII, for example, > which prevents problems with mixing right to left and left to right > scripts. Domain names have similar restrictions. > > We have to have visually unique identifiers. As others stated before, this is unlikely to become a problem in practice. Project-internal standards will usually define a specific language for a project, in which case these issues will not arise. In general, programmers from a specific language/script background will stick to that script and not magically start typing foreign characters. And projects where multiple languages are involved will have to define a target language anyway, most likely (although not necessarily) English. Note that adherence to a specific script can easily checked programmatically through Unicode ranges - if the need ever arises. Stefan From maric at aristote.info Thu May 31 12:17:05 2007 From: maric at aristote.info (Maric Michaud) Date: Thu, 31 May 2007 18:17:05 +0200 Subject: How to clean a module? In-Reply-To: <1180622824.836459.222090@q19g2000prn.googlegroups.com> References: <1180622824.836459.222090@q19g2000prn.googlegroups.com> Message-ID: <465EF501.7040207@aristote.info> ai a ?crit : > It assumes that there is a module A which have two global variables X > and Y. If I run "import A" in the IDLE shell, then I can use A.X and > A.Y correctly. But if I want to change the module A and then delete > the variable Y, I find I can use A.Y just the same as before! It's unlikely to be true, see below. > In fact, I have tried all the following methods but can't remove the > A.Y: > execute "import A" again > "reload(A)" > "del A; import A" > Yes, if you use "del A.Y", it works. But it is stupid since there are > probably many names. In my thought, if no one references objects in A, > "del A" will release all memory about A. But it seems that the fact is > not. So I can not refresh the namespace to follow changes of a module > easily and I will worry about the memory if I del a module. > I want to know if there is a way to clear a module entirely. > Actually I do not see your problem and your exact need, when I type the following in python prompt I just see expected behavior, what is a problem to you ? Maybe you could post a code explaining it. In [64]: import a In [65]: a.X Out[65]: 0 In [66]: a.X = 2 In [67]: del a In [68]: import a as b In [69]: b.X Out[69]: 2 In [71]: for name in [ n for n in b.__dict__ if not n.startswith('__') ] : ....: b.__dict__.__delitem__(name) ....: ....: In [72]: b.X --------------------------------------------------------------------------- Traceback (most recent call last) C:\Documents and Settings\maric\Bureau\ in () : 'module' object has no attribute 'X' In [73]: reload(b) Out[73]: In [74]: b.X Out[74]: 0 In [75]: del b.X In [76]: del b In [77]: import a In [78]: a.b --------------------------------------------------------------------------- Traceback (most recent call last) C:\Documents and Settings\maric\Bureau\ in () : 'module' object has no attribute 'b' From mailmaverick666 at gmail.com Thu May 17 05:38:46 2007 From: mailmaverick666 at gmail.com (rishi pathak) Date: Thu, 17 May 2007 15:08:46 +0530 Subject: Code Explanation In-Reply-To: <7103149233943231302@unknownmsgid> References: <7103149233943231302@unknownmsgid> Message-ID: <180b672e0705170238i3daad94n6f812113239549f8@mail.gmail.com> On 5/17/07, Robert Rawlins - Think Blue wrote: > > Hello Guys, > > > > I'm currently working on a non-python project, and I'm trying to overcome > a task of parsing a text file into a database and/or xml file. I've managed > to find a parser example written in python, and I'm hoping to deconstruct > the code methodology a bit so I can write it in another language. So I'm > hoping someone can explain to me what these following bits of code are > doing. > > > > lines = range(data.count("\n")) > > lined_data = data.split("\n") > eg: data="abc\n123\ngh\nxyz\n" data.split("\n") will give you an array(list in python) in the following manner ['abc', '123', 'gh', 'xyz'] print "Read %i vendors, now processing" % data.count("(hex)") > > > > I've not used the split() function before, but it partly makes sense to > me. What is that piece of code doing? 'Data' is the content of the text > file, presumably the first line there is counting the number of lines in the > file, but I don't get the rest of it. > > > > The rest of the code seems like a relatively simple set of loops, but it's > just this splitting stuff that's got me confused. > > > > Thanks, > > > > Rob > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Regards-- Rishi Pathak National PARAM Supercomputing Facility Center for Development of Advanced Computing(C-DAC) Pune University Campus,Ganesh Khind Road Pune-Maharastra -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter_7003 at yahoo.com Wed May 2 13:36:33 2007 From: peter_7003 at yahoo.com (Peter Fischer) Date: Wed, 2 May 2007 10:36:33 -0700 (PDT) Subject: how to use Dispatch to open an application in win32com.client Message-ID: <545586.61889.qm@web63405.mail.re1.yahoo.com> Hello, I also use the COM API via python to dispatch an application. My problem now is that I want to dispatch a second instance of this application (Google Earth by the way). But when I invoke dispatch the second time, nothing happens although using another variable to store the returned value: GE_1 = win32com.client.Dispatch("GoogleEarth.ApplicationGE") GE_2 = win32com.client.Dispatch("GoogleEarth.ApplicationGE") (import and while not .IsInitialized() statements omitted for brevity) Does anyone know how to start a second, third, and so on, instance of the application? You would help me very much since I am new to this and have no clue where to look at documentation for that. Best regards, Peter. --------------------------------- Ahhh...imagining that irresistible "new car" smell? Check outnew cars at Yahoo! Autos. -------------- next part -------------- An HTML attachment was scrubbed... URL: From half.italian at gmail.com Wed May 23 15:37:36 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 23 May 2007 12:37:36 -0700 Subject: Parallel/distributed generator In-Reply-To: <1179943256.575473.62610@q66g2000hsg.googlegroups.com> Message-ID: <1179949056.119991.263950@d30g2000prg.googlegroups.com> On May 23, 11:00 am, George Sakkis wrote: > I'm looking for any existing packages or ideas on how to implement the > equivalent of a generator (in the Python sense, i.e.http://www.python.org/dev/peps/pep-0255/) in a parallel/distributed > way. As a use case, imagine a function that generates a range of > primes. I'd like to be able to do something along the following lines: > > def iterprimes(start=1, end=None): > # ... > yield prime > > # rpc-related initialization > ... > rpc_proxy = some_rpc_lib(iterprimes, start=1e6, end=1e12) > for prime in proxy: > print prime > > Is there any module out there that does anything close to this ? > > George Parellel Python? http://www.parallelpython.com/content/view/17/31/#SUM_PRIMES I've never used it, but looks like it does what you are looking for. ~Sean From manishk at cybage.com Tue May 15 03:05:59 2007 From: manishk at cybage.com (Manish Kumar) Date: Tue, 15 May 2007 12:35:59 +0530 Subject: Help needed to install ZOracleDA Message-ID: Hi All, How can I install ZOracleDA on Red Hat Linux machine? Configuration of my system is as below: Zope-2.7 Python-2.3.5 Oracle-9i I have tried to install ZOracleDA but installable needed rh-7.1-python-1.5.2-dco2.so file which is not present in Binaries directory. Any help from you people is appreciable. Regards, Manish Kumar "Legal Disclaimer: This electronic message and all contents contain information from Cybage Software Private Limited which may be privileged, confidential, or otherwise protected from disclosure. The information is intended to be for the addressee(s) only. If you are not an addressee, any disclosure, copy, distribution, or use of the contents of this message is strictly prohibited. If you have received this electronic message in error please notify the sender by reply e-mail to and destroy the original message and all copies. Cybage has taken every reasonable precaution to minimize the risk of malicious content in the mail, but is not liable for any damage you may sustain as a result of any malicious content in this e-mail. You should carry out your own malicious content checks before opening the e-mail or attachment." www.cybage.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From seyensubs at yahoo.com Mon May 14 12:05:08 2007 From: seyensubs at yahoo.com (seyensubs at yahoo.com) Date: 14 May 2007 09:05:08 -0700 Subject: Sorting troubles Message-ID: <1179158708.433792.127150@h2g2000hsg.googlegroups.com> I have the following implementations of quicksort and insertion sort: def qSort(List): if List == []: return [] return qSort([x for x in List[1:] if x< List[0]]) + List[0:1] + \ qSort([x for x in List[1:] if x>=List[0]]) def insertSort(List): for i in range(1,len(List)): value=List[i] j=i while List[j-1]>value and j>0: List[j]=List[j-1] j-=1 List[j]=value Now, the quickSort does not modify the original list, mostly because it works on products and concatenations, rather than alterations. The insertion sort, however, does modify the list. Now, to give results, they should be called in such a way( A is an unsorted list) A=qSort(A) # the insertion sort does not require this, insertSort(A) I would like to know how can I modify the qSort function such that it affects the list directly inside I have tried doing it like this def qSort(List): if List == []: return [] List = qSort([x for x in List[1:] if x< List[0]]) + List[0:1] + \ qSort([x for x in List[1:] if x>=List[0]]) return List while processing, the list changes, but those changes remain inside the function, so that once it's over, if nothis catches the return, the original List remains unchanged. If not a solution, I would like to at least know why it does what it does. I so understand that List(above) is only a reference to the actual data(a list), but I'm not passing a copy of the data to the function, but the actual reference(hence, insertSort does modifications). But then how can I change, inside the function, the object List is referencing to? If I can't modify the original list, maybe I can make the variable List point to another list? But changes inside the function are local. Sorry if this is a bit confusing. From claird at lairds.us Sat May 26 11:19:44 2007 From: claird at lairds.us (Cameron Laird) Date: Sat, 26 May 2007 15:19:44 +0000 Subject: Module listing in order. References: <1179905562.541601.264400@m36g2000hse.googlegroups.com> <1180120016.349259.9540@x18g2000prd.googlegroups.com> Message-ID: In article , Wildemar Wildenburger wrote: . . . >Good God! Is there *anything* that python does not already do? I hardly >feel the need to write programs anymore ... >Its really 80% like of the questions that are asked here get answered >along the lines of: > >import some_fancy_module > >solution = some_fancy_module.exactly_the_right_function_to_solve(problem) > > > >Kinda scary ... :) >W I can tell you that one of my personal goals is to make it so that most posts to comp.lang.python can be adequately answered by "See ." Then we just concentrate on elaboration of some_fancy_module and its Wiki correspondents, and clp manages itself. From g_bumes at web.de Tue May 22 14:22:04 2007 From: g_bumes at web.de (Walter Bumes) Date: Tue, 22 May 2007 20:22:04 +0200 Subject: pipe tutorial In-Reply-To: References: <6LOdndzGvuaCZ8_bnZ2dnUVZ_oDinZ2d@comcast.com> Message-ID: Larry Bates schrieb: > Gabriel Genellina wrote: >> En Tue, 22 May 2007 11:11:45 -0300, Larry Bates >> escribi?: >> >>> Gigs_ wrote: >>>> does anyone know some good tutorial on pipes in python? >>> Pipes is specific only to Windows (you can use sockets >>> on Windows/Linux/mac). The only specific treatment of >>> pipes I've seen is in Python Programming for Win32 by >>> Mark Hammond/Andy Robinson. >> There are pipes in Unix too, named and anonymous, and I think they >> predate its introduction in Windows (first on NT4 I believe). "Pipes" >> used to redirect standard input/output are certainly much older. >> To the OP: what do you want to do, exactly? >> >> --Gabriel Genellina >> > You are right. I didn't think about piping of commands since that > wouldn't really be a Python question. I thought user wanted pipes > for interprocess communication that is prevalent in Windows. I > guess the OP can chime in and we can answer the question better. > > -Larry Hello Larry, i have programmed pipes with Windows NT for about 8-9 years ago and have made an update of the program two years ago under Windows XP. There are differences in the security settings. Under XP it's not allowed to connect to the pc by network! You have to set security options when you create the pipe on the local machine to allow external access to the pipe. Afterwards, i would prefer a standard TCP or UDP connection, because it's available on every system and i do not see any advantage for using the pipes. In actual projects i use only TCP or UDP - depending what i have to to. Walter From gh at gregor-horvath.com Fri May 18 13:32:23 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Fri, 18 May 2007 19:32:23 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179508599.868680.177960@e65g2000hsc.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <464C5382.6080403@v.loewis.de> <1179423799.254286.294930@w5g2000hsg.googlegroups.com> <1179503525.018943.95740@u30g2000hsc.googlegroups.com> <1179508599.868680.177960@e65g2000hsc.googlegroups.com> Message-ID: <80c33$464de327$547078de$4708@news.chello.at> Paul Boddie schrieb: > Perhaps, but the treatment by your mail/news software plus the > delightful Google Groups of the original text (which seemed intact in > the original, although I don't have the fonts for the content) would > suggest that not just social or cultural issues would be involved. I do not see the point. If my editor or newsreader does display the text correctly or not is no difference for me, since I do not understand a word of it anyway. It's a meaningless stream of bits for me. It's save to assume that for people who are finding this meaningful their setup will display it correctly. Otherwise they could not work with their computer anyway. Until now I did not find a single Computer in my German domain who cannot display: ?. Gregor From bbxx789_05ss at yahoo.com Mon May 28 11:34:11 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 28 May 2007 08:34:11 -0700 Subject: itertools.groupby In-Reply-To: <1180313441.598026.198230@d30g2000prg.googlegroups.com> References: <1180295221.3163.9.camel@localhost.localdomain> <1180313441.598026.198230@d30g2000prg.googlegroups.com> Message-ID: <1180366451.826290.142430@m36g2000hse.googlegroups.com> On May 27, 6:50 pm, Raymond Hettinger wrote: > On May 27, 2:59 pm, Steve Howell wrote: > > > These docs need work. Please do not defend them; > > please suggest improvements. > > FWIW, I wrote those docs. Suggested improvements are > welcome; however, I think they already meet a somewhat > high standard of quality: > > - there is an accurate, succinct one-paragraph description > of what the itertool does. > > - there is advice to pre-sort the data using the same > key function. > > - it also advises when to list-out the group iterator > and gives an example with working code. > > - it includes a pure python equivalent which shows precisely > how the function operates. > > - there are two more examples on the next page. those two > examples also give sample inputs and outputs. > > This is most complex itertool in the module. I believe > the docs for it can be usable, complete, and precise, > but not idiot-proof. > > The groupby itertool came-out in Py2.4 and has had remarkable > success (people seem to get what it does and like using it, and > there have been no bug reports or reports of usability problems). > All in all, that ain't bad (for what 7stud calls a poster child). > > Raymond >- there is an accurate, succinct one-paragraph description > of what the itertool does. As is often the case, the specifics of the description may only be meaningful to someone who already knows what groupby does. There are many terms and concepts that experienced programmers use to describe programming problems, but often the terms and concepts only ring true with people who already understand the problem, and they are not at all helpful for someone who is trying to learn about the concept. Sometimes when you describe a function accurately, the description becomes almost impossible to read because of all the detail. What is really needed is a general, simple description of the primary use of the function, so that a reader can immediately employ the function in a basic way. Code snippets are extremely helpful in that regard. Subsequently, the details and edge cases can be fleshed out in the rest of the description. >- there is advice to pre-sort the data using the same > key function. But you have to know why that is relevant in the first place-- otherwise it is just a confusing detail. Two short code examples could flesh out the relevance of that comment. I think I now understand why pre-sorting is necessary: groupby only groups similar items that are adjacent to each other in the sequence, and similar items that are elsewhere in the sequence will be in a different group. >- it includes a pure python equivalent which shows precisely > how the function operates. It's too complicated. Once again, it's probably most useful to an experienced programmer who is trying to figure out some edge case. So the code example is certainly valuable to one group of readers--just not a reader who is trying to get a basic idea of what groupby does. >- there are two more examples on the next page. those two > examples also give sample inputs and outputs. I didn't see those. > people seem to get what it does and like > using it, and > there have been no bug reports or reports of > usability problems Wouldn't you get the same results if not many people used groupby because they couldn't understand what it does? I don't think you even need good docs if you allow users to attach comments to the docs because all the issues will get fleshed out by the users. I appreciate the fact that it must be difficult to write the docs--that's why I think user comments can help. How about this for the beginning of the description of groupby in the docs: groupby divides a sequence into groups of similar elements. Compare to: > Make an iterator that returns consecutive keys and groups > from the iterable. Huh? Continuing with a kinder, gentler description: With a starting sequence like this: lst = [1, 2, 2, 2, 1, 1, 3] groupby divides the sequence into groups like this: [1], [2, 2, 2], [1, 1], [3] groupby takes similar elements that are adjacent to each other and gathers them into a group. If you sort the sequence beforehand, then all the similar elements in a sequence will be adjacent to one another, and therefore they will all end up in one group. Optionally, you can specify a function func which groupby will use to determine which elements in the sequence are similar (if func isn't specified or is None, then func defaults to the identity function which returns the element unchanged). An example: ------ import itertools lst = [1, 2, 2, 2, 1, 1, 3] def func(num): if num == 2: return "a" else: return "b" keys = [] groups = [] for k, g in itertools.groupby(lst, func): keys.append(k) groups.append( list(g) ) print keys print groups ---output:--- ['b', 'a', 'b'] [[1], [2, 2, 2], [1, 1, 3]] When func is applied to an element in the list, and the return value(or key) is equal to "a", the element is considered similar to other elements with a return value(or key) equal to "a". As a result, the adjacent elements that all have a key equal to "a" are put in a group; likewise the adjacent elements that all have a key equal to "b" are put in a group. RETURN VALUE: groupby returns a tuple consisting of: 1) the key for the current group; all the elements of a group have the same key 2) an iterator for the current group, which you normally use list(g) on to get the current group as a list. ----------------- That description probably contains some inaccuracies, but sometimes a less accurate description can be more useful. From apatheticagnostic at gmail.com Sat May 5 04:25:31 2007 From: apatheticagnostic at gmail.com (kaens) Date: Sat, 5 May 2007 04:25:31 -0400 Subject: Calling Exe from Python In-Reply-To: <1178102899.910368.114140@n76g2000hsh.googlegroups.com> References: <1178102899.910368.114140@n76g2000hsh.googlegroups.com> Message-ID: <163f0ce20705050125l65825326t3e75fbc703b1b387@mail.gmail.com> I've been using subprocess.call(['name','arg1','arg2']) Works fine. On 2 May 2007 03:48:19 -0700, M Abbas wrote: > Hello Folks, > > This is what i am required to do. > Call an executable from my python script, and when the executable is > fininshed running, i should continue with my python script. > > I have tried "os.exec()" but it calls the executable and never returns > to the calling python script. > I tried "os.fork" it will start an independent process, > since logic of my program depends on the results of executable. > > I am unable to figure, how to do it. > Hope you folks would help me. > > ~JinBaba > > -- > http://mail.python.org/mailman/listinfo/python-list > From andrew at nospam.com Tue May 15 15:46:36 2007 From: andrew at nospam.com (Andrew Holme) Date: Tue, 15 May 2007 20:46:36 +0100 Subject: Extended characters in MATPLOTLIB (newbie) Message-ID: I'm using MATPLOTLIB on Windows. How can I get extended characters such as the micro symbol (greek letter mu) to appear in my axis labels? I've tried: xlabel('?s', font) and xlabel('\xB5s', font) but it just appears as a box. TIA From gerald.kaszuba at gmail.com Sun May 13 05:30:46 2007 From: gerald.kaszuba at gmail.com (Gerald Kaszuba) Date: 13 May 2007 02:30:46 -0700 Subject: Setting thread priorities In-Reply-To: <2sy1i.2542$LR5.1451@newssvr17.news.prodigy.net> References: <2sy1i.2542$LR5.1451@newssvr17.news.prodigy.net> Message-ID: <1179048645.972142.92140@e51g2000hsg.googlegroups.com> Hi John On May 13, 4:46 pm, John Nagle wrote: > There's no way to set thread priorities within Python, is there? Not exactly. You can however use the ctypes module to access the o/s methods of pthread_setschedparam() for UNIX and SetThreadPriority() for Windows. I'm not sure why this hasn't been implemented in Python. Gerald http://geraldkaszuba.com/ From trentm at activestate.com Wed May 9 15:30:56 2007 From: trentm at activestate.com (Trent Mick) Date: Wed, 09 May 2007 12:30:56 -0700 Subject: preferred windows text editor? In-Reply-To: <1178738724.695273.191930@n59g2000hsh.googlegroups.com> References: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> <1178738724.695273.191930@n59g2000hsh.googlegroups.com> Message-ID: <46422170.5080004@activestate.com> nufuhsus at gmail.com wrote: > I like IDLE but it seems to stop working after the first few times and > I would then re-install it and it would work a few times more. > ActivePython was cool but I could not find a version of it that used > Python 2.5 (as far as I can see, it only uses 2.4) ActivePython is the distribution of Python. The distro includes PyWin32 (a bunch o' Windows stuff for Python). Part of that stuff is "Pythonwin" -- the editor that you are probably referring to. There is an ActivePython 2.5.1 now: http://www.activestate.com/products/activepython/ You should give Komodo Edit a try too: http://www.activestate.com/products/komodo_edit/ Cheers, Trent -- Trent Mick trentm at activestate.com From jr244 at kent.ac.uk Tue May 15 04:43:42 2007 From: jr244 at kent.ac.uk (J. Robertson) Date: Tue, 15 May 2007 09:43:42 +0100 Subject: How to calculate definite integral with python In-Reply-To: References: Message-ID: fdu.xiaojf at gmail.com wrote: > I'm trying to do some integral calculation. I have searched the web, but > haven't found any useful information. Will somebody point me to the > right resources on the web for this job ? > > Thanks a lot. > > ps. Can numpy be used for this job?* > * It can be done with scipy (see http://www.scipy.org/doc/api_docs/scipy.integrate.html ) for example: >>> import scipy.integrate >>> func = lambda x: x**2 >>> scipy.integrate.quadrature(func, 0.0, 1.0) Took 4 points. (0.333333333333, 0.0) From johnzenger at gmail.com Wed May 16 11:36:41 2007 From: johnzenger at gmail.com (John Zenger) Date: 16 May 2007 08:36:41 -0700 Subject: removing common elemets in a list In-Reply-To: <1179296224.885877.187200@q23g2000hsg.googlegroups.com> References: <1179296224.885877.187200@q23g2000hsg.googlegroups.com> Message-ID: <1179329801.699092.154700@o5g2000hsb.googlegroups.com> On May 16, 2:17 am, saif.shak... at gmail.com wrote: > Hi, > Suppose i have a list v which collects some numbers,how do i > remove the common elements from it ,without using the set() opeartor. > Thanks Submit this as your homework answer -- it will blow your TA's mind! import base64 def uniq(v): return eval(base64.b64decode('c29ydGVkKGxpc3Qoc2V0KHYpKSxrZXk9bGFtYmRhIHg6di5pbmRleCh4KSk='),locals()) From fw3 at hotmail.co.jp Fri May 4 15:32:06 2007 From: fw3 at hotmail.co.jp (wang frank) Date: Fri, 04 May 2007 19:32:06 +0000 Subject: how to find a lable quickly? Message-ID: Hi, I am a new user on Python and I really love it. I have a big text file with each line like: label 3 teststart 5 endtest 100 newrun 2345 I opened the file by uu=open('test.txt','r') and then read the data as xx=uu.readlines() In xx, it contains the list of each line. I want to find a spcefic labels and read the data. Currently, I do this by for ss in xx: zz=ss.split( ) if zz[0] = endtest: index=zz[1] Since the file is big and I need find more lables, this code runs slowly. Are there anyway to speed up the process? I thought to convert the data xx from list to a dictionay, so I can get the index quickly based on the label. Can I do that effeciently? Thanks Frank _________________________________________________________________ ??????????????????2???????????????? http://campaign.live.jp/dizon/ From martin at v.loewis.de Fri May 11 02:07:35 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 11 May 2007 08:07:35 +0200 Subject: SQLObject 0.9.0 In-Reply-To: References: <1178824322.008520.239540@y5g2000hsa.googlegroups.com> Message-ID: <46440827.1050206@v.loewis.de> > For reasons others will know, there are different branches to the > SQLObject project. I think, analogously, python still has an active 2.4 > branch, if that helps make sense of maintaining branches based on > versions. I'm not sure why the announcements aren't bundled into one > because just about everyone who sees this for the first time asks the > same question. For the community being addressed (namely, users of SQLObject), this form provides a useful service: - they know that three branches are actively being maintained (0.7, 0.8, and 0.9). I would expect that in particular users of the 0.7 branch are glad to see that 0.7 is still alive even though 0.9 was just started. This is indeed more than is common, so releasing 0.7.7 simultaneously sends a clear message of affirmation (I explicitly looked for a notice that this would be the last 0.7 release, and found none) - for each branch, there is a list of changes for the branch, and I can easily see what changed in the version I'm interested in. Googling for old release announcements (e.g. SQLObject 0.7.5) brings up the announcement on hit 2, so I can also easily find announcemnts if I missed one. Those not using SQLObject, or even see this for the first time, this form gives the project higher attention than other projects - so it may attract users. It may also shy away users if they think this obsessive form of sending three usenet articles in a single hour is spam, but I guess the author is willing to take that risk. Martin From kerny404 at gmail.com Fri May 11 16:36:49 2007 From: kerny404 at gmail.com (andrea) Date: 11 May 2007 13:36:49 -0700 Subject: Path python versions and Macosx Message-ID: <1178915809.065874.133030@o5g2000hsb.googlegroups.com> Hi everyone, I use python on macosx with textmate as editor (great program). I also use macport to install unix programs from the command line and I find it great too. Well I would like to have all my modules in the path when I'm using textmate AND when I use the commandline (ipython), but because textmate and the command line use different python versions they also search in different places.. I found somewhere to write .pythonrc.py like this #!/usr/bin/env python import sys PATH='/opt/local/lib/python2.4/site-packages/' sys.path.append(PATH) del sys But it doesn't work either, I also tried to append this PATH="/Library/Frameworks/Python.framework/Versions/Current/bin:/opt/ local/lib/python2.4/site-packages:${PATH} to .bash_profile but nothing. Where should I set this variables?? Thanks a lot From arkanes at gmail.com Thu May 31 17:13:45 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 31 May 2007 16:13:45 -0500 Subject: Python memory handling In-Reply-To: References: <1180611604.247696.149060@h2g2000hsg.googlegroups.com> <1180627331.756615.132650@k79g2000hse.googlegroups.com> Message-ID: <4866bea60705311413o5dc50e2aq19079859a0efc7f9@mail.gmail.com> On 5/31/07, Thorsten Kampe wrote: > * Chris Mellon (Thu, 31 May 2007 12:10:07 -0500) > > > Like: > > > import pool > > > pool.free() > > > pool.limit(size in megabytes) > > > > > > Why not letting the user choosing that, why not giving the user more > > > flexibility ? > > > I will try later under linux with the latest stable python > > > > > > Regards, > > > FP > > > > > > > The idea that memory allocated to a process but not being used is a > > "cost" is really a fallacy, at least on modern virtual memory sytems. > > It matters more for fully GCed languages, where the entire working set > > needs to be scanned, but the Python GC is only for breaking refcounts > > and doesn't need to scan the entire memory space. > > > > There are some corner cases where it matters, and thats why it was > > addressed for 2.5, but in general it's not something that you need to > > worry about. > > If it's swapped to disk than this is a big concern. If your Python app > allocates 600 MB of RAM and does not use 550 MB after one minute and > this unused memory gets into the page file then the Operating System > has to allocate and write 550 MB onto your hard disk. Big deal. > It happens once, and only in page-sized increments. You'd have to have unusual circumstances to even notice this "big deal", totally aside from the unusual and rare conditions that would trigger it. From gagsl-py2 at yahoo.com.ar Wed May 30 13:32:23 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 30 May 2007 14:32:23 -0300 Subject: print bypasses calling write method for objects inheriting from file? References: <1180508789.556984.204520@o11g2000prd.googlegroups.com> Message-ID: En Wed, 30 May 2007 04:24:30 -0300, Peter Otten <__peter__ at web.de> escribi?: >> I created an object that inherits from file and was a bit surprised to >> find that print seems to bypass the write method for objects >> inheriting from file. An optimization I suppose. Does this surprise >> anyone else at all or am I missing something? > > No, your analysis is correct, though I'd consider optimization an > euphemism > for bug here. Noone was annoyed enough to write a patch, it seems. A one-line patch, I guess, PyFile_CheckExact instead of PyFile_Check. Or a few lines, checking if the write method is still the builtin one. As this is the third time I see this question I'll try to submit the patch. -- Gabriel Genellina From nogradi at gmail.com Sat May 12 14:17:17 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Sat, 12 May 2007 20:17:17 +0200 Subject: [Newbie] design question In-Reply-To: <1178992981.143066.279690@o5g2000hsb.googlegroups.com> References: <1178992981.143066.279690@o5g2000hsb.googlegroups.com> Message-ID: <5f56302b0705121117ob87808ft148051c45476031f@mail.gmail.com> > Suppose I have class ShoppingCart which has one method called buy(), > and class Buyer who has one reference to ShoppingCart... Can I also > have method buy() in class Buyer, which will then called > ShoppingCard.buy(), and also do some other stuff? Is this legal > design pattern, have methods with same name? Yes, something like this is perfectly fine. class ShoppingCart( object ): def buy( self ): print 'buy in shoppingcart' class Buyer( object ): def __init__( self, cart ): self.cart = cart def buy( self ): print 'buy in buyer' self.cart.buy( ) print 'some extra stuff' acart = ShoppingCart( ) abuyer = Buyer( cart=acart ) abuyer.buy( ) HTH, Daniel From michele.simionato at gmail.com Tue May 8 05:40:09 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 8 May 2007 02:40:09 -0700 Subject: how do you implement a reactor without a select? In-Reply-To: References: <1178543812.260333.39280@w5g2000hsg.googlegroups.com> <1hxqfgq.4sjxga1dz7vv3N%aleax@mac.com> <1178552069.229745.124040@l77g2000hsb.googlegroups.com> <1hxrdhf.179bobg6tzv9cN%aleax@mac.com> <1178596109.282088.175300@u30g2000hsc.googlegroups.com> Message-ID: <1178617209.160802.249330@l77g2000hsb.googlegroups.com> On May 8, 11:23 am, Antoon Pardon wrote: > I once played with the following module to do something similar. That looks interesting, I will have a look at it. Michele Simionato From sonmez at lavabit.com Wed May 9 15:30:26 2007 From: sonmez at lavabit.com (=?ISO-8859-1?Q?S=F6nmez_Kartal?=) Date: Wed, 09 May 2007 22:30:26 +0300 Subject: preferred windows text editor? In-Reply-To: <1178737231.565326.12810@o5g2000hsb.googlegroups.com> References: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> <1178737231.565326.12810@o5g2000hsb.googlegroups.com> Message-ID: <46422152.3060103@lavabit.com> GNU Emacs with python-mode -- S?nmez Kartal From p.lavarre at ieee.org Thu May 31 22:27:24 2007 From: p.lavarre at ieee.org (p.lavarre at ieee.org) Date: 31 May 2007 19:27:24 -0700 Subject: FAQ: how to vary the byte offset of a field of a ctypes.Structure In-Reply-To: References: <1180634138.944362.88590@d30g2000prg.googlegroups.com> Message-ID: <1180643491.076119.92800@o11g2000prd.googlegroups.com> I see that changing self._fields_ doesn't change ctypes.sizeof(self). I guess ctypes.Structure.__init__(self) fetches self.__class__._fields_ not self._fields_. From jstroud at mbi.ucla.edu Thu May 24 01:06:31 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 23 May 2007 22:06:31 -0700 Subject: 0 == False but [] != False? In-Reply-To: <1179982400.412340.178710@g4g2000hsf.googlegroups.com> References: <1179982400.412340.178710@g4g2000hsf.googlegroups.com> Message-ID: Rajarshi wrote: > This is a slightly naive question, but I know that 0 can be used to > represent False. So > > >>>>0 == False > > True > > But, I know I can use [] to represent False as in > > >>>>if not []: print 'empty' > > ... > empty > > But then doing the following gives a surprising (to me!) result > > >>>>[] == False > > False > > Could anybody point out why this is the case? > > Thanks, > Rajarshi > Meditate on: py> isinstance(False, int) True py> isinstance([], int) False py> bool([]) False James From steve at REMOVE.THIS.cybersource.com.au Thu May 10 01:33:46 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 10 May 2007 15:33:46 +1000 Subject: change of random state when pyc created?? References: <5ae25fF2oggbqU1@mid.uni-berlin.de> Message-ID: On Thu, 10 May 2007 01:06:33 -0400, Carsten Haese wrote: > On Thu, 10 May 2007 12:46:05 +1000, Steven D'Aprano wrote >> It is natural to expect two runs of any program to give the same >> result if there are (1) no random numbers involved; (2) the same >> input data; (3) and no permanent storage from run to run. > > Which of those three categories does time.time() fall into? What about > id("hello")? I didn't say there were no exceptions to the heuristic "expect any computer program to do the same thing on subsequent runs". I said it was a natural expectation. Obviously one of the differences between a naive programmer and a sophisticated programmer is that the sophisticated programmer has learnt more exceptions to the rule. And that's why I have described this behaviour as a gotcha, not as a bug or a mis-feature or anything else. -- Steven. From john at datavoiceint.com Mon May 7 18:39:22 2007 From: john at datavoiceint.com (HMS Surprise) Date: 7 May 2007 15:39:22 -0700 Subject: No module named urllib In-Reply-To: <87tzuop8s2.fsf@gmail.com> References: <1178575589.059564.226060@q75g2000hsh.googlegroups.com> <87tzuop8s2.fsf@gmail.com> Message-ID: <1178577562.498615.222340@e51g2000hsg.googlegroups.com> On May 7, 5:29 pm, Jorge Godoy wrote: > HMS Surprise writes: > > I edited environment varialbes and have added C:\Python25\Lib to > > PYTHONPATH but get the no module message when the statement > > > import urllib > > > is executed. > > > Even tried copying the urllib file to my working directory. > > > Any suggestions? > > No messages is good! :-) > > If you got any error messages then you'd have a problem. > > -- > Jorge Godoy Perhaps I should have put qoutes in my sentence. I get the "no module message named urllib". From michal.lipinski at gmail.com Fri May 25 17:33:15 2007 From: michal.lipinski at gmail.com (Michal Lipinski) Date: Fri, 25 May 2007 23:33:15 +0200 Subject: problem with eval while using PythonCard Message-ID: <3203440c0705251433v5ca01bc9ydfd360e76a82130d@mail.gmail.com> Hi its my first post. I have a problem, I want to user eval() function in a for loop to set labels to staticText so i done something like this: dzien=self.components.Calendar.GetDate().GetDay() for i in range(1,8): act=dzien+i -1 eval( 'self.components.d' + str(i) + '.text = "'+ str(act) + '"') but there is a problem, the program returned error: File "/home/lipton/Projekty/kami-organizer/grafik.py", line 27, in __init__ eval( 'self.components.d' + str(i) + '.text = "'+ str(act) + '"') File "", line 1 self.components.d1.text = "25" SyntaxError: invalid syntax dont know what is wrong, becouse when i copy and paste in to code : self.components.d1.text = "25" it work great, but when Im trying to do it using eval() it give me a SyntaxError Please help. ps. sorry for my english ;) From saif.shakeel at gmail.com Wed May 16 10:26:35 2007 From: saif.shakeel at gmail.com (saif.shakeel at gmail.com) Date: 16 May 2007 07:26:35 -0700 Subject: Unusual i/o problems Message-ID: <1179325595.708882.289510@e65g2000hsc.googlegroups.com> Hi, I am parsing an xml file ,before that i have replaced a string in the original xml file with another and made a new xml file which will now be parsed.I am also opening some more files for output.The following code shows some i/o commands. file_input = raw_input("Enter The ODX File Path:") input_xml = open(file_input,'r') (shortname,ext)=os.path.splitext(file_input) f_open_out=shortname+".ini" log=shortname+".xls" test_file=shortname+"testxml.xml" saveout = sys.stdout xmlcont=input_xml.read() input_xml.close() xmlcont=xmlcont.replace('localId','dataPackageId') output_file = open(test_file,"w") output_file.write(xmlcont) output_file.close() f_open=open(f_open_out, 'w') logfile=open(log,"w") sys.stdout = f_open After this i have to parse the new xml file which is in output_file .hence input_xml_sec = open(output_file,'r') xmldoc = minidom.parse(input_xml_sec) But i am getting an error on this line (input_xml_sec = open(output_file,'r')).I have tried to figure out but not able to debug.Can someone throw some light or anything they feel could be going wrong somewhere. Thanks From eugene.vandenbulke at gmail.com Fri May 4 05:47:40 2007 From: eugene.vandenbulke at gmail.com (EuGeNe Van den Bulke) Date: Fri, 04 May 2007 11:47:40 +0200 Subject: base64 and unicode References: Message-ID: Duncan Booth wrote: > However, the decoded text looks as though it is utf16 encoded so it should be written as binary. i.e. > the output mode should be "wb". Thanks for the "wb" tip that works (see bellow). I guess it is experience based but how could you tell that it was utf16 encoded? > Simpler than using the base64 module you can just use the base64 codec. > This will decode a string to a byte sequence and you can then decode that > to get the unicode string: > > with file("hebrew.b64","r") as f: > text = f.read().decode('base64').decode('utf16') > > You can then write the text to a file through any desired codec or process > it first. >>> with file("hebrew.lang","wb") as f: >>> ... file.write(text.encode('utf16')) Done ... superb! > BTW, you may just have shortened your example too much, but depending on > python to close files for you is risky behaviour. If you get an exception > thrown before the file goes out of scope it may not get closed when you > expect and that can lead to some fairly hard to track problems. It is much > better to either call the close method explicitly or to use Python 2.5's > 'with' statement. Yes I had shortened my example but thanks for the 'with' statement tip ... I never think about using it and I should ;) Thanks, EuGeNe -- http://www.3kwa.com From zubeido at yahoo.com.br Sun May 20 06:50:03 2007 From: zubeido at yahoo.com.br (aiwarrior) Date: 20 May 2007 03:50:03 -0700 Subject: Unable to strip \n characters Message-ID: <1179658203.040541.220800@p77g2000hsh.googlegroups.com> Hi Im writing a personal wrapper to the perl script offered by rapidshare, so that im able to use multiple files and glob pathnames, but im using a file so i can track and resume any uploading data. The problem is the lines come with a \n character that im not bein able to take out, files = f.readlines() for upload in files: upload.strip("\n") final_args = "./rsapiresume.pl %s prem user password" % (upload) print upload #os.system( final_args ) My upload string still comes with the \n making the system call look like this: ./rsapiresume.pl filename_to_upload prem user password I've already tried replace but it doesn't work either From basilisk96 at gmail.com Tue May 8 16:03:00 2007 From: basilisk96 at gmail.com (Basilisk96) Date: 8 May 2007 13:03:00 -0700 Subject: chdir() In-Reply-To: <1178652809.436141.176900@u30g2000hsc.googlegroups.com> References: <1178652809.436141.176900@u30g2000hsc.googlegroups.com> Message-ID: <1178654580.556747.306890@w5g2000hsg.googlegroups.com> On May 8, 3:54 pm, HMS Surprise wrote: > Tried executing os.chdir("c:\twill") from a python Tk shell and got > the error message: > > WindowsError: [Error 123] The filename, directory name, or volume > label syntax is incorrect: 'c:\twill'. > > I have the directory exists as I copied the name from the explorer > window that was open to it. > > What is wrong with the syntax? > > thanks, > > jh Use os.chdir(r"c:\twill") instead. The "\t" character is the escape character for a tab. You can avoid such a faux pas by using the raw string construct of the form r"some string". Otherwise, any backslashes in in your string will be interpreted as escape characters. -Basilisk96 From kirkjobsluder at gmail.com Tue May 1 13:39:14 2007 From: kirkjobsluder at gmail.com (kirkjobsluder) Date: 1 May 2007 10:39:14 -0700 Subject: sqlite for mac? In-Reply-To: <1178039558.882802.214030@n59g2000hsh.googlegroups.com> References: <1177993261.572563.70370@n76g2000hsh.googlegroups.com> <1178039558.882802.214030@n59g2000hsh.googlegroups.com> Message-ID: <1178041154.480155.78220@o5g2000hsb.googlegroups.com> On May 1, 1:12 pm, 7stud wrote: > I'm using python 2.4.4 because the download said there were more mac > modules available for 2.4.4. than 2.5, and I can't seem to locate a > place to download sqlite for mac. I it comes on OS X Tiger, and possibly earlier versions as well (it's used as an index for Mail.app).. You just need to download and install the pysqlite libraries. From carsten at uniqsys.com Thu May 24 13:35:35 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 24 May 2007 13:35:35 -0400 Subject: installing cx_Oracle. In-Reply-To: References: Message-ID: <1180028135.3395.25.camel@dot.uniqsys.com> On Thu, 2007-05-24 at 16:15 +0000, Dennis Lee Bieber wrote: > On Thu, 24 May 2007 09:07:07 -0500, Carl K > declaimed the following in comp.lang.python: > > > Getting closer, thanks Bill and Diez. > > > > $ export ORACLE_HOME > > $ ORACLE_HOME=/usr/lib/oracle/xe/app/oracle/product/10.2.0/client > > Don't those lines need to be reversed? Set the variable in the > current shell, and /then/ export it? It also works the other way around, at least on the non-empty set of systems that contains my workstation. export simply marks the variable name for automatic export to the environment of subsequent commands. The value at that time doesn't matter. What matters is the value that the name has at the time the command is run: [carsten at dot ~]$ export FOOD [carsten at dot ~]$ FOOD=spam [carsten at dot ~]$ python -c "import os; print os.environ['FOOD']" spam [carsten at dot ~]$ FOOD=eggs [carsten at dot ~]$ python -c "import os; print os.environ['FOOD']" eggs Regards, -- Carsten Haese http://informixdb.sourceforge.net From bob at snee.com Tue May 22 20:37:01 2007 From: bob at snee.com (bob at snee.com) Date: 22 May 2007 17:37:01 -0700 Subject: trying to gzip uncompress a StringIO In-Reply-To: <46536E01.2080702@lexicon.net> Message-ID: <1179880621.469302.183180@m36g2000hse.googlegroups.com> Perfect, thanks! Now I have a working WMF file and everything. Bob From Leo.Kislov at gmail.com Fri May 4 02:13:12 2007 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 3 May 2007 23:13:12 -0700 Subject: relative import broken? In-Reply-To: References: <1hxa9x3.c0unyd1jw7vu9N%aleax@mac.com> <1hxcdkq.47p2r6beuctcN%aleax@mac.com> Message-ID: <1178259192.544786.287540@e65g2000hsc.googlegroups.com> On May 3, 10:08 am, "Alan Isaac" wrote: > "Alex Martelli" wrote in message > > news:1hxcdkq.47p2r6beuctcN%aleax at mac.com... > > > Very simply, PEP 328 explains: > > """ > > Relative Imports and __name__ > > > Relative imports use a module's __name__ attribute to determine that > > module's position in the package hierarchy. If the module's name does > > not contain any package information (e.g. it is set to '__main__') then > > relative imports are resolved as if the module were a top level module, > > regardless of where the module is actually located on the file system. > > """ > > To change my question somewhat, can you give me an example > where this behavior (when __name__ is '__main__') would > be useful for a script? (I.e., more useful than importing relative > to the directory holding the script, as indicated by __file__.) Do you realize it's a different behaviour and it won't work for some packages? One possible alternative is to assume empty parent package and let from . import foo work but not from .. import bar or any other upper levels. The package author should also realize __init__.py will be ignored. -- Leo From nkabir at gmail.com Mon May 7 13:57:08 2007 From: nkabir at gmail.com (bourbaki) Date: 7 May 2007 10:57:08 -0700 Subject: Unittest Automation In-Reply-To: References: Message-ID: <1178560628.174189.82070@y5g2000hsa.googlegroups.com> On May 7, 7:29 am, "Calvin Spealman" wrote: > I'm trying to find a better way, a shell one-liner, that I can use to > recurse through my project, find all my test_ modules, aggregate the > TestCase classes into a suite, and run all my tests. Basically, what > py.test does out of the box. Why am I having such trouble doing it? > > -- > Read my blog! I depend on your acceptance of my opinion! I am interesting!http://ironfroggy-code.blogspot.com/ See Nose ... nose provides an alternate test discovery and running process for unittest, one that is intended to mimic the behavior of py.test as much as is reasonably possible without resorting to too much magic. ... http://somethingaboutorange.com/mrl/projects/nose/ Cheers, --Norm From fadereu at gmail.com Sun May 27 07:11:25 2007 From: fadereu at gmail.com (DJ Fadereu) Date: 27 May 2007 04:11:25 -0700 Subject: Help with PySMS Message-ID: <1180264285.477306.137830@r19g2000prf.googlegroups.com> Hello - Background: I'm not a coder, but I got a degree in Chem Engg about 7 years ago. I have done some coding in my life, and I'm only beginning to pick up Python. So assume that I'm very stupid when and if you are kind enough to help me out. Problem: I need an SMS server running on my WinXP PC, as soon as possible. I'm currently using a Nokia 6300 phone which has the S60 platform. I downloaded the PySMS by Dave Berkeley from http://www.wordhord.co.uk/pysms.html and started testing it, but I haven't been able to get it working. Maybe I don't know how to do some configurations before using it, I dunno. I'm pretty lost. Do I need to tweak Nokia.ini? What ports am I supposed to use? Can anybody tell me a step-by-step way of setting up and getting this thing running? I don't have enough to pay for this information, or I would gladly shell out some cash. But I can bet that I'll be able to help you out with something or the other in the future, if not money. And I am willing to negotiate a portion of royalties if I make any money off this project. My project is very simple - I will use incoming SMS to generate a visualisation and automatic responder. This system will be part of a multiplayer game that lots of people can play using SMS. cheers, DJ Fadereu http://www.algomantra.com From michael at jedimindworks.com Wed May 16 03:13:36 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Wed, 16 May 2007 02:13:36 -0500 Subject: Trying to choose between python and java In-Reply-To: References: Message-ID: <7901D6CC-E9FF-45B8-997E-F6BB26669D48@jedimindworks.com> On May 15, 2007, at 8:21 PM, Anthony Irwin wrote: > I saw on the python site a slide from 1999 that said that python was > slower then java but faster to develop with is python still slower > then java? I guess that all depends on the application. Whenever I have a choice between using something written in Java -- and *anything else* -- I choose the non-Java option because the JVM is such a hog-beast. Sure, once it is running, it may run at a nice clip (which is not my experience but I don't want to seem argumentative) but loading the Java environment is a pain. Perfect example is with Aptana, which I *really* like -- but if I want to use it, I've got to shut everything else off -- and it still brings my poor old machine to its knees (note: my computer doesn't actually have knees). I've never developed in Java though. Lots of people do, so it must have it's merits. Michael --- The Rules of Optimization are simple. Rule 1: Don't do it. Rule 2 (for experts only): Don't do it yet. -Michael A. Jackson From maksim.kasimov at gmail.com Fri May 25 10:30:48 2007 From: maksim.kasimov at gmail.com (Maksim Kasimov) Date: Fri, 25 May 2007 17:30:48 +0300 Subject: just a bug In-Reply-To: References: <1179841504.782279.86490@u36g2000prd.googlegroups.com> <1180082137.329142.45350@p77g2000hsh.googlegroups.com> Message-ID: Richard Brodie ?????: > "Neil Cerutti" wrote in message > news:slrnf5do1c.1g8.horpner at FIAD06.norwich.edu... > >> Web browsers are in the very business of reasonably rendering >> ill-formed mark-up. It's one of the things that makes >> implementing a browser take forever. ;) > > For HTML, yes. it accepts all sorts of garbage, like most > browsers; I've never, before now, seen it accept an invalid > XML document though. > > I do not think, that will be constructive to discuss correctness of work Mozilla insted to notice me on a contradiction in my message. Isn't it. Try to browse any file with garbage with "xml" extension. If you do, then you will see error message of XML-parser. I insist - my message is correct and not contradicts no any point of w3.org xml-specification. -- Maksim Kasimov From newsgroups at debain.org Sat May 26 21:13:43 2007 From: newsgroups at debain.org (Samuel) Date: Sun, 27 May 2007 01:13:43 +0000 (UTC) Subject: PyGTK and HTML rendering? References: Message-ID: On Sat, 26 May 2007 23:23:19 +0200, Ivan Voras wrote: > Is there an easy off-the-shelf way to get HTML formatting inside the > TextArea widget? Gtk does not support this currently, but they would love to see this feature added into Gtk: > http://bugzilla.gnome.org/show_bug.cgi?id=59390 It shouldn't be too hard to do, sounds like a nice project? :-) -Samuel From gagsl-py2 at yahoo.com.ar Sun May 6 18:51:13 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 06 May 2007 19:51:13 -0300 Subject: msbin to ieee References: <1178487847.671199.108140@h2g2000hsg.googlegroups.com> Message-ID: En Sun, 06 May 2007 18:44:07 -0300, revuesbio escribi?: > Does anyone have the python version of the conversion from msbin to > ieee? I imagine this will be done just once - msbin is a really old format. Instead of coding the conversion in Python, you could: - write a small QuickBasic program using the functions CVSMBF, CVDMBF to do the conversion - download this DLL http://www.microdexterity.com/products.html -- Gabriel Genellina From alan.franzoni_invalid at geemail.invalid Fri May 11 11:44:38 2007 From: alan.franzoni_invalid at geemail.invalid (Alan Franzoni) Date: Fri, 11 May 2007 17:44:38 +0200 Subject: vim e autoindentazione commenti References: Message-ID: <1vs63pgax2emf$.gjyp0labjlmy.dlg@40tude.net> Il Fri, 11 May 2007 13:15:01 GMT, Neil Cerutti ha scritto: >:help format-comments > > (Spiacente per la mia scrittura difettosa. Sto utilizzando il > traduttore di altavista.) Really sorry ^_^ I thought I was posting in it.comp.lang.python Thank you BTW! -- Alan Franzoni - Togli .xyz dalla mia email per contattarmi. Remove .xyz from my address in order to contact me. - GPG Key Fingerprint (Key ID = FE068F3E): 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From __peter__ at web.de Thu May 24 17:46:47 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 24 May 2007 23:46:47 +0200 Subject: Can I reference 1 instance of an object by more names ? rephrase References: <4654289a$0$2326$426a74cc@news.free.fr> <3dc25$4655ebd1$d443bb3a$31378@news.speedlinq.nl> Message-ID: Stef Mientki wrote: > Maric Michaud wrote: def bit(index): >> def fset(self, value): >> value = ( value & 1L ) << index >> mask = ( 1L ) << index >> self._d = ( self._d & ~mask ) | value >> def fget(self): >> return ( self._d >> index ) & 1 >> return property(**locals()) >> >> >> class cpu_ports(object) : p1 = bit(1) p2 = bit(2) p3 = bit(3) p4 = bit(4) p5 = bit(5) > Looks good, but I miss the index :-( No more. Peter From bbxx789_05ss at yahoo.com Fri May 25 15:49:43 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 25 May 2007 12:49:43 -0700 Subject: csv.reader length? In-Reply-To: <1180118981.024036.163590@p47g2000hsd.googlegroups.com> References: <1180118981.024036.163590@p47g2000hsd.googlegroups.com> Message-ID: <1180122583.282729.275840@p47g2000hsd.googlegroups.com> On May 25, 12:49 pm, cjl wrote: > P: > > Stupid question: > > reader = csv.reader(open('somefile.csv')) > for row in reader: > do something > > Any way to determine the "length" of the reader (the number of rows) > before iterating through the rows? > > -CJL How about: f = open("somefile.csv") numlines = len(f.readlines()) From snewman18 at gmail.com Wed May 30 23:26:32 2007 From: snewman18 at gmail.com (snewman18 at gmail.com) Date: 30 May 2007 20:26:32 -0700 Subject: How to parse usenet urls? In-Reply-To: References: <1180573018.786188.220260@h2g2000hsg.googlegroups.com> Message-ID: <1180581992.342613.302370@k79g2000hse.googlegroups.com> > Are you aware of nntplib? > > http://docs.python.org/lib/module-nntplib.html I am, but I once I got into the article itself, I couldn't figure out how to "call" a link inside the resulting message text: import nntplib username = my username password = my password nntp_server = 'newsclip.ap.org' n = nntplib.NNTP(nntp_server, 119, username, password) n.group('ap.spanish.online.headlines') m_id = n.next()[1] n.article(m_id) I'll get output like this headline and full story message link: (truncated for length) >>> ... 'Castro: Bush desea mi muerte, pero las ideas no se matan', 'news://newsclip.ap.org/D8PE2G6O0 at news.ap.org', ... How can I take the message link 'news://newsclip.ap.org/ D8PE2G6O0 at news.ap.org' and follow it? From sgeiger at ncee.net Wed May 30 12:52:02 2007 From: sgeiger at ncee.net (Shane Geiger) Date: Wed, 30 May 2007 11:52:02 -0500 Subject: Creating a distro of python... What would you include in it? In-Reply-To: <740c3aec0705300943o1d42c32eje6ab054b7dd7977a@mail.gmail.com> References: <1180538748.448426.182820@g4g2000hsf.googlegroups.com> <740c3aec0705300943o1d42c32eje6ab054b7dd7977a@mail.gmail.com> Message-ID: <465DABB2.9050905@ncee.net> This is for Windows only, but since your target audience is newbies, that might be fine. Python Sumo-Distribution for Windows - Freely downloadable Python distributions for Windows with many extra packages already installed and ready for use. -- http://code.enthought.com/enthon/ BJ?rn Lindqvist wrote: > On 30 May 2007 08:25:48 -0700, farksimmons at yahoo.com > wrote: > >> I am creating a distro of Python to be licensed as GPL.... am >> wondering, what would anyone suggest as to 3rd party modules being put >> into it (non-commercial of course!)? I know I'd put MySQLdb into it at >> the very least. Any suggestions? >> > > If your distro is to be GPL-licensed, does that mean that you want > your components to be GPL too? If so, the number of components you can > select is reduced drastically. > > I'd like a distro with a good IDE, GUI toolkit (PyGTK for example), > Django and PyGame. Something you could point a newbie to and they > would be able to create "real" applications with, without needing to > download hundreds of dependencies. > > -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy -------------- next part -------------- A non-text attachment was scrubbed... Name: sgeiger.vcf Type: text/x-vcard Size: 310 bytes Desc: not available URL: From arvind1.singh at gmail.com Sun May 20 10:35:08 2007 From: arvind1.singh at gmail.com (Arvind Singh) Date: Sun, 20 May 2007 20:05:08 +0530 Subject: questions about programming styles In-Reply-To: <46501710.6090904@gmail.com> References: <46501710.6090904@gmail.com> Message-ID: On 5/20/07, fdu.xiaojf at gmail.com wrote: > which is the better way to calculate the value of attributes of a class ? > for example: > > (A) > def cal_attr(self, args): > #do some calculations > self.attr = calculated_value > and then if the vlue of attribute is needed, > self.cal_attr(args) > some_var = self.attr > or I can define cal_attr() as follows: > (B) > def cal_attr(self, args): > #do some calculations > return calculated_value > and then, if the value of attribute is needed, > self.attr = self.cal_attr(args) > some_var = self.attr The way, I get it: you are trying to *cache* the value of an *expensive* calculation. You should worry about it if only if: a. It is *really* expensive to calculate the value. b. The value is read more often then it can change. Otherwise, just don't bother with it (i.e.use some_var = obj.cal_value(*args) ). But if you really want to cache the value, maybe you should keep track if the value is valid: class C(object): def calc_attr(self, *args): """Calculates value of "attr". """ self._attr = calculated_value self._attr_valid = True def get_attr(self, *args): """Use this to get values.""" self._attr_valid or self.calc_attr(*args) return self._attr def another_method(self, *args): """Does some calculations which invalidate *cached* value of "attr". """ # do something self._attr_valid = False > (2) > when to use class methods and when to use functions ? > > In my opinion, both of class methods and functions have advantages and > disadvantages. I have to pass many arguments to a function, which is > annoying. When using class methods, the arguments can be stored as > attributes of the class, which is convenient for later use. But I have > to create an object in advance. I hope you know about all of it, but here it is, anyway: - In Python, *everything* is an object. - Whenever Python finds a class definition, it creates a *class object*. - A class objects acts as a *template* to create new objects called *instances* (of that class). - The template and the instance can both have *attributes* (to store data). - *Class attributes* can be accessed by both -- class as well as its instances. - *Instance attributes* can only be accesses by instances (because class doesn't have to know about these). - All the class attributes are shared among all the instances. If you change an attribute of a class, all the instances of that class (irrespective of when they were instantiated) will see the change. That gives us: - *Instance methods* (or simply, "methods") can access: class attributes, instance attributes, class methods, and instance methods. (And are accessible via an instance only.) - *Class methods* can ONLY access class attributes or other class methods. (And are accessible via the class or its instance.) - The first argument to instance methods is traditionally called "self" (which is an *instance object*) and that of class methods is called "cls" (which is a *class object*). Design choices: - The data which is to be shared by all the instances (and is mostly immutable) should be kept as class attribute (to minimize memory consumption). - The methods which should produce same result for all instances (and don't need to access instance attributes) should be declared as class methods. - Class attributes are also useful to *share state* among various instances (so that they can co-operate). Such "sharing functionality" is mostly implemented as class methods. It's just whatever I could recollect and thought might be relevant. I hope it helps. Arvind PS: Defining something as "property" suggests (to the class users) that it is inexpensive to access that value -- just a matter of style. From nospam at noemailhere.nowhere Wed May 16 23:31:41 2007 From: nospam at noemailhere.nowhere (Anthony Irwin) Date: Thu, 17 May 2007 13:31:41 +1000 Subject: how do I count spaces at the beginning of a string? In-Reply-To: References: <1179367338.906430.97420@k79g2000hse.googlegroups.com> Message-ID: Anthony Irwin wrote: > walterbyrd wrote: >> The strings start with whitespace, and have a '*' or an alphanumeric >> character. I need to know how many whitespace characters exist at the >> beginning of the string. >> > > Hi, > > I am new to python and just really learning but this is what I came up > with. > > #!/usr/bin/env python > > def main(): > s = " abc def ghi" > count = 0 > > for i in s: > if i == ' ': > count += 1 > else: > break > > print count > > if __name__ == '__main__': > main() > Ahh even better would be to use some of the python library functions that I am still finding more about. s = " abc def ghi" print (len(s) - len(s.lstrip())) I am really starting to like python the more I use it. -- Kind Regards, Anthony Irwin http://www.irwinresources.com http://www.makehomebusiness.com email: anthony at above domains, - www. From sgeiger at ncee.net Fri May 18 10:09:32 2007 From: sgeiger at ncee.net (Shane Geiger) Date: Fri, 18 May 2007 09:09:32 -0500 Subject: A best approach to a creating specified http post body In-Reply-To: <6e42ec490705180657h1a7d8777qe2c1fb2b6ac7fe7b@mail.gmail.com> References: <1179486210.398916.251970@o5g2000hsb.googlegroups.com> <6e42ec490705180657h1a7d8777qe2c1fb2b6ac7fe7b@mail.gmail.com> Message-ID: <464DB39C.6040008@ncee.net> Why not use scotch.recorder? Dave Borne wrote: >> I need to build a special http post body that consists of : >> name=value +\r\n strings. >> Problem is that depending on operations the number of name,value >> pairs can increase and decrease. >> Values need to be initialized at runtime, so storing premade text >> files is not possible. >> > > I'm not completely understanding your problems here. Can you explain > why urllib.urlencode wouldn't work? > (http://docs.python.org/lib/module-urllib.html) > > Thanks, > -Dave > -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy -------------- next part -------------- A non-text attachment was scrubbed... Name: sgeiger.vcf Type: text/x-vcard Size: 310 bytes Desc: not available URL: From mcl.office at googlemail.com Thu May 31 13:25:35 2007 From: mcl.office at googlemail.com (mosscliffe) Date: 31 May 2007 10:25:35 -0700 Subject: HTML Form/Page and Navigation with multiple buttons In-Reply-To: References: <1180617750.709628.180070@p77g2000hsh.googlegroups.com> <465edbfa$0$784$426a34cc@news.free.fr> <1180624671.896662.174390@m36g2000hse.googlegroups.com> Message-ID: <1180632334.966554.263500@w5g2000hsg.googlegroups.com> On May 31, 5:19 pm, Steve Holden wrote: > mosscliffe wrote: > > Excellent - thanks for all your help. I now have a form created by a > > python script executing an HTML page, doing everything I need, except > > for Session Data (probably use hidden fields ?? future research) and > > the actual paging logic !!! > > In fact you should find you can name all of the buttons the same. Then > when you click one the value associated with that name tells you which > button the user pressed. > > Just don't call your button "submit", since that masks a JavaScript form > method that you will probably end up using sooner or later. > > > If I use a link. I have to add all my hidden fields to the query > > string, otherwise cgi.FieldStorage(), does not return the hidden > > fields. This would also mean users see all the hidden field data. > > > Is there another way, other than a cookie ? > > > Why is a link better than a button ? > > Beats me why you got that advice. Buttons are perfectly adequate for > that purpose. > > However, you can if you want use links with "javascript: ..." href > values to accomplish local scripting which can do funky stuff like > setting form field values and submitting the form. This can get tricky > though, and it sounds like you are maybe a little too new to the web to > be messing with client-side scripting. Later ... > > > I have been using 'post' for my form, to eliminate the displaying of > > field values. > > That does make the location bar easier on the user's eye, and is the > standard way to proceed. It doesn't add anything in the way of security, > however. > > > I accept I am quite niave about FORM/HTML logic. > > We all have to start somewhere! > > 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 your way to fame!! > holdenweb.blogspot.com squidoo.com/pythonology > tagged items: del.icio.us/steve.holden/python > All these services currently offer free registration! > -------------- Thank You for Reading ---------------- Mr Holden, Thanks for the button naming tip. Just aquired your book, so hopefully I will need to ask less questions in the future. Sorting out some sort of session management is my next task. Being a bit old fashioned, I am against javascript, because I need my site to work with simple mobile phone browsers, which do not always support javascript. Richard From exarkun at divmod.com Tue May 8 14:44:49 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 8 May 2007 14:44:49 -0400 Subject: Setting up python socket server with non-standard termination string. In-Reply-To: <1178632766.853553.322660@q75g2000hsh.googlegroups.com> Message-ID: <20070508184449.19381.375453952.divmod.quotient.10169@ohm> On 8 May 2007 06:59:26 -0700, indy1000 at gmail.com wrote: >Hi, > >I'm trying to create a tcp/ip port listening socket server for various >cellular devices that don't use the standard "\r\n" termination string >at the end of their message. Instead, they use "-ND-". Do you know >how I can setup such a server, preferably using either 'socket.py', >'serversocket.py' or 'twisted.py'? You can use the LineReceiver (or LineOnlyReceiver) from Twisted to do this quite easily: from twisted.internet import reactor from twisted.internet.protocol import ServerFactory from twisted.protocols.basic import LineOnlyReceiver class CellProtocol(LineOnlyReceiver): delimiter = '-ND-' def lineReceived(self, line): print 'got a line' f = ServerFactory() f.protocol = CellProtocol reactor.listenTCP(12345, f) reactor.run() Jean-Paul From godzillaismad at gmail.com Fri May 11 00:18:31 2007 From: godzillaismad at gmail.com (Godzilla) Date: 10 May 2007 21:18:31 -0700 Subject: how to use cx_Oracle callfunc In-Reply-To: <1178848279.652462.291690@e51g2000hsg.googlegroups.com> References: <1178848279.652462.291690@e51g2000hsg.googlegroups.com> Message-ID: <1178857111.377900.178290@p77g2000hsh.googlegroups.com> On May 11, 11:51 am, Godzilla wrote: > Hi all, > > I need to know how to use the method callfunc in cx_Oracle. I am > trying to get a primary key after an insert via a function call, but I > do not know how to pass the return value from the function via the > callfunc method. Can anyone help? > > I also tried the execute(), and callproc(), but to no avail. My > function is as below: > > create or replace function addRow(desc table1.col1%type) return number > is id number; > begin > insert into table1 (description) values (desc) returning table1ID > into id; > return(id); > exception > when others then return(-1) > end; > > The code in the callfunc: > > cur.callfunc("addRow", returnType, param) > > Question is: > - What is returnType and how to I declare that before passing into the > function? > - How do I define the parameters? > > I tried the setinputsizes and setoutputsize, but I keep getting errors > saying the parameter is incorrectly defined. Please help. Thank. Hello, found a solution in another thread... see http://groups.google.com/group/comp.lang.python/browse_thread/thread/ab13d3364aafdd28/4ca1fde2069ff3da?lnk=st&q=cx_oracle+how+to+setinputsizes&rnum=9&hl=en#4ca1fde2069ff3da for more info. Thanks. From ptmcg at austin.rr.com Sat May 26 22:58:59 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 26 May 2007 19:58:59 -0700 Subject: ten small Python programs In-Reply-To: References: <1180229019.873381.52800@m36g2000hse.googlegroups.com> Message-ID: <1180234739.661905.31890@q66g2000hsg.googlegroups.com> Out of curiosity, how does this style jibe with the latest embracing of Unicode identifiers? Ever tried to type an underscore on a non-US keyboard? I have a heck of a time finding/typing the '_' character when I visit our clients in Germany, but this may just be my own personal Amerocentric issue (I also get messed up by the transposition of Y and Z on German keyboards, but my German colleagues understandably are not bothered by it). For someone already familiar with that keyboard layout, is typing an underscore any more difficult than my pressing Shift-_ on my US keyboard? -- Paul From silverburgh.meryl at gmail.com Thu May 24 11:36:10 2007 From: silverburgh.meryl at gmail.com (silverburgh.meryl at gmail.com) Date: 24 May 2007 08:36:10 -0700 Subject: How can I time a method of a class in python using Timeit Message-ID: <1180020970.039576.319230@m36g2000hse.googlegroups.com> Hi, I am using timeit to time a global function like this t = timeit.Timer("timeTest()","from __main__ import timeTest") result = t.timeit(); But how can i use timeit to time a function in a class? class FetchUrlThread(threading.Thread): def aFunction(self): # do something .... def run(self): # how can I time how long does aFunction() take here? aFunction(); Thank you. From mail at timgolden.me.uk Wed May 2 11:41:55 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 02 May 2007 16:41:55 +0100 Subject: Active Directory: how to delete a user from a group? In-Reply-To: <1178119465.469546.275440@e65g2000hsc.googlegroups.com> References: <1178119465.469546.275440@e65g2000hsc.googlegroups.com> Message-ID: <4638B143.9040805@timgolden.me.uk> Dirk Hagemann wrote: > Hi! > > Does anyone has experience with manipulating MS Active Directory > objects? I'd like to delete some users from a group, but so far I > couldn't find anything about this. > There is some good stuff about retrieving data out of the AD (thanks > to Tim Golden!), but how can I manipulate or change AD objects like > users, computers and groups with Python? Is there somewhere a > documentation or some code? I freely admit I don't do too much changing of AD objects, but my module should at least support the methods for doing things. Some examples in Active Directory Cookbook: http://techtasks.com/code/viewbook/2 To delete a user, apparently: import active_directory user = active_directory.find_user ("name-of-user") # or user = active_directory.AD_object ("user-moniker") user.DeleteObject (0) TJG From joeedh at gmail.com Fri May 11 15:38:52 2007 From: joeedh at gmail.com (Joe Eagar) Date: Fri, 11 May 2007 12:38:52 -0700 Subject: test Message-ID: <4644C64C.3000504@gmail.com> sorry just a test. Joe From gagsl-py2 at yahoo.com.ar Sun May 20 14:28:14 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 20 May 2007 15:28:14 -0300 Subject: Inverse of id()? References: <1179618173.280286.284120@n59g2000hsh.googlegroups.com> Message-ID: En Sat, 19 May 2007 20:42:53 -0300, Paul McGuire escribi?: >>>> z = id(results) >>>> for x in globals().values(): > ... if id(x)==z: break > ... > > This gives me a variable x that is indeed another ref to the results > variable: >>>> x is results > True >>>> x.x > 123 > > Now is there anything better than this search technique to get back a > variable, given its id? py> class A:pass ... py> class B:pass ... py> a=A() py> id(a) 10781400 py> del a py> b=B() py> id(b) 10781400 Now if you look for id=10781400 you'll find b, which is another, absolutely unrelated, object. Enabling this pointer -> objects ability would bring into Python the "wild pointer" nightmare of C programs... -- Gabriel Genellina From sturlamolden at yahoo.no Sat May 19 07:05:06 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 19 May 2007 04:05:06 -0700 Subject: Anti-Aliasing in wxPython? In-Reply-To: <0brr43to59ltspg1g7cu32jpgqrbonandj@4ax.com> References: <0brr43to59ltspg1g7cu32jpgqrbonandj@4ax.com> Message-ID: <1179572706.362372.246110@h2g2000hsg.googlegroups.com> On May 18, 8:20 pm, Alexander D?nisch wrote: > i haven't found anything like this in wxPython yet. > Thanks wxPython uses native widgets, so it is OS dependent. You will have to turn it in Windows, MacOSX (on by default?) or GNOME. From nagle at animats.com Sat May 26 03:27:31 2007 From: nagle at animats.com (John Nagle) Date: Sat, 26 May 2007 00:27:31 -0700 Subject: Large Amount of Data In-Reply-To: References: Message-ID: Jack wrote: > I need to process large amount of data. The data structure fits well > in a dictionary but the amount is large - close to or more than the size > of physical memory. I wonder what will happen if I try to load the data > into a dictionary. Will Python use swap memory or will it fail? > > Thanks. What are you trying to do? At one extreme, you're implementing something like a search engine that needs gigabytes of bitmaps to do joins fast as hundreds of thousands of users hit the server, and need to talk seriously about 64-bit address space machines. At the other, you have no idea how to either use a database or do sequential processing. Tell us more. John Nagle From Edwin.Madari at VerizonWireless.com Mon May 7 12:35:40 2007 From: Edwin.Madari at VerizonWireless.com (Edwin.Madari at VerizonWireless.com) Date: Mon, 7 May 2007 12:35:40 -0400 Subject: building python from source on HP Message-ID: <20070507164542.B34111E400C@bag.python.org> appreciate hints or pointers for building python on HP. running 'make test' fails with following cryptic message, after running configure, & make. Attempting to build python from source on HP-UX B.11.11 U 9000/800 3314646674 unlimited-user license *** Error exit code 1 Stop. not sure if output from configure and make would make a difference. If so I can send them. thanks in advance Edwin 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. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Wed May 2 03:09:08 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 02 May 2007 04:09:08 -0300 Subject: Why are functions atomic? References: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> <1178044821.864741.235260@o5g2000hsb.googlegroups.com> <1178063341.779617.289690@o5g2000hsb.googlegroups.com> <1178065685.161372.81790@y80g2000hsf.googlegroups.com> <463816a9$0$9276$9b622d9e@news.freenet.de> Message-ID: En Wed, 02 May 2007 01:42:17 -0300, Martin v. L?wis escribi?: > Michael schrieb: >> A bit more info, but still no clear picture about why functions are >> mutable but have immutable copy symantics. There are arguments why >> functions should be immutable, but the decision was to make user- >> defined functions mutable. My question is still: why the present >> ummutable copy symantics? > > The answer is really really simple. The implementation of copy predates > mutability. When the copy code was written, functions *were* immutable. > When functions became mutable, the copy code was not changed, and > nobody noticed or complained. Likely scenario, but not true. Support for copying user functions was added on 2.5 (see http://svn.python.org/view/python/trunk/Lib/copy.py?rev=42573&r1=38995&r2=42573) and functions were mutable since a long time ago. On previous versions, functions could be pickled but not copied. The same thing happens for classes: they are mutable too, but copy considers them immutable and returns the same object. This is clearly stated on the documentation (but the module docstring is still outdated). -- Gabriel Genellina From aldo at nullcube.com Wed May 16 00:49:23 2007 From: aldo at nullcube.com (Aldo Cortesi) Date: Wed, 16 May 2007 14:49:23 +1000 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1hy69gm.eh6m866urk03N%aleax@mac.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1hy2qg3.iqfvwnrvr9kjN%aleax@mac.com> <1hy69gm.eh6m866urk03N%aleax@mac.com> Message-ID: <20070516044923.GA29008@nullcube.com> Thus spake Alex Martelli (aleax at mac.com): > I can't find any reference for Steven's alleged idiomatic use of "by > eye", either -- _however_, my wife Anna (an American from Minnesota) > came up with exactly the same meaning when I asked her if "by eye" had > any idiomatic connotations, so I suspect it is indeed there, at least in > the Midwest. Funniest, of course, is that the literal translation into > Italian, "a occhio", has a similiar idiomatic meaning to _any_ native > speaker of Italian -- and THAT one is even in the Italian wikipedia!-) > > I'll be the first to admit that this issue has nothing to do with the > substance of the argument (on which my wife, also my co-author of the > 2nd ed of the Python Cookbook and a fellow PSF member, deeply agrees > with you, Aldo, and me), but natural language nuances and curios are my > third-from-the-top most consuming interest (after programming and... > Anna herself!-). I must admit to a fascination with language myself - I even have a degree in English literature to prove it! To be fair to Steven, I've asked some of my colleagues here in Sydney about their reactions to the phrase "by eye", and none of them have yet come up with anything that has the strong pejorative taint Steven gave it. At any rate, it's clear that the phrase is not well defined anywhere (not even in the OED), and I'm sure there are substantial regional variations in interpretation. In cases like these, however, context is paramount, so I will quote sentences that started this petty bickering: > The security implications have not been sufficiently explored. I don't want > to be in a situation where I need to mechanically "clean" code (say, from a > submitted patch) with a tool because I can't reliably verify it by eye. Surely, in context, the meaning is clear? "By eye" here means nothing more nor less than a literal reading suggests. Taking these sentences to be an argument for a slip-shod, careless approach to code, as Steven did, is surely perverse. Regards, Aldo -- Aldo Cortesi aldo at nullcube.com http://www.nullcube.com Mob: 0419 492 863 From aisaac at american.edu Wed May 9 22:47:51 2007 From: aisaac at american.edu (Alan Isaac) Date: Thu, 10 May 2007 02:47:51 GMT Subject: change of random state when pyc created?? References: <5ae25fF2oggbqU1@mid.uni-berlin.de> Message-ID: "Robert Kern" wrote in message news:mailman.7497.1178763539.32031.python-list at python.org... > Actually, the root cause of Peter's specific example is the fact that the > default implementation of __hash__() and __eq__() rely on identity comparisons. > Two separate invocations of the same script give different objects by identity > and thus the "history of insertions and deletions" is different. OK. Thank you. Alan From paul at science.uva.nl Mon May 7 04:44:35 2007 From: paul at science.uva.nl (Paul Melis) Date: Mon, 07 May 2007 10:44:35 +0200 Subject: Properties on old-style classes actually work? Message-ID: Hello, The python library docs read in section 2.1 (http://docs.python.org/lib/built-in-funcs.html): " ... property( [fget[, fset[, fdel[, doc]]]]) Return a property attribute for new-style classes (classes that derive from object). ... " But in 2.4 at least properties also seem to work for old-style classes: class O: def __init__(self): self._x = 15 def get_x(self): return self._x x = property(get_x) o = O() print o.x outputs "15" as expected for the property. Regards, Paul From sjmachin at lexicon.net Sat May 19 21:16:06 2007 From: sjmachin at lexicon.net (John Machin) Date: Sun, 20 May 2007 11:16:06 +1000 Subject: converting strings to most their efficient types '1' --> 1, 'A' ---> 'A', '1.2'---> 1.2 In-Reply-To: <1179551680.283157.19000@y80g2000hsf.googlegroups.com> References: <1179529661.555196.13070@k79g2000hse.googlegroups.com> <1179551680.283157.19000@y80g2000hsf.googlegroups.com> Message-ID: <464FA156.2070704@lexicon.net> On 19/05/2007 3:14 PM, Paddy wrote: > On May 19, 12:07 am, py_genetic wrote: >> Hello, >> >> I'm importing large text files of data using csv. I would like to add >> some more auto sensing abilities. I'm considing sampling the data >> file and doing some fuzzy logic scoring on the attributes (colls in a >> data base/ csv file, eg. height weight income etc.) to determine the >> most efficient 'type' to convert the attribute coll into for further >> processing and efficient storage... >> >> Example row from sampled file data: [ ['8','2.33', 'A', 'BB', 'hello >> there' '100,000,000,000'], [next row...] ....] >> >> Aside from a missing attribute designator, we can assume that the same >> type of data continues through a coll. For example, a string, int8, >> int16, float etc. >> >> 1. What is the most efficient way in python to test weather a string >> can be converted into a given numeric type, or left alone if its >> really a string like 'A' or 'hello'? Speed is key? Any thoughts? >> >> 2. Is there anything out there already which deals with this issue? >> >> Thanks, >> Conor > > You might try investigating what can generate your data. With luck, > it could turn out that the data generator is methodical and column > data-types are consistent and easily determined by testing the > first or second row. At worst, you will get to know how much you > must check for human errors. > Here you go, Paddy, the following has been generated very methodically; what data type is the first column? What is the value in the first column of the 6th row likely to be? "$39,082.00","$123,456.78" "$39,113.00","$124,218.10" "$39,141.00","$124,973.76" "$39,172.00","$125,806.92" "$39,202.00","$126,593.21" N.B. I've kindly given you five lines instead of one or two :-) Cheers, John From johnjsal at NOSPAMgmail.com Wed May 9 10:34:22 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 09 May 2007 10:34:22 -0400 Subject: Suggestions for how to approach this problem? In-Reply-To: <1178656468.602613.4740@y80g2000hsf.googlegroups.com> References: <4640ca5b$0$23392$c3e8da3@news.astraweb.com> <4640d69b$0$31446$c3e8da3@news.astraweb.com> <1178656468.602613.4740@y80g2000hsf.googlegroups.com> Message-ID: <4641dbc1$0$8784$c3e8da3@news.astraweb.com> Dave Hansen wrote: > Questions: > > 1) Do the citation numbers always begin in column 1? Yes, that's one consistency at least. :) > 2) Are the citation numbers always followed by a period and then at > least one whitespace character? Yes, it seems to be either one or two whitespaces. > find the beginning of each cite. then I would output each cite > through a state machine that would reduce consecutive whitespace > characters (space, tab, newline) into a single character, separating > each cite with a newline. Interesting idea! I'm not sure what "state machine" is, but it sounds like you are suggesting that I more or less separate each reference, process it, and then rewrite it to a new file in the cleaner format? That might work pretty well. From Alexandre.Bergel at hpi.uni-potsdam.de Fri May 11 10:04:55 2007 From: Alexandre.Bergel at hpi.uni-potsdam.de (Alexandre Bergel) Date: Fri, 11 May 2007 16:04:55 +0200 Subject: Dyla'07: 3rd Workshop on Dynamic Languages and Applications Message-ID: <46F1207E-CD01-41B5-9A20-95D7DBB3CB59@hpi.uni-potsdam.de> Dear colleague, Please, note that after the workshop, best papers will be selected, and a second deadline will then be set regarding preparation of the Electronic Communications of the EASST. Note that we submission deadline has been extended. The important dates: - May 27: deadline for the workshop submissions. Submissions should follow LNCS format (www.springer.com/lncs) and should be sorter than 10 pages. **extended deadline** - June 12-13: Author notification of their submission - June 15, 2007: ECOOP'07 Early Registration - July 31: Workshop - August 5: Selection of best papers for Electronic Communications of the EASST - September 10: deadline for revised and extended version of submission for the communications. Regards, Dyla organisers ********************************************************* Call for Papers Dyla 2007: 3rd Workshop on Dynamic Languages and Applications July 31, 2007, Berlin (Collocated with ECOOP 2007) http://dyla2007.unibe.ch ********************************************************* Objective ========= The goal of this workshop is to act as a forum where we can discuss new advances in the conception, implementation and application of object-oriented languages that radically diverge from the statically typed class-based reflectionless doctrine. The goal of the workshop is to discuss new as well as older "forgotten" languages and features in this context. Topics of interest include, but are certainly not limited to: - agents, actors, active objects, distribution, concurrency and mobility - delegation, prototypes, mixins - first-class closures, continuations, environments - reflection and meta-programming - (dynamic) aspects for dynamic languages - higher-order objects & messages - ... other exotic dynamic features which you would categorize as OO - multi-paradigm & static/dynamic-marriages - (concurrent/distributed/mobile/aspect) virtual machines - optimisation of dynamic languages - automated reasoning about dynamic languages - "regular" syntactic schemes (cf. S-expressions, Smalltalk, Self) - Smalltalk, Python, Ruby, Scheme, Lisp, Self, ABCL, Prolog, ... - ... any topic relevant in applying and/or supporting dynamic languages. We solicit high-quality submissions on research results and/or experience. Submitted papers must be unpublished and not submitted for publication elsewhere. Submissions should not exceed 10 pages, LNCS format (www.springer.com/lncs). Submission ========== Prospective attendees are requested to submit a position paper or an essay (max 10 pages, references included) on a topic relevant to the workshop to Alexandre Bergel (Alexandre.Bergel at cs.tcd.ie). Submissions are demanded to be in .pdf format and should arrive before May 13, 2007. A selection of the best papers will be made, which will require an extension for an inclusion in a special issue in Electronic Communications of the EASST (eceasst.cs.tu-berlin.de). For this purpose, a new deadline will be set after the workshop. Moreover, Springer publishes a Workshop-Reader (as in the case of previous ECOOPs) which appears after the Conference and which contains Workshop-Reports (written by the organizers) and not the position papers submitted by the participants. Important dates =============== May 27, 2007: deadline for the workshop submissions. Submissions should follow LNCS format (www.springer.com/lncs) and should be sorter than 10 pages. **extended deadline** June 12-13, 2007: Author notification of their submission June 15, 2007: ECOOP'07 Early Registration July 31, 2007: Workshop August 05, 2007: Selection of best papers for Electronic Communications of the EASST September 10, 2007: deadline for revised and extended version of submission for the communications. Organisers ========== Alexandre Bergel Wolfgang De Meuter St?phane Ducasse Oscar Nierstrasz Roel Wuyts Program committee ================= Alexandre Bergel (Hasso-Plattner-Institut, University of Potsdam, Germany) Johan Brichau (Universit? catholique de Louvain, Belgium) Pascal Costanza (Vrije Universiteit Brussel, Belgium) Wolfgang De Meuter (Vrije Universiteit Brussel, Belgium) St?phane Ducasse (University of Savoie, France) Erik Ernst (University of Aarhus, Denmark) Robert Hirschfeld (Hasso-Plattner-Institut, University of Potsdam, Germany) Oscar Nierstrasz (University of Bern, Switzerland) Matthew Flatt (University of Utah, USA) Dave Thomas (Bedarra Research Labs, Canada) Laurence Tratt (King's College London, UK) Roel Wuyts (IMEC & Universit? Libre de Bruxelles, Belgium) -- _,.;:~^~:;._,.;:~^~:;._,.;:~^~:;._,.;:~^~:;._,.;: Alexandre Bergel http://www.software-artist.eu ^~:;._,.;:~^~:;._,.;:~^~:;._,.;:~^~:;._,.;:~^~:;. From castironpi at gmail.com Sat May 5 20:29:21 2007 From: castironpi at gmail.com (castironpi at gmail.com) Date: 5 May 2007 17:29:21 -0700 Subject: module console Message-ID: <1178411361.485947.251940@w5g2000hsg.googlegroups.com> Can I get the console to behave like it's in a module? So far I have inspect.getsource() working by setting the filename and linenumbers of the return from compiler.parse(). I'm looking too. -me From grante at visi.com Wed May 9 21:25:04 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 10 May 2007 01:25:04 -0000 Subject: Single precision floating point calcs? References: <1343v0emvdjr545@corp.supernews.com> Message-ID: <1344t3gauu8b486@corp.supernews.com> On 2007-05-09, Terry Reedy wrote: >| I'm pretty sure the answer is "no", but before I give up on the >| idea, I thought I'd ask... >| >| Is there any way to do single-precision floating point >| calculations in Python? > > Make your own Python build from altered source. And run it on > an ancient processor/OS/C compiler combination that does not > automatically convert C floats to double when doing any sort > of calculation. It wouldn't have to be that ancient. The current version of gcc supports 32-bit doubles on quite a few platforms -- though it doesn't seem to for IA32 :/ Simply storing intermediate and final results as single-precision floats would probably be sufficient. > Standard CPython does not have C single-precision floats. I know. > The only point I can think of for doing this with single numbers, as > opposed to arrays of millions, is to show that there is no point. I use Python to test algorithms before implementing them in C. It's far, far easier to do experimentation/prototyping in Python than in C. I also like to have two sort-of independent implementations to test against each other (it's a good way to catch typos). In the C implementations, the algorithms will be done implemented in single precision, so doing my Python prototyping in as close to single precision as possible would be "a good thing". > Or do you have something else in mind? -- Grant Edwards grante Yow! Yow! Is my fallout at shelter termite proof? visi.com From s.mientki at id.umcn.nl Tue May 22 11:00:28 2007 From: s.mientki at id.umcn.nl (stef) Date: Tue, 22 May 2007 17:00:28 +0200 Subject: drag and drop with wxPython ? Message-ID: hello, I'm trying to move from Delphi to Python (move from MatLab to Python already succeeded, also thanks to this discussion group). From the discussions in this list about "the best" GUI for Python, it now seems to me that wxPython is th? choice for my kind of applications. I've no experience with wxPython yet, I just run a few examples and indeed it looks good (as expected from the discussions in this list). What I really need at this moment for a new project, (and I coulnd't find any example, lot of broken links ;-) is how to implement some drag & drop facilities, both to drag and drop normal button, but also to drag and drop some dynamically created objects. Just like a CAD program, but far more simpler. Does anyone has an example how to drag & drop components with wxPython ? thanks, Stef Mientki From deets at nospam.web.de Wed May 9 08:45:12 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 09 May 2007 14:45:12 +0200 Subject: Boolean confusion References: Message-ID: <5adu2oF2p0j69U1@mid.uni-berlin.de> Greg Corradini wrote: > > Hello all, > I'm having trouble understanding why the following code evaluates as it > does: > >>>> string.find('0200000914A','.') and len('0200000914A') > 10 > True >>>> len('0200000914A') > 10 and string.find('0200000914A','.') > -1 > > In the 2.4 Python Reference Manual, I get the following explanation for > the 'and' operator in 5.10 Boolean operations: > " The expression x and y first evaluates x; if x is false, its value is > returned; otherwise, y is evaluated and the resulting value is returned." > > Based on what is said above, shouldn't my first expression ( > string.find('0200000914A','.') and len('0200000914A') > 10) evaluate to > false b/c my 'x' is false? And shouldn't the second expression evaluate to > True? The first evaluates to True because len(...) > 10 will return a boolean - which is True, and the semantics of the "and"-operator will return that value. And that precisely is the reason for the -1 in the second expression. y=-1 and it's just returned by the and. in python, and is implemented like this (strict evaluation nonwithstanding): def and(x, y): if bool(x) == True: return y return x Diez From stugots at qwest.net Wed May 30 11:30:01 2007 From: stugots at qwest.net (John DeRosa) Date: Wed, 30 May 2007 08:30:01 -0700 Subject: Is PEP-8 a Code or More of a Guideline? References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <5c1jpkF2tl0ilU1@mid.individual.net> Message-ID: +1 QOTW On Wed, 30 May 2007 06:18:36 GMT, Tim Roberts wrote: >Frank Swarbrick wrote: >> >>Then you'd really love COBOL! >> >>:-) >> >>Frank >>COBOL programmer for 10+ years > >Hey, did you hear about the object-oriented version of COBOL? They call it >"ADD ONE TO COBOL". From stefan.behnel-n05pAM at web.de Tue May 15 05:05:23 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 15 May 2007 11:05:23 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> <4648294F.2000704@web.de> <46487a6c$0$2400$426a74cc@news.free.fr> Message-ID: <464977D3.6010703@web.de> Eric Brunel wrote: > You have a point here. When learning to program, or when programming for > fun without any intention to do something serious, it may be better to > have a language supporting "native" characters in identifiers. My > problem is: if you allow these, how can you prevent them from going > public someday? My personal take on this is: search-and-replace is easier if you used well chosen identifiers. Which is easier if you used your native language for them, which in turn is easier if you can use the proper spellings. So I don't see this problem getting any worse compared to the case where you use a transliteration or even badly chosen english-looking identifiers from a small vocabulary that is foreign to you. For example, how many German names for a counter variable could you come up with? Or english names for a function that does domain specific stuff and that was specified in your native language using natively named concepts? Are you sure you always know the correct english translations? I think native identifiers can help here. Using them will enable you to name things just right and with sufficient variation to make a search-and-replace with english words easier in case it ever really becomes a requirement. Stefan From ceball at gmail.com Sun May 6 04:39:54 2007 From: ceball at gmail.com (Chris) Date: 6 May 2007 01:39:54 -0700 Subject: Strange terminal behavior after quitting Tkinter application In-Reply-To: References: <1178257164.415485.155290@q75g2000hsh.googlegroups.com> <1178290933.793501.110130@c35g2000hsg.googlegroups.com> <1178332719.691025.321370@p77g2000hsh.googlegroups.com> Message-ID: <1178440794.659370.47230@y5g2000hsa.googlegroups.com> On May 5, 2:21 pm, Dennis Lee Bieber wrote: > On 4 May 2007 19:38:39 -0700, Chris declaimed the > following in comp.lang.python: > > > > > Thanks, but I was just explaining why I don't want to call mainloop(). > > In my original example, I can type Application() at the interactive > > prompt and get a GUI (which seems to work apart from not quitting > > properly and leaving a messed-up terminal on some versions of linux) > > while still being able to use the interactive interpreter. > > I guess I'm confused by "while still being able to use the > interactive interpreter"... Unless your "Application()" starts a > separate thread to handle the GUI interaction, the interpreter itself > will not interact until it exits and returns control to the interpreter. Maybe the Python interpreter is setup specially for Tkinter, I don't know - but one can definitely have a Tkinter GUI working and use the interpreter too (by not calling mainloop()). The Application example in my first post works (except for the messed-up terminal) and the interpreter is not blocked. Perhaps it becomes necessary to call update or update_idletasks() after some operations for the GUI to update itself - I'm not entirely sure (I haven't been able to find any documentation) - but apart from that there are no problems I know about. > > > I need to find out what cleanup is performed after mainloop() exists, > > I guess. > > If you are calling it, it "exists"... Whether it "exits" is > another matter > > > > > Incidentally, I found the information in the thread > >http://thread.gmane.org/gmane.comp.python.scientific.user/4153 > > quite useful regarding mainloop() and being able to use python > > interactively from the prompt while still having a GUI. > > I'll admit to being surprised at seeing a claim that a tkinter > application, started within an interactive session, without a mainloop, > even runs... I could see it maybe happening from Idle, since Idle is > running a tkinter mainloop, so the application bindings may have just > become "added widgets" to the Idle loop (but of course, a second > mainloop would conflict heavily). You can try by building a working Tkinter GUI interactively from the standard Python interpreter, and see that the GUI works (i.e. processes events) at the same time. > That link reads as if the IronPython interpreter can be started with > a wx/gtk mainloop already running as a thread -- so any application code > might, as with my tkinter/Idle thoughts, be added to the already running > loop. I don't know how ipython works, just that it allows a GUI and interpreter to work together for wxpython (whereas usually you can only use a GUI and the python interpreter when the GUI is Tkinter). Chris From fumanchu at amor.org Wed May 23 11:35:25 2007 From: fumanchu at amor.org (fumanchu) Date: 23 May 2007 08:35:25 -0700 Subject: Cherrypy setup questions In-Reply-To: Message-ID: <1179934525.187552.177730@w5g2000hsg.googlegroups.com> On May 23, 6:11 am, Brian Blais wrote: > fumanchu wrote: > > > On May 22, 6:38 pm, Brian Blais wrote: > >> I'd like to start trying out some cherrypy apps, but I've > >> been having some setup problems. I think I need some > >> bone-head simple example to clear my understanding. :) > >> 1) can I configure cherrypy to look at requests only > >> off a base url, like: > >> > >> http://www.provider.com:8080/~myusername/apps > > > > Yes, you can. Assuming you're using the "cherrypy.quickstart" > > function, supply the "base url" in the "script_name" argument; for > > example: > > > > sn = 'http://www.provider.com:8080/~myusername/apps' > > cherrypy.quickstart(Root(), sn, config) > > > > Thanks for your reply, but for some reason it is not > working as stated. I'm probably missing something. No, you're not missing anything; my fault. I wasn't very awake when I wrote that, I guess. Don't include the hostname, just write: sn = '/~myusername/apps' cherrypy.quickstart(Root(), sn, config) > When I start, I usually get: > The Application mounted at '' has an empty config. That's normal behavior; just a warning, not an error. Robert Brewer System Architect Amor Ministries fumanchu at amor.org From rfg007 at gmail.com Wed May 30 08:04:52 2007 From: rfg007 at gmail.com (rfg007 at gmail.com) Date: 30 May 2007 05:04:52 -0700 Subject: Tkinter Listbox - Different Text colors in one listbox In-Reply-To: <1180458123.139727.182500@d30g2000prg.googlegroups.com> References: <1180458123.139727.182500@d30g2000prg.googlegroups.com> Message-ID: <1180526692.171952.310950@w5g2000hsg.googlegroups.com> On May 29, 2:02 pm, rahulna... at yahoo.com wrote: > Hi, > Is it possible to havedifferentitems in alistboxindifferentcolors? Or is it justonecolor for all items in alistbox? > Thanks > Rahul from Tkinter import * root = Tk() l = Listbox(root) l.pack() for x in range(10): l.insert(END, x) l.itemconfig(2, bg='red', fg='white') l.itemconfig(4, bg='green', fg='white') l.itemconfig(5, bg='cyan', fg='white') root.mainloop() You can _only_ configurate 'background', 'foreground', 'selectbackground', 'selectforegroud', not font :( HTH From __peter__ at web.de Fri May 4 17:46:21 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 04 May 2007 23:46:21 +0200 Subject: adding methods at runtime and lambda References: <1178221975.149008.192410@y5g2000hsa.googlegroups.com> <1178300759.455134.60560@n59g2000hsh.googlegroups.com> <1178311451.947716.231640@q75g2000hsh.googlegroups.com> Message-ID: Mike wrote: > I just realized in working with this more that the issues I was having > with instancemethod and other things seems to be tied solely to What you describe below is a function that happens to be an attribute of an instance. There are also "real" instance methods that know about "their" instance: >>> import new >>> class A(object): ... def __init__(self, name): ... self.name = name ... >>> def method(self): # a function... ... print self.name ... >>> a = A("alpha") >>> b = A("beta") >>> a.method = new.instancemethod(method, a) # ...turned into a method... >>> a.method() alpha >>> b.method() # ... but only known to a specific instance of A Traceback (most recent call last): File "", line 1, in AttributeError: 'A' object has no attribute 'method' > builtins like dict or object. I remember at some point just doing > something like: > > x.fn = myfnFunction > > and having it just work. With the caveat that x.fn is now an alias for myfnFunction, but doesn't get x passed as its first argument (conventionally named 'self') and therefore has no knowledge of the instance x. > If I do that with an instance of generic > object however, I get an AttributeError. So: > > x = object() > x.fn = myFn > > blows up. However, if I do > > class nc(object):pass > x = nc() > x.fn = myFn > > Then all is well. > > checking for an ability on somebody is as simple as > > 'fn' in dir(x) > > or > > hasattr(x, 'fn') > > > I had thought this was a lot easier than I was making it out to be. > What I don't know is why using an object derived from object allows > you to dynamically add methods like this but the base object does not. > At this point it is more of a curiosity than anything, but if somebody > knows the answer off the top of their head, that would be great. Arbitrary instance attributes are implemented via a dictionary (called __dict__), and that incurs a certain overhead which is sometimes better to avoid (think gazillion instances of some tiny class). For example, tuples are derived from object but don't have a __dict__. As a special case, what would happen if dict were to allow attributes? It would need a __dict__ which would have a __dict__ which would have... As a consequence object could no longer be the base class of all (newstyle) classes. Peter From bscrivener42 at gmail.com Mon May 28 17:35:07 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: 28 May 2007 14:35:07 -0700 Subject: Tkinter error Message-ID: <1180388107.105473.203510@h2g2000hsg.googlegroups.com> Finally started trying to build a simple gui form for inserting text data into a mysql db of quotations. I found this nice Tkinter tutorial, http://www.ibiblio.org/obp/py4fun/gui/tkPhone.html but midway I'm getting an error. from Tkinter import * >>> win = Tk() >>> f = Frame(win) >>> b1 = Button(f, "One") Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 1936, in __init__ Widget.__init__(self, master, 'button', cnf, kw) File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 1859, in __init__ BaseWidget._setup(self, master, cnf) File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 1839, in _setup if cnf.has_key('name'): AttributeError: 'str' object has no attribute 'has_key' From steve at REMOVEME.cybersource.com.au Thu May 3 23:50:19 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Fri, 04 May 2007 13:50:19 +1000 Subject: Decorating class member functions References: <1178241696.641350.292210@n59g2000hsh.googlegroups.com> <1178244237.702552.201410@l77g2000hsb.googlegroups.com> <1178245732.628599.251020@l77g2000hsb.googlegroups.com> Message-ID: On Thu, 03 May 2007 19:28:52 -0700, Andy Terrel wrote: > I just need to keep the state around. I make a call to some function > that is pretty expensive so I want to save it as a member during the > __init__ of the decorator. > > Yeah I'm afraid it can't be done either, that's why I asked the group. You can do it if you give up on using the decorator syntax. (Now that I've said that, some clever bunny will show me how to do it.) def make_decorator(n): def addspam(fn): def new(*args): print "spam " * n return fn(*args) return new return addspam class Parrot(object): def __init__(self, count=3): from new import instancemethod as im self.describe = im(make_decorator(count)(self.__class__.describe), self) def describe(self): return "It has beautiful plummage." >>> bird = Parrot() >>> bird.describe() spam spam spam 'It has beautiful plummage.' >>> >>> >>> bird = Parrot(5) >>> bird.describe() spam spam spam spam spam 'It has beautiful plummage.' -- Steven D'Aprano From janzon at gmail.com Fri May 4 06:22:02 2007 From: janzon at gmail.com (John) Date: 4 May 2007 03:22:02 -0700 Subject: High resolution sleep (Linux) Message-ID: <1178274122.142071.91740@y5g2000hsa.googlegroups.com> The table below shows the execution time for this code snippet as measured by the unix command `time': for i in range(1000): time.sleep(inter) inter execution time ideal 0 0.02 s 0 s 1e-4 4.29 s 0.1 s 1e-3 4.02 s 1 s 2e-3 4.02 s 2 s 5e-3 8.02 s 5 s Hence it seems like the 4 s is just overhead and that the time.sleep method treats values below approximately 0.001 as 0. Is there a standard way (or slick trick) to get higher resolution? If it is system dependent it's acceptable but not very nice :) From rene at korteklippe.de Wed May 16 08:35:28 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Wed, 16 May 2007 14:35:28 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <46478694$0$1412$426a34cc@news.free.fr> <1hy252p.1anf7sr1p4yp12N%aleax@mac.com> <464988a4$0$20289$9b4e6d93@newsspool3.arcor-online.net> <464aaee8$0$10188$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <464afa8d$0$10200$9b4e6d93@newsspool4.arcor-online.net> You have misread my statements. Carsten Haese schrieb: > There is evidence against your assertions that knowing some English is a > prerequisite for programming I think it is a prerequesite for "real" programming. Yes, I can imagine that if you use Python as a teaching tool for Chinese 12 year-olds, then it might be nice to be able to spell identifiers with Chinese characters. However, IMO this is such a special use-case that it is justified to require the people who need this to explicitly enable it, by using a patched interpreter or by enabling an interpreter option for example. > in Python and that people won't use non-ASCII > identifiers if they could. I did not assert that at all, where did you get the impression that I do? If I were convinced that noone would use it, I would have not such a big problem with it. I fear that it *will* be used "in the wild" if the PEP in its current form is accepted and that I personally *will* have to deal with such code. -- Ren? From steven.bethard at gmail.com Thu May 10 16:39:37 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 10 May 2007 14:39:37 -0600 Subject: which is more pythonic/faster append or +=[] In-Reply-To: <1178825802.319573.113930@w5g2000hsg.googlegroups.com> References: <1hxtelz.7f6rvnw4cyxmN%aleax@mac.com> <1178726923.909537.209300@l77g2000hsb.googlegroups.com> <1178739061.919664.128260@y80g2000hsf.googlegroups.com> <1178825802.319573.113930@w5g2000hsg.googlegroups.com> Message-ID: 7stud wrote: >> Is there any documentation for the syntax you used with timeit? > > This is the syntax the docs describe: [snip > python timeit.py [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement ...] [snip] > Then in the examples in section 10.10.2 [snip] > timeit.py 'try:' ' str.__nonzero__' 'except AttributeError:' ' pass' [snip] > and then there is Alex Martelli's syntax: [snip] > python -mtimeit 'L=range(3); n=23' 'x=L[:]; x.append(n)' The following three things are equivalent: python /path/to/.py /path/to/.py # assuming the OS knows how to exec it python -m # assuming is on sys.path So that just leaves the differences between: [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement ...] 'try:' ' str.__nonzero__' 'except AttributeError:' ' pass' 'L=range(3); n=23' 'x=L[:]; x.append(n)' Those look pretty similar to me (aside from the fact that they're testing different things). Each argument in single quotes is a line of the code you want timed. HTH, STeVe From grante at visi.com Fri May 11 23:27:26 2007 From: grante at visi.com (Grant Edwards) Date: Sat, 12 May 2007 03:27:26 -0000 Subject: Newbie look at Python and OO References: <1178812734.860473.236370@y80g2000hsf.googlegroups.com> <1346hrvgve90nea@corp.supernews.com> <1178939255.996029.263520@p77g2000hsh.googlegroups.com> Message-ID: <134ad0ur6g79718@corp.supernews.com> On 2007-05-12, walterbyrd wrote: >> He's thinking in Pascal, not C. > > Actually, I have programmed in many languages. I just first learned in > Pascal. > > For me, going from Pascal, to basic,c,cobol,fortran . . was not that > difficult. That's because those languages are all very similar in most of the basic concepts. > Python, however, feels strange. That's because it's different than the languages you already knew. I might be an eye-opener to learn some other "strange" languages: Prolog, Scheme, Smalltalk, APL, Erlang, Haskell, Eiffel, ... > As crazy as this may sound: Python, in some ways, reminds me > of assembly language. I haven' t programmed in assembly in a > *long* time. But I vaugly remember doing a lot of stuff where > I used memory addresses as pointers to data, and also as > pointers to pointers. Although, when I first started assembly > language, I think it took me a week to write a program to > print "hello world." I still do assembly language stuff pretty regularly, and I don't really see any similarity between Python and assembly (at least not for the targets I work with). -- Grant Edwards grante at visi.com From montyphyton at gmail.com Thu May 31 08:16:30 2007 From: montyphyton at gmail.com (montyphyton at gmail.com) Date: 31 May 2007 05:16:30 -0700 Subject: PEP 8 style enforcing program Message-ID: <1180613790.317480.314600@p47g2000hsd.googlegroups.com> Some recent posts about Python programming style got me thinking. Since we have the PEP 8 which gives some guidelines about the style to be used, do we have any program that can check for violations of these guidelines within the source code? I understand that there are a lot of code beautifiers out there, but i haven't seen one specially tailored for Python... Is there even a desire in Python community for a program like this (by Python community I mean the people in this group:) ) ? I think it would be a nice little project for practice and I'd like to do it, but if there is already something like this then I can probably spend my time on something more productive. So, I'd like to hear your opinion on this... There is one thing that I don't understand about PEP 8 - why is using spaces considered more desirable than using tabs for indentation? From howe.steven at gmail.com Fri May 18 20:20:32 2007 From: howe.steven at gmail.com (Steven Howe) Date: Fri, 18 May 2007 17:20:32 -0700 Subject: remove all elements in a list with a particular value In-Reply-To: <464CCF93.6060102@gmail.com> References: <1179328873.105705.95580@l77g2000hsb.googlegroups.com> <1179435415.258096.167900@y80g2000hsf.googlegroups.com> <464CCF93.6060102@gmail.com> Message-ID: <464E42D0.6070503@gmail.com> Steven Howe wrote: > MRAB wrote: >> On May 16, 4:21 pm, Lisa wrote: >> >> I am reading in data from a text file. I want to enter each value on >> the line into a list and retain the order of the elements. The number >> of elements and spacing between them varies, but a typical line looks >> like: >> >> ' SRCPARAM 1 6.35e-07 15.00 340.00 1.10 3.0 ' >> > Using builtin functions: > > ax = ' SRCPARAM 1 6.35e-07 15.00 340.00 1.10 3.0 ' > >>> ax.replace(' ','') # replace all double spaces with nothing > ' SRCPARAM 1 6.35e-07 15.00340.00 1.103.0 ' > >>> ax.replace(' ','').strip() # strip leading/trailing white spaces > 'SRCPARAM 1 6.35e-07 15.00340.00 1.103.0' > >>> ax.replace(' ','').strip().split(' ') # split string into a > list, using remaining white space as key > ['SRCPARAM', '1', '6.35e-07', '15.00340.00', '1.103.0'] > > def getElements( str ): > return str.replace( ' ', '' ).strip().split(' ') > > > sph > Made a mistake in the above code. Works well so long as there are no double spaces in the initial string. Try 2: def compact( y ): if y.find(' ') == -1: return y else: y = y.replace( ' ', ' ' ) return compact( y ) >>> ax = ' acicd 1.345 aex a;dae ' >>> print compact( ax ) acicd 1.345 aex a;dae >>> print compact( ax ).strip().split() ['acicd', '1.345', 'aex', 'a;dae'] sph > -- > HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 > -- HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 From aleax at mac.com Sun May 13 14:56:34 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 13 May 2007 11:56:34 -0700 Subject: Off Topic: Is the use of supererogatory supererogatory? References: <1178986686.510137.195490@p77g2000hsh.googlegroups.com> <1178991933.421386.58500@u30g2000hsc.googlegroups.com> <1178992910.318929.77790@e51g2000hsg.googlegroups.com> <1178995630.925969.207740@w5g2000hsg.googlegroups.com> <1hy0cy8.eg6p1p135hbo3N%aleax@mac.com> <1179041572.791862.293010@h2g2000hsg.googlegroups.com> Message-ID: <1hy1vi2.1ht71vs1v4ah67N%aleax@mac.com> Paddy wrote: > On May 13, 12:13 am, a... at mac.com (Alex Martelli) wrote: > > > As somebody else alredy pointed out, the lambda is supererogatory (to > > say the least). > > What a wonderful new word! > I did not know what supererogatory meant, and hoped it had nothing to > do with Eros :-) > Answers.com gave me a meaning synonymous with superfluous, which > I think is what was meant here, Kind of, yes, cfr . > but Chambers gave a wonderful > definition where they say it is from the RC Church practice of doing > more > devotions than are necessary so they can be 'banked' for distribution > to others (I suspect, that in the past it may have been for a fee or > a favour). "Doing more than necessary" may be wonderful in a devotional context, but not necessarily in an engineering one (cfr also, for a slightly different slant on "do just what's needed", ). > Supererogatory, my word of the day. Glad you liked it!-) Alex From s.mientki at id.umcn.nl Tue May 29 05:30:16 2007 From: s.mientki at id.umcn.nl (stef) Date: Tue, 29 May 2007 11:30:16 +0200 Subject: ten small Python programs In-Reply-To: References: Message-ID: <1f80c$465bf2a8$83aef404$13181@news2.tudelft.nl> > >> Secondly, Python is nowadays not only used by >> programmers, >> but also by e.g. Scientific users (former MatLab >> users), >> who are not interested in the code itself, >> but just in the results of that particular code. >> For these people a lot of example programs, >> for which they can easily see the results, >> make some small changes and see the result again, >> would be a wonderful addition. >> >> > > In your own personal use, what are some > libraries/techniques/etc. that you think could benefit > from some kind of more organized presentation of > example programs (or better way of showing how the > examples work, etc.)? for example SciPy, but I think it yield for all libs/techniques. And I guess Windows users have a much greater need for such an organization than *nix users. > Are you part of the Scientific > community? > > sort of, I indeed work at a university, but not doing scientific work myself, I work on a supporting department. > How new are you to Python? very new ;-) (I've lot of experience in a other programming languages, last years mostly Delphi, JAL, MatLab) > I do think > newbies/intermediates/advanceds all have different > needs. > agreed. cheers, Stef Mientki From stefan.behnel-n05pAM at web.de Tue May 15 18:29:32 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 16 May 2007 00:29:32 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464a25e9$0$10188$9b4e6d93@newsspool4.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649dd55$0$23144$9b4e6d93@newsspool1.arcor-online.net> <464a25e9$0$10188$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <464A344C.6040202@web.de> Ren? Fleschenberg wrote: > We all know what the PEP is about (we can read). BTW: who is this "we" if it doesn't include you? Stefan From gherron at islandtraining.com Wed May 16 02:33:18 2007 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 15 May 2007 23:33:18 -0700 Subject: removing common elemets in a list In-Reply-To: <1179296224.885877.187200@q23g2000hsg.googlegroups.com> References: <1179296224.885877.187200@q23g2000hsg.googlegroups.com> Message-ID: <464AA5AE.4060902@islandtraining.com> saif.shakeel at gmail.com wrote: > Hi, > Suppose i have a list v which collects some numbers,how do i > remove the common elements from it ,without using the set() opeartor. > Thanks > > Several ways, but probably not as efficient as using a set. (And why don't you want to use a set, one wonders???) >>> l = [1,2,3,1,2,1] Using a set: >>> set(l) set([1, 2, 3]) Building the list element by element: >>> for e in l: ... if e not in r: ... r.append(e) ... >>> print r [1, 2, 3] Using a dictionary: >>> d = dict(zip(l,l)) >>> d {1: 1, 2: 2, 3: 3} >>> d.keys() [1, 2, 3] >>> From schliep at molgen.mpg.de Wed May 9 03:10:27 2007 From: schliep at molgen.mpg.de (Alexander Schliep) Date: Wed, 09 May 2007 09:10:27 +0200 Subject: Designing a graph study program References: <1178619753.077639.112510@q75g2000hsh.googlegroups.com> Message-ID: andrea writes: > Well then I wanted to draw graphs and I found that pydot is working > really nicely. > BUT I'd like to do this, an interactive program to see ho the > algorithms works... > For example in the breath search first, every time the algorithm > colors a node, the program should redraw the graphs. Which modules > should I use for graphics (I use macosX and I'd like something cross > platforms). Check out http://gato.sf.net (LGPL license). It does exactly what you want to do and there is a binary for MacOS X. Algorithms are implemented using Gato's graph class and rudimentary visualizations you get for free by replacing standard data structures (e.g., a vertex queue) by animated ones (AnimatedVertexQueue). There is a Springer textbook forthcoming. We are also starting to collect contributed algorithms, which we would like to make available from our website. Full disclosure: I am the author of Gato Best, Alexander From rene at korteklippe.de Tue May 15 12:18:31 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 15 May 2007 18:18:31 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> Message-ID: <4649dd55$0$23144$9b4e6d93@newsspool1.arcor-online.net> Carsten Haese schrieb: > Allowing people to use identifiers in their native language would > definitely be an advantage for people from such cultures. That's the use > case for this PEP. It's easy for Euro-centric people to say "just suck > it up and use ASCII", but the same people would probably starve to death > if they were suddenly teleported from Somewhere In Europe to rural China > which is so unimaginably different from what they know that it might > just as well be a different planet. "Learn English and use ASCII" is not > generally feasible advice in such cultures. This is a very weak argument, IMHO. How do you want to use Python without learning at least enough English to grasp a somewhat decent understanding of the standard library? Let's face it: To do any "real" programming, you need to know at least some English today, and I don't see that changing anytime soon. And it is definitely not going to be changed by allowing non-ASCII identifiers. I must say that the argument about domain-specific terms that programmers don't know how to translate into English does hold some merit (although it does not really convince me, either -- are these cases really so common that you cannot feasibly use a transliteration?). But having, for example, things like open() from the stdlib in your code and then ?ffnen() as a name for functions/methods written by yourself is just plain silly. It makes the code inconsistent and ugly without significantly improving the readability for someone who speaks German but not English. -- Ren? From rurpy at yahoo.com Thu May 17 10:05:59 2007 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 17 May 2007 07:05:59 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649dd55$0$23144$9b4e6d93@newsspool1.arcor-online.net> <464a25e9$0$10188$9b4e6d93@newsspool4.arcor-online.net> <1179291296.561359.286230@h2g2000hsg.googlegroups.com> <464ab64f$0$10185$9b4e6d93@newsspool4.arcor-online.net> <1179349116.088747.167990@n59g2000hsh.googlegroups.com> Message-ID: <1179410759.049712.204100@n59g2000hsh.googlegroups.com> On May 16, 8:49 pm, Gregor Horvath wrote: > r... at yahoo.com schrieb: > >> 2) Create a way to internationalize the standard library (and possibly > >> the language keywords, too). Ideally, create a general standardized way > >> to internationalize code, possibly similiar to how people > >> internationalize strings today. > > > > Why? Or more acurately why before adopting the PEP? > > The library is very usable by non-english speakers as long as > > there is documentation in their native language. It would be > > Microsoft once translated their VBA to foreign languages. > I didn't use it because I was used to "English" code. > If I program in mixed cultural contexts I have to use to smallest > dominator. Mixing the symbols of the programming language is confusing. Yup, I agree wholeheartedly. So do almost all the other people who have responded in this thread. In public code, open source code, code being worked on by people from different countries, English is almost always the best choice. Nothing in the PEP interferes with or prevents this. The PEP only allows non-ascii indentifiers, when they are appropriate: in code that is unlikely to be ever be touched by people who don't know that language. (Obviously any language feature can be misused but peer-pressure, documentation, and education have been very effective in preventing such misuse. There is no reason they shouldn't be effective here too.) And yes, some code will be developed in a single language enviroment and then be found to be useful to a wider audience. It's not the end of the world. It is no worse than when code written with a single language UI that is becomes public -- it will get fixed so that it meets the standards for a internationaly collaborative project. Seems to me that replacing identifiers with english ones is fairly trivial isn't it? One can identify identifiers by parsing the program and replacing them from a prepared table of replacements? This seems much easier than fixing comments and docstrings which need to be done by hand. But the comment/docstring problem exists now and has nothing to do with the PEP. > Long time ago at the age of 12 I learned programming using English > Computer books. Then there were no German books at all. It was not easy. > It would have been completely impossible if our schools system would not > have been wise enough to teach as English early. > > I think millions of people are handicapped because of this. > Any step to improve this, is a good step for all of us. In no doubt > there are a lot of talents wasted because of this wall. I agree that anyone who wants to be a programmer is well advised to learn English. I would also advise anyone who wants to be a programmer to go to college. But I have met very good programmers who were not college graduates and although I don't know any non- english speakers I am sure there are very good programers who don't know English. There is a big difference between encouraging someone to do something, and taking steps to make them do something. A lot of the english-only retoric in this thread seems very reminiscent of arguments a decade+ ago regarding wide characters and unicode, and other i18n support. "Computing is ascii-based, we don't need all this crap, and besides, it doubles the memory used by strings! English is good enough". Except of course that it wasn't. When technology demands that people adapt to it, it looses. When technology adapts to the needs of people, it wins. The fundamental question is whether languages designers, or the people writing the code, should be the ones to decide what language identifiers are most appropriate for their program. Do language designers, all of whom are English speakers, have the wisdom to decide for programmers all over the world, and for years to come, that they must learn English to use Python effectively? And if they do, will the people affected agree, or will they choose a different language? From garcigal at gmail.com Tue May 15 17:28:36 2007 From: garcigal at gmail.com (garcigal at gmail.com) Date: 15 May 2007 14:28:36 -0700 Subject: Python Newbie Suggestions Message-ID: <1179264515.958714.72880@l77g2000hsb.googlegroups.com> I'm a mechanical engineer with little experience programming. I've used C++ and machine language for getting micro-controllers to work and thats about it. I work allot with software developers at my job and can read C++ code pretty good (ie. I understand whats going on). Does anyone have any good tips or resources for someone interested in learning PYTHON. This is purely for hobby purposes and I'd like to expose my kids to a programing language too. If any one has any helpful books, tips or suggestions please let me know. I have Windows, MAC and Linux box's at my house but I'm a primarily a MAC user. From deepbroke6 at gmail.com Tue May 15 17:59:45 2007 From: deepbroke6 at gmail.com (deepbroke6 at gmail.com) Date: 15 May 2007 14:59:45 -0700 Subject: ^* Britney Spears Back and more naked than ever* Message-ID: <1179266384.989588.221100@y80g2000hsf.googlegroups.com> http://scargo.in/2007/05/wachovia-checking-accounts.html - Download these amazing movies and videos of britney naked! Shes back and seczyer than ever OOPS! I Did it again.!@. From nospam at invalid.com Sat May 26 04:21:56 2007 From: nospam at invalid.com (Jack) Date: Sat, 26 May 2007 01:21:56 -0700 Subject: Large Amount of Data References: Message-ID: If swap memery can not handle this efficiently, I may need to partition data to multiple servers and use RPC to communicate. "Dennis Lee Bieber" wrote in message news:YYO5i.13645$Ut6.9256 at newsread1.news.pas.earthlink.net... > On Fri, 25 May 2007 11:11:28 -0700, "Jack" > declaimed the following in comp.lang.python: > >> Thanks for the replies! >> >> Database will be too slow for what I want to do. >> > Slower than having every process on the computer potentially slowed > down due to page swapping (and, for really huge data, still running the > risk of exceeding the single-process address space)? > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com wulfraed at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-asst at bestiaria.com) > HTTP://www.bestiaria.com/ From steven at REMOVE.THIS.cybersource.com.au Tue May 15 20:46:21 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 16 May 2007 00:46:21 GMT Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <1hy2qg3.iqfvwnrvr9kjN%aleax@mac.com> Message-ID: On Tue, 15 May 2007 20:43:31 +1000, Aldo Cortesi wrote: > Thus spake Steven D'Aprano (steven at REMOVE.THIS.cybersource.com.au): > >> >> Me, I try to understand a patch by reading it. Call me >> >> old-fashioned. >> > >> > I concur, Aldo. Indeed, if I _can't_ be sure I understand a patch, I >> > don't accept it -- I ask the submitter to make it clearer. >> >> >> Yes, but there is a huge gulf between what Aldo originally said he does >> ("visual inspection") and *reading and understanding the code*. > > Let's set aside the fact that you're guilty of sloppy quoting here, > since the phrase "visual inspection" is yours, not mine. Yes, my bad, I apologize, that was sloppy of me. What you actually said was "I can't reliably verify it by eye". > Regardless, > your interpretation of my words is just plain dumb. My phrasing was > intended to draw attention to the fact that one needs to READ code in > order to understand it. You know - with one's eyes. VISUALLY. And VISUAL > INSPECTION of code becomes unreliable if this PEP passes. Not withstanding my misquote, I find it ... amusing ... that after hauling me over the coals for using the term "visual inspection", you're not only using it, but shouting it. Perhaps you aren't aware that doing something "by eye" is idiomatic English for doing it quickly, roughly, imprecisely. It is the opposite of taking the time and effort to do the job carefully and accurately. If you measure something "by eye", you just look at it and take a guess. So, as I said, if you're relying on VISUAL INSPECTION (your words _now_) you're already vulnerable. Fortunately for you, you're not relying on visual inspection, you are actually _reading_ and _comprehending_ the code. That might even mean, in extreme cases, you sit down with pencil and paper and sketch out the program flow to understand what it is doing. Now that (I hope!) you understand why I said what I said, can we agree that _understanding_ is critical to the process? If you don't understand the code, you don't accept it. If somebody submits a patch with identifiers like a9472302 and a 9473202 you're going to reject it as too difficult to understand. How do non-ASCII identifiers change that situation? What will be different? >> If I've understood Martin's post, the PEP states that identifiers are >> converted to normal form. If two identifiers look the same, they will >> be the same. > > I'm sorry to have to tell you, but you understood Martin's post no > better than you did mine. There is no general way to detect homoglyphs > and "convert them to a normal form". Observe: > > import unicodedata > print repr(unicodedata.normalize("NFC", u"\u2160")) print u"\u2160" > print "I" Yes, I observe two very different glyphs, as different as the ASCII characters I and |. What do you see? > So, a round 0 for reading comprehension this lesson, I'm afraid. Better > luck next time. Ha ha, very funny. So, let's summarize... Non-ASCII identifiers are bad, because they are vulnerable to the exact same problems as ASCII identifiers, only we're happy to live with those problems if they are ASCII, and just install a font that makes I and l look different, but we won't install a font that makes I and ? look different, because that's too hard. Well, you've convinced me. Obviously expecting Python programmers to cope with something as complicated as installing a decent set of fonts is such a major huddle that people will abandon the language in droves, probably taking up Haskel and Visual Basic and Lisp and all those other languages that allow non-ASCII identifiers. -- Steven. From thardy99 at gmail.com Thu May 17 01:13:50 2007 From: thardy99 at gmail.com (Teresa Hardy) Date: Wed, 16 May 2007 22:13:50 -0700 Subject: Python Newbie Suggestions In-Reply-To: <1179264515.958714.72880@l77g2000hsb.googlegroups.com> References: <1179264515.958714.72880@l77g2000hsb.googlegroups.com> Message-ID: As a newbie, Python has my vote for beginners. It is easy to get started with some quick and satisfying scripts but tricky to learn good OOP form. That's why I highly recommend the Programming Python Part 1 article that just came out in the June 2007 Linux Journal. You can use some of the sections in it to explain classes and instances to the kids. And I'd cast a second vote for www.diveintopython.org. Teresa -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Tue May 1 20:34:39 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 1 May 2007 20:34:39 -0400 Subject: pre-PEP: Standard Microthreading Pattern References: <20070501205820.GE11383@v.igoro.us> Message-ID: wrote in message news:20070501205820.GE11383 at v.igoro.us... Sounds like a good idea to me. Travis Oliphant has spent over a year on http://www.python.org/dev/peps/pep-3118/ so array-making-using programs can better operate together. I hope you have the same patience and persistance. | .. [2] PEP 342, "Coroutines via Enhanced Generators", van Rossum, Eby | (http://www.python.org/peps/pep-0342) This gave 404 Not Found while this works (/dev added): http://www.python.org/dev/peps/pep-0342/ | .. [3] PEP 355, "Simple Generators", Schemenauer, Peters, Hetland | (http://www.python.org/peps/pep-0342) 255, not 355 or 342 again: http://www.python.org/dev/peps/pep-0255/ Terry Jan Reedy From rowan at sylvester-bradley.org Wed May 9 19:55:31 2007 From: rowan at sylvester-bradley.org (rowan at sylvester-bradley.org) Date: 9 May 2007 16:55:31 -0700 Subject: Change serial timeout per read Message-ID: <1178754931.060029.135800@w5g2000hsg.googlegroups.com> I'm writing a driver in Python for an old fashioned piece of serial equipment. Currently I'm using the USPP serial module. From what I can see all the serial modules seem to set the timeout when you open a serial port. This is not what I want to do. I need to change the timeout each time I do a "read" on the serial port, depending on which part of the protocol I've got to. Sometimes a return character is expected within half a second, sometimes within 2 seconds, and sometimes within 20 seconds. How do I do this in USPP, or Pyserial, or anything else? Currently I'm working in Windows, but I'd prefer a platform independent solution if possible... Thanks - Rowan From irstas at gmail.com Thu May 24 05:05:04 2007 From: irstas at gmail.com (irstas at gmail.com) Date: 24 May 2007 02:05:04 -0700 Subject: Inheriting from Python list object(type?) In-Reply-To: <1179947267.368622.92350@m36g2000hse.googlegroups.com> References: <1179947267.368622.92350@m36g2000hse.googlegroups.com> Message-ID: <1179997504.720450.202740@p47g2000hsd.googlegroups.com> On May 23, 10:07 pm, Mangabasi wrote: > This is the winner: > > class Point(list): > def __init__(self, x, y, z = 1): > super(Point, self).__init__([x, y, z]) > self.x = x > self.y = y > self.z = z > > def __getattr__(self, name): > if name == 'x': > return self[0] > elif name == 'y': > return self[1] > elif name == 'z': > return self[2] > else: > return self.__dict__[name] > > def __setattr__(self, name, value): > if name == 'x': > self[0] = value > elif name == 'y': > self[1] = value > elif name == 'z': > self[2] = value > else: > self.__dict__[name] = value Inheritation is an "is a" relation. Point, however, is not a list. This adds some weird behaviour to Point: p = Point(1,2,3) p.append(4) print p[3] That makes no sense but your Point implementation allows it. This is probably even more surprasing behaviour: p = Point(1,2,3) + Point(4,5,6) print p One might expect the points to be added to Point(5,7,9), not into a list containing [1,2,3,4,5,6]. I'd suggest you don't inherit Point from anything, and just add an __iter__ member function that iterates through x,y and z. E.g. def __iter__(self): yield self.x yield self.y yield self.z Then you can convert a Point p to a list by doing list(p). Or to a tuple with tuple(p). __array__ could also be implemented for convenince with numpy (if I understood that correctly). From walterbyrd at iname.com Wed May 16 17:47:01 2007 From: walterbyrd at iname.com (walterbyrd) Date: 16 May 2007 14:47:01 -0700 Subject: How do I tell the difference between the end of a text file, and an empty line in a text file? Message-ID: <1179352021.803070.200780@k79g2000hse.googlegroups.com> Python's lack of an EOF character is giving me a hard time. I've tried: ----- s = f.readline() while s: . . s = f.readline() -------- and ------- s = f.readline() while s != '' . . s = f.readline() ------- In both cases, the loop ends as soon it encounters an empty line in the file, i.e. xxxxxxxxxx xxxxxxxxxxx xxxxxxx < - - - loop end here xxxxxxxxxxxxxx xxxxxxxxxx x < ---- loop should end here From rene at korteklippe.de Tue May 15 08:19:46 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 15 May 2007 14:19:46 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <1hy2qg3.iqfvwnrvr9kjN%aleax@mac.com> <46482624.6050507@web.de> <7xd512onsx.fsf@ruckus.brouhaha.com> <464951EF.7030900@web.de> <464997a5$0$10193$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <4649a561$0$10187$9b4e6d93@newsspool4.arcor-online.net> Thorsten Kampe schrieb: >> Identifiers which my terminal cannot even display surely >> are not very readable. > > This PEP is not about you. It's about people who write in their native > language and who are forced to use a dodgy transcription from > characters of their own language to ASCII. It is impossible to write Python in a native language other than English even with the implementation of this PEP. All you get is a weird mixture of English identifiers from various libraries and identifiers in your native language. And even if you consider that more clear and readable than English-only Python code, the fact that it discourages code sharing remains. -- Ren? From larry.bates at websafe.com Thu May 31 09:38:38 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 31 May 2007 08:38:38 -0500 Subject: Examples of high-quality python code? In-Reply-To: References: Message-ID: kaens wrote: > Hey everyone, I'm relatively new to python - I actually picked it up > to see how quickly I could start building non-trivial apps with it. > > Needless to say, I was quite pleased. > > Anyhow, I'm looking to expand my understanding of python, and I feel > that one of the best ways to do that is looking at other peoples code. > > Unfortunately, I don't feel like I grok the python mindset quite well > enough to fully distinguish between awesome, average, and not-pythony > code, so I was hoping some of the more experienced python people could > point me to some (preferably FOSS) non-trivial apps written in python > that are examples of great python code. > > I realize this may be a bit ambiguous - basically I don't want to go > randomly downloading other people's source and end up assimilating > techniques that aren't . . . well . . . pythonistic. > > So, who wants to hook me up? You should consider picking up a copy of Python Cookbook. Alex and others have reviewed the code it contains and IMHO it is well written. I've also learned quite a lot from: Python on Win32 (book by Mark Hammond/Andy Robinson) Reading source code to standard library Reading ReportLab source (www.reportlab.org) Reading PIL source (www.effbot.org) Reading wxPython source (www.wxpython.org) Monitoring this list on a daily basis -Larry From jeff at taupro.com Wed May 2 09:02:00 2007 From: jeff at taupro.com (Jeff Rush) Date: Wed, 02 May 2007 08:02:00 -0500 Subject: Need Help in Preparing for Study of Python by Forrester Research Message-ID: <46388BC8.9000806@taupro.com> Forrester Research is doing a study on dynamic languages and has asked that Python be represented. As advocacy coordinator I've volunteered to drive this, collecting answers from the community and locating representatives to participate in interviews. The goal of the study is to: - identify the criteria to use for evaluating such languages - identify the relevant choices of dynamic languages - identify how the different dynamic languages stack up - examine where dynamic languages work best Initially, they'd like feedback (not yet the answers themselves) from us regarding their proposed evaluation criteria - questions to add or that give no value, rewording to make them more clear. I've posted their draft criteria, which came as a spreadsheet at: http://dfwpython.org/uploads/ForresterPrep/DynamicLanguagesCriteria.xls Later, between May 8 and 25, the researchers will need to interview via 1-hour telephone calls, several developers with experience using Python. And they want to also interview one person with an executive viewpoint, able to describe relevant background, positioning, value proposition, customer base, and strategic vision. And later they would also like snippets of Python code that illustrate the power of Python, and I hope to call upon community members to help in producing that. The snippets do not have to be originally written and can be pulled from existing projects. But those steps come later. For now let's focus on analysis of the evaluation criteria at the above URL. Time is short as they'd like that feedback by May 3, so please get any responses to me as soon as possible. And be thinking who would best represent the executive view of Python in an interview. Thanks for your help, Jeff Rush Advocacy Coordinator From nszabolcs at gmail.com Wed May 30 11:43:10 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 30 May 2007 08:43:10 -0700 Subject: Is PEP-8 a Code or More of a Guideline? In-Reply-To: References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <5c1jpkF2tl0ilU1@mid.individual.net> Message-ID: <1180539790.654176.26900@q75g2000hsh.googlegroups.com> John DeRosa wrote: > +1 QOTW > > >Hey, did you hear about the object-oriented version of COBOL? They call it > >"ADD ONE TO COBOL". actually it is "ADD 1 TO COBOL GIVING COBOL" http://en.wikipedia.org/wiki/COBOL#Aphorisms_and_humor_about_COBOL From mail at sphinx.net.ru Sat May 12 12:42:27 2007 From: mail at sphinx.net.ru (Dmitry Dzhus) Date: Sat, 12 May 2007 20:42:27 +0400 Subject: Basic question In-Reply-To: <1178986686.510137.195490@p77g2000hsh.googlegroups.com> (Cesar G. Miguel's message of "12 May 2007 09\:18\:06 -0700") References: <1178986686.510137.195490@p77g2000hsh.googlegroups.com> Message-ID: <878xbuoux8.fsf@sphinx.net.ru> > "j=j+2" inside IF does not change the loop > counter ("j") You might be not truly catching the idea of Python `for` statements sequence nature. It seems that will make things quite clear. > The suite may assign to the variable(s) in the target list; this > does not affect the next item assigned to it. In C you do not specify all the values the "looping" variable will be assigned to, unlike (in the simplest case) you do in Python. -- Happy Hacking. Dmitry "Sphinx" Dzhus http://sphinx.net.ru From broek at cc.umanitoba.ca Wed May 30 17:59:58 2007 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Wed, 30 May 2007 17:59:58 -0400 Subject: c[:]() In-Reply-To: <003601c7a301$dfcff0b0$240110ac@Muse> References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com><1180504773.374529.161740@q66g2000hsg.googlegroups.com><002801c7a2eb$288a8750$240110ac@Muse> <1180554872.3356.30.camel@dot.uniqsys.com> <003601c7a301$dfcff0b0$240110ac@Muse> Message-ID: <465DF3DE.40404@cc.umanitoba.ca> Warren Stringer said unto the world upon 05/30/2007 05:31 PM: > Hmmm, this is for neither programmer nor computer; this is for a user. If I > wanted to write code for the benefit for the computer, I'd still be flipping > switches on a PDP-8. ;-) > > This is inconsistent: > > why does c[:][0]() work but c[:]() does not? c[:][0]() says take a copy of the list c, find its first element, and call it. Since c is a list of functions, that calls a function. c[:]() says take a copy of the list c and call it. Since lists are not callable, that doesn't work. > Why does c[0]() has exactly the same results as c[:][0]() ? Because c[0] is equal to c[:][0]. > Moreover, c[:][0]() implies that a slice was invoked Yes, but the complete slice. > So, tell me, for scheduling a lot of asynchronous events, what would be more > readable than this: > > bidders = [local_members] + [callin_members] > bidders[:].sign_in(roster) > ... for bidder in [local_members] + [callin_members]: bidder.sign_in(roster) Best, Brian vdB > \~/ > >> -----Original Message----- >> From: python-list-bounces+warren=muse.com at python.org [mailto:python-list- >> bounces+warren=muse.com at python.org] On Behalf Of Carsten Haese >> Sent: Wednesday, May 30, 2007 12:55 PM >> To: python-list at python.org >> Subject: Re: c[:]() >> >> On Wed, 2007-05-30 at 11:48 -0700, Warren Stringer wrote: >>> I want to call every object in a tupple, like so: >>> >>> #------------------------------------------ >>> def a: print 'a' >>> def b: print 'b' >>> c = (a,b) >>> >>>>>> c[:]() # i wanna >>> [...] >>> Is there something obvious that I'm missing? >> Yes: Python is not Perl. >> >> Python is based on the principle that programmers don't write computer >> code for the benefit of the computer, but for the benefit of any >> programmer who has to read their code in the future. Terseness is not a >> virtue. To call every function in a tuple, do the obvious: >> >> for func in funcs: func() >> >> HTH, >> >> -- >> Carsten Haese >> http://informixdb.sourceforge.net >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list > > From wildemar at freakmail.de Sat May 19 07:52:26 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Sat, 19 May 2007 13:52:26 +0200 Subject: (Modular-)Application Framework / Rich-Client-Platform in Python In-Reply-To: <871whd60dx.fsf@benfinney.id.au> References: <8ea03$464dc950$d443bb3a$5229@news.speedlinq.nl> <871whd60dx.fsf@benfinney.id.au> Message-ID: <464EE4FA.3080509@freakmail.de> Ben Finney wrote: > You already have Python, and can embed it in your program. The only > missing piece seems to be the primitive operations at the core, which > surely depend on what exactly it is you have in mind for your program > and can't really be provided in a generic form by some other party. > > That's where you're wrong. Such a tool exists. I really can't explain any better than I (and Jarek even better so) already did. The keyword is Rich-Client-Platform. Wikipedia explains it, so does the already presented Eclipse-wiki, as does the Enthought Tools Site (specifically Envisage), which also holds the answer to my problem/question. It is solved. If you don't understand what I want, go to and read what it does. I really, really appreciate the effort you (all of you) make in helping me and getting me on the right track, but I'm a bit confounded by how you can be trying to convince me that the tools I'm currently reading the docs for don't exist. I don't mean to be bitching, really. I just don't get your point here. :) W From kvs at acm.org Mon May 21 15:54:09 2007 From: kvs at acm.org (Kathryn Van Stone) Date: Mon, 21 May 2007 15:54:09 -0400 Subject: unittest for threading function always failed... In-Reply-To: <1179532675.996634.33030@k79g2000hse.googlegroups.com> References: <1179530016.500072.177880@y80g2000hsf.googlegroups.com> <1179532675.996634.33030@k79g2000hse.googlegroups.com> Message-ID: If all you are doing is testing that run() works correctly, you could probably also get away with just calling run() directly instead of also implicitly testing the Thread class as well. -Kathy From mail at microcorp.co.za Sun May 27 02:49:35 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 27 May 2007 08:49:35 +0200 Subject: Ancient projectiles (was: Muzzle Velocity (was: High resolution sleep(Linux)) References: <1178274122.142071.91740@y5g2000hsa.googlegroups.com> <3f0mi4-mj8.ln1@lairds.us> Message-ID: <006601c7a02b$30da4fc0$03000080@hendrik> "Cameron Laird" wrote: > In article , > Dennis Lee Bieber wrote: > . > . > . > >> Did you know that the first military smokeless powder > >> round was for the French Lebel? - It threw a bronze > >> ball, and could punch through a single brick wall. > >> > > Well, extreme high speed wouldn't help for that -- just get a > >surface splatter. Heavy and slower... (or some sort of solid core -- > >depleted uranium with a teflon coating) > . > . > . > Hmmm; now you've got me curious. What *were* the first > composite projectiles? Conceivably archers, catapultists, > and slings would all have the potential to find advantage > in use of coated dense projectiles; is there any evidence > of such? There certainly was "mass production" of cheap > projectiles (clay pellets, for example). How were stones > chosen for large catapults? Was there a body of craft > knowledge for balancing density and total mass in > selection of stones? Would a toggle headed harpoon count as a "composite projectile" ? - they have been around a long time. Also the San people (better known as Bushmen) have made their poison arrows so that the point detaches from the shaft and stays in the wound, ensuring better contact between the sticky gum like poison and the blood of the victim. - Hendrik From p.f.moore at gmail.com Thu May 24 11:44:14 2007 From: p.f.moore at gmail.com (Paul Moore) Date: 24 May 2007 08:44:14 -0700 Subject: Reading (and writing?) audio file tags Message-ID: <1180021454.086004.126170@p47g2000hsd.googlegroups.com> I'd like to write some scripts to analyze and manipulate my music files. The files themselves are in MP3 and FLAC format (mostly MP3, but FLAC where I ripped original CDs and wanted a lossless format). I've no idea what form of tags are used in the files (ID3v1, ID3v2, OGG, APE, ...) I just used whatever the program that set them up used. I'm completely confused by the various tag formats that exist - there seems to be little standardisation, and quite a few compatibility pitfalls. For example, I have files with tags using accented characters - I suspect that this causes some tools to switch format (because I've seen what looked like corrupt data at times, which turned out to be the program displaying the "wrong format" of tag). I've seen various Python libraries that talk about ID3 tag reading - but I'm not clear if they read other tag formats (many applications which call themselves "ID3 readers" actually handle multiple formats, but I don't know if that's true for (Python) libraries. Also, there seem to be few libraries that will *write* tags. Is there a good "music file tag handling" library for Python that's worth looking at? I use Windows, so it would have to be for that platform, and although I have a compiler, I don't really want to spend a lot of time collecting and porting/building support libraries, so I'd be looking for a binary distribution. In the absence of something suitable, I'll probably go back to dumping the tags via a generic "MP3 tag reader" program, then manipulate them as a text file, then try to do some sort of bulk reload. Thanks, Paul. From gagsl-py2 at yahoo.com.ar Sun May 27 10:45:02 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 27 May 2007 11:45:02 -0300 Subject: Is PEP-8 a Code or More of a Guideline? References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <1180272049.3157.2.camel@localhost.localdomain> Message-ID: En Sun, 27 May 2007 10:20:49 -0300, Carsten Haese escribi?: > On Sun, 2007-05-27 at 07:30 +0000, OKB (not okblacke) wrote: >> Underscores are harder to type than any alphanumeric character. > > This is a discussion about underscores versus capital letters denoting > the word boundaries in identifiers. How is an underscore harder to type > than a capital letter? Underscores are not always easily available on non us-layout keyboards, like \ and @ and many other "special" characters. A language that requires more symbols than the 26 english letters has to make room somewhere - keyboards usually have "only" 102 keys (or 105 nowadays). Back to the style, I think that mixedCaseIsEnough to determine_word_endings and looksBetter. alllowercase is hard to read. -- Gabriel Genellina From bellman at lysator.liu.se Fri May 18 03:28:31 2007 From: bellman at lysator.liu.se (Thomas Bellman) Date: Fri, 18 May 2007 07:28:31 +0000 (UTC) Subject: An expression that rebinds a variable? References: <1179411429.536764.5620@q75g2000hsh.googlegroups.com> Message-ID: GreenH writes: > Can I know what kind of expressions rebind variables, of course unlike > in C, assignments are not expressions (for a good reason) > So, eval(expr) should bring about a change in either my global or > local namespace, where 'expr' is the expression List comprehensions: >>> c Traceback (most recent call last): File "", line 1, in NameError: name 'c' is not defined >>> eval('[ord(c) for c in "parrot"]') [112, 97, 114, 114, 111, 116] >>> c 't' This is supposed to be changed in Python 3.0. -- Thomas Bellman, Lysator Computer Club, Link?ping University, Sweden "What sane person could live in this world ! bellman @ lysator.liu.se and not be crazy?" -- Ursula K LeGuin ! Make Love -- Nicht Wahr! From Eric_Dexter at msn.com Fri May 25 20:06:47 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 25 May 2007 17:06:47 -0700 Subject: How to get started as a xhtml python mysql freelancer ? In-Reply-To: <1180136893.220560.49340@q75g2000hsh.googlegroups.com> References: <1180136893.220560.49340@q75g2000hsh.googlegroups.com> Message-ID: <1180138007.085690.242620@m36g2000hse.googlegroups.com> On May 25, 6:48 pm, gert wrote: > I made something that i was hoping it could make people happy enough > so i could make a living by providing support for commercial use ofhttp://sourceforge.net/projects/dfo/ > > But in reality i am a lousy sales men and was wondering how you people > sell stuff as a developer ? What does it do exactly. I am sort of looking into database stuff as a way to organise files that could be loaded from disk.. I would start with your basic journalism (about yourself of course) who what where why exc about my "product" I don't have the whole story on freelance although I do know that you can bid on products on different sites.. my thoughts anyway... Is your product usefull with my product???.. https://sourceforge.net/projects/dex-tracker From david.bostwick at chemistry.gatech.edu Tue May 8 09:37:58 2007 From: david.bostwick at chemistry.gatech.edu (David Bostwick) Date: Tue, 08 May 2007 13:37:58 GMT Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> <08qk33t594ih0ulmjmev90d22lkfnotgoe@4ax.com> <1178351229.212479.237050@l77g2000hsb.googlegroups.com> Message-ID: In article , James Stroud wrote: [...] > >Conspiracy theorists at least have thought behind their crazy ideas--but >you just come up with monkey talk insults. Good job monkey. > >Monkey can't think of something to say but monkey talk? That's ok, >here's a banana, monkey. Waiting for monkey response, monkey. Conspiracy buffs won't accept anything that contradicts their conclusions, so there's no sense discussing things with them. If there is no evidence proving their point, that in itself is evidence of a cover-up, and proof that they are right. There is no thought, only belief. And I'm glad you made logical arguments, instead of just hurling insults. From DirkHagemann at gmail.com Fri May 4 06:57:44 2007 From: DirkHagemann at gmail.com (Dirk Hagemann) Date: 4 May 2007 03:57:44 -0700 Subject: Active Directory: how to delete a user from a group? In-Reply-To: References: <1178119465.469546.275440@e65g2000hsc.googlegroups.com> <4638B143.9040805@timgolden.me.uk> Message-ID: <1178276264.704155.26130@c35g2000hsg.googlegroups.com> On 2 Mai, 17:48, Tim Golden wrote: > Tim Golden wrote: > >Dirk Hagemannwrote: > >> Hi! > > >> Does anyone has experience with manipulating MS Active Directory > >> objects? I'd like to delete some users from a group, but so far I > >> couldn't find anything about this. > >> There is some good stuff about retrieving data out of the AD (thanks > >> to Tim Golden!), but how can I manipulate or change AD objects like > >> users, computers and groups with Python? Is there somewhere a > >> documentation or some code? > > > I freely admit I don't do too much changing of AD objects, > > but my module should at least support the methods for doing > > things. Some examples in Active Directory Cookbook: > > > http://techtasks.com/code/viewbook/2 > > Sorry, you wanted to remove a user *from a group*. Misread. > > Translated fromhttp://techtasks.com/code/viewbookcode/1626 > > > import active_directory > group = active_directory.find_group ("name-of-group") > # or group = active_directory.AD_object ("group-moniker") > > user = active_directory.find_user ("name-of-user") > # or user = active_directory.AD_object ("user-moniker") > > group.Remove (user.path ()) > > > > Obviously, for something this simple using an extra module > is overkill. You might as well: > > > import win32com.client > > group = win32com.client.GetObject ("group-moniker") > group.Remove ("user-moniker") > > > > NB I haven't tried these, I've just translated them > from the Cookbook site! > > TJG Hi Tim! The first code does exactly what I want - thanks a lot again for your help. Dirk From development-2006-8ecbb5cc8aREMOVETHIS at ANDTHATm-e-leypold.de Thu May 3 15:53:32 2007 From: development-2006-8ecbb5cc8aREMOVETHIS at ANDTHATm-e-leypold.de (Markus E Leypold) Date: Thu, 03 May 2007 21:53:32 +0200 Subject: Why stay with lisp when there are python and perl? References: <1178155239.007219.205020@y5g2000hsa.googlegroups.com> <1178219732.127815.3260@y80g2000hsf.googlegroups.com> Message-ID: Xah Lee writes: > (if there is some demand, i will add a concrept, little programing No. There ain't. - M From hafeliel at yahoo.com Sat May 19 09:54:32 2007 From: hafeliel at yahoo.com (Gre7g Luterman) Date: Sat, 19 May 2007 07:54:32 -0600 Subject: _PyObject_New / PyObject_Init / PyInstance_New / etc? Message-ID: (My apologies if this appears twice. It did not post the first time.) I'm so confuzzled! How do I instantiate my new C Python object from C? After flailing helplessly with my own code, and searching tirelessly with Google, I stepped back to the classic noddy2.c example in the Python help files and tried to modify it to not just define a Noddy object, but to instantiate one as well. I'm not having any luck. In noddy2.c, I added some printf statements just after the beginning of the Noddy_dealloc, Noddy_new, and Noddy_init. I compiled noddy2.c and when called from Python, it does exactly what I would expect: >>> import noddy2 >>> n=noddy2.Noddy() Noddy_new Noddy_init >>> ^Z Noddy_dealloc Perfect! Now I wanted to create a Noddy() object from C. The simplest way to do this was to stick it in the Noddy_name function, since that was easily called. I tried inserting some code with _PyObject_New and PyObject_Init: static PyObject * Noddy_name(Noddy* self) { static PyObject *format = NULL; PyObject *args, *result; printf("Noddy_name\n"); args=_PyObject_New(&NoddyType); printf("%p\n", args); PyObject_Init(args, &NoddyType); printf("init done\n"); Py_DECREF(args); printf("dec done\n"); ... (I left all the original Noddy_name code here) ... Then I compiled, went into the Python interpreter and tried it. I would have expected Noddy_name to create and destroy a Noddy object just like noddy2.Noddy() does from the interpreter, but it doesn't: >>> import noddy2 >>> n=noddy2.Noddy() Noddy_new Noddy_init >>> n.name() Noddy_name 00B1A1B8 init done Noddy_dealloc As you can see, calling the name function did my printf of Noddy_name, and then _PyObject_New returned a pointer to a Python object, but I don't think it really is a Noddy object (not entirely at least). After all, Noddy_new and Noddy_init are never called! The funny thing is that the Py_DECREF destroys a Noddy object (you can see that Noddy_dealloc got called), but now something is out of sync. since the construction didn't happen as expected and Python crashes hard. I've tried this as above, and with PyInstance_New, with PyObject_New (no underscore), and PyObject_Call, but none of them work as I would expect. So what is the *CORRECT* way to do this? Obviously I'm neglecting something important. My modified noddy2.c in case anyone wants to try it: http://pastie.textmate.org/62901 Many thanks to anyone who can point me in the correct direction! Gre7g From S.Mientki-nospam at mailbox.kun.nl Fri May 25 05:46:51 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Fri, 25 May 2007 11:46:51 +0200 Subject: drag and drop with wxPython ? In-Reply-To: <1179863040.585516.155490@k79g2000hse.googlegroups.com> References: <1179863040.585516.155490@k79g2000hse.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: > On May 22, 10:00 am, stef wrote: >> hello, >> >> I'm trying to move from Delphi to Python >> (move from MatLab to Python already succeeded, also thanks to this >> discussion group). >> From the discussions in this list about "the best" GUI for Python, >> it now seems to me that wxPython is th? choice for my kind of applications. >> >> I've no experience with wxPython yet, >> I just run a few examples and indeed it looks good (as expected from the >> discussions in this list). >> >> What I really need at this moment for a new project, >> (and I coulnd't find any example, lot of broken links ;-) >> is how to implement some drag & drop facilities, >> both to drag and drop normal button, >> but also to drag and drop some dynamically created objects. >> Just like a CAD program, but far more simpler. >> >> Does anyone has an example how to drag & drop components with wxPython ? >> >> thanks, >> Stef Mientki > > Stef, > > wxPython's wiki has a couple examples: > > http://wiki.wxpython.org/DragAndDrop?highlight=%28drop%29%7C%28drag%29 > http://wiki.wxpython.org/DragAndDropWithFolderMovingAndRearranging?highlight=%28drop%29%7C%28drag%29 > > I think Larry meant to say that the wxPython demo has an example. It's > under the "Clipboard and DnD" category. > > For lots of help from people that create wxPython and its widgets, > check out the wxPython user's group here: http://www.wxpython.org/maillist.php > thanks Mike and Larry, I didn't succeed in testing (and understand what you both meant), because I had an old version of wxPython. After updating to the last version, WOW,... ... that demo is really an example how to interatively teach wxPython. BEAUTIFUL ! cheers, Stef Mientki > Mike > From tuom.larsen at gmail.com Thu May 10 08:45:24 2007 From: tuom.larsen at gmail.com (tuom.larsen at gmail.com) Date: 10 May 2007 05:45:24 -0700 Subject: Thread-safe dictionary Message-ID: <1178801124.236604.153070@u30g2000hsc.googlegroups.com> Hi, please consider the following code: from __future__ import with_statement class safe_dict(dict): def __init__(self, *args, **kw): self.lock = threading.Lock() dict.__init__(self, *args, **kw) def __getitem__(self, key): with self.lock: return dict.__getitem__(self, key) def __setitem__(self, key, value): with self.lock: dict.__setitem__(self, key, value) def __delitem__(self, key): with self.lock: dict.__delitem__(self, key) - would I need to override another methods e.g. update() or items() in order to remain thread-safe or is this enough? - in __getitem__, does it release the lock after returning the item? - wouldn't it be better to use threading.RLock, mutex, ... instead? Thanks a lot! From bdesth.quelquechose at free.quelquepart.fr Thu May 10 16:34:27 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 10 May 2007 22:34:27 +0200 Subject: elegant python style for loops In-Reply-To: <1178776272.535735.166540@h2g2000hsg.googlegroups.com> References: <1178776272.535735.166540@h2g2000hsg.googlegroups.com> Message-ID: <464377c5$0$18010$426a74cc@news.free.fr> ian.team.python at saltmob.com a ?crit : > To step through a list, the python style is avoid an explicit index. > But what if the same hidden index is to be used for more than one list > > for example:- > for key,value in listKeys,listValues : > newdict[key]=value newdict = dict(zip(listKeys, listValues)) From aleax at mac.com Thu May 3 11:02:05 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 3 May 2007 08:02:05 -0700 Subject: Microsoft's Dynamic Languages Runtime (DLR) References: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> <59s6kbF2kq8uoU1@mid.individual.net> <1178145895.865828.18220@p77g2000hsh.googlegroups.com> <59tcidF2lob6mU1@mid.individual.net> Message-ID: <1hxj28j.8erkws1cruwarN%aleax@mac.com> Duncan Booth wrote: > means in pure Python code the string has python methods, but in Python > using the CLR it gains the CLR methods. Presumably in Ruby code it looks > like a Ruby string and so on, but (and this is what's new) it is the same > object, not a bunch of language specific wrappers around the string type. So is it changeable (making Python code using it deeply unhappy) or unchangeable (making Ruby or Javascript code similarly unhappy)? The idea of just having one string type across languages is fascinating, but I'm not sure it can work as stated due to different semantics such as mutable vs immutable... Alex From bj_666 at gmx.net Wed May 16 04:01:09 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 16 May 2007 10:01:09 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649dd55$0$23144$9b4e6d93@newsspool1.arcor-online.net> <464a25e9$0$10188$9b4e6d93@newsspool4.arcor-online.net> <464A3354.4060205@web.de> Message-ID: In <464A3354.4060205 at web.de>, Stefan Behnel wrote: > Ren? Fleschenberg wrote: >> We all know what the PEP is about (we can read). The point is: If we do >> not *need* non-English/ASCII identifiers, we do not need the PEP. If the >> PEP does not solve an actual *problem* and still introduces some >> potential for *new* problems, it should be rejected. So far, the >> "problem" seems to just not exist. The burden of proof is on those who >> support the PEP. > > The main problem here seems to be proving the need of something to people who > do not need it themselves. So, if a simple "but I need it because a, b, c" is > not enough, what good is any further prove? Maybe all the (potential) programmers that can't understand english and would benefit from the ability to use non-ASCII characters in identifiers could step up and take part in this debate. In an english speaking newsgroup? =:o) There are potential users of Python who don't know much english or no english at all. This includes kids, old people, people from countries that have "letters" that are not that easy to transliterate like european languages, people who just want to learn Python for fun or to customize their applications like office suites or GIS software with a Python scripting option. Some people here seem to think the user base is or should be only from the computer science domain. Yes, if you are a programming professional it may be mandatory to be able to write english identifiers, comments and documentation, but there are not just programming professionals out there. Ciao, Marc 'BlackJack' Rintsch From rurpy at yahoo.com Thu May 10 21:55:01 2007 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 10 May 2007 18:55:01 -0700 Subject: ANN: eGenix mxODBC Distribution 3.0.0 (mxODBC Database Interface) In-Reply-To: References: Message-ID: <1178848501.032095.217850@o5g2000hsb.googlegroups.com> On May 10, 9:34 am, "eGenix Team: M.-A. Lemburg" wrote: > ANNOUNCING > eGenix.com mxODBC Database Interface I gather this is no longer free for non-commercial use (as the previous version was) and is now a totally for-pay product? From john at datavoiceint.com Tue May 8 15:54:39 2007 From: john at datavoiceint.com (HMS Surprise) Date: 8 May 2007 12:54:39 -0700 Subject: chdir() Message-ID: <1178652809.436141.176900@u30g2000hsc.googlegroups.com> Tried executing os.chdir("c:\twill") from a python Tk shell and got the error message: WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect: 'c:\twill'. I have the directory exists as I copied the name from the explorer window that was open to it. What is wrong with the syntax? thanks, jh From newsgroups at nospam.demon.co.uk Thu May 31 04:07:03 2007 From: newsgroups at nospam.demon.co.uk (Douglas Woodrow) Date: Thu, 31 May 2007 09:07:03 +0100 Subject: c[:]() References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> Message-ID: On Thu, 31 May 2007 08:57:56, Douglas Woodrow wrote >On Wed, 30 May 2007 23:23:22, Warren Stringer wrote >> >>def a(): return 'b' >>def b(): print 'polly! wakey wakey' >>c = {} >>c['a'] = b >>c[a()]() #works! > > >(typo correction for other easily-confused newbies like myself) > >I think you mean >,---- >| c['a']() #works! >`---- > Oh no, I get it, you meant... ,---- | c['b'] = b | c[a()]() #works! `---- ...or was it?:- ,---- | def a(): return 'a' `---- -- Doug Woodrow From rurpy at yahoo.com Wed May 16 16:58:36 2007 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 16 May 2007 13:58:36 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464ab64f$0$10185$9b4e6d93@newsspool4.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649dd55$0$23144$9b4e6d93@newsspool1.arcor-online.net> <464a25e9$0$10188$9b4e6d93@newsspool4.arcor-online.net> <1179291296.561359.286230@h2g2000hsg.googlegroups.com> <464ab64f$0$10185$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <1179349116.088747.167990@n59g2000hsh.googlegroups.com> On May 16, 1:44 am, Ren? Fleschenberg wrote: > rurpy at yahoo.com schrieb: > > I'm not sure how you conclude that no problem exists. > > - Meaningful identifiers are critical in creating good code. > > I agree. > > > - Non-english speakers can not create or understand > > english identifiers hence can't create good code nor > > easily grok existing code. > > I agree that this is a problem, but please understand that is problem is > _not_ solved by allowing non-ASCII identifiers! > > > Considering the vastly greater number of non-English > > spreakers in the world, who are not thus unable to use > > Python effectively, seems like a problem to me. > > Yes, but this problem is not really addressed by the PEP. I agree that the PEP does not provide a perfect solution (whatever that is) to the difficulties faced by non-english speaking Python users, but it provides a big and useful improvement. > If you want to > do something about this: > 1) Translate documentation. Done. (In some cases.) For example here are the Standard Library and Python Tutorial in Japanese: http://www.python.jp/doc/release/lib/lib.html http://www.python.jp/doc/release/tut/tut.html (I mentioned this yesterday in http://groups.google.com/group/comp.lang.python/msg/6ca67e21e9dc5358?hl=en& but I can't critisize anyone for missing messages in this hughmongous disscusion :-) > 2) Create a way to internationalize the standard library (and possibly > the language keywords, too). Ideally, create a general standardized way > to internationalize code, possibly similiar to how people > internationalize strings today. Why? Or more acurately why before adopting the PEP? The library is very usable by non-english speakers as long as there is documentation in their native language. It would be nice to have an internationalized standard library but there is no reason why this should be a prerequisite to the PEP. > When that is done, non-ASCII identifiers could become useful. But of > course, doing that might create a hog of other problems. I disagree, non-ascii identifiers are an immensely useful change, right now. Python is somewhat useable by non-english speakers now, but the identifier issue is a significant barrier. If I can't write code with identifiers that are meaninful to me (and my non-fluent-in-english colleagues) then I either write code that is hard to understand by anyone (using ascii transliterations) or write code understandable to you but not me (using english). Neither option makes sense and in practice I just use some language other than Python. > > That all programers know enough english to create and > > understand english identifiers is currently speculation or > > based on tiny personaly observed samples. > > It is based on a look at the current Python environment. You do *at > least* have the problem that the standard library uses English names. I don't know every nook and corner of the standard library. Even as an english speaker, I only look up names for things I already know. Those same things I recognise in code because I use them. Otherwise I look in the index (which is in my native language if I am not fluent in english). True, I can't use docstrings effectively. And true, I can't guess at the use of an unfamiliar name (but I have documentation) Neither of those prevent my effective use of Python, nor negate the immense value to me of being able to write code that I and my colleagues can maintain. So I see the use of english names in the standard lib as a small problem, certainly not a reason to reject the PEP. > This assumes that there is documentation in the native language that is > good enough (i.e. almost as good as the official one), which I can tell > is not the case for German. There is a chicken-and-egg problem here. Why would many non-english speaking people want to adopt Python if they cannot write maintainable (for them) programs in it? If there aren't many non-english speaking Python users, why would anyone want to put the effort into translating docs for them? This is particularly true for people that use scripts not based on latin letters. From matt at exemail.com.au Sat May 26 22:23:34 2007 From: matt at exemail.com.au (Matt van de Werken) Date: Sun, 27 May 2007 12:23:34 +1000 Subject: Python and GUI In-Reply-To: References: <1179761984.704369.116310@b40g2000prd.googlegroups.com> <38a37$4651e295$4275d90a$15861@FUSE.NET> Message-ID: <4658eba7$0$4609$61c65585@un-2park-reader-01.sydney.pipenetworks.com.au> brad wrote: > Kevin Walzer wrote: > >> 2. wxPython is big, harder to learn than Tkinter, but looks good on >> Mac, Windows, and *Nix. It will require users to install a lot of >> extra stuff (or you'll have to bundle the extra stuff). > > PyInstaller builds binaries beautifully from raw py source. No need to > bundle the wx stuff. I develop on Linux, build on Windows (with > PyInstaller) and it works great. The source runs on any platform, the > Windows binaries is neat for the point and click users. > Hi Brad: This is my preferred method of development, but I am a newcomer to python having lived in the C world for a long time. Have you any experience with this development method using boa constructor as the GUI builder? Cheers, mvdw From mail at microcorp.co.za Wed May 16 03:04:21 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 16 May 2007 09:04:21 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de><46477f19$0$19845$426a74cc@news.free.fr> <4648294F.2000704@web.de><46487a6c$0$2400$426a74cc@news.free.fr> Message-ID: <03f701c7979e$83fd7000$03000080@hendrik> "Eric Brunel" wrote: >So what? Does it mean that it's acceptable for the standard library and >keywords to be in English only, but the very same restriction on >user-defined identifiers is out of the question? Why? If I can use my own >language in my identifiers, why can't I write: > >classe MaClasse: > d?finir __init__(moi_m?me, maListe): > moi_m?me.monDictionnaire = {} > pour i dans maListe: > moi_m?me.monDictionnaire[i] = Rien > >For a French-speaking person, this is far more readable than: > >class MaClasse: > def __init__(self, maListe): > self.monDictionnaire = {} > for i in maListe: > self.monDictionnaire[i] = None > >Now, *this* is mixing apples and peaches... And this would look even >weirder with a non-indo-european language... > I don't have any French, but I support this point absolutely - having native identifiers is NFG if you can't also have native reserved words. You may be stuck with English sentence construction though. - Would be hard, I would imagine, to let the programmer change the word order, or to incorporate something as weird as the standard double negative in Afrikaans... We say things that translate literally to: "I am not a big man not.", and it is completely natural, so the if statements should follow the pattern. - Hendrik From grahn+nntp at snipabacken.dyndns.org Wed May 2 10:55:02 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 2 May 2007 14:55:02 GMT Subject: Python un-plugging the Interpreter References: <1hwu415.1yyvbo61efn1uqN%aleax@mac.com> <1hx2dgy.zizz7ir95hlgN%aleax@mac.com> Message-ID: On Tue, 24 Apr 2007 07:49:46 -0700, Alex Martelli wrote: > Jorgen Grahn wrote: > ... >> > Perhaps the current wave of dual-core and quad-core CPUs in cheap >> > consumer products would change people's perceptions -- I wonder... >> >> Maybe it would change /perceptions/, but would normal users suddenly >> start running things that are (a) performance-critical, (b) written in >> Python and (c) use algorithms that are possible to parallellize? > > That depends on what "normal" means. I used your phrase "cheap consumer products" to the max -- defining "normal users" as people who wouldn't have used an SMP machine two years ago, and don't actively choose dual core today (or choose it because they like HP's tandem bike ads). > For the common definition (users > that don't _write_ programs), it would depend on what ``developers'' > release to the world. >> I doubt it. (But I admit that I am a bit negative towards thread >> programming in general, and I have whined about this before.) > > I'm no big fan of threading either, believe me. But with multi-core > CPUs onrushing, exploiting them requires either that or multiple > processes [...] Yes. But that's where the current "concurrent programming craze" seems so odd to me. It's as if the reasoning goes: "New machines are multi-core; thus we have to find first a reason, then a way to exploit them, on the process level". Personally, I'm rarely CPU bound in my work, so I have a hard time finding that reason. I doubt even Windows users are CPU bound, except when a program hangs at 100% CPU. When I get a multi-core CPU eventually, those other CPUs will mostly do kernel-space tasks, offload things like rendering windows and doing ssh encryption/compression, and let me type "make -j2" to compile my C source code faster. No threading is needed for those things. (And even if it was, I doubt anyone would rewrite either the Linux kernel, X11, ssh or make in Python ;-) BR, /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From stefan.behnel-n05pAM at web.de Tue May 15 06:15:10 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 15 May 2007 12:15:10 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46498514$0$6402$9b4e6d93@newsspool2.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476081.7080609@web.de> <46498514$0$6402$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <4649882E.3060005@web.de> Ren? Fleschenberg wrote: > Marc 'BlackJack' Rintsch schrieb: >> You find it in the sources by the line number from the traceback and the >> letters can be copy'n'pasted if you don't know how to input them with your >> keymap or keyboard layout. > > Typing them is not the only problem. They might not even *display* > correctly if you don't happen to use a font that supports them. Sounds like high time for an editor that supports the project team in their work, don't you think? Stefan From paddy3118 at googlemail.com Mon May 21 13:58:56 2007 From: paddy3118 at googlemail.com (Paddy) Date: 21 May 2007 10:58:56 -0700 Subject: Python-URL! - weekly Python news and links (May 21) In-Reply-To: References: Message-ID: <1179770336.437369.41880@x18g2000prd.googlegroups.com> On May 21, 1:48 pm, "Gabriel Genelli" wrote: > John Nagle captures Python in a single taxonomic paragraph, and > Alex Martelli details his GUI preferences, in a thread valuable > for more than just the beginners its original poster might have > imagined: > http://groups.google.com/group/comp.lang.python/browse_thread/thread/... ... But you need to check Christopher Arndt's immediate reply to John for the corrections! - Paddy. From rurpy at yahoo.com Sun May 13 19:52:18 2007 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 13 May 2007 16:52:18 -0700 Subject: docs patch: dicts and sets In-Reply-To: <1178934092.773288.31830@o5g2000hsb.googlegroups.com> References: <1178934092.773288.31830@o5g2000hsb.googlegroups.com> Message-ID: <1179100338.610239.299180@k79g2000hse.googlegroups.com> On May 11, 7:41 pm, Raymond Hettinger wrote: > On May 11, 5:59 pm, "Alan Isaac" wrote: > > > This is an attempt to synthesize Bill and Carsten's proposals. > > (I'm changing the subject line to better match the topic.) > > >http://docs.python.org/lib/typesmapping.html:forfootnote (3) > > > Keys and values are listed in an arbitrary order. This order is > > indeterminate and generally depends on factors outside the scope of > > the > > containing program. However, if items(), keys(), values(), > > iteritems(), iterkeys(), and itervalues() are called with no > > intervening modifications to the dictionary, the lists will directly > > correspond. > > >http://docs.python.org/lib/types-set.html:appenda new sentence to 2nd par. > > > Iteration over a set returns elements in an indeterminate > > order,which > > generally depends on factors outside the scope of the containing > > program. > > This doesn't improve the docs. It suggests some mystic forces at work > while offering nothing that is actionable or that improves > understanding. Adding this kind of muck will only make the docs less > clear. I too find the suggested text not very clear and would not immediately predict from it the effects that started this thread (or actually, the thread in http://groups.google.com/group/comp.lang.python/msg/4dc632b476fdc6d3?hl=en&) > Recommend dropping this one and moving on to solve some real problems. Perhaps this attitude helps explain some of the problems in the current documentation. Dismissing this as not a "real problem" is both wrong and offensive to people taking the time to actually propose improvements. The current docs are clearly wrong. To repeat what has already been pointed out, they say, "Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary's history of insertions and deletions." It has been shown that even when the history of insertions and deletions is the same, the order may be different. Taking "history" to extend across program invocation boundaries is unconventional to put it charitably, and there is no reason to assume that interpretation would occur to a reasonable reader. The whole issue can be cleared up simply by clarifying the documentation; I really fail to see why this should be at all controversial. I will offer my own suggestion based on the belief that documentation should be as explicit as possible: "Keys and values are listed in an arbitrary but non-random order which may vary across Python versions, implementations, and the dictionary's history of insertions and deletions. When the contents are objects using the default implementation of __hash__() and __eq__(), the order will depend on the objects' id() values which may be different even between different invocations of a program (whether executed from a .py or a .pyc file for example.)" Apropos sig... -- Any software can be broken or fixed simply by changing the documentation. From wim.vogelaaratmc2worlddotorg Mon May 28 04:37:12 2007 From: wim.vogelaaratmc2worlddotorg (Wim Vogelaar) Date: Mon, 28 May 2007 10:37:12 +0200 Subject: Can python create a dictionary from a list comprehension? References: <1180299312.207986.4340@k79g2000hse.googlegroups.com> <465a90a8$0$55856$dbd43001@news.wanadoo.nl> Message-ID: <465a94a0$0$98669$dbd4f001@news.wanadoo.nl> > > why this output isn't ordered, giving: > {2: 3, 4: 5, 6: 7, 8: 9, 10: 11 } > > I made the original list two elements longer: a = [1,2,3,4,5,6,7,8,9,10,11,12] and to my surprise the output is now ordered, giving: {2: 3, 4: 5, 6: 7, 8: 9, 10: 11, 12: 13} I am running ActiveState ActivePython 2.5 From jeff at taupro.com Mon May 14 06:24:52 2007 From: jeff at taupro.com (Jeff Rush) Date: Mon, 14 May 2007 05:24:52 -0500 Subject: A Call for Professional Trainers of Python Message-ID: <464838F4.7080102@taupro.com> I am seeking to organize the list of those, both individuals and companies, who offer training on Python and related frameworks and technologies. This is for those who provide this, typically to businesses, as part of their professional offerings, in order to provide an answer to Forrester Research. They are surveying the various dynamic programming languages and want to know, essentially, how easily can an IT manager get his people trained up on Python in comparison to other languages. There is a wiki page at: http://wiki.python.org/moin/PythonTraining with some training organizations. If your information is already there *and current*, no response is necessary. But if you are not mentioned, please update that wiki page so we can get an accurate accounting and perhaps send business your way. Thanks, Jeff Rush Python Advocacy Coordinator From hg at nospam.org Thu May 3 08:20:03 2007 From: hg at nospam.org (hg) Date: Thu, 03 May 2007 14:20:03 +0200 Subject: Real Time Battle and Python Message-ID: Hi, I have started to work on a python-based robot, and am interested in your feedback: http://realtimebattle.sourceforge.net/ www.snakecard.com/rtb hg From kelvin.you at gmail.com Wed May 30 03:05:36 2007 From: kelvin.you at gmail.com (=?gb2312?B?yMvR1MLkyNXKx8zs0cSjrM37vKvM7NHEsru8+7zS?=) Date: 30 May 2007 00:05:36 -0700 Subject: How to print this character u'\u20ac' to DOS terminal In-Reply-To: <465D0A6B.1000203@v.loewis.de> References: <1180501468.957322.106650@z28g2000prd.googlegroups.com> <465D0A6B.1000203@v.loewis.de> Message-ID: <1180508736.598924.26170@r19g2000prf.googlegroups.com> On 5??30??, ????1??23??, "Martin v. Lo"wis" wrote: > ?????????????????????????????? schrieb: > > > Who could explain the follow issue ? > >>>> print u'\u0394' > > ?? > >>>> print u'\u20ac' > > Traceback (most recent call last): > > File "", line 1, in > > UnicodeEncodeError: 'gbk' codec can't encode character u'\u20ac' in > > position 0: > > illegal multibyte sequence > > > My terminal is cmd.exe under windows XP. > > what's the different between the two character ? what can I do if I > > want to print the u'\u20ac'? > > The problem is that your terminal uses (some form of) the GBK encoding; > seehttp://zh.wikipedia.org/wiki/GBKfor details on GBK. > > It seems that GBK (or, rather, code page 936) supports the delta > character, but not the euro sign. > > To change that, you can use "chcp" in your terminal window. > For example, if you do "chcp 850", you should be able to > display the euro sign (but will simultaneously use the ability > to display the letter delta, and the chinese letters). > > I don't know whether the terminal supports an UTF-8 code > page; you can try setting the terminal's code page to > 65001 (which should be UTF-8). > > Regards, > Martin Thanks, but it seems not work yet. ---------------------------------------------------- C:\WINDOWS>chcp 850 Active code page: 850 C:\WINDOWS>python 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. >>> print u'\u20ac' Traceback (most recent call last): File "", line 1, in File "C:\Python25\lib\encodings\cp850.py", line 12, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeEncodeError: 'charmap' codec can't encode character u'\u20ac' in position 0: character maps to C:\WINDOWS>chcp 65001 Active code page: 65001 C:\WINDOWS>python 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. >>> print u'\u20ac' Traceback (most recent call last): File "", line 1, in LookupError: unknown encoding: cp65001 ----------------------------------------------- I find that the u'\u20ac' related 'mbcs' encode is 0x80, I could print it directly >>> print '\x80' ? >>> But the string contained the u'\u20ac' is get from remote host. Is there any method to decode it to the local 'mbcs'? From noagbodjivictor at gmail.com Thu May 3 19:52:34 2007 From: noagbodjivictor at gmail.com (noagbodjivictor at gmail.com) Date: 3 May 2007 16:52:34 -0700 Subject: When does input() return an empty string? In-Reply-To: <1178236247.729807.172790@y5g2000hsa.googlegroups.com> References: <1178235780.197074.161700@h2g2000hsg.googlegroups.com> <1178236247.729807.172790@y5g2000hsa.googlegroups.com> Message-ID: <1178236354.617544.177590@y5g2000hsa.googlegroups.com> On May 3, 7:50 pm, Andr? wrote: > On May 3, 8:43 pm, noagbodjivic... at gmail.com wrote: > > > I'm filling an array with user input, I want an empty string to be > > returned when nothing is entered; ie return key hit twice... How do I > > do that? > > use raw_input(), not input(). input() attempts to evaluate the > result, assuming it is a valid python expression. > > Andr? Thanks From robert.kern at gmail.com Wed May 9 15:51:08 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 09 May 2007 14:51:08 -0500 Subject: Single precision floating point calcs? In-Reply-To: <1343v0emvdjr545@corp.supernews.com> References: <1343v0emvdjr545@corp.supernews.com> Message-ID: Grant Edwards wrote: > I'm pretty sure the answer is "no", but before I give up on the > idea, I thought I'd ask... > > Is there any way to do single-precision floating point > calculations in Python? > > I know the various array modules generally support arrays of > single-precision floats. I suppose I could turn all my > variables into single-element arrays, but that would be way > ugly... We also have scalar types of varying precisions in numpy: In [9]: from numpy import * In [10]: float32(1.0) + float32(1e-8) == float32(1.0) Out[10]: True In [11]: 1.0 + 1e-8 == 1.0 Out[11]: False If you can afford to be slow, I believe there is an ASPN Python Cookbook recipe for simulating floating point arithmetic of any precision. -- 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 Mon May 7 19:54:53 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 07 May 2007 19:54:53 -0400 Subject: No module named urllib In-Reply-To: <1178580280.902179.248000@w5g2000hsg.googlegroups.com> References: <1178575589.059564.226060@q75g2000hsh.googlegroups.com> <87tzuop8s2.fsf@gmail.com> <1178577562.498615.222340@e51g2000hsg.googlegroups.com> <87ps5cp816.fsf@gmail.com> <1178578923.067315.14440@q75g2000hsh.googlegroups.com> <1178580280.902179.248000@w5g2000hsg.googlegroups.com> Message-ID: <1178582093.3231.6.camel@localhost.localdomain> On Mon, 2007-05-07 at 16:24 -0700, HMS Surprise wrote: > Since sys.path = ['.', 'C:\\maxq\\lib\\Lib', 'C:\\maxq\\jython'] I > copied urllib to c:\maxq\lib\Lib. > > Now I get the error - > > Traceback (innermost last): > File "", line 5, in ? > File "C:\maxq\lib\Lib\urllib.py", line 1148 > _hextochr = dict(('%02x' % i, chr(i)) for i in range(256)) > ^ > SyntaxError: invalid syntax The urllib.py you're using is not compatible with the Python you're using. The snippet above uses Python 2.4+ syntax, and Jython's syntax is at 2.1 (stable) or 2.2 (beta). -- Carsten Haese http://informixdb.sourceforge.net From gagsl-py2 at yahoo.com.ar Wed May 2 13:09:23 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 02 May 2007 14:09:23 -0300 Subject: I need help speeding up an app that reads football scores and generates rankings References: <1178118022.865173.266300@h2g2000hsg.googlegroups.com> Message-ID: En Wed, 02 May 2007 12:16:56 -0300, Marc 'BlackJack' Rintsch escribi?: > In <1178118022.865173.266300 at h2g2000hsg.googlegroups.com>, jocknerd > wrote: > >> The biggest difference in my two apps is the C app uses linked lists. >> I feel my Python app is doing too many lookups which is causing the >> bottleneck. > > Then replace those linear searches you wrote in Python with a dictionary. As an example: using a Team object instead of a dictionary, and using teamlist (not a good name now) as a dictionary of Team objects indexed by name: def lookupTeam (teamname): team = teamlist.get(teamname) if team is None: teamlist[teamname] = team = Team(teamname) return team def updateTeamStats (tname1, score1, tname2, score2): team1 = lookupTeam (tname1) team2 = lookupTeam (tname2) team1.pf += score1 team1.pa += score2 if (score1 > score2): team1.won += 1 elif (score1 < score2): team1.lost += 1 else: team1.tied += 1 team2.pf += score2 team2.pa += score1 if (score1 < score2): team2.won += 1 elif (score1 > score2): team2.lost += 1 else: team2.tied += 1 Then you should realize that those last two blocks are too similar, and you can make a function of it. And then you realize that in fact they act on a Team object, so you should make a Team method... -- Gabriel Genellina From turbana at gmail.com Tue May 1 17:46:18 2007 From: turbana at gmail.com (Ian Clark) Date: Tue, 1 May 2007 14:46:18 -0700 Subject: Removing the continous newline characters from the pythong string In-Reply-To: <1178055012.135278.104430@p77g2000hsh.googlegroups.com> References: <1178055012.135278.104430@p77g2000hsh.googlegroups.com> Message-ID: On 1 May 2007 14:30:12 -0700, mobil wrote: > Hi guys i m trying out newline characters and to clean them up > a\n\n\n\n\n\n\n\n\nsss\n\n\n\n\n\n\n\n\n\n\nvvvv\n\n\n\nvsa\n\n\n\nasf > \n\nafs > > hello guys > > im trying to replace > \n\n\n\n\n\n\n\n\n with \n > > thanks for help > > \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n also with \n as the browser gives > \r carrriage returns > > thanks for any help or pointers Is this what you were looking for? >>> import re >>> message = '\n\r\n\r\n\n\nhello there\n\r\n!\n' >>> regex = re.compile('[\n\r]+') >>> regex.sub('\n', s) '\nhello there\n!\n' Ian From alan.franzoni_invalid at geemail.invalid Wed May 2 17:30:20 2007 From: alan.franzoni_invalid at geemail.invalid (Alan Franzoni) Date: Wed, 2 May 2007 23:30:20 +0200 Subject: Can I use Python instead of Joomla? References: <1178138925.498663.252920@o5g2000hsb.googlegroups.com> Message-ID: <1gcfs4rajxd32$.1nulvl3d7rkv3$.dlg@40tude.net> Il 2 May 2007 13:48:45 -0700, walterbyrd ha scritto: > If I wanted to build a website with forums, news feeds, galleries, > event calander, document managment, etc. I do so in Joomla easily. You're using Joomla, which is a CMS written in PHP. Python is a language, you should ask 'can I use Python instead of PHP'. There are various Python CMSes lying around, you already got the link from the Python wiki. Now, you should check if they offer the same level of functionality and support that Joomla offers - and it may or may not be the case; consider that Joomla and Mambo have been around since years, while Python cmses and web frameworks are relatively young. Finally, Django is a framework, not a CMS. It is used to create websites and may be used to actually create CMSes. Now the important part: if you're not a PHP programmer, you can still use Joomla. You just download it, follow the instructions, plug in any pre-packed addon, and use it. You could probably do the very same with some of the Python CMSes around. Django is different: you must be able to program Python in order to use it. Nothing works from the beginning, since it's not a CMS: you must code it. -- Alan Franzoni - Togli .xyz dalla mia email per contattarmi. Remove .xyz from my address in order to contact me. - GPG Key Fingerprint (Key ID = FE068F3E): 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From theller at ctypes.org Wed May 9 14:13:08 2007 From: theller at ctypes.org (Thomas Heller) Date: Wed, 09 May 2007 20:13:08 +0200 Subject: ctypes: Problems using Windows-DLL from VB example code In-Reply-To: <4642091d$1@news.broadpark.no> References: <4641fd20$1@news.broadpark.no> <4642091d$1@news.broadpark.no> Message-ID: >> Have you tried to pass the structure by reference? >> >> dso_lib.port_init(byref(init_data)) > > That gives me another exeption: > > print dso_lib.port_init(byref(init_data)) > ValueError: Procedure called with not enough arguments (4 bytes missing) or > wrong calling convention Please try using 'windll' instead of 'cdll' to load the library; then call 'dso_lib.port_init(byref(init_data))'. Thomas From rurpy at yahoo.com Wed May 16 18:38:01 2007 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 16 May 2007 15:38:01 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179337277.347833.237450@n59g2000hsh.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179289167.723990.223890@u30g2000hsc.googlegroups.com> <464abd12$0$23364$426a34cc@news.free.fr> <1179307776.953405.207680@l77g2000hsb.googlegroups.com> <464ad388$0$28786$426a34cc@news.free.fr> <1179337277.347833.237450@n59g2000hsh.googlegroups.com> Message-ID: <1179355081.828574.241690@h2g2000hsg.googlegroups.com> On May 16, 11:41 am, "sjdevn... at yahoo.com" wrote: > Christophe wrote: ....snip... > > Who displays stack frames? Your code. Whose code includes unicode > > identifiers? Your code. Whose fault is it to create a stack trace > > display procedure that cannot handle unicode? You. > > Thanks but no--I work with a _lot_ of code I didn't write, and looking > through stack traces from 3rd party packages is not uncommon. Are you worried that some 3rd-party package you have included in your software will have some non-ascii identifiers buried in it somewhere? Surely that is easy to check for? Far easier that checking that it doesn't have some trojan code it it, it seems to me. > And I'm often not creating a stack trace procedure, I'm using the > built-in python procedure. > > And I'm often dealing with mailing lists, Usenet, etc where I don't > know ahead of time what the other end's display capabilities are, how > to fix them if they don't display what I'm trying to send, whether > intervening systems will mangle things, etc. I think we all are in this position. I always send plain text mail to mailing lists, people I don't know etc. But that doesn't mean that email software should be contrainted to only 7-bit plain text, no attachements! I frequently use such capabilities when they are appropriate. If your response is, "yes, but look at the problems html email, virus infected, attachements etc cause", the situation is not the same. You have little control over what kind of email people send you but you do have control over what code, libraries, patches, you choose to use in your software. If you want to use ascii-only, do it! Nobody is making you deal with non-ascii code if you don't want to. From SuperM at ssiveBlackHoleAtTheCenterOfTheMilkyWayGalaxy.org Thu May 3 07:21:09 2007 From: SuperM at ssiveBlackHoleAtTheCenterOfTheMilkyWayGalaxy.org (The Great Attractor) Date: Thu, 03 May 2007 04:21:09 -0700 Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> <1178162456.929395.139390@q75g2000hsh.googlegroups.com> <1178163851.199354.14450@n59g2000hsh.googlegroups.com> Message-ID: On 2 May 2007 20:44:11 -0700, Midex wrote: > >You're that ignorant and brainwashed lost that you can't see that the >media didn't want youto see this footage and thus why you havn't seen >it before? You're a fucking idiot. From xah at xahlee.org Thu May 3 15:15:32 2007 From: xah at xahlee.org (Xah Lee) Date: 3 May 2007 12:15:32 -0700 Subject: Why stay with lisp when there are python and perl? In-Reply-To: <1178155239.007219.205020@y5g2000hsa.googlegroups.com> References: <1178155239.007219.205020@y5g2000hsa.googlegroups.com> Message-ID: <1178219732.127815.3260@y80g2000hsf.googlegroups.com> Nameless wrote: ? Python has readable syntax, a huge library, and bindings for what seems like every major in linux. Perl has CPAN. It seems with those languages if you want to do something all you have to do is import functionality from a library someone had written and use that. In lisp you'd have to "roll your own". Why should I keep on learning lisp when there are python and perl? ? You question is a valid question. Unfortunately, so far in the 14 replies in the thread, vast majority are one-liner drivels from reactionary lisp fuckheads, many of which long time dwellers of comp.lang.lisp. A common scene in any programing newsgroup. They feel attacked, reasonably by your irrespective and incentive tone, and they have the need to sputter drivel back, to entertain themselves. (I wish perl and python programers take a glimpse of that thread to realize what computing factions are driveling behind each other's back) Although your message is written in a taunting style, but it has a valid point, and in fact is a Frequently Ask Question among the vast majority of programers in the computing industry. Namely, today, languages like Perl, PHP, and to a lesser degree Python, are so popular, and ubiquitous, widely deployed and widely demanded in the job market, and also, that these languages in general and in comparison to Lisp, have far wide library support and as well as community support, and also, that these comparatively young languages are relatively high-level modern languages, that they are at a level above C, Java, making them ideal for saving programer's time as does lisp. So, what are some reasons, if any, should today's programer invest time into another language lisp (especially it has trivial percentage in programing job market), while not using the time, to perhaps master a industrial language they already know, such as Perl, or even venture into another language like Python, PHP or the new kid on the block Ruby? So far, ?D Herring? and ?fireblade/bobi? has given their personal take on this question. Lars Rune N?stdal, provided a link http://wiki.alu.org/The_Road_to_Lisp_Survey that details lispers's stories on why lispers lisp. Please allow me to give my take, and i believe it is a most important _technical_ reason, why, Perl, Python, etc languages today simply cannot replace lisp. And why, if you are a programer with serious intention of refining your craft, then learning lisp is a good investment. (one non-technical reason in learning lisp, is that the widely popular programer's text editor emacs has lisp embedded as its extension language. As a coder, knowing emacs and lisp, will enpower you greatly in the long term.) I think the one most important techincal aspect, that lisp is in fact superior and cannot be replaced by the current crop of high-level languages, is the peculiar fact that the language deals with symbols. Namely, sometimes called symbolic computing. I have written a exposition on this issue before. It is archived at this page: ?What is Expressiveness in a Computer Language? http://xahlee.org/perl-python/what_is_expresiveness.html at the section Symbolic Computation. There are many ?papers? or articles that address the question of what does it mean when someone says lisp is a symbolic language. In my opnion, they are all fuzzy, or filled with academic jargons that is practically and most likely theoretically useless. In the following exposition, you will see what lisp's ?symbolic computation? in a way that makes you understand. I excerpt the section below. SYMBOLIC COMPUTATION Lisp differs from most imperative programing languages in that it deals with symbols. What does this mean? In imperative languages, a value can be assigned a name, and this name is called a variable. For example, ?x=3?, and whenever this ?name? is encountered, it is evaluated to its value. It does not make any sense, to have variables without a assigned value. That is, the ?x? is not useful and cannot be used until you assign something to it. However, in lisp, there is a concept of Symbols. As a way of explanation, a ?variable? needs not to be something assigned of a value. Symbols can stand by themselves in the language. And, when a symbol is assigned a value, the symbol can retain its symbolic form without becoming a value. This means that in lisp, ?variables? can be manipulated in its un- evaluated state. The situation is like the need for the ?evaluate? command in many languages, where the programer can built code as strings and do ?evaluate(myCodeString)? to achieve meta-programing. For example, in imperatives languages once you defined ?x=3?, you cannot manipulate the variable ?x? because it gets evaluated to 3 right away. If you want, you have to build a string ?"x"? and manipulate this string, then finally use something like ?evaluate(myCodeString)? to achieve the effect. If the imperative language does provide a ?evaluate()? function, its use breaks down quickly because the language is not designed for doing it. It's extremely slow, and impossible to debug, because there lacks facilities to deal with such meta programing. In lisp, variable's unevaluated form are always available. One just put a apostrophe ' in front of it. In ?x=3?, the x is a variable in the contex of the code logic, x is a name of the variable in the context of meaning analysis, and x is a symbol in the context of the programing language. This Symbols concept is foreign to imperative languages. It is also why lisp are known as symbolic languages. Such makes meta-programing possible. The power of symbolic processing comes when, for example, when you take user input as code, or need to manipulate math formulas, or writing programs that manipulates the source code, or generate programs on the fly. These are often needed in advanced programing called Artificial Intelligence. This is also the reason, why lisp's ?macro? facility is a powerful feature unlike any so-called ?pre- processors? or ?templates? in imperative languages. Mathematica for example, is sometimes known as a Computer Algebra System. It too, works with symbols in the language. They can be manipulated, transformed, assigned a value, evaluated, hold unevaluated etc. One way for a imperative programer to understand symbols, is to think of computing with strings, such as which Perl and Python are well known for. With strings, one can join two strings, select sub strings, use string pattern (regex) to transform strings, split a string into a list for more powerful manipulation, and use ?evaluate()? to make the string alive. Now imagine all these strings need not be strings but as symbols in the language, where the entire language works in them and with them, not just string functions. That is symbolic computation. Here we see, a expressibility unseen in non-lisp family of languages. -------------------------- End excerpt. (if there is some demand, i will add a concrept, little programing example, that shows, how lisp's symbols and macros concepts, set it apart from new scripting languages) This lisp's symbol concept, as far as i know, does not exist in some other high-level functional programing languages such as Haskell. I'm not familiar with many functional languages except Lisp and Mathematica. I'm curious, as to how Haskell, which itself is quite with capable of symbolic computation i think, deals with it even though the language doesn't employ the concep of lisp's symbols per se. Xah xah at xahlee.org ? http://xahlee.org/ From bj_666 at gmx.net Sun May 20 15:59:22 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sun, 20 May 2007 21:59:22 +0200 Subject: TIFF to PDF References: <1179687595.142454.23850@z24g2000prd.googlegroups.com> Message-ID: In <1179687595.142454.23850 at z24g2000prd.googlegroups.com>, revuesbio wrote: > I'm looking for : > 1/ the best method to convert tiff files to PDF. > 2/ and I want to merge these pdf files. If it doesn't need to be done in pure Python I would use the command line tools from libtiff: `tiffcp` to copy several tiffs into one multipage tiff and `tiff2pdf` to convert it into PDF. Ciao, Marc 'BlackJack' Rintsch From steve at holdenweb.com Sat May 19 09:36:53 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 19 May 2007 09:36:53 -0400 Subject: Writelines() a bit confusing In-Reply-To: <1179578195.565952.244110@u30g2000hsc.googlegroups.com> References: <1179578195.565952.244110@u30g2000hsc.googlegroups.com> Message-ID: aiwarrior wrote: > If file.WriteLines( seq ) accepts a list and it says it writes lines, > why does it write the whole list in a single line. Be cause of that > the reverse of file.writelines(seq) is not file.readlines(). > Are the assumptions i made correct? If yes why is this so? > > I find a function called writelines not actualy writing the list in > lines wierd. > > [code] > something = ['re','ri','ro'] > f.writelines( something ) > something_else = f.readlines() > [/code] > In this case the list something_else will be diffrent from something > Your list is *not* what you would get in from a call to readlines. Try 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From http Sun May 13 23:12:23 2007 From: http (Paul Rubin) Date: 13 May 2007 20:12:23 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <20070513160046.GC29172@v.igoro.us> <7x646wa9wz.fsf@ruckus.brouhaha.com> <7xfy608bkk.fsf@ruckus.brouhaha.com> Message-ID: <7xejlk3xpk.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > If I'm mistaken, please explain why I'm mistaken, not just repeat your > claim in different words. if user_entered_password != stored_password_from_database: password_is_correct = False ... if password_is_correct: log_user_in() Does "password_is_correct" refer to the same variable in both places? From apatheticagnostic at gmail.com Wed May 23 02:15:00 2007 From: apatheticagnostic at gmail.com (kaens) Date: Wed, 23 May 2007 02:15:00 -0400 Subject: xml.parsers.expat loading xml into a dict and whitespace In-Reply-To: <163f0ce20705222307n2bc79f44r6099e8e008beb460@mail.gmail.com> References: <163f0ce20705222253h2d171b1fs61efa448ad86dc8e@mail.gmail.com> <163f0ce20705222307n2bc79f44r6099e8e008beb460@mail.gmail.com> Message-ID: <163f0ce20705222315o24ca3e6co318d949b1e76070b@mail.gmail.com> Ok, I can fix it by modifying if self.inOptions and self.curTag != "options": to if self.inOptions and self.curTag != "options" and self.curTag != "" but this feels really freaking ugly. Sigh. Any suggestions? I know I must be missing something. Also, I hate the tendency I have to figure stuff out shortly after posting to a mailing list or forum. Happens all the time, and I swear I don't solve stuff until I ask for help. On 5/23/07, kaens wrote: > Wait. . . it's because the curTag is set to "", thus it sets the > whitespace after a tag to that part of the dict. > > That doesn't explain why it does it on a xml file containing no > whitespace, unless it's counting newlines. > > Is there a way to just ignore whitespace and/or xml comments? > > On 5/23/07, kaens wrote: > > Hey everyone, this may be a stupid question, but I noticed the > > following and as I'm pretty new to using xml and python, I was > > wondering if I could get an explanation. > > > > Let's say I write a simple xml parser, for an xml file that just loads > > the content of each tag into a dict (the xml file doesn't have > > multiple hierarchies in it, it's flat other than the parent node) > > > > so we have > > > > foo > > bar > > . . . > > > > > > (I'm using xml.parsers.expat) > > the parser sets a flag that says it's in the parent, and sets the > > value of the current tag it's processing in the start tag handler. > > The character data handler sets a dictionary value like so: > > > > dictName[curTag] = data > > > > after I'm done processing the file, I print out the dict, and the first value is > > : > > > > There are comments in the xml file - is this what is causing this? > > There are also blank lines. . .but I don't see how a blank line would > > be interpreted as a tag. Comments though, I could see that happening. > > > > Actually, I just did a test on an xml file that had no comments or > > whitespace and got the same behaviour. > > > > If I feed it the following xml file: > > > > > > hey > > bee > > eff > > > > > > it prints out: > > " : > > > > three : eff > > two : bee > > one : hey" > > > > wtf. > > > > For reference, here's the handler functions: > > > > def handleCharacterData(self, data): > > if self.inOptions and self.curTag != "options": > > self.options[self.curTag] = data > > > > def handleStartElement(self, name, attributes): > > if name == "options": > > self.inOptions = True > > if self.inOptions: > > self.curTag = name > > > > > > def handleEndElement(self, name): > > if name == "options": > > self.inOptions = False > > self.curTag = "" > > > > Sorry if the whitespace in the code got mangled (fingers crossed...) > > > From exarkun at divmod.com Fri May 4 08:56:45 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 4 May 2007 08:56:45 -0400 Subject: Non blocking sockets with select.poll() ? In-Reply-To: Message-ID: <20070504125645.19381.772631055.divmod.quotient.8302@ohm> On Fri, 4 May 2007 15:05:46 +0300, Maxim Veksler wrote: >On 5/4/07, Maxim Veksler wrote: >>On 5/4/07, Jean-Paul Calderone wrote: >> > On Fri, 4 May 2007 13:04:41 +0300, Maxim Veksler >>wrote: >> > >Hi, >> > > >> > >I'm trying to write a non blocking socket port listener based on >> > >poll() because select is limited to 1024 fd. >> > > >> > >Here is the code, it never gets to "I did not block" until I do a >> > >telnet connection to port 10000. >> > > >> > >> > What were you expecting? >> > >> >>I'll try to explain. >>I'm doing a little experiment: Capturing the whole tcp 1-65535 range >>of the machine, allowing me to connect to the my service on the >>machine on every port. I know that it's probably the most dumb thing >>to do with TCP/IP communication please don't forget it's an >>experiment. > >[snip] > >I think I got it working now :) > >""" >#!/usr/bin/env python >import socket >import select > >class PollingSocket(socket.socket): > > > def __init__(self, port_number): > self.__poll = select.poll() > self.tcp_port_number = port_number > > socket.socket.__init__(self, socket.AF_INET, socket.SOCK_STREAM) > self.setblocking(0) > self.bind(('0.0.0.0', self.tcp_port_number)) > self.listen(5) > self.__poll.register(self) > > def poll(self, timeout = 0): > return self.__poll.poll(timeout) > >def debugPollingSocket(port_num): > print "BIND TO PORT: ", port_num > return PollingSocket(port_num) > >all_sockets = map(debugPollingSocket, xrange(10000, 19169)) > >print "We have this in stock:" >for nb_active_socket in all_sockets: > print nb_active_socket.tcp_port_number > >while 1: > for nb_active_socket in all_sockets: > print "Asking", nb_active_socket.tcp_port_number > if nb_active_socket.poll(0): > print "Found", nb_active_socket.tcp_port_number > conn, addr = nb_active_socket.accept() > while 1: > data = conn.recv(1024) > if not data: break > conn.send(data) > conn.close() >""" > This will only handle one connection at a time, of course. The polling it does is also somewhat inefficient. Perhaps that's fine for your use case. If not, though, I'd suggest this version (untested): from twisted.internet import pollreactor pollreactor.install() from twisted.internet import reactor from twisted.protocols.wire import Echo from twisted.internet.protocol import ServerFactory f = ServerFactory() f.protocol = Echo for i in range(10000, 19169): reactor.listenTCP(i, f) reactor.run() This will handle traffic from an arbitrary number of clients at the same time and do so more efficiently than the loop in your version. You can also try epollreactor instead of pollreactor, if the version of Linux you are using supports epoll, for even better performance. Jean-Paul From steve at holdenweb.com Thu May 24 19:09:09 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 24 May 2007 19:09:09 -0400 Subject: 0 == False but [] != False? In-Reply-To: <1180047740.001604.267170@q66g2000hsg.googlegroups.com> References: <1179982400.412340.178710@g4g2000hsf.googlegroups.com> <1rda53hphn117k5scvcqrc7c2e37utfhgu@4ax.com> <1180047740.001604.267170@q66g2000hsg.googlegroups.com> Message-ID: Dan Bishop wrote: > On May 24, 1:59 am, Tim Roberts wrote: > ... >> False is just a constant. 0, (), '', [], and False are all constants that >> happen to evaluate to a false value in a Boolean context, but they are not >> all the same. >> >> As a general rule, I've found code like "if x == False" to be a bad idea in >> ANY language. > > I have a job as a C++ programmer, and they make us write it like that, > apparently because the ! operator is hard to see. But "if (x == > TRUE)" is discouraged. > Find a new employer. I'm not joking. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From carsten at uniqsys.com Wed May 9 17:16:18 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 09 May 2007 17:16:18 -0400 Subject: change of random state when pyc created?? In-Reply-To: References: <5ae25fF2oggbqU1@mid.uni-berlin.de> Message-ID: <1178745378.3355.108.camel@dot.uniqsys.com> On Wed, 2007-05-09 at 15:35 -0500, Alan G Isaac wrote: > Robert Kern wrote: > > http://docs.python.org/lib/typesmapping.html > > """ > > Keys and values are listed in an arbitrary order which is non-random, varies > > across Python implementations, and depends on the dictionary's history of > > insertions and deletions. > > """ > > > Even this does not tell me that if I use a specified implementation > that my results can vary from run to run. That is, it still does > not communicate that rerunning an *unchanged* program with an > *unchanged* implementation can produce a change in results. It doesn't say that rerunning the program won't produce a change in results. It doesn't say that the order depends *only* on those factors in a deterministic and reproducible manner. The documentation shouldn't be expected to list every little thing that might change the order of keys in a dictionary. The documentation does say explicitly what *is* guaranteed: Order of keys is preserved as long as no intervening modifications happen to the dictionary. Tearing down the interpreter, starting it back up, and rebuilding the dictionary from scratch is very definitely an intervening modification. Regards, -- Carsten Haese http://informixdb.sourceforge.net From __peter__ at web.de Thu May 24 04:47:38 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 24 May 2007 10:47:38 +0200 Subject: Call script which accepts com. line par. from another scriptand error control References: Message-ID: Karim Ali wrote: > What I still dont know though is how do I handle the fact that the first > script is expecting command line parameters. I would like to be able to > replace the command line parameters by a variable such that the second > script can call: first_script.main("command line"). Is this possible? I think it is better to pass a list of arguments # first_script.py def main(args=None): parser = optparse.OptionParser() # add options options, positional_args = parser.parse_args(args) # process if __name__ == "__main__": # will read options from the command line # if module is invoked as a standalone script main() # second_script.py import first_script first_script.main(["-f", "--bar", "what", "you want"]) That way you don't have to deal with escaping spaces etc. Peter From siasookhteh at gmail.com Wed May 23 07:53:55 2007 From: siasookhteh at gmail.com (Siah) Date: 23 May 2007 04:53:55 -0700 Subject: Basic Class/Instance Question In-Reply-To: Message-ID: <1179921235.622391.230150@h2g2000hsg.googlegroups.com> I think that's because: >>> [] is [] False >>> () is () True -- Sia From JoeSalmeri at hotmail.com Thu May 24 13:49:55 2007 From: JoeSalmeri at hotmail.com (Joe Salmeri) Date: Thu, 24 May 2007 13:49:55 -0400 Subject: pyodbc data corruption problem References: Message-ID: I have done some additiona investigate into this problem and found the following: As described below the problem does not begin to appear until the return value size is > 2048. Once the return value is greater than 2048 bytes the value returned by pyodbc is 2 times the actual size of the return value data. The return value data is padded by exactly the same number of null characters as there are in the actual data size. In other words if the actual database value is 4868 bytes, then pyodbc will return a value that is 9736 bytes long. The first 4868 bytes will be the real data, followed by 4868 bytes of nulls. I did a second test where the actual data size was 11,109 bytes. In that case pyodbc returned a value that was 22,218 bytes long. The first 11,109 bytes are the real data, followed by 11,109 null bytes. This seems to confirm the bug. "Joe Salmeri" wrote in message news:EPidnR__UJAnp9PbnZ2dnUVZ_u6rnZ2d at comcast.com... >I have found a data corruption problem with pyodbc. > > OS = Windows XP SP2 > DB = Microsoft Access XP > > PROBLEM: > > When selecting columns from a table that are of type Memo the value > returned is padded with a bunch of null characters at the end. > > The problems does not seem to occur until the length of the Memo column > exceeds 2048 bytes. > > I have attached several scripts to help demonstrate the problem. > > To recreate the problem: > > 1. Create a blank Access database named test. > 2. Create a ODBC DSN named test for that database > 3. Run the createtable.py script to create the table > and load it with the dummy data > 4. Run the broke.py script to show the problem. > > The issue is when the data value is > 2048 bytes. > > The size in the createtable.py is 2046 bytes plus 3 bytes at the end that > contain "JOE" for a total of 2049 bytes. > > If you change it from 2046 to 2045 (or less) then the problem does not > occur. > > # > # createtable.py script > # > > import pyodbc > > dbs = pyodbc.connect('dsn=test') > > c = dbs.cursor() > > try: > sql = 'drop table test_memo' > c.execute(sql) > dbs.commit() > except: > # ignore drop table failure > pass > > sql = 'create table test_memo (c1 int not null, c2 memo not null)' > > c.execute(sql) > > dbs.commit() > > sql = 'insert into test_memo values(1, ?)' > > c2_value = '1' * 2046 > > c2_value = '%sJOE' % (c2_value) > > c.execute(sql, (c2_value,)) > > dbs.commit() > > c.close() > dbs.close() > > # > # broke.py script > # > > > import pyodbc > > dbs = pyodbc.connect('dsn=test') > > c = dbs.cursor() > > sql = 'select c2, len(c2) as c2_db_len from test_memo where c1 = 1' > > c.execute(sql) > > row = c.fetchone() > > ( > c2, > c2_db_len > ) = row > > print repr(c2) > > print 'c2 length :', len(c2) > print 'c2_db_length :', c2_db_len > > print 'before nul length:', len(c2[0:c2.find('\x00')]) > > c.close() > dbs.close() > > > From email at christoph-haas.de Mon May 7 03:13:06 2007 From: email at christoph-haas.de (Christoph Haas) Date: Mon, 7 May 2007 09:13:06 +0200 Subject: N00b question on Py modules In-Reply-To: <1178521238.333095.111370@h2g2000hsg.googlegroups.com> References: <1178521238.333095.111370@h2g2000hsg.googlegroups.com> Message-ID: <20070507071306.GA11562@torf.workaround.org> On Mon, May 07, 2007 at 12:00:38AM -0700, lokesh.jagasia at gmail.com wrote: > Hi. Sorry to sound like a noob but that's what I am when it comes to > Python. I just wrote the below module and it behaves funny. > > My python module: > > _exitcode = 0 > > def setExitCode(): > _exitcode = 1 > > if __name__ == '__main__': > print _exitcode > setExitCode() > print _exitcode > > Actual O/P: > 0 > 0 > > I expected to see an output of 0 followed by 1. But it turns out that > the _exitcode variable is not changed at all. It seems that > setExitCode() might be editing a local copy of the _exitcode variable. > But then, how do I tell it to change the value of the module variable > and not its local variable. _exitcode is a global variable in your program. In functions (def) you can read global variables. But if you change or reassign them the change will be only local to the function. If you want to change the global variable your def needs to be: def setExitCode(): global _exitcode _exitcode = 1 Kindly Christoph From bbxx789_05ss at yahoo.com Tue May 1 13:06:23 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 1 May 2007 10:06:23 -0700 Subject: Having problems accepting parameters to a function In-Reply-To: <1178037488.163487.114930@l77g2000hsb.googlegroups.com> References: <1178037488.163487.114930@l77g2000hsb.googlegroups.com> Message-ID: <1178039183.030942.86270@y5g2000hsa.googlegroups.com> On May 1, 10:38 am, rh0dium wrote: > Hi Experts!! > > I am trying to get the following little snippet to push my data to the > function func(). What I would expect to happen is it to print out the > contents of a and loglevel. But it's not working. Can someone please > help me out. > > ----------------------- > #!/usr/bin/env python > > import random > > def func(*args, **kwargs): > print kwargs.get('a', "NOPE") > print kwargs.get('loglevel', "NO WAY") > > def main(): > b = [] > for x in range(5): > b.append({'a':random.random(), "loglevel":10}) > > for y in b: > apply(func,y) > > # First attempt - didn't work > # for y in b: > # func(y) > > if __name__ == '__main__': > main() 1) apply() is deprecated 2) You need to unpack the dictionary using ** before sending it to func(), whereupon it will be repacked into a dictionary. import random def func(*args, **kwargs): print kwargs.get('a', "NOPE") print kwargs.get('loglevel', "NO WAY") def main(): b = [] for x in range(5): b.append({'a':random.random(), "loglevel":10}) for y in b: func(**y) if __name__ == '__main__': main() You might consider redefining func() so that you don't have to do the unpack--repack: From aspineux at gmail.com Wed May 30 16:40:41 2007 From: aspineux at gmail.com (aspineux) Date: 30 May 2007 13:40:41 -0700 Subject: replace the base class Message-ID: <1180557641.633245.189900@p77g2000hsh.googlegroups.com> Hi I would like a kind of function able to replace the base class like that: class Graph: pass class Circle(Graph): pass class Square(Graph): pass class ColorGraph: pass def Adopt(new_base_class, child_class, old_base_class): .... return newclass ColorCircle=Adopt(ColorGraph, Circle, Graph) ColorSquare=Adopt(ColorGraph, Square, Graph) I have a lot of classes (Circle, Square, ...) that inherit all from base class Graph I have a more powerful class ColorGraph that do the same as Graph and more. I want to have new classes ColorCircle, ColorSquare that share exactly the same code has Circle or Square but inherit from base class ColorGraph to take benefit the new features ? How can I do that ? I can get what I want by duplicating the source of all my child classes, and replace any occurrence of Graph by ColorGraph. But when the code of Circle or Square is changed, I don't want to redo the job. I could also have a lot of new base class : 3DGraph, ...... Thanks Alain From lyoshaM at gmail.com Thu May 17 19:45:46 2007 From: lyoshaM at gmail.com (Lyosha) Date: 17 May 2007 16:45:46 -0700 Subject: How to convert a number to binary? In-Reply-To: References: <1179444832.775573.55830@y80g2000hsf.googlegroups.com> Message-ID: <1179445546.307017.275850@p77g2000hsh.googlegroups.com> On May 17, 4:40 pm, Michael Bentley wrote: > On May 17, 2007, at 6:33 PM, Lyosha wrote: > > > Converting binary to base 10 is easy: > >>>> int('11111111', 2) > > 255 > > > Converting base 10 number to hex or octal is easy: > >>>> oct(100) > > '0144' > >>>> hex(100) > > '0x64' > > > Is there an *easy* way to convert a number to binary? > > def to_base(number, base): > 'converts base 10 integer to another base' > > number = int(number) > base = int(base) > if base < 2 or base > 36: > raise ValueError, "Base must be between 2 and 36" > if not number: > return 0 > > symbols = string.digits + string.lowercase[:26] > answer = [] > while number: > number, remainder = divmod(number, base) > answer.append(symbols[remainder]) > return ''.join(reversed(answer)) > > Hope this helps, > Michael That's way too complicated... Is there any way to convert it to a one- liner so that I can remember it? Mine is quite ugly: "".join(str((n/base**i) % base) for i in range(20) if n>=base**i) [::-1].zfill(1) From apatheticagnostic at gmail.com Sat May 26 15:00:48 2007 From: apatheticagnostic at gmail.com (kaens) Date: Sat, 26 May 2007 15:00:48 -0400 Subject: conditionally creating functions within a class? In-Reply-To: <46585436.2080405@holdenweb.com> References: <163f0ce20705251744j5c728e9fn53585fe0c9250827@mail.gmail.com> <163f0ce20705251948p75adb3d2vaa2d2c70f6542d48@mail.gmail.com> <46585436.2080405@holdenweb.com> Message-ID: <163f0ce20705261200y4a2373a0h1ef6fda846551e39@mail.gmail.com> On 5/26/07, Steve Holden wrote: > I have taken the liberty of copying this back to the list, since other > people may have stringer opinions than I on your approach. > > Frankly, I wouldn't worry about the "expense" of declaring two classes. > If you need SQL-handling and XML-handling code then just declare two > classes (with inheritance from a common class if that makes sense) and > stop worrying about cost. It really doesn't make sense to try and fiddle > the class methods to accommodate the needs of a single instance. > > "Premature optimization is the root of all evil". > > regards > Steve > > PS: Many people prefer it when newsgroup conversations read linearly, > with the most recent contributions at the bottom. That way a reader can > easily "pick up the story". > > > Thanks, I've been reading this list in gmail, and occasionally I'll forget to hit the "reply to all" button, and instead jut hit "reply", which always makes me think of just using a freaking news-reader instead. From zefria at gmail.com Sun May 20 17:53:51 2007 From: zefria at gmail.com (Daniel Gee) Date: 20 May 2007 14:53:51 -0700 Subject: Translating some Java to Python In-Reply-To: <1179693288.768882.34200@x18g2000prd.googlegroups.com> References: <1179692679.422164.27700@r3g2000prh.googlegroups.com> <1179693288.768882.34200@x18g2000prd.googlegroups.com> Message-ID: <1179698030.712978.321670@y2g2000prf.googlegroups.com> Alright, sounds good. I'm just not as familiar with the preferred designs of python. As to wanting to have them in a class, sometimes I do. Persisting a roll in a class is only for the slightly more complicated rolls such as 3d6+5d4-1d12 or "4d6 (drop the lowest and re-roll ones)", things of that sort. From cesar.gomes at gmail.com Sat May 12 14:17:55 2007 From: cesar.gomes at gmail.com (Cesar G. Miguel) Date: 12 May 2007 11:17:55 -0700 Subject: Basic question In-Reply-To: References: <1178986686.510137.195490@p77g2000hsh.googlegroups.com> <1178991933.421386.58500@u30g2000hsc.googlegroups.com> <1178992910.318929.77790@e51g2000hsg.googlegroups.com> Message-ID: <1178993875.203578.117750@u30g2000hsc.googlegroups.com> On May 12, 3:09 pm, Karlo Lozovina <_karlo_ at _mosor.net> wrote: > Cesar G. Miguel wrote: > > ------------------------------------- > > L = [] > > file = ['5,1378,1,9', '2,1,4,5'] > > str='' > > for item in file: > > j=0 > > while(j > while(item[j] != ','): > > str+=item[j] > > j=j+1 > > if(j>= len(item)): break > > > if(str != ''): > > L.append(float(str)) > > str = '' > > > j=j+1 > > > print L > > But I'm not sure this is an elegant pythonic way of coding :-) > > Example: > > In [21]: '5,1378,1,9'.split(',') > Out[21]: ['5', '1378', '1', '9'] > > So, instead of doing that while-based traversal and parsing of `item`, > just split it like above, and use a for loop on it. It's much more > elegant and pythonic. > > HTH, > Karlo. Great! Now it looks better :-) From steve at REMOVEME.cybersource.com.au Fri May 4 02:40:35 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Fri, 04 May 2007 16:40:35 +1000 Subject: Getting some element from sets.Set References: <1178258913.095438.173020@h2g2000hsg.googlegroups.com> Message-ID: On Thu, 03 May 2007 23:08:33 -0700, jm.suresh at no.spam.gmail.com wrote: > It is not possible to index set objects. That is OK. > But, what if I want to find some element from the Set. > > from sets import Set > s = Set( range(12 ) > > if I do pop, that particular element gets removed. > I do not want to remove the element, but get some element > from the Set. > > s.some_element() # Is not available Looking at help(sets.Set), it seems that there is no direct way to ask for a single element of a set, except with pop. So you can pop an element, then add it back in: some_element = s.pop() s.add(some_element) Another solution is to extract all the elements, then pick one: some_element = list(s)[0] -- Steven D'Aprano From deets at nospam.web.de Mon May 21 06:06:50 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 21 May 2007 12:06:50 +0200 Subject: Components for a client/server architecture References: Message-ID: <5bd99qF2s85heU1@mid.uni-berlin.de> > - Java (and possibly Jython) or Mono/C# (or possibly IronPython) on the > server. Requirements are: A strong and fair threading model. This is > actually what drove me away from Perl and what essentially prevents > using a normal Python interpreter on the server. I don't know whether > the GIL and starvation issues also apply to IronPython or Jython. > Sharing non thread-aware objects of arbitrary type between threads > without any restriction is absolutely necessary (this is not possible > in Perl). I'm not sure which configuration you want to change how often. But I'm not convinced that the python threading limitations really do make a difference here. Do you really benefit from multi-core capabilities in this scenario? Because that's what you are asking here, and somehow I doubt that all of a sudden the bazillion of single-core-servers that suited us so well are a major PITA, together with all the apps running on them. > - Perl or Python on the client side. Clients have to provide a UI (a > web application is not an option). > > Unfortunately, I have very little experience with client/server > architectures and the protocols involved, so I would like to collect your > recommendations as a starting point for further research: > > - Are there any standard protocols that make it easy to share objects > between Java/Jython/IronPython and Python or Perl over the network? I > am thinking of a portable, language independent object > (de-)serialization, if such a thing exists. > Having a defined protocol/interface between the client and the server > that makes it easy to switch technologies on either side of the > architecture is a strong requirement. > > - How does bi-directional communication in such a protocol work? I am > assuming that the client should not poll the server for callbacks, > OTOH, leaving a TCP connection open also does not seem right. > > - What is the security model of that protocol? > > If my description of the project is inaccurate or too incomplete I > apologize; the problem is that I still find it hard to tell which > requirements actually matter. > > If you have any pointers that might be of interest for such an > architecture, please let me know. Sounds like CORBA to me. CORBA has a very mature and good implementation for Python called OmniORB, and interoperability with other orbs (the ones available for e.g. Java) is very good - as CORBA as standard is mature. Having call-backs and the like is also no issue in CORBA. However, it is _not_ serialization of objects, just RPC - you expose an object living in your server to clients. It's not transferred. And the other way round, you can pass client-side object references to the server and call these. I can't comment too much on the security aspects, but AFAIK at least SSL is an option. And from what I know about SOAP it's certainly not better suited (besides the fact that it sucks big time anyway) HTH, Diez From tjreedy at udel.edu Fri May 18 22:23:24 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 18 May 2007 22:23:24 -0400 Subject: A Few More Forrester Survey Questions References: <464DC49F.1090608@taupro.com> Message-ID: "Jeff Rush" wrote in message news:464DC49F.1090608 at taupro.com... | I'm down to the wire here on answering the Forrester survey but am stumped on | a few questions I hope someone can help me out with. You are really into this free work for paid products thing. I should think of such a scheme for me. But some free tidbits. | | 1) What -existing- examples of the use of Python to create social | web applications are there? These include chat, collaboration, | forum boards, and editable content pages, RSS feeds. | | I know I use a lot of these, but under pressure I'm not coming | up with a lot of names. You should have listed them so we could try to think of others. | Can you throw a few my way? Bittorrent !-) Jabbar, Roundup | 2) How easy is it to install an application written in the language? Generally as easy as other applications on the same platform | How is the application deployed? Same way as other apps on the same platform, (on Windows, .msi, .zip, .exe, etc) plus some Python specific methods. | | I'm having some trouble understanding the difference between | "deployment" and "installation". I suspect those words may | have a special meaning to Java developers (who designed the survey) | or to Big Corporate IT developers. Ideas? | | I can tell the story of distutils, python eggs and PyPI, and py2exe | and py2mumble for the Mac -- is there more to the story than that? | | 3) What is the value of the language to developers? Makes programming fun. Terry Jan Reedy From sjmachin at lexicon.net Sat May 26 21:19:16 2007 From: sjmachin at lexicon.net (John Machin) Date: 26 May 2007 18:19:16 -0700 Subject: Large Amount of Data In-Reply-To: References: Message-ID: <1180228756.574525.16110@q19g2000prn.googlegroups.com> On May 26, 6:17 pm, "Jack" wrote: > I have tens of millions (could be more) of document in files. Each of them > has other > properties in separate files. I need to check if they exist, update and > merge properties, etc. And then save the results where? Option (0) retain it in memory Option (1) a file Option (2) a database And why are you doing this agglomeration of information? Presumably so that it can be queried. Do you plan to load the whole file into memory in order to satisfy a simple query? > And this is not a one time job. Because of the quantity of the files, I > think querying and > updating a database will take a long time... Don't think, benchmark. > > Let's say, I want to do something a search engine needs to do in terms of > the amount of > data to be processed on a server. I doubt any serious search engine would > use a database > for indexing and searching. A hash table is what I need, not powerful > queries. Having a single hash table permits two not very powerful query methods: (1) return the data associated with a single hash key (2) trawl through the whole hash table, applying various conditions to the data. If that is all you want, then comparisons with a serious search engine are quite irrelevant. What is relevant is that the whole hash table has be in virtual memory before you can start either type of query. This is not the case with a database. Type 1 queries (with a suitable index on the primary key) should use only a fraction of the memory that a full hash table would. What is the primary key of your data? From gagsl-py2 at yahoo.com.ar Thu May 31 16:47:31 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 31 May 2007 17:47:31 -0300 Subject: Standalone HTTP parser? References: Message-ID: En Thu, 31 May 2007 15:07:00 -0300, Christopher Stawarz escribi?: > Does anyone know of a standalone module for parsing and generating > HTTP messages? I'm looking for something that will take a string and > return a convenient message object, and vice versa. All the Python > HTTP parsing code I've seen is either intimately bound to the > corresponding socket I/O operations (e.g. httplib, httplib2, > BaseHTTPServer) and/or buried in somebody's framework (e.g. Twisted). HTTP messages are like RFC 822. You can use the email.Message class to generate and parse HTTP headers. -- Gabriel Genellina From padhia at yahoo.com Mon May 21 17:47:08 2007 From: padhia at yahoo.com (P. Adhia) Date: 21 May 2007 14:47:08 -0700 Subject: Invalid pointer when accessing DB2 using python scripts Message-ID: <1179784028.787919.58070@b40g2000prd.googlegroups.com> Hello, I was wondering if anyone is successfully using using Python(2.5)+DB2+pydb2. I get an error in all situations. It seems that this problem might be limited to python 2.5. A quick Google search suggests that with Python 2.5, memory model has become more stringent and mixing various types of memory calls are likely to produce this error. I am not familiar with writing Python C extensions, but from what I can tell, pydb2 extension is using only one type of memory call. Any workaround besides falling back to python 2.4? It seems pydb2 project isn't very active. I think IBM officially supports only PHP, ruby and perl, does IBM have any plans to support python bindings for DB2? Thanks P Adhia Environment: Ubuntu : Fiesty Fawn Python 2.5.1c1 (release25-maint, Apr 12 2007, 21:00:25) DB2 9.1.2 Error: *** glibc detected *** python: free(): invalid pointer: 0xppppppp *** A simple program to reproduce this error. #! /usr/bin/env python import DB2 con = DB2.connect('ANYDB', 'xxxxxx', 'xxxxxx') csr = con.cursor() csr.close() con.close() From obaudys at gmail.com Fri May 18 01:41:26 2007 From: obaudys at gmail.com (obaudys at gmail.com) Date: 17 May 2007 22:41:26 -0700 Subject: trouble with pyvtk In-Reply-To: <1179462146.957576.193110@o5g2000hsb.googlegroups.com> References: <1179462146.957576.193110@o5g2000hsb.googlegroups.com> Message-ID: <1179466886.812669.95170@w5g2000hsg.googlegroups.com> On May 18, 2:22 pm, LokiDawg wrote: > All is well until the last line (writing the file), after which the > following error occurs: > File "/usr/lib/python2.4/site-packages/pyvtk/common.py", line 140, > in get_datatype > if is_int(obj): return self.default_int > RuntimeError: maximum recursion depth exceeded > > I'm assuming my pyvtk installation is at issue here (?), but I don't > know enough about python to tell what has gone wrong, or how to fix > it. Can someone point me in the right direction? This could be very well be a bug where infinite recursion happens, but see if changing the recursion limit fixes this: >>> import sys >>> sys.getrecursionlimit() 1000 >>> sys.setrecursionlimit(10000) Regards, Ondrej From arnodel at googlemail.com Mon May 7 15:16:21 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 7 May 2007 12:16:21 -0700 Subject: Simulating simple electric circuits In-Reply-To: <5a9838F2nlbanU1@mid.individual.net> References: <5a9838F2nlbanU1@mid.individual.net> Message-ID: <1178565381.136800.250100@o5g2000hsb.googlegroups.com> On May 7, 7:05 pm, Bjoern Schliessmann wrote: > Hello all, > > I'm trying to simulate simple electric logic (asynchronous) > circuits. By "simple" I mean that I only want to know if I > have "current" or "no current" (it's quite digital) and the only > elements need to be (with some level of abstraction to my specific > problem) > > - sources (here begin currents) > - ground (here end currents) > - joints > - switches (which are able to let current pass or not, depending on > outside influence) > - loads (which can signal change in current flow to the outside -- > just like a light bulb) > > Is there any library for this? I couldn't find one. > > I tried to implement this using objects that are two-way linked; > every object has "ports". For every port, there is > > - an input function (that is called by the neighbour if "current" > comes in) > - a reference to the neighbour's input function, to be able to let > current flow the other way > > There is a master "current controller" object which tells > the "source" object to start a "current" by calling its neighbour. > The calls traverse the network until they reach a "ground" object. > Specifically, the source passes a "telegram" instance with these > calls, and everyone it passes through "registers" himself with it > (telegrams are duplicated at joints). Then, the ground object calls > back to the controller with all received telegrams. Like this I'm > already able to get all possible ways through the network. Then you can get all 'potential' paths that depend on one or more switches being on. Each path could know what switches it depends on and be 'active' if and only if all those switches are on. And each switch would know what paths depend on it. Similarly each lightbulb would know what paths it depends on and be 'on' if at least one path is active; and each path would know which lightbulbs it powers > But that's where my ideas go out. Let's assume there is a load in > the middle of such a current, e. g. a light bulb. So if the current > flows through it it gets notice of this because there is a telegram > passing through it. But what if a contact before it now "cuts" the > current, how could I notify all objects behind the cut? I tried > several ways the past few days, but all lead to confusing (and > non-working) code. (I'm sorry I can't provide any working code yet) > Often it boils down to the need to check all possible ways in the > entire network with every change. This shouldn't, in perfomance > terms, be a big problem for me here, but it feels very dirty, and I > smell inconsistencies. When you turn a switch off, it would send a message to the paths that depend on it (maybe via the controller?) so that they would be deactivated. In turn the lightbulbs on these paths would be informed that they are no longer active. When you turn a switch on, it would send a message to the paths that depend on it so that those who do not have another off switch would be activated. In turn the lightbulbs on these paths would be informed that they have a new power source. It seems to me that it would work well with the way you started it out, but I may have misunderstood some aspects or overlooked some problems ;) -- Arnaud From grahn+nntp at snipabacken.dyndns.org Wed May 2 10:16:53 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 2 May 2007 14:16:53 GMT Subject: Python un-plugging the Interpreter References: <1hwu415.1yyvbo61efn1uqN%aleax@mac.com> Message-ID: On Wed, 25 Apr 2007 08:05:01 +0200, Hendrik van Rooyen wrote: > "Jorgen Grahn" wrote: ... >> I doubt it. (But I admit that I am a bit negative towards thread >> programming in general, and I have whined about this before.) >> > > I find this last statement interesting, because it differs so much > from my own attitude - getting a thread running was one of the > first things I did when I started getting to grips with python. > > Do you mind "whining" some more - maybe I can learn > something - threads seem to me to make a lot of things so > much easier and more natural, as I see them as sequences > that run "at the same time", and I find this immensely useful > for all sorts of things, as it enables me to think in a simple > linear fashion about parts of complicated things. It's the other way around for me -- using a threaded design looks superficially more linear, but all the complexity is still there, and then some. I mean, threads are well known for causing surprising and hard-to-track-down (and hard to trigger!) bugs and performance problems. (I'm comparing with the Unix select() call, and I assume the APIs I want to use are designed to work with select(). i.e. use select()able file descriptors.) > And if you > add queues, you have something in your hand that you can > do quite fancy stuff with in a robust, simple manner... > > *grin* before I discovered the queue module, I was using > named pipes to communicate between threads... > > So you could say I am a threading freak if you want to, and > I won't argue. > > But I would like to hear the opposite viewpoint.. Good. My viewpoint is due to my Unix background (but I'm not insinuating that all Unix users dislike threads). Eric Raymond's "The Art of Unix Programming" sums up the threading criticism, I think: http://catb.org/~esr/writings/taoup/html/multiprogramchapter.html /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From jitudon at hotmail.com Wed May 23 07:05:25 2007 From: jitudon at hotmail.com (jitudon at hotmail.com) Date: 23 May 2007 04:05:25 -0700 Subject: stdlib doc for logger.findCaller() needs update. Message-ID: <1179918325.803451.76820@o5g2000hsb.googlegroups.com> The logger objects findCaller() method is returning a "3" element tuple instead of "2" two as documented in the 2.4.4 Python Library Reference .DocString is showing it correctly. findCaller() Finds the caller's source filename and line number. Returns the filename and line number as a 2-element tuple. [jnair at sunazaki python]$ python Python 2.4.4 (#1, Feb 2 2007, 17:43:17) [GCC 3.4.3 20041212 (Red Hat 3.4.3-9.EL4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import logging >>> logging.basicConfig() >>> logger = logging.getLogger() >>> help(logger.findCaller) Help on method findCaller in module logging: findCaller(self) method of logging.RootLogger instance Find the stack frame of the caller so that we can note the source file name, line number and function name. >>> logger.findCaller() ('', 1, '?') >>> From dborne at gmail.com Thu May 31 09:53:14 2007 From: dborne at gmail.com (Dave Borne) Date: Thu, 31 May 2007 08:53:14 -0500 Subject: HTML Form/Page and Navigation with multiple buttons In-Reply-To: <1180617750.709628.180070@p77g2000hsh.googlegroups.com> References: <1180617750.709628.180070@p77g2000hsh.googlegroups.com> Message-ID: <6e42ec490705310653r240201f2h6b6c6f31160e1a6c@mail.gmail.com> > How can I identify which button has been pressed. Do I need a > separate form for each button and hide all the relevant session fields > in each form or is there a way of identifying which button has been > pressed on the page. Hi, Richard, Just give each button (or input) tag a distinct name attribute and a value attribute. Also make sure the button is inside the form. When the button is used to submit the form, FieldStorage will return the name:value pair. -Dave From google at mrabarnett.plus.com Wed May 16 15:33:27 2007 From: google at mrabarnett.plus.com (MRAB) Date: 16 May 2007 12:33:27 -0700 Subject: Spotting Crashed Application In-Reply-To: References: <11505.3843394437$1178703827@news.gmane.org> Message-ID: <1179344007.902009.69360@q23g2000hsg.googlegroups.com> On May 16, 1:55 am, Steve Holden wrote: > Robert Rawlins - Think Blue wrote: > > > Hello Guys, > > > I've got an application that I've written, and it sits in an embedded > > system, from time to time the application will crash, I'm not quite sure > > what's causing this, but as we test it more and more we'll grasp a > > better understanding and fix the issues. > > > However, until then I need a quick solution which can spot the crash and > > reboot the system. Is there any generic way of writing a separate > > application that'll spot the crash in my main application? If not then i > > was thinking about having my core application log itself as 'alive' > > every 5 minutes or so. My new 'spotter' application can check this log, > > if it's not been written too in say 6 minutes then the main app must > > have crashed, and it can reboot. > > > Any suggestions on how best to handle this? Obviously finding the bug in > > my main app is paramount, but a failsafe will never hurt. > > I don't know of any pre-written functionality, but I'd recommend using a > UDP socket for this. Let your application send a packet (say) every 30 > seconds and have the monitoring application restart it if it doesn't > hear a packet for 90 seconds. > An alternative would be for the spotter to start the application using CreateProcess (this is on MS Windows) and then wait on the handle with WaitForSingleObject. When the application quits or crashes the wait will succeed and the spotter can then start the application again. From Leo.Kislov at gmail.com Fri May 4 01:17:22 2007 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 3 May 2007 22:17:22 -0700 Subject: hp 11.11 64 bit python 2.5 build gets error "import site failed" In-Reply-To: <463a5a2c$0$6904$9b622d9e@news.freenet.de> References: <1178131203.719353.91360@y80g2000hsf.googlegroups.com> <4638fe11$0$1098$9b622d9e@news.freenet.de> <1178197261.294121.157120@h2g2000hsg.googlegroups.com> <463a5a2c$0$6904$9b622d9e@news.freenet.de> Message-ID: <1178255842.821465.114090@u30g2000hsc.googlegroups.com> On May 3, 2:54 pm, "Martin v. L?wis" wrote: > >>> "import site failed" > >>> OverflowError: signed integer is greater than the maximum. > >> - what is the value of ival? > > ival: 4294967295 > > I see. This is 0xFFFFFFFF, which would be -1 if it were of type > int. So perhaps some value got cast incorrectly at some point, > breaking subsequent computations > > > > >> - where does that number come from? > > > It is coming from the call to PyInt_AsLong. In that function there is > > a call to: > > PyInt_AS_LONG((PyIntObject*)op) > > which returns the value of ival. > > That was not my question, really. I wanted to know where the object > whose AsLong value was taken came from. And before you say "it's > in the arg parameter" of convertsimple() - sure it is. However, how > did it get there? It's in an argument tuple - and where came > that from? Looking at the call stack OP posted, -1 is coming as forth parameter of __import__, I *guess* at the first import in site.py or at implicit "import site". I think it'd be helpful if OP also tried if it works: python -S -c -v "print -1, type(-1), id(0), id(-1)" -- Leo From whamil1 at entergy.com Wed May 9 10:45:20 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Wed, 9 May 2007 09:45:20 -0500 Subject: Simulating simple electric circuits In-Reply-To: <5ae44aF2ku9rtU1@mid.individual.net> Message-ID: <588D53831C701746A2DF46E365C018CE01D2CA92@LITEXETSP001.etrsouth.corp.entergy.com> > From: Bjoern Schliessmann > Sounds more familiar than the analog approach. Maybe I misunderstood > something ... but I can't transfer my problem to this way of > thinking yet. My biggest problem is the fact that relays aren't > really interested in voltage, but current. > > Also, I find it difficult to transfer this circuit logic to boolean > logic I can contruct logic gates from. Sometimes, electric circuits > are used in different directions. You shouldn't have to worry about current degrading. You apply a current to the relay's coil, and it passes through the coil to ground and triggers the relay. The relay's outputs open or close connections from the current source to the connected devices' inputs. The only time you'd have to worry about low currents is if a single relay is connected to a lot of device inputs, because the current is split across the inputs. >From a logic standpoint, all you care about is whether each input and output is on or off. --- -Bill Hamilton From DustanGroups at gmail.com Sat May 5 20:43:55 2007 From: DustanGroups at gmail.com (Dustan) Date: 5 May 2007 17:43:55 -0700 Subject: change of random state when pyc created?? In-Reply-To: References: <1178388186.631422.290580@w5g2000hsg.googlegroups.com> <008%h.379$HR1.364@trnddc01> <1178406414.901845.223410@y80g2000hsf.googlegroups.com> Message-ID: <1178412235.376566.66330@y80g2000hsf.googlegroups.com> On May 5, 6:30 pm, "Alan Isaac" wrote: > "John Machin" wrote in message > > news:1178406414.901845.223410 at y80g2000hsf.googlegroups.com... > > > You can't say that you have "documented" the behaviour when you > > haven't published files that exhibit the alleged behaviour. > > Fine. I have "observed" this behavior. > The files are not appropriate for posting. > I do not yet have a "minimum" case. > But surely I am not the first to notice this! > Alan Isaac > PS I'll send you the files off list. I got the files and tested them, and indeed got different results depending on whether or not there was a pyc file. I haven't looked at the source files in great detail yet, but I will. I would certainly agree that there's a bug going on here; we just need to narrow down the problem (ie come up with a "minimum" case). From fabien.wahl at snecma.fr Tue May 15 11:23:32 2007 From: fabien.wahl at snecma.fr (fabien.wahl at snecma.fr) Date: Tue, 15 May 2007 17:23:32 +0200 Subject: [f2py] f2py problem Message-ID: Bonjour, f2py is a "dos" command, and cannot be run from inside python open a dos window and type f2py on the prompt (provided that you indicate the right path, or that you entered f2py path to the PATH variable) if "f2py" does not work, try to type "f2py.py" instead. Then read the help for the arguments @+ -------------------- Fabien WAHL Ing=E9nieur Etudes Nouvelles Unit=E9 de conception de Turbomachines SNECMA, Division Moteur Spatiaux Direction Grosse Propulsion =E0 Liquides For=EAt de Vernon BP 802 27208 VERNON FRANCE Tel +33 (0)2 32 21 72 77 Fax +33 (0)2 32 21 76 30 mailto:fabien.wahl at snecma.fr |---------+-------------------------------> | | | | | | | | | | | Alberto Vera | | | | | | Envoy=E9 par : | | | f2py-users-bounces at c| | | ens.ioc.ee | | | | | | | | | 15/05/2007 16:42 | | | | |---------+-------------------------------> >-------------------------------------------------------------------------= --------------------------------------------------| | Pour : f2py-users at cens.ioc.ee, python-list at python.org = | | cc : = | | Objet : [f2py] f2py problem = | >-------------------------------------------------------------------------= --------------------------------------------------| Hello. After I installed f2py using Python, NumPy and Numarray software, I can't use f2py I saw this error: Traceback (most recent call last): File "", line 1, in NameError: name 'f2py' is not defined >>> Could you tell me what is the problem? Regards. _______________________________________________ f2py-users mailing list f2py-users at cens.ioc.ee http://cens.ioc.ee/mailman/listinfo/f2py-users #=0A= " This e-mail and any attached documents may contain confidential or proprie= tary information. If you are not the intended recipient, please advise the s= ender immediately and delete this e-mail and all attached documents from you= r computer system. Any unauthorised disclosure, distribution or copying here= of is prohibited."=0A= =0A= " Ce courriel et les documents qui y sont attaches peuvent contenir des inf= ormations confidentielles. Si vous n'etes pas le destinataire escompte, mer= ci d'en informer l'expediteur immediatement et de detruire ce courriel ains= i que tous les documents attaches de votre systeme informatique. Toute divul= gation, distribution ou copie du present courriel et des documents attaches= sans autorisation prealable de son emetteur est interdite."=0A= # From hat at se-126.se.wtb.tue.nl Mon May 7 03:19:52 2007 From: hat at se-126.se.wtb.tue.nl (A.T.Hofkamp) Date: Mon, 07 May 2007 09:19:52 +0200 Subject: c macros in python. References: <1178485280.394666.51970@n76g2000hsh.googlegroups.com> Message-ID: On 2007-05-06, noagbodjivictor at gmail.com wrote: > Hey, > > I'm writing a script to generate code. I'm a bit tired of typing > outfile.write(....). Does python have a way to c-like macros? Every > instance of o(...) in the code will be replaced by outfile.write(...)? Just in case you don't know, you can write an arbitrary number of lines in one write. Below is how I format a usage() message of a program in one write call: def usage(fp): fp.write("Usage: convert options [infile] [outfile]\n" "with\n" " options\n" "\t--prefix=\t(obligatory)\n" "\t--write-size\t\tWrite a line containing the size\n" "\t--append-zero\t\tAppend a terminating 0 byte\n") ie one multi-line write call. Pyhon concatenates two consequtive string literals for us. Unfortunately, this gets less pretty when inserting variable values. In other code generation code, I normally use a list of lines. Rather than writing everything directly to file, I make a list data structure containing lines, then dump the list to file, as in: lines = [] gencode_first(lines) gencode_second(lines) lines.append("the end") write_lines(lines) where write_lines() is def write_lines(lines): for line in lines: outfile.write(line) outfile.write('\n') (i left out the opening and closing of outfile). I normally do not include the \n in the list but instead add it while writing it to file. This makes life much easier since there are no special last-value problems in the code generator itself. The nice thing here is that 'lines' is a normal data structure which you can manipulate if you like. For more demanding code generators (ie C or C++ code) I use the concept 'sections'. At a global level, the generated code has an 'include', 'declarations', 'definitions', and 'main' section, each section is a list of lines. I use a dictionary for this, like output = { 'incl': [], 'decl': [], 'def': [], 'main': [] } then pass around this in the code generator. Each part of the generator can write in each section, for example when defining a C function, you can write the declaration in the decl section and the definition in the def section at the same time. For example def write_c_function(output): output['decl'].append('int mycfunc(void);') output['def'].extend(['int myfunc(void)', '{' 'return 131;', }' ]) Reducing such a dictionary to a list is then something like def make_lines(sec_list, output): lines = [] for sec in sec_list: lines.extend(output[sec]) return lines And outputting the code is then something like write_lines(make_lines(['incl', 'decl', 'def', 'main'], output)) In this way you can abstract away from the order of code as required by the target language and instead generate code in a nicer order. Note that this section trick can be done recursively. for example, a function can be thought of as a number of sections like funcoutput = { 'header': [], 'opening-bracket' : [], 'localvars':[], 'closing-bracket': [] } so you can generate a function using sections as well, then at the end reduce funcoutput to a list of lines, and insert that in a section of the global 'output'. Last but not least, if you replace the lists by an object, you can do much smarter things. For example, in general you don't want to have double #include lines in the 'incl' section. Instead of worrying about generation of doubles, just make an object that behaves like a list but silently drops doubles. In the same way, you can create a list-like object that handles indenting for you. The possibilities here are endless!! Good luck with your code generation problem, I hope I gave you some ideas of alternative solutions that are available. Albert From saif.shakeel at gmail.com Thu May 3 08:39:37 2007 From: saif.shakeel at gmail.com (saif.shakeel at gmail.com) Date: 3 May 2007 05:39:37 -0700 Subject: file Error Message-ID: <1178195977.521889.167910@p77g2000hsh.googlegroups.com> Hi, I am parsing an xml file,and using raw_input command to ask the user to enter the file name.Ex >>> Enter The ODX File Path: Suppose my code does not work properly,then in the python idle window it shows something like this: >>> C:\Projects\ODX Import\Sample Files\MiscFiles \CIM_A3300_diag_spec_sw49.xml Traceback (most recent call last): File "C:\Projects\ODX Import\code_ini\odxparse_mod_off_comm.py", line 339, in process_variant(variant) File "C:\Projects\ODX Import\code_ini\odxparse_mod_off_comm.py", line 285, in process_variant triplet = triplet + get_did_lengths(iservice,local_service_id) File "C:\Projects\ODX Import\code_ini\odxparse_mod_off_comm.py", line 238, in get_did_lengths local_min = local_min + ddoref_min[ddorefstring] KeyError: '_210' This is some bug related to code ..thats ok..but when i run the program immediately again for some other input..then it does not show the prompt : >>> Enter The ODX File Path: but instead a blinking prompt which accepts the filename something like this: >>> C:\Projects\ODX Import\Sample Files\MiscFiles\Diagnostic CTS Global Epsilon TIM V1.4.xml I want the inputfile prompt to appear regardless of the error condition.I dont know where the problem lies.Can someone help me out. Thanks From pete.losangeles at gmail.com Tue May 15 23:22:29 2007 From: pete.losangeles at gmail.com (MisterPete) Date: 15 May 2007 20:22:29 -0700 Subject: inherit from file and create stdout instance? In-Reply-To: <1179284919.465498.277290@w5g2000hsg.googlegroups.com> References: <1179267498.154549.58370@h2g2000hsg.googlegroups.com> <1179270178.281061.34860@k79g2000hse.googlegroups.com> <1179272294.058634.140760@k79g2000hse.googlegroups.com> <1179280223.545538.81900@n59g2000hsh.googlegroups.com> <1179284919.465498.277290@w5g2000hsg.googlegroups.com> Message-ID: <1179285749.481738.301220@w5g2000hsg.googlegroups.com> > class Output(file): > def __init__(self, name, mode='w', buffering=None, verbosity=1): > super(Output, self).__init__(name, mode, buffering) > self.verbosity = verbosity > > def write(self, string, messageVerbosity=1): > if messageVerbosity <= self.verbosity > super(Output, self).write(string) I may have to just accept name as a string or as a file object so that I can still provide the same interface as a file object. It'll just store and use a separate file object when it needs to handle writing to stdout and sterr. This way it should always be able to be used in place of a file object. err, and again, not that it matters but in the code above verbosity should of course get the value passed in, not 1 :/ From carsten at uniqsys.com Fri May 25 08:42:47 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 25 May 2007 08:42:47 -0400 Subject: just a bug In-Reply-To: <1180090985.066935.218250@h2g2000hsg.googlegroups.com> References: <1179841504.782279.86490@u36g2000prd.googlegroups.com> <1180082137.329142.45350@p77g2000hsh.googlegroups.com> <1180090985.066935.218250@h2g2000hsg.googlegroups.com> Message-ID: <1180096967.3743.3.camel@dot.uniqsys.com> On Fri, 2007-05-25 at 04:03 -0700, sim.sim wrote: > my CDATA-section contains only symbols in the range specified for > Char: > Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | > [#x10000-#x10FFFF] > > > filter(lambda x: ord(x) not in range(0x20, 0xD7FF), iMessage) That test is meaningless. The specified range is for unicode characters, and your iMessage is a byte string, presumably utf-8 encoded unicode. Let's try decoding it: >>> iMessage = "3c3f786d6c2076657273696f6e3d22312e30223f3e0a3c6d657373616\ ... 7653e0a202020203c446174613e3c215b43444154415bd094d0b0d0bdd0bdd18bd0b5\ ... 20d0bfd0bed0bfd183d0bbd18fd180d0bdd18bd18520d0b7d0b0d0bfd180d0bed181d\ ... 0bed0b220d0bcd0bed0b6d0bdd0be20d183d187d0b8d182d18bd0b2d0b0d182d18c20\ ... d0bfd180d0b820d181d0bed0b1d181d182d0b2d0b5d0bdd0bdd18bd18520d180d0b5d\ ... 0bad0bbd0b0d0bcd0bdd15d5d3e3c2f446174613e0a3c2f6d6573736167653e0a0a".\ ... decode('hex') >>> iMessage.decode("utf-8") Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/encodings/utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeDecodeError: 'utf8' codec can't decode bytes in position 176-177: invalid data >>> iMessage[176:178] '\xd1]' And that's your problem. In general you can't just truncate a utf-8 encoded string anywhere and expect the result to be valid utf-8. The \xd1 at the very end of your CDATA section is the first byte of a two-byte sequence that represents some unicode code-point between \u0440 and \u047f, but it's missing the second byte that says which one. Whatever you're using to generate this data needs to be smarter about splitting the unicode string. Rather than encoding and then splitting, it needs to split first and then encode, or take some other measures to make sure that it doesn't leave incomplete multibyte sequences at the end. HTH, -- Carsten Haese http://informixdb.sourceforge.net From half.italian at gmail.com Wed May 23 22:52:17 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 23 May 2007 19:52:17 -0700 Subject: Parallel/distributed generator In-Reply-To: <1179951739.408556.129420@h2g2000hsg.googlegroups.com> References: <1179943256.575473.62610@q66g2000hsg.googlegroups.com> <1179950286.087794.5430@x18g2000prd.googlegroups.com> <1179951739.408556.129420@h2g2000hsg.googlegroups.com> Message-ID: <1179975137.199385.316620@a35g2000prd.googlegroups.com> On May 23, 1:22 pm, Paul McGuire wrote: > On May 23, 2:58 pm, half.ital... at gmail.com wrote: > > > > > On May 23, 11:00 am, George Sakkis wrote: > > > > I'm looking for any existing packages or ideas on how to implement the > > > equivalent of a generator (in the Python sense, i.e.http://www.python.org/dev/peps/pep-0255/) in a parallel/distributed > > > way. As a use case, imagine a function that generates a range of > > > primes. I'd like to be able to do something along the following lines: > > > > def iterprimes(start=1, end=None): > > > # ... > > > yield prime > > > > # rpc-related initialization > > > ... > > > rpc_proxy = some_rpc_lib(iterprimes, start=1e6, end=1e12) > > > for prime in proxy: > > > print prime > > > > Is there any module out there that does anything close to this ? > > > > George > > > DOLT!- Hide quoted text - > > > - Show quoted text - > > I thought you were making a joke about parallel processing. > I thought you were making a joke about parallel processing. > I thought you were making a joke about parallel processing. > I thought you were making a joke about parallel processing. > > -- Paul Damn computers! From john at datavoiceint.com Tue May 8 21:09:52 2007 From: john at datavoiceint.com (HMS Surprise) Date: 8 May 2007 18:09:52 -0700 Subject: String parsing Message-ID: <1178672992.522463.228620@l77g2000hsb.googlegroups.com> The string below is a piece of a longer string of about 20000 characters returned from a web page. I need to isolate the number at the end of the line containing 'LastUpdated'. I can find 'LastUpdated' with .find but not sure about how to isolate the number. 'LastUpdated' is guaranteed to occur only once. Would appreciate it if one of you string parsing whizzes would take a stab at it. Thanks, jh References: <1180231245.444827.171390@g37g2000prf.googlegroups.com> <1180267656.857094.260980@d30g2000prg.googlegroups.com> Message-ID: <1180361131.415361.163550@j4g2000prf.googlegroups.com> On May 27, 11:25 pm, "Gabriel Genellina" wrote: > En Sun, 27 May 2007 09:07:36 -0300, momobear escribi?: > > >> Instead of extending join(), write a specific method to signal the > >> quitEvent or just let the caller signal it. And I don't see in this > >> example why do you need two different events (one on the thread, another > >> on the service controller), a single event would suffice. > > > I don't think a single event is enought, since I think the event > > python created and windows event are not same kind of event. > > They are not the same object, of course (altough the threading.Event > object relies eventually on a mutex implemented using CreateEvent). But in > this case both can be successfully used; of course, having the Python > object a more "pythonic" interfase (not a surprise!), it's easier to use. > The same example modified using only a threading.Event object (and a few > messages to verify how it runs): > > import threading > from win32api import OutputDebugString as ODS > > class workingthread(threading.Thread): > def __init__(self, quitEvent): > self.quitEvent = quitEvent > self.waitTime = 1 > threading.Thread.__init__(self) > > def run(self): > while not self.quitEvent.isSet(): > ODS("Running...\n") > self.quitEvent.wait(self.waitTime) > ODS("Exit run.\n") > > import win32serviceutil > import win32event > > class testTime(win32serviceutil.ServiceFramework): > _svc_name_ = "testTime" > _svc_display_name_ = "testTime" > _svc_deps_ = ["EventLog"] > > def __init__(self, args): > win32serviceutil.ServiceFramework.__init__(self, args) > self.hWaitStop = threading.Event() > self.thread = workingthread(self.hWaitStop) > > def SvcStop(self): > self.hWaitStop.set() > > def SvcDoRun(self): > self.thread.start() > self.hWaitStop.wait() > self.thread.join() > > if __name__ == '__main__': > win32serviceutil.HandleCommandLine(testTime) > > -- > Gabriel Genellina Great! thanks, now I understand the real work of the python windows service. From gert.cuykens at gmail.com Fri May 25 19:48:13 2007 From: gert.cuykens at gmail.com (gert) Date: 25 May 2007 16:48:13 -0700 Subject: How to get started as a xhtml python mysql freelancer ? Message-ID: <1180136893.220560.49340@q75g2000hsh.googlegroups.com> I made something that i was hoping it could make people happy enough so i could make a living by providing support for commercial use of http://sourceforge.net/projects/dfo/ But in reality i am a lousy sales men and was wondering how you people sell stuff as a developer ? From goon12 at gmail.com Wed May 30 14:43:01 2007 From: goon12 at gmail.com (Joe Riopel) Date: Wed, 30 May 2007 14:43:01 -0400 Subject: Off Topic: What is the good book to learn Python ? In-Reply-To: <1180549522.350380.276570@q66g2000hsg.googlegroups.com> References: <1180549522.350380.276570@q66g2000hsg.googlegroups.com> Message-ID: <6a2ccd190705301143t321c4141q6a93be8d2348a3be@mail.gmail.com> I am new to Python but these 2 have been great resources, so far: http://diveintopython.org/toc/index.html http://docs.python.org/tut/ From duncan.booth at invalid.invalid Thu May 3 13:43:41 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 3 May 2007 17:43:41 GMT Subject: Microsoft's Dynamic Languages Runtime (DLR) References: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> <59s6kbF2kq8uoU1@mid.individual.net> <1178145895.865828.18220@p77g2000hsh.googlegroups.com> <59tcidF2lob6mU1@mid.individual.net> <1hxj28j.8erkws1cruwarN%aleax@mac.com> Message-ID: aleax at mac.com (Alex Martelli) wrote: > Duncan Booth wrote: > >> means in pure Python code the string has python methods, but in >> Python using the CLR it gains the CLR methods. Presumably in Ruby >> code it looks like a Ruby string and so on, but (and this is what's >> new) it is the same object, not a bunch of language specific wrappers >> around the string type. > > So is it changeable (making Python code using it deeply unhappy) or > unchangeable (making Ruby or Javascript code similarly unhappy)? The > idea of just having one string type across languages is fascinating, > but I'm not sure it can work as stated due to different semantics such > as mutable vs immutable... > I think they said in the video that Ruby strings were a whole other talk. My guess is that, as .Net strings are immutable, Ruby can use them but its own strings must be some other class. I did a bit of experimenting with Python and JScript in the DLRconsole sample (http://silverlight.net/Samples/1.1/DLR-Console/python/index.htm). Sadly I cannot figure out any way of copying text from the DLR console so I'll attempt to retype it (hopefully without too many mistakes). BTW, this is a straight copy: the console really does let you flip languages while keeping the same variables in scope. py> s = System.String("abc") py> s 'abc' py> type(s) py> s2 = "abc" py> type(s2) is System.String True js> typeof(s) 'string' js>typeof(s2) 'string' js> System.String py> n = 42 py> type(n) js> typeof(n) 'number' py> System.Int32 py> type(n) is System.Int32 True py> p = 2**64 py> type(p) py> type(p) is System.Int64 False js> typeof(p) 'Microsoft.Scripting.Math.BigInteger' py> lst = [1, 2, 3] js> typeof(lst) 'IronPython.Runtime.List' js> x = 42 42.0 py> type(x) js> var a = [1, 2, 3] py> type(a) So it looks like str, int, long, float all map to common types between the languages but list is an IronPython type. Also as you might expect JScript will happily use an integer but it only produces float values. From not at valid.com Thu May 17 18:38:25 2007 From: not at valid.com (yomgui) Date: Thu, 17 May 2007 15:38:25 -0700 Subject: alternative to eclipse [ python ide AND cvs ] Message-ID: Hi, Eclipse is just not really working on linux 64 bit (I tried ubuntu and centos, it is freesing and crashing and extremly slow) I use eclipse for python and cvs, what is "the" good alternative ? thanks yomgui From tkpmep at hotmail.com Wed May 9 17:25:18 2007 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: 9 May 2007 14:25:18 -0700 Subject: Behavior of mutable class variables In-Reply-To: <1178744257.369030.95310@w5g2000hsg.googlegroups.com> References: <1178744257.369030.95310@w5g2000hsg.googlegroups.com> Message-ID: <1178745918.395377.282470@u30g2000hsc.googlegroups.com> To test some theories, I created a new class variable, an int named N1, which is not mutable. So my Stock class now looks as follows: class Stock(object): NStocks = [] #Class variables N1 = 0 def __init__(self, id, returnHistory): self.id = id self.retHist = returnHistory Stock.N1 += 1 for i in range(len(returnHistory)): if len(Stock.NStocks) <= i and retHist[i] != '': Stock.NStocks.append(1) elif len(Stock.NStocks) <= i and retHist[i] == '': Stock.NStocks.append(0) elif retHist[i] != '': Stock.NStocks[i] +=1 I expect Stock.N1 to reset to zero at each call to simulation(), but it does not - it keeps incrementing! I then added a line to simulation( ) that deletes all the stocks at the end of each simulation (see below). You guessed it - no change! NStocks and N1 keep increasing! At this point I am thoroughly mystified. What gives? def simulation(N, par1, par2, idList, returnHistoryDir): port = [] for i in range(N): port.append( Stock(idList[i], returnHistoryDir[idList[i]] ) del port[:] results = ...... print results. From python at rcn.com Tue May 29 02:34:36 2007 From: python at rcn.com (Raymond Hettinger) Date: 28 May 2007 23:34:36 -0700 Subject: itertools.groupby In-Reply-To: References: <1180286272.100790.131670@q75g2000hsh.googlegroups.com> <7xveecr5xx.fsf@ruckus.brouhaha.com> <6Y6dnb0mTLsaCsbbnZ2dnUVZ_hCdnZ2d@comcast.com> Message-ID: <1180420476.785936.322400@g37g2000prf.googlegroups.com> On May 28, 8:36 pm, "Carsten Haese" wrote: > And while > we're at it, it probably should be keyfunc(value), not key(value). No dice. The itertools.groupby() function is typically used in conjunction with sorted(). It would be a mistake to call it keyfunc in one place and not in the other. The mental association is essential. The key= nomenclature is used throughout Python -- see min(), max(), sorted(), list.sort(), itertools.groupby(), heapq.nsmallest(), and heapq.nlargest(). Really. People need to stop making-up random edits to the docs. For the most part, the current wording is there for a reason. The poster who wanted to rename the function to telescope() did not participate in the extensive python-dev discussions on the subject, did not consider the implications of unnecessarily breaking code between versions, did not consider that the term telescope() would mean A LOT of different things to different people, did not consider the useful mental associations with SQL, etc. I recognize that the naming of things and the wording of documentation is something *everyone* has an opinion about. Even on python-dev, it is typical that posts with technical analysis or use case studies are far outnumbered by posts from folks with strong opinions about how to name things. I also realize that you could write a book on the subject of this particular itertool and someone somewhere would still find it confusing. In response to this thread, I've put in additional documentation (described in an earlier post). I think it is time to call this one solved and move on. It currently has a paragraph plain English description, a pure python equivalent, an example, advice on when to list-out the iterator, triply repeated advice to pre-sort using the same key function, an alternate description as a tool that groups whenever key(x) changes, a comparison to UNIX's uniq filter, a contrast against SQL's GROUP BY clauses, and two worked-out examples on the next page which show sample inputs and outputs. It is now one of the most throughly documented individual functions in the language. If someone reads all that, runs a couple of experiments at the interactive prompt, and still doesn't get it, then god help them when they get to the threading module or to regular expressions. If the posters on this thread have developed an interest in the subject, I would find it useful to hear their ideas on new and creative ways to use groupby(). The analogy to UNIX's uniq filter was found only after the design was complete. Likewise, the page numbering trick (shown above by Paul and in the examples in the docs) was found afterwards. I have a sense that there are entire classes of undiscovered use cases which would emerge if serious creative effort where focused on new and interesting key= functions (the page numbering trick ought to serve as inspiration in this regard). The gauntlet has been thrown down. Any creative thinkers up to the challenge? Give me cool recipes. Raymond From i3dmaster at gmail.com Fri May 18 19:13:36 2007 From: i3dmaster at gmail.com (i3dmaster) Date: 18 May 2007 16:13:36 -0700 Subject: unittest for threading function always failed... Message-ID: <1179530016.500072.177880@y80g2000hsf.googlegroups.com> I am having a little difficulty to figure out why this unittest for a Thread subclass always fails... # unittest code: class SPThreadUnitTest(unittest.TestCase): def testgetresult(self): from random import randint self.i = randint(1,10) def p(n): return n self.t = spthread.SPThread(target=p, args=(self.i)) self.t.start() #self.t._res = self.t._target(self.t._args) self.assertEquals(self.i,self.t.getresult()) #spthread.SPThread code: import threading class SPThread(threading.Thread): def __init__(self,target=None,args=None): threading.Thread.__init__(self) self._target = target self._args = args self._res = None def getresult(self): return self._res def run(self): self._res = self._target(self._args) A simple little test. But no matter what, the self._res didn't get any value but None, so the assertion of self.i and self.t.getresult() always fails. If I use the commented out code, it works. So the start() function has some tricky stuff? Can someone point me out where the problem is? Thanks, Jim From fw3 at hotmail.co.jp Mon May 21 19:04:06 2007 From: fw3 at hotmail.co.jp (wang frank) Date: Mon, 21 May 2007 23:04:06 +0000 Subject: A newbie question Message-ID: Hi, I am trying to write a python class with a new data type such as: class Cc14: def __init__(self, realpart, imagpart): self.r=realart self.i=imagpart def __add__(self,x): return self.r+x,r, self.i+x.i If I have x=Cc14(4,5) y=Cc14(4,5) z=x+y z will be a tuple instead of Cc14. How can I return a Cc14 class? Thanks Frank _________________________________________________________________ ????????????????????????? MSN?IE7 ???? http://promotion.msn.co.jp/ie7/ From sturlamolden at yahoo.no Wed May 30 12:50:53 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 30 May 2007 09:50:53 -0700 Subject: writing to a file In-Reply-To: <1180536826.630382.89610@u30g2000hsc.googlegroups.com> References: <1180515758.671628.43200@k79g2000hse.googlegroups.com> <5c5681F2t82noU1@mid.uni-berlin.de> <1180536826.630382.89610@u30g2000hsc.googlegroups.com> Message-ID: <1180543853.055718.275590@w5g2000hsg.googlegroups.com> On May 30, 4:53 pm, sturlamolden wrote: > However, numpy has a properly working memory mapped array class, > numpy.memmap. It seems that NumPy's memmap uses a buffer from mmap, which makes both of them defunct for large files. Damn. mmap must be fixed. From robert.rawlins at thinkbluemedia.co.uk Mon May 21 06:30:57 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Mon, 21 May 2007 11:30:57 +0100 Subject: SOAPpy My Class Message-ID: <005501c79b93$26c9b6c0$745d2440$@rawlins@thinkbluemedia.co.uk> Hello Chaps, I've used SOAPpy in its very basic form for consuming web services on my web server, but I'm now looking to publish a web service from my application. Basically I'm looking to create a public 'proxy' of an object I have in the application. The idea being that my application will be able to use the instance of the object, and other applications will also be able to access this same object, using the web service. I've got my object built, and it has a few basic functions inside of it, most of them just serving as wrappers for other simple python functions, working on dicts and lists. What's the best way to go about publishing a web service that calls on that instance? I've done simple publishing of services in a standard script before, but I've not worked on this idea of publishing a public facade for an existing class. Thanks, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From jorgen.maillist at gmail.com Tue May 22 03:13:38 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Tue, 22 May 2007 09:13:38 +0200 Subject: [Fwd: Re: managed lists?] In-Reply-To: References: <4651fe96$0$24671$426a34cc@news.free.fr> Message-ID: <11e49df10705220013q11c35e6axba72cc4227401ac2@mail.gmail.com> Hi, Thanks. I agree that it is only 'me' that is the one doing it wrong. But consider this scenario: - Somewhere in my app I add a wrong type to an open regular list - The app continues like it should - After a (long) while I need to perform some search on the list, or whatever - Exception occurs It makes it hard to test this way. For example I can do something to that list and not know about it much later .. If it blows up in my face, I can fix it, but when that error hinders people who are using my application, it is much worse. With a somewhat managed list (forget about the types then, it was only meant for my own satisfaction I guess), the access violation always occurs on adding elements, which is always the path that a user creates something 'new'. And if something new gets not added correctly, I know where to look.. Anyway, I was looking for such a list class but i do understand that most of the resposobility is for the programmer anyways and people interacting with it. I did however need this solution so that I can also add a better support for my database objects, add generic find routines to that list class etc. So I basically added the interface methods needed to let it be treated like a general list, like the iterator, get method and what else. I was surprised it was so easy to be done. Python is cool when it comes to the "interface specification" v.s. "class specification" it opens a lot of doors to paradigms otherwise hard to implement, and I like the fact that every object can be "adapted" to mimic another object needed by an internal routine in Python, very-very dynamic indeed. But being a strong typed C++ guy once, it takes some getting used to ;-) Regards, - Jorgen From revuesbio at gmail.com Mon May 21 07:52:07 2007 From: revuesbio at gmail.com (revuesbio) Date: 21 May 2007 04:52:07 -0700 Subject: TIFF to PDF In-Reply-To: References: <1179687595.142454.23850@z24g2000prd.googlegroups.com> <1179744141.027494.60590@r3g2000prh.googlegroups.com> Message-ID: <1179748327.111820.279310@u36g2000prd.googlegroups.com> On 21 mai, 13:01, "Gabriel Genellina" wrote: > En Mon, 21 May 2007 07:42:21 -0300, revuesbio > escribi?: > > > os.system('"C:\Program Files\GnuWin32\bin\tiff2pdf.exe" -o C:\test.pdf > > C:\test.TIF') > > \ is used as a escape character in strings. > Use either \\ or a raw string, that is: > > os.system('"C:\\Program Files\\GnuWin32\\bin\\tiff2pdf.exe" -o > C:\\test.pdf C:\\test.TIF') > os.system(r'"C:\Program Files\GnuWin32\bin\tiff2pdf.exe" -o C:\test.pdf > C:\test.TIF') > > (This should be added to the Python FAQ - the most related entry is about > raw strings ending in \) > > -- > Gabriel Genellina Thank you very much, all is ok! From xnews2 at fredp.lautre.net Sat May 19 13:04:37 2007 From: xnews2 at fredp.lautre.net (Fred Pacquier) Date: 19 May 2007 17:04:37 GMT Subject: Python-URL! - weekly Python news and links (May 16) References: <1179408898.460231.292340@k79g2000hse.googlegroups.com> <9q11i4-mgf.ln1@lairds.us> Message-ID: claird at lairds.us (Cameron Laird) said : > I'll make a few personal comments. > > I knew the choice of quotes was in questionable taste. I was > out to be provocative without being offensive, though. My > apologies to Mr. Beliavsky and anyone else I disappointed. On > the whole, I still think I constructed the QOTWs appropriately. > > I have very little patience with The Analysts as a category. I > have friends and acquaintances in the business, and I respect > them individually. I am VERY skeptical about the sausage they > produce at an institutional level, and can only experience its > making for a few minutes at a time. I myself found that QOTW twice hilarious : once for whom it was directed at, and once for whom it came from :-) Thanks for a good laugh ! -- YAFAP : http://www.multimania.com/fredp/ From half.italian at gmail.com Sat May 12 15:45:24 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 12 May 2007 12:45:24 -0700 Subject: Creating a function to make checkbutton with information from a list? In-Reply-To: <1178993091.198864.94590@k79g2000hse.googlegroups.com> References: <1178993091.198864.94590@k79g2000hse.googlegroups.com> Message-ID: <1178999124.821594.290160@n59g2000hsh.googlegroups.com> On May 12, 11:04 am, Thomas Jansson wrote: > Dear all > > I am writing a program with tkinter where I have to create a lot of > checkbuttons. They should have the same format but should have > different names. My intention is to run the functions and the create > all the buttons with the names from the list. > > I now the lines below doesn't work, but this is what I have so far. I > don't really know how call the element in the dict use in the for > loop. I tried to call +'item'+ but this doesn't work. > > def create_checkbox(self): > self.checkbutton = ["LNCOL", "LFORM", "LPOT", "LGRID", "LERR", > "LCOMP"] > for item in self.checkbutton: > self.+'item'+Checkbutton = Chekcbutton(frame, onvalue='t', > offvalue='f', variable=self.+'item'+) > self.+'item'+Checkbutton.grid() > > How should I do this? > > Kind regards > Thomas Jansson You can use exec("self." + name + " = " + value) to do what you want, but then you need to exec() each time you want to access the variable. I think it is much better to create a class. Here's what I came up with: from Tkinter import * class Window(Frame): def __init__(self, parent=None): Frame.__init__(self,parent=None) self.names = ["LNCOL", "LFORM", "LPOT", "LGRID", "LERR", "LCOMP", "Sean"] self.checkbuttons = [] self.f = Frame(root) for name in self.names: self.checkbuttons.append(CButton(parent=self.f, name=name, default="f")) self.f.pack(side="top",padx=5, pady=5) class CButton(object): def __init__(self, parent=None, name=None, default=None): self.name = name self.parent = parent self.variable = StringVar() self.variable.set(default) self.checkbutton = None self.create_checkbox(name) def create_checkbox(self,name): f = Frame(self.parent) Label(f, text=name).pack(side="left") self.checkbutton = Checkbutton(f, onvalue='t', offvalue='f', variable=self.variable) self.checkbutton.bind("", self.state_changed) self.pack() f.pack() def pack(self): self.checkbutton.pack() def state_changed(self, event=None): print "%s: %s" % (self.name, self.variable.get()) if __name__ == '__main__': root = Tk() Window().mainloop() ~Sean From gagsl-py2 at yahoo.com.ar Mon May 7 16:21:49 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 07 May 2007 17:21:49 -0300 Subject: long lists References: <1178522894.357829.28250@u30g2000hsc.googlegroups.com> <1178540073.988964.196860@w5g2000hsg.googlegroups.com> Message-ID: En Mon, 07 May 2007 09:14:34 -0300, Merrigan escribi?: > The Script it available at this url : > http://www.lewendewoord.co.za/theScript.py I understand this as a learning exercise, since there are lot of utilities for remote syncing. Some comments: - use os.path.join to build file paths, instead of concatenating strings. - instead of reassigning sys.stdout before the call to retrlines, use the callback: saveinfo = sys.stdout fsock = open(tempDir + "remotelist.txt", "a") sys.stdout = fsock ftpconn.cwd(remotedir) #This changes to the remote directory ftpconn.retrlines("LIST") #This gets a complete list of everything in the directory sys.stdout = saveinfo fsock.close() becomes: fsock = open(os.path.join(tempDir,"remotelist.txt"), "a") ftpconn.cwd(remotedir) #This changes to the remote directory ftpconn.retrlines("LIST", fsock.write) #This gets a complete list of everything in the directory fsock.close() (Why mode="a"? Shouldn't it be "w"? Isn't the listing for a single directory?) - Saving both file lists may be useful, but why do you read them again? If you already have a list of local filenames and remote filenames, why read them from the saved copy? - It's very confusing having "filenames" ending with "\n" - strip that as you read it. You can use fname = fname.rstrip() - If you are interested on filenames with a certain extension, only process those files. That is, filter them *before* the processing begins. - The time-consuming part appears to be this: def comp_are(): global toup temptoup = [] for file1 in remotefiles: a = file1 for file2 in localfiles: b = file2 if str(a) == str(b): pass if str(b) != str(a): temptoup.append(str(str(b))) toup = list(sets.Set(temptoup)) for filename in remotefiles: fn2up = filename for item in toup: if fn2up == item: toup.remove(item) else: pass toup.sort() (It's mostly nonsense... what do you expect from str(str(b)) different from str(b)? and the next line is just a waste of time, can you see why?) I think you want to compare two lists of filenames, and keep the elements that are on one "localfiles" list but not on the other. As you appear to know about sets: it's the set difference between "localfiles" and "remotefiles". Keeping the same "globalish" thing: def comp_are(): global toup toup = list(sets.Set(localfiles) - sets.Set(remotefiles)) toup.sort() Since Python 2.4, set is a builtin type, and you have sorted(), so you could write: def comp_are(): global toup toup = sorted(set(localfiles) - set(remotefiles)) - Functions may have parameters and return useful things :) That is, you may write, by example: remotefiles = getRemoteFiles(host, remotedir) localfiles = getLocalFiles(localdir) newfiles = findNewFiles(localfiles, remotefiles) uploadFiles(host, newfiles) -- Gabriel Genellina From nick at craig-wood.com Mon May 14 05:30:03 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 14 May 2007 04:30:03 -0500 Subject: Asyncore Help? References: Message-ID: Erik Max Francis wrote: > Paul Kozik wrote: > > > While basic socket work was rather easy to deal with, this has proved > > significantly more difficult. Are there any good free sources for > > information on Asyncore, and dealing with TCP? > > You haven't said specifically what you're having a problem with. The > more general name for asyncore/asynchat is Medusa, and there are some > resources with more examples available here: > > http://www.nightmare.com/medusa/ > http://www.amk.ca/python/code/medusa.html There is also twisted of course if we are talking about async networking libraries. http://twistedmatrix.com/trac/ The learning curve of twisted is rather brutal, but it will do everything you want and a whole lot more! I haven't tried Medusa, but I've done several things with twisted. It takes a bit of getting your head round but you'll be impressed with the speed. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From chris.arndt at web.de Mon May 21 13:35:39 2007 From: chris.arndt at web.de (Christopher Arndt) Date: 21 May 2007 10:35:39 -0700 Subject: A few questions In-Reply-To: References: Message-ID: <1179768939.695708.299940@u36g2000prd.googlegroups.com> I have a few quibles with your summary of Python's properties: On 21 Mai, 08:16, John Nagle wrote: > If you have a computer science background, here's all you need > to know: Python is a byte-code interpreted untyped Python is strongly but dynamically typed. The fact that you don't have to declare which type a variable is, doesn't mean it's untyped. > procedural In Python you can programm in imperative/procedural, object-oriented and functional style. It can thus be called a multi-paradigm language. IMO it is best suited for the object-oriented paradigm. > dynamic language with implicit declaration. Syntax is vaguely C-like. It shares many syntax rules with C (variable names, literals, functions, ...) but it doesn't look at all like C (no braces, semicolons, assignment expressions, pointers, ...). > Block structure is determined by indentation. Objects use a class definition/ > explicit instantiation/multiple inheritance model. Most important, classes are defined at run-time, not compile time, which makes them highly dynamic. Furthermore, classes, functions and methods are first-class data- types, i.e you can pass them (or more correctly, references to them) around as arguments or assign them to variables. > Memory management > is safe and managed by reference counts backed by a garbage collector. > Weak references are supported. Built in data types are numerics, ASCII > and Unicode strings, dynamic arrays, fixed size tuples, and hashes. Python lists are much more than arrays. More like a linked list. You forgot sets. And functions, classes, methods, instances.... (see above) > Implementation speed is typically 2% of C. Execution speed is approx. 2% - 150% of C :-) Chris From jzgoda at o2.usun.pl Fri May 18 04:48:09 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 18 May 2007 10:48:09 +0200 Subject: (Modular-)Application Framework / Rich-Client-Platform in Python In-Reply-To: References: Message-ID: Wildemar Wildenburger napisa?(a): >> There are few GUI frameworks building on various toolkits. I used to use >> Kiwi for PyGTK, it's mature and stable, although the approach is not the >> same as, for example, Delphi > Thanks for the effort, but I think I'm not well understood. I'm not > looking for a GUI framework (which, by the way, is most likely to be > wxPython), but for a pure plugin architecture. A rich-client-platform, > as it is sometimes called. Nothing specific about anythin in particular, > just something that runs plugins. Like Eclipse does these days. I know what is Eclipse RCP. The world would be much better place to live if we had something similar. :) Many applications employ "plugin framework"-like things and in Python this is specially easy to do, but I saw none that is built as one big plugin framework. The one that mostly resembles such approach is PIDA (http://www.pida.co.uk/), which is built around the concept of pluggable views and services, but again, this is far from Eclipse RCP. -- Jarek Zgoda "We read Knuth so you don't have to." From tijs_news at artsoftonline.com Wed May 30 11:11:40 2007 From: tijs_news at artsoftonline.com (Tijs) Date: Wed, 30 May 2007 17:11:40 +0200 Subject: How to print this character u'\u20ac' to DOS terminal References: <1180501468.957322.106650@z28g2000prd.googlegroups.com> <465D0A6B.1000203@v.loewis.de> <1180508736.598924.26170@r19g2000prf.googlegroups.com> <465d760d$0$338$e4fe514c@news.xs4all.nl> <1180537263.762432.37770@n15g2000prd.googlegroups.com> Message-ID: <465d942c$0$320$e4fe514c@news.xs4all.nl> ??????????????? wrote: > Yes, it works, thank you. > But I doubt this way may not work on linux. Maybe I should write some > additional code for supporting both windows and linux OS. Depends on what you want to do. Printing to a DOS terminal is hard in Linux :-) If you write server code, best to keep all text in unicode. -- Regards, Tijs From adrian_p_smith at yahoo.com Mon May 7 00:30:16 2007 From: adrian_p_smith at yahoo.com (Adrian Smith) Date: 6 May 2007 21:30:16 -0700 Subject: CGI python use "under a curse" Message-ID: <1178512216.246621.38960@p77g2000hsh.googlegroups.com> While waiting for my paid-for web-hosting company to get back to me about my difficulties running python scripts on their servers... http://groups.google.com/group/comp.lang.python/browse_frm/thread/39b52bcf0dffec4c/4ff805bf283acc15?lnk=gst&q=adrian+smith&rnum=1&hl=en#4ff805bf283acc15 ...I went and found a free one as a stopgap. And it worked! I was as happy as a clam. But then it stopped working. Ah. I stripped the script down to the same minimalist hello-world effort I used previously: #!/usr/local/bin/python import cgi print "Content-type: text/html\n" form = cgi.FieldStorage() print form["essay"].value (page here: http://essays.profusehost.net/) As before, this should print out the contents of a textarea going by the name of "essay". But it does nothing but throw internal server errors. The support guy looked at it and gave me this: Traceback (most recent call last): File "python1.cgi", line 6, in ? print form["essay"].value File "/usr/local/lib/python2.4/cgi.py", line 559, in __getitem__ raise KeyError, key KeyError: 'essay' (http://www.profusehost.net/forum/support/10894-cgi-blink.html) He says I have a syntax error, though I'm b*ed if I can see where it could be. Can anyone here suggest anything? TIA for your forbearance etc. From google at mrabarnett.plus.com Sun May 6 17:12:24 2007 From: google at mrabarnett.plus.com (MRAB) Date: 6 May 2007 14:12:24 -0700 Subject: Newbie prob: How to write a file with 3 threads? In-Reply-To: References: <1178440537.257526.40980@y5g2000hsa.googlegroups.com> Message-ID: <1178485944.755068.321740@y5g2000hsa.googlegroups.com> On May 6, 9:51 am, Marc 'BlackJack' Rintsch wrote: > In <1178440537.257526.40... at y5g2000hsa.googlegroups.com>, est wrote: > > I need to write a file using 3 threads simutaniously, e.g. Thread 1 > > write the first byte of test.bin with an "a", second thread write the > > second byte "b", third thread write the third byte "c". Anyone could > > give a little example on how to do that? > > Simplest solution is: don't do that. Write from one thread and send the > date from the other threads via a `Queue.Queue` to the writing thread. > Send the number of the thread with the data so the writer thread knows in > which order the data has to be written. > [snip] Or have a `Queue.Queue` for each source thread and make the writer thread read from each in turn. From sjmachin at lexicon.net Wed May 2 20:44:41 2007 From: sjmachin at lexicon.net (John Machin) Date: 2 May 2007 17:44:41 -0700 Subject: Slicing Arrays in this way In-Reply-To: References: <4638fe20$0$16403$88260bb3@free.teranews.com> Message-ID: <1178153081.907748.242110@h2g2000hsg.googlegroups.com> On May 3, 10:21 am, Michael Hoffman wrote: > Tobiah wrote: > > > >>> elegant_solution([1,2,3,4,5,6,7,8,9,10]) > > [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] > > That's not an array, it's a list. See the array module for arrays > (fixed-length, unlike variable-length lists). You must have your very own definitions of "fixed-length" and "unlike". >>> import array >>> fixed = array.array('b') >>> fixed.append(42) >>> fixed.extend([0, 1, 127]) >>> fixed array('b', [42, 0, 1, 127]) >>> fixed.append(2) >>> fixed array('b', [42, 0, 1, 127, 2]) >>> fixed[2:4] = array.array('b', [8]) >>> fixed array('b', [42, 0, 8, 2]) >>> From samfeltus at gmail.com Thu May 3 12:28:49 2007 From: samfeltus at gmail.com (SamFeltus) Date: 3 May 2007 09:28:49 -0700 Subject: SonomaSunshine Get's a Little Peppier In-Reply-To: <1177916383.119425.210920@e65g2000hsc.googlegroups.com> References: <1177916383.119425.210920@e65g2000hsc.googlegroups.com> Message-ID: <1178209729.306006.284790@y5g2000hsa.googlegroups.com> The TurboGears app from Outer Space... Sam the Gardener http://samfeltus.com/as3/codetalking3.html From istvan.albert at gmail.com Sat May 19 23:17:38 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: 19 May 2007 20:17:38 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464EA85E.1040508@v.loewis.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <464C5382.6080403@v.loewis.de> <1179423799.254286.294930@w5g2000hsg.googlegroups.com> <1179503525.018943.95740@u30g2000hsc.googlegroups.com> <_pq3i.1390$wH4.1177@news-server.bigpond.net.au> <464EA85E.1040508@v.loewis.de> Message-ID: <1179631058.310012.123480@e65g2000hsc.googlegroups.com> On May 19, 3:33 am, "Martin v. L?wis" wrote: > > That would be invalid syntax since the third line is an assignment > > with target identifiers separated only by spaces. > > Plus, the identifier starts with a number (even though ? is not DIGIT > SIX, but FULLWIDTH DIGIT SIX, it's still of category Nd, and can't > start an identifier). Actually both of these issues point to the real problem with this PEP. I knew about them (note that the colon is also missing) alas I couldn't fix them. My editor would could not remove a space or add a colon anymore, it would immediately change the rest of the characters to something crazy. (Of course now someone might feel compelled to state that this is an editor problem but I digress, the reality is that features need to adapt to reality, moreso had I used a different editor I'd be still unable to write these characters). i. From rahulnag22 at yahoo.com Wed May 9 15:59:08 2007 From: rahulnag22 at yahoo.com (rahulnag22 at yahoo.com) Date: 9 May 2007 12:59:08 -0700 Subject: tkinter get widget option value In-Reply-To: References: <1178649638.119603.265380@y5g2000hsa.googlegroups.com> Message-ID: <1178740748.656420.77000@u30g2000hsc.googlegroups.com> On May 8, 6:51 pm, James Stroud wrote: > rahulna... at yahoo.com wrote: > > Hi, > > If I have abuttonwidget > > > w =Button(root, text = "Button", state = 'disabled') > > > How can I get the value of option 'state' from the widget 'w'. > > I want something like -- > > > print w.state >> to print out >> 'disabled' > > > Thanks > > Rahul > > print w["state"] > > James Thanks! James From tmp123 at menta.net Thu May 3 10:42:17 2007 From: tmp123 at menta.net (tmp123) Date: 3 May 2007 07:42:17 -0700 Subject: newbie: copy base class fields In-Reply-To: References: <1178201644.920048.205400@y5g2000hsa.googlegroups.com> Message-ID: <1178203337.871306.171680@y80g2000hsf.googlegroups.com> On May 3, 4:29 pm, Marc 'BlackJack' Rintsch wrote: > > > #!/usr/bin/python > > # > > > class A: > > def __init__(self): > > self.v1=1 > > > def __repr__(self): > > return "v1=%d\n" % self.v1 > > > class B(A): > > def __init__(self,a): > > self=a > > self.v2=2 > > > def __repr__(self): > > return A.__repr__(self) + ("v2=%d\n" % self.v2) > > > x=A() > > print x > > > y=B(x) > > print y > > > $ ./prueba.pl > > v1=1 > > > Traceback (most recent call last): > > File "./prueba.pl", line 23, in > > print y > > File "./prueba.pl", line 17, in __repr__ > > return A.__repr__(self) + ("v2=%d\n" % self.v2) > > File "./prueba.pl", line 9, in __repr__ > > return "v1=%d\n" % self.v1 > > AttributeError: B instance has no attribute 'v1' > Hello Marc, Thanks for your help. I'm sorry, I've not correctly explained the subject. It is need to init class B with the current value of the A instance, not with the initial ones. A best example is: x=A() print x x.v1=3 y=B(x) print y at the end, y.v1 must be equal to 3. Sorry again. From broek at cc.umanitoba.ca Tue May 22 15:01:53 2007 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Tue, 22 May 2007 15:01:53 -0400 Subject: Inheritance In-Reply-To: <1179859216.425460.252130@w5g2000hsg.googlegroups.com> References: <1179859216.425460.252130@w5g2000hsg.googlegroups.com> Message-ID: <46533E21.7090203@cc.umanitoba.ca> HMS Surprise said unto the world upon 05/22/2007 02:40 PM: > I am trying to understand the 'if' statement and the exec statement in > the code below. I would like to add several common routines to this > class and then inherit it into a class in another file. This other > class would need to access these common functions as well as inherit > the PyHttpTestCase class. In particular what is the purpose of the > surrounding plus signs? May I assume the if statement overrides an > imported assignment statement. > > > Thanks, > > jh > > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > from PyHttpTestCase import PyHttpTestCase > from com.bitmechanic.maxq import Config > global validatorPkg > if __name__ == 'main': > validatorPkg = Config.getValidatorPkgName() > # Determine the validator for this testcase. > exec 'from '+validatorPkg+' import Validator' The if test is, AFAICT, ensuring that validatorPkg is defined. Config.getValidatorPkgName() likely returns a string. The + signs are just concatenating a string to be exec'ed: >>>> validatorPkg = 'some string returned by getValidatorPkgName()' >>>> 'from '+validatorPkg+' import Validator' > 'from some string returned by getValidatorPkgName() import Validator' >>>> > HTH, Brian vdB From toby at tobiah.org Wed May 2 18:29:32 2007 From: toby at tobiah.org (Tobiah) Date: Wed, 02 May 2007 15:29:32 -0700 Subject: Slicing Arrays in this way In-Reply-To: <1178144265.751484.318830@y80g2000hsf.googlegroups.com> References: <4638fe20$0$16403$88260bb3@free.teranews.com> <1178144265.751484.318830@y80g2000hsf.googlegroups.com> Message-ID: <4639043f$0$10194$88260bb3@free.teranews.com> Matimus wrote: > On May 2, 3:03 pm, Tobiah wrote: >> >>> elegant_solution([1,2,3,4,5,6,7,8,9,10]) >> [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] >> >> -- >> Posted via a free Usenet account fromhttp://www.teranews.com > >>>> seq = range(1,11) >>>> seq > [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>>> zip( seq[0::2],seq[1::2] ) > [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)] > > if you _really_ need lists then... >>>> map(list, zip( seq[0::2],seq[1::2] )) > [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] > I had come up with: [[a[x], a[x + 1]] for x in range(0, 10, 2)] I was hoping for something a little more concise. Something like list[::2:2] if that existed. -- Posted via a free Usenet account from http://www.teranews.com From rridge at caffeine.csclub.uwaterloo.ca Wed May 16 08:16:15 2007 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Wed, 16 May 2007 08:16:15 -0400 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: Ross Ridge schrieb: > non-ASCII identifiers. While it's easy to find code where comments use > non-ASCII characters, I was never able to find a non-made up example > that used them in identifiers. Gregor Horvath wrote: >If comments are allowed to be none English, then why are identifier not? In the code I was looking at identifiers were allowed to use non-ASCII characters. For whatever reason, the programmers choose not use non-ASCII indentifiers even though they had no problem using non-ASCII characters in commonets. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From ptmcg at austin.rr.com Sun May 13 12:48:46 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 13 May 2007 09:48:46 -0700 Subject: need help with python In-Reply-To: <1179069008.711095.301770@p77g2000hsh.googlegroups.com> References: <1178934447.719778.197150@h2g2000hsg.googlegroups.com> <1178988911.443161.287350@k79g2000hse.googlegroups.com> <1179069008.711095.301770@p77g2000hsh.googlegroups.com> Message-ID: <1179074926.028768.157090@h2g2000hsg.googlegroups.com> On May 13, 10:10 am, adamur... at hotmail.com wrote: > On May 12, 11:55 am, BartlebyScrivener wrote: > > > > > > > I'm not sure how you installed Python, or how you are using it, but I > > made something last year to help Windows XP users who are brand new to > > Python and can't get things to run, etc. > > > You might try either jumping into somewhere midway, or if you keep > > having trouble, uninstall whatever you installed and start over using > > this: > > >http://www.richarddooling.com/index.php/2006/03/14/python-on-xp-7-min... > > > If that link breaks, use this: > > >http://tinyurl.com/w7wgp > > > Good luck. > > > rd > > That is one of my problems, I don't know exactly how the whole command > line thing works. The other day, I got it to open python by itself, > but I accidentally closed the window and couldn't get it to work > again. I know how to do file paths and stuff but I'm not sure what to > put directly after it says C:\Documents and Settings\HP_Owner>. Do I > leave it like that and then put the next location in the line? Like > this: > C:\Documents and Settings\HP_Owner> Python 2.5.1\Python area.py > Or is that wrong. I've already uninstalled and reinstalled because I > couldn't copy and paste it to another location, so I just reinstalled > it to HP_Owner. I'll try that link. > Thanks.- Hide quoted text - > > - Show quoted text - cd will change your current directory to . Type "help" after the "C:\Documents and Settings\HP_Owner>" (which is called the 'prompt') to get a summarized list of commands, or "help " to get help on that particular command. For instance try typing this at the command line prompt: help cd and you'll get a lot more info on the cd command. It sounds like a Windows tutorial would not be wasted time for you, especially one that helps with the whole command line thing. You'll learn about files, directories, deleting, renaming, and so on. -- Paul From C.delete_this.Sanders at BoM.GOv.AU Wed May 9 05:37:21 2007 From: C.delete_this.Sanders at BoM.GOv.AU (Charles Sanders) Date: Wed, 09 May 2007 19:37:21 +1000 Subject: Multiple regex match idiom In-Reply-To: <87r6pqxtgh.fsf@busola.homelinux.net> References: <87r6pqxtgh.fsf@busola.homelinux.net> Message-ID: <46419652$0$83120$c30e37c6@lon-reader.news.telstra.net> Hrvoje Niksic wrote: > I often have the need to match multiple regexes against a single > string, typically a line of input, like this: > > if (matchobj = re1.match(line)): > ... re1 matched; do something with matchobj ... > elif (matchobj = re2.match(line)): > ... re2 matched; do something with matchobj ... > elif (matchobj = re3.match(line)): > .... [snip] > > There are ways to work around the problem, for example by writing a > utility predicate that passes the match object as a side effect, but > that feels somewhat non-standard. I'd like to know if there is a > Python idiom that I'm missing. What would be the Pythonic way to > write the above code? Only just learning Python, but to me this seems better. Completely untested. re_list = [ re1, re2, re3, ... ] for re in re_list: matchob = re.match(line) if matchob: .... break Of course this only works it the "do something" is the same for all matches. If not, maybe a function for each case, something like re1 = re.compile(....) def fn1( s, m ): .... re2 = .... def fn2( s, m ): .... re_list = [ (re1, fn1), (re2, fn2), ... ] for (r,f) in re_list: matchob = r.match(line) if matchob: f( line, matchob ) break f(line,m) Probably better ways than this exist. Charles From stefan.sonnenberg at pythonmeister.com Sun May 6 23:33:43 2007 From: stefan.sonnenberg at pythonmeister.com (Stefan Sonnenberg-Carstens) Date: Mon, 07 May 2007 05:33:43 +0200 Subject: import conflict In-Reply-To: <1178504177.697440.23740@p77g2000hsh.googlegroups.com> References: <1178504177.697440.23740@p77g2000hsh.googlegroups.com> Message-ID: <463E9E17.6070605@pythonmeister.com> rplzqx402 at sneakemail.com schrieb: > Hello, > > I have a problem where I need to set up two separate Python projects > that each live under the same package. Once they are distributed, > they will live under the same filesystem path, but during development, > they are separated. > > For example: > proj1/lib/pkg/foo/mod1.py > proj2/lib/pkg/bar/mod2.py > > Furthermore, proj1 is dependent on proj2, so I want to be able to say > things like this, from within proj1: > > import pkg.foo.mod1 > import pkg.bar.mod2 > > Of course this doesn't work, even with a PYTHONPATH configured to see > both projects, because it will find 'pkg' in proj1/lib and so pkg.bar > will be hidden from view. > > Any suggestions? > > Thanks! > > Hi, my only suggestion would be to overthink your project organization. You can surely solve that problem with symlinks, but if they depend on another, perhaps the structure is not optimal. If you use python 2.5 you can try absolute imports (which I personally find not so well): from __future__ import absolute_import See here: http://python.mirrors-r-us.net/dev/peps/pep-0328/ Cheers, Stefan From george.sakkis at gmail.com Tue May 15 08:57:14 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 15 May 2007 05:57:14 -0700 Subject: Subprocess with and without shell In-Reply-To: References: <1179194910.310317.38730@y80g2000hsf.googlegroups.com> Message-ID: <1179233834.596515.147010@k79g2000hse.googlegroups.com> On May 15, 5:30 am, Nick Craig-Wood wrote: > George Sakkis wrote: > > I'm trying to figure out why Popen captures the stderr of a specific > > command when it runs through the shell but not without it. IOW: > > > cmd = [my_exe, arg1, arg2, ..., argN] > > if 1: # this captures both stdout and stderr as expected > > pipe = Popen(' '.join(cmd), shell=True, stderr=PIPE, stdout=PIPE) > > else: # this captures only stdout > > pipe = Popen(cmd, shell=False, stderr=PIPE, stdout=PIPE) > > > # this prints the empty string if not run through the shell > > print "stderr:", pipe.stderr.read() > > # this prints correctly in both cases > > print "stdout:", pipe.stdout.read() > > > Any hints ? > > Post an example which replicates the problem! I would, but the specific executable being spawned is not a python script, it's a compiled binary (it's not an extension module either; it's totally unrelated to python). I don't claim there is a bug or anything suspicious about Popen, but rather I'd like an explanation of how can a program display different behavior depending on whether it runs through the shell or not. George From bytter at gmail.com Wed May 16 13:58:44 2007 From: bytter at gmail.com (Hugo Ferreira) Date: Wed, 16 May 2007 18:58:44 +0100 Subject: Typed named groups in regular expression Message-ID: <4e8efcf50705161058i206a43c7v7b1002d28058b41f@mail.gmail.com> Hi! Is it possible to "automagically" coerce the named groups to python types? e.g.: >>> type(re.match('(?P\d*)', '123').groupdict()['x']) But what I'm looking forward is for the type to be 'int'. Cheers! Hugo Ferreira From deets at nospam.web.de Wed May 16 10:49:27 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 16 May 2007 16:49:27 +0200 Subject: Unusual i/o problems References: <1179325595.708882.289510@e65g2000hsc.googlegroups.com> Message-ID: <5b0jvoF2q6rhtU1@mid.uni-berlin.de> saif.shakeel at gmail.com wrote: > Hi, > I am parsing an xml file ,before that i have replaced a string in > the original xml file with another and made a new xml file which will > now be parsed.I am also opening some more files for output.The > following code shows some i/o commands. > file_input = raw_input("Enter The ODX File Path:") > input_xml = open(file_input,'r') > > (shortname,ext)=os.path.splitext(file_input) > f_open_out=shortname+".ini" > log=shortname+".xls" > test_file=shortname+"testxml.xml" > > saveout = sys.stdout > > xmlcont=input_xml.read() > input_xml.close() > > xmlcont=xmlcont.replace('localId','dataPackageId') > > output_file = open(test_file,"w") > output_file.write(xmlcont) > output_file.close() > > f_open=open(f_open_out, 'w') > logfile=open(log,"w") > sys.stdout = f_open > > After this i have to parse the new xml file which is in > output_file .hence > > input_xml_sec = open(output_file,'r') > xmldoc = minidom.parse(input_xml_sec) > > But i am getting an error on this line > (input_xml_sec = open(output_file,'r')).I have tried to figure out but > not able to debug.Can someone throw some light or anything they feel > could be going wrong somewhere. How about telling us what the error is? Suggested read: http://www.catb.org/~esr/faqs/smart-questions.html Diez Diez From michael at jedimindworks.com Fri May 18 15:43:08 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Fri, 18 May 2007 14:43:08 -0500 Subject: Python compared to other language In-Reply-To: <464DF8A3.90704@rogers.com> References: <464DF8A3.90704@rogers.com> Message-ID: <375599AC-B6D9-407F-8037-EA52C1B211D9@jedimindworks.com> On May 18, 2007, at 2:04 PM, scott wrote: > > I have been looking at the various programming languages > available. I > have programed in Basic since I was a teenager and I also have a basic > understanding of C, but I want something better. > > Can anybody tell me the benefits and weaknesses of using Python? Hi Scott, I think it is best that you learn Python's benefits and weaknesses for yourself. I don't mean to sound dismissive -- it's just that a list of benefits and weaknesses will be little more than hollow words until you have your own personal experiences. http://docs.python.org/tut/tut.html is a pretty good place to start. hth, Michael --- Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. --Brian W. Kernighan From grante at visi.com Fri May 11 12:03:41 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 11 May 2007 16:03:41 -0000 Subject: Newbie look at Python and OO References: <1178812734.860473.236370@y80g2000hsf.googlegroups.com> <1178832102.256466.235020@l77g2000hsb.googlegroups.com> <13490canfv56c9c@corp.supernews.com> Message-ID: <13494utet9ahb60@corp.supernews.com> On 2007-05-11, Duncan Booth wrote: > Grant Edwards wrote: > >> http://www.ariel.com.au/jokes/An_Interview_with_Bjarne_Stroustrup.html >> >> Maybe BS thought he was joking, but IMO, it's true. >> >> "Stroustrup: Remember the length of the average-sized 'C' >> project? About 6 months. Not nearly long enough for a guy >> with a wife and kids to earn enough to have a decent >> standard of living. Take the same project, design it in C++ >> and what do you get? I'll tell you. One to two years." >> > > I doubt very much that BS was involved at any point in writing it. You > forgot to quote the bit at the end: > > [Note - for the humor-impaired, not a true story] My bad. I completely missed that -- I thought it was a real interview where BS was joking. -- Grant Edwards grante Yow! I just remembered at something about a TOAD! visi.com From steve at holdenweb.com Sat May 26 21:35:54 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 26 May 2007 21:35:54 -0400 Subject: ten small Python programs In-Reply-To: <1180229019.873381.52800@m36g2000hse.googlegroups.com> References: <1180229019.873381.52800@m36g2000hse.googlegroups.com> Message-ID: Paul McGuire wrote: [...]. > > I guess pyparsing with its mixedCase functions and attributes is > doomed for the Dunce Corner. Too bad for BeautifulSoup, cElementTree, > and wxPython that are also at variance with this canon of Python > coding style. ("Modules should have short, all-lowercase names. ... > Python packages should also have short, all-lowercase names, although > the use of underscores is discouraged.") > Although the names in wxPython are indeed contrary to PEP 8 (because they are the same as the names used in wxWidgets) I should point out that nowadays the name you import is "wx". 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From sjdevnull at yahoo.com Wed May 16 05:31:59 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 16 May 2007 02:31:59 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464AC0E0.3040107@web.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476081.7080609@web.de> <46498514$0$6402$9b4e6d93@newsspool2.arcor-online.net> <1179288668.417582.210470@u30g2000hsc.googlegroups.com> <464AC0E0.3040107@web.de> Message-ID: <1179307919.182504.297930@q75g2000hsh.googlegroups.com> Stefan Behnel wrote: > sjdevnull at yahoo.com wrote: > > I even sometimes > > read code snippets on email lists and websites from my handheld, which > > is sadly still memory-limited enough that I'm really unlikely to > > install anything approaching a full set of Unicode fonts. > > One of the arguments against this PEP was that it seemed to be impossible to > find either transliterated identifiers in code or native identifiers in Java > code using a web search. So it is very unlikely that you will need to upgrade > your handheld as it is very unlikely for you to stumble into such code. Sure, if the feature isn't going to be used then it won't present problems. I can't really see much of an argument for a PEP that isn't going to be used, though, and if it is used then it's worthwhile to think about the implications of having code that many common systems simply can't deal with (either displaying it incorrectly or actually corrupting files that pass through them). From walterbyrd at iname.com Fri May 11 23:07:36 2007 From: walterbyrd at iname.com (walterbyrd) Date: 11 May 2007 20:07:36 -0700 Subject: Newbie look at Python and OO In-Reply-To: References: <1178812734.860473.236370@y80g2000hsf.googlegroups.com> <1346hrvgve90nea@corp.supernews.com> Message-ID: <1178939255.996029.263520@p77g2000hsh.googlegroups.com> > He's thinking in Pascal, not C. > Actually, I have programmed in many languages. I just first learned in Pascal. For me, going from Pascal, to basic,c,cobol,fortran . . was not that difficult. Python, however, feels strange. As crazy as this may sound: Python, in some ways, reminds me of assembly language. I haven' t programmed in assembly in a *long* time. But I vaugly remember doing a lot of stuff where I used memory addresses as pointers to data, and also as pointers to pointers. Although, when I first started assembly language, I think it took me a week to write a program to print "hello world." From larry.bates at websafe.com Wed May 16 18:56:37 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 16 May 2007 17:56:37 -0500 Subject: zipfile stupidly broken In-Reply-To: References: Message-ID: Martin Maney wrote: > To quote from zipfile.py (2.4 library): > > # Search the last END_BLOCK bytes of the file for the record signature. > # The comment is appended to the ZIP file and has a 16 bit length. > # So the comment may be up to 64K long. We limit the search for the > # signature to a few Kbytes at the end of the file for efficiency. > # also, the signature must not appear in the comment. > END_BLOCK = min(filesize, 1024 * 4) > > So the author knows that there's a hard limit of 64K on the comment > size, but feels it's more important to fail a little more quickly when > fed something that's not a zipfile - or a perfectly legitimate zipfile > that doesn't observe his ad-hoc 4K limitation. I don't have time to > find a gentler way to say it because I have to find a work around for > this arbitrary limit (1): this is stupid. > > > (1) the leading candidate is to copy and paste the whole frigging > zipfile module so I can patch it, but that's even uglier than it is > stupid. "This battery is pining for the fjords!" > > > Normally I despise being CC'd on a reply to list or group traffic, but > in this case it's probably necessary, as I haven't had time to keep up > with this place for several years. :-/ > Are you serious? A zipfile with a comment > 4Kbytes. I've never encountered such a beast. As with any open source product it is much better to roll up your sleeves and pitch in to fix a problem than to rail about "how it is stupidly broken". You are welcome to submit a patch or at the very least a good description of the problem and possible solutions. If you have gotten a lot of value out of Python, you might consider this "giving back". You haven't paid anything for the value it has provided. -Larry From mcl.office at googlemail.com Thu May 31 09:22:30 2007 From: mcl.office at googlemail.com (mosscliffe) Date: 31 May 2007 06:22:30 -0700 Subject: HTML Form/Page and Navigation with multiple buttons Message-ID: <1180617750.709628.180070@p77g2000hsh.googlegroups.com> I am struggling to find a python example of the scenario - I have. I have a python script, which generates a page with a search button (actually an input field). The data from the above submissions is interrogated and the same script produces a new search option and the a page of results from the previous search request. - as done by Google's Main search page. The user then has the option of a new search or navigating to a different page of results with the usual Start, Previous, Next and Last Buttons. How can I identify which button has been pressed. Do I need a separate form for each button and hide all the relevant session fields in each form or is there a way of identifying which button has been pressed on the page. I only want to use the same python script, which is called each time. No javascript and no cookies. I have a very skimpy knowledge of Forms, Get and Post - so be gentle with me. I have got CGI and FieldStorage to work. Any help or suitable introductory site information appreciated. Richard From sjmachin at lexicon.net Tue May 8 17:58:09 2007 From: sjmachin at lexicon.net (John Machin) Date: 8 May 2007 14:58:09 -0700 Subject: XLRD Python 2.51 Question In-Reply-To: References: <1178638018.606763.162650@e51g2000hsg.googlegroups.com> Message-ID: <1178661489.009127.242980@w5g2000hsg.googlegroups.com> On May 9, 1:36 am, Carsten Haese wrote: > On Tue, 2007-05-08 at 08:26 -0700, kylan... at gmail.com wrote: > > CompDocError: MSAT extension: accessing sector 1717046 but only 2887 > > in file > > > I am not sure what this means at all > > At least superficially that sounds like the file you're trying to open > is truncated or otherwise corrupted to the point where xlrd doesn't know > what to do with it. Looks like to me it's truncated or corrupted to the point where xlrd knows *exactly* what to do: pull the ejection handle. Amplifying the error message: The extension to the Master Sector Allocation Table appears to be referencing sector number 1717046 but there are only 2887 sectors in the file. The default sector size is 512. Note that 1717046 * 512 > 800 Mb. > What happens if you try to open the file with Excel? > If Excel manages to open the file, maybe the file is using a storage > format that's newer than what xlrd is prepared to handle. There is no newer format that uses .XLS as an extension. Default from Excel 2007 is .XLSX (XML format -- xlrd upgrade in preparation); there's also a binary format (.XLSB) ... If Excel manages to open the file, there are two other possibilities (both of which have historical antecedents): (1) we've fallen into the 0.1% gap in openoffice.org's 99.9% brilliant reverse-engineering of the arcane structures in an OLE2 Compound Document (2) the file is trash an' Bill don't care :-( Trying to open the file with openoffice.org's Calc (version 2.1) and with Gnumeric is a good idea, if they are available conveniently. I'd suggest that the OP send a copy of the file to the package author, together with the following information: (a) version of xlrd (b) what platform (c) what version of Python (d) background to creation of file especially what software created it (e) has xlrd been used successfully before/since to open files? (f) does the path2 thingy in the first entry in the traceback indicate that the file is on a network? startRow = 0, sh_idx = 0, path2 = '//otaam.com/root/SharedFiles/ GlobeOp/Risk/Cal Projects/temp/') If so, what happens if the file is put on a local hard drive and this is done: shell-prompt> python import xlrd xlrd.open_workbook('the_file.xls') HTH, John From jemnader at gmail.com Tue May 22 06:29:23 2007 From: jemnader at gmail.com (jolly) Date: 22 May 2007 03:29:23 -0700 Subject: NOOOOB Message-ID: <1179829763.464614.123920@a26g2000pre.googlegroups.com> Hey guys, I want to begin python. Does anyone know where a good starting point is? Thanks, Jem From fidtz at clara.co.uk Thu May 3 08:54:29 2007 From: fidtz at clara.co.uk (fidtz at clara.co.uk) Date: 3 May 2007 05:54:29 -0700 Subject: ascii to unicode line endings In-Reply-To: References: <1178122765.162546.59680@l77g2000hsb.googlegroups.com> Message-ID: <1178196869.679780.171030@n59g2000hsh.googlegroups.com> On 3 May, 13:39, "Jerry Hill" wrote: > On 2 May 2007 09:19:25 -0700, f... at clara.co.uk wrote: > > > The code: > > > import codecs > > > udlASCII = file("c:\\temp\\CSVDB.udl",'r') > > udlUNI = codecs.open("c:\\temp\\CSVDB2.udl",'w',"utf_16") > > udlUNI.write(udlASCII.read()) > > udlUNI.close() > > udlASCII.close() > > > This doesn't seem to generate the correct line endings. Instead of > > converting 0x0D/0x0A to 0x0D/0x00/0x0A/0x00, it leaves it as 0x0D/ > > 0x0A > > That code (using my own local files, of course) basically works for me. > > If I open my input file with mode 'r', as you did above, my '\r\n' > pairs get transformed to '\n' when I read them in and are written to > my output file as 0x00 0x0A. If I open the input file in binary mode > 'rb' then my output file shows the expected sequence of 0x00 0x0D 0x00 > 0x0A. > > Perhaps there's a quirk of your version of python or your platform? I'm running > Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit > (Intel)] on win32 > > -- > Jerry Thanks very much! Not sure if you intended to fix my whole problem, but changing the read mode to 'rb' has done the trick :) Dom From rabbitsfriendsandrelations at hotmail.com Sat May 5 02:54:50 2007 From: rabbitsfriendsandrelations at hotmail.com (Eeyore) Date: Sat, 05 May 2007 07:54:50 +0100 Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> <08qk33t594ih0ulmjmev90d22lkfnotgoe@4ax.com> Message-ID: <463C2A3A.8332D211@hotmail.com> quasi wrote: > Gib Bogle wrote: > > >Ah, so the firefighters were in on the conspiracy! > > No, but the firefighters are very much aware that there is more to > 9/11 than has been officially revealed. > > This is even more true at Pentagon. The firefighters there brought > dogs trained to search for survivors and/or remains Sounds like good practice. > and found nothing. And the significance of this is ? Graahm From evenprimes at gmail.com Thu May 17 12:07:24 2007 From: evenprimes at gmail.com (Chris Cioffi) Date: Thu, 17 May 2007 12:07:24 -0400 Subject: Python Web Programming - looking for examples of solid high-traffic sites In-Reply-To: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> Message-ID: I think the first question I would have is what kind of dynamic content are you talking about? Is this a web app kind of thing, or just a content pushing site? While Django might not be v1.0 yet, it seems very solid and stable, and perfect for quickly building powerful content based dynamic sites. Other Python frameworks might be well suited to other types of dynamic sites. (I like TurboGears for actual web apps...) Depending on your needs you might also consider a non-python solution (!) like Drupal. (I'm not a PHP fan, but since other people have done all that great work....:) As others have said, there might be no framework currently in existence that meets all of your requirements. You'll need to work with your team to decide what kinds of compromises you can all live with. Chris -- "A little government and a little luck are necessary in life, but only a fool trusts either of them." -- P. J. O'Rourke From saif.shakeel at gmail.com Fri May 18 03:06:03 2007 From: saif.shakeel at gmail.com (saif.shakeel at gmail.com) Date: 18 May 2007 00:06:03 -0700 Subject: i/o prob revisited Message-ID: <1179471963.303052.136690@q23g2000hsg.googlegroups.com> Hi, I am parsing an xml file ,before that i have replaced a string in the original xml file with another and made a new xml file which will now be parsed.I am also opening some more files for output.The following code shows some i/o commands. file_input = raw_input("Enter The ODX File Path:") input_xml = open(file_input,'r') (shortname,ext)=os.path.splitext(file_input) f_open_out=shortname+".ini" log=shortname+".xls" test_file=shortname+"testxml.xml" saveout = sys.stdout xmlcont=input_xml.read() input_xml.close() xmlcont=xmlcont.replace('localId','dataPackageId') output_file = open(test_file,"w") output_file.write(xmlcont) output_file.close() f_open=open(f_open_out, 'w') logfile=open(log,"w") sys.stdout = f_open After this i have to parse the new xml file which is in output_file .hence input_xml_sec = open(output_file,'r') xmldoc = minidom.parse(input_xml_sec) But i am getting an error on this line (input_xml_sec = open(output_file,'r')).I have tried to figure out but not able to debug.Can someone throw some light or anything they feel could be going wrong somewhere. How do i capture the error as it vanishes very qucikly when i run through command prompt,(the idle envir gives indentation errors for no reason(which runs perfectly from cmd prompt),hence i dont run using conventional F5. From stefan.sonnenberg at pythonmeister.com Thu May 10 10:32:48 2007 From: stefan.sonnenberg at pythonmeister.com (Stefan Sonnenberg-Carstens) Date: Thu, 10 May 2007 16:32:48 +0200 (CEST) Subject: Read binary data from MySQL database In-Reply-To: <1178806756.509611.192130@e51g2000hsg.googlegroups.com> References: <1178806756.509611.192130@e51g2000hsg.googlegroups.com> Message-ID: <1068189.7450.BlRUCl8VTQA=.1178807568.squirrel@webmailer.hosteurope.de> On Do, 10.05.2007, 16:19, Christoph Krammer wrote: > Hello, > > I try to write a python application with wx that shows images from a > MySQL database. I use the following code to connect and get data when > some event was triggered: > > dbconn = MySQLdb.connect(host="localhost", user="...", passwd="...", > db="images") > dbcurs = dbconn.cursor() > dbcurs.execute("""SELECT imgdata FROM images LIMIT 1""") > imgstring = dbcurs.fetchone()[0] > frame.showImage(imgstring) > > Within my frame, the following method is defined: > > def showImage(self, imgstring): > imgdata = StringIO.StringIO() > imgdata.write(imgstring) Use imgdata.write(imgstring.tostring()) or imgstring.tofile(imgdata) > print imgdata.getvalue() > wx.ImageFromStream(imgdata, wx.BITMAP_TYPE_GIF) > panel = wx.Panel(self, -1) > self.panel = panel > > But this does not work. The converter says that the data is not valid > GIF. When I print the content of imgstring after the database select > statement, it contains something like this: > > array('c', 'GIF89aL\x01=\x01\x85\x00\x00\x00\x00\x00\xff\xff\xff > \x00\xff\xff\xff[...]\x00\x00;') > > When I try to print imgstring[1], the result is "I". So I don't quite > get what this print result is about and why my input should not be > valid. The data in the database is correct, I can restore the image > with tools like the MySQL Query Browser. > > Thanks in advance, > Christoph > > -- > http://mail.python.org/mailman/listinfo/python-list > > From tjreedy at udel.edu Thu May 10 13:33:20 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 10 May 2007 13:33:20 -0400 Subject: Newbie (but improving) - Passing a function name with parameters as aparameter References: <1178785638.736644.312970@e51g2000hsg.googlegroups.com> Message-ID: "mosscliffe" wrote in message news:1178785638.736644.312970 at e51g2000hsg.googlegroups.com... Asun Friere pointed out the central flaw in your program. Since passing functions as arguments is an important concept, here, for any newbies who did not understand, is a restatement of the problem and the fix. | timeloop(lookup(myrecs,mypatts), 10) This does not pass the lookup function to timeloop. Rather it calls lookup and passes the boolean result. The attempt to 'call' that boolean gives |I am trying to time a function's execution, but I get 'TypeError: | 'bool' object is not callable' when I try to run it. | I suspect it is my calling of 'timeloop' with the function name | 'lookup' and its associated variables Yes. Make the following changes and all should be well. | def timeloop(dofunction,iters=10): def timeloop(func, args, iters=10) | import datetime | print "->-> Start of test", "LOOPS=", iters, | datetime.datetime.now().ctime() | for x in xrange(iters): | print x | dofunction() func(*args) | print "<-<- End of test", "LOOPS=", iters, | datetime.datetime.now().ctime() | | def lookup(recs,patterns): | matchcount = 0 | pattcount = 0 | for patt in patterns: | if matchcount < pattcount: | break | pattcount += 1 | for rec in recs: | # print "PATT:", patt, " REC:", rec, " PATTCOUNT=", pattcount | if patt in rec: | matchcount +=1 | break | # print"MATCHCOUNT=",matchcount, "PATTCOUNT=", pattcount | if matchcount == pattcount: | return True | else: | return False | | | | myrecs = ['This is a title for Brian', 'this is detail one for brian', | 'this is detail two for brian', 'this is another detail one for | brian'] | | test1 = ['one', 'nomatch'] | test2 = ['one', 'two'] | test3 = ['title', 'two', 'nomatcheither'] | | mypatts = test1 | | timeloop(lookup(myrecs,mypatts), 10) timeloop(lookup, (myrecs, mypaths), 10) Terry Jan Reedy From p.lavarre at ieee.org Thu May 31 13:55:39 2007 From: p.lavarre at ieee.org (p.lavarre at ieee.org) Date: 31 May 2007 10:55:39 -0700 Subject: FAQ: how to vary the byte offset of a field of a ctypes.Structure Message-ID: <1180634138.944362.88590@d30g2000prg.googlegroups.com> How do I vary the byte offset of a field of a ctypes.Structure? How do I "use the dynamic nature of Python, and (re-)define the data type after the required size is already known, on a case by case basis"? \\\ For example, suppose sometimes I receive the value '\x03hi' + \x04bye' for the struct: class Struct34(ctypes.Structure): _pack_ = 1 _fields_ = [('first', 3 * ctypes.c_ubyte), ('second', 4 * ctypes.c_ubyte)] but then sometimes instead I receive the value '\x05left' + \x06right' for the struct: class Struct56(ctypes.Structure): _pack_ = 1 _fields_ = [('first', 5 * ctypes.c_ubyte), ('second', 6 * ctypes.c_ubyte)] Thus in general I receive (0xFF ** 2) possible combinations of field lengths. /// How do I declare all those hugely many simply regular combinations as one CTypes.structure? I also need to do series of 3 or 4 or 5 strings, not just 2 strings. But always the byte offsets of the subsequent fields vary when the byte sizes of the preceding fields vary. The byte size of the enclosing packed struct varies as the length of the packed bytes it contains. The errors I get as I try techniques that don't work include: AttributeError: '_fields_' must be a sequence of pairs AttributeError: _fields_ is final ValueError: Memory cannot be resized because this object doesn't own it TypeError: incompatible types, c_ubyte_Array_2 instance instead of c_ubyte_Array_1 instance How do I change the offset of a field of a ctypes.Structure? Is the answer to contribute to the next version of CTypes? Or is this feature already supported somehow? Curiously yours, thank in advance, http://www.google.com/search?q=ctypes+variable+size http://www.google.com/search?q=ctypes+variable+length http://www.google.com/search?q=ctypes+variable+offset http://www.google.com/search?q=ctypes+%22string+of+strings%22 http://www.google.com/search?q=ctypes+%22vary+the+byte+offset%22 http://www.google.com/search?q=ctypes+%22change+the+byte+offset%22 From flavio.preto at gmail.com Thu May 10 02:17:18 2007 From: flavio.preto at gmail.com (Flavio Preto) Date: Thu, 10 May 2007 03:17:18 -0300 Subject: preferred windows text editor? In-Reply-To: <1178749301.768963.278070@w5g2000hsg.googlegroups.com> References: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> <1178749301.768963.278070@w5g2000hsg.googlegroups.com> Message-ID: <5fb10ac20705092317u3465d818md043cb63b14eaa6d@mail.gmail.com> I use VIM here too. Mainly because i always switch from Windows to Linux and using the same text editor is a way to avoid getting crazy. []'s Preto On 9 May 2007 15:21:41 -0700, BartlebyScrivener wrote: > > On May 9, 1:26 pm, "Looney, James B" wrote: > > > I'm using Vim (http://www.vim.org/). > > I too vote for VIM. I use it on both Windows XP and Debian Etch. I > can't find anything it doesn't do. > > rd > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rurpy at yahoo.com Wed May 16 15:11:46 2007 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 16 May 2007 12:11:46 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179258692.237438.110860@p77g2000hsh.googlegroups.com> Message-ID: <1179342706.604528.281240@p77g2000hsh.googlegroups.com> "Hendrik van Rooyen" wrote in message news:mailman.7745.1179308671.32031.python-list at python.org... > wrote: > > First "while" is a keyword and will remain "while" so > > that has nothing to do with anything. > > I think this cuts right down to why I oppose the PEP. > It is not so much for technical reasons as for aesthetic > ones - I find reading a mix of languages horrible, and I am > kind of surprised by the strength of my own reaction. But to reiterate, most public code will remain english because that is the only practical way of managing an international project. If don't understand this almost pathological fear that if the PEP is adopted, the world will be deluged by a torrent of non-english programs. 99.9% of such programs will be born an die in an enviroment where only speakers of those languages will touch them. The few that leak into the wider world will have to be internationalized before most people will consider adopting them, volenteering to maintain them, etc. And has been already pointed out this is already the case. How can you maintain a python program written with only ascii identifiers but transliterated from a non-english language and with documention, comments, prompts and messages in that language? This situation exists right now and it hasn't caused the end of python-programming-as-we-know-it. > If I try to analyse my feelings, I think that really the PEP > does not go far enough, in a sense, and from memory > it seems to me that only E Brunel, R Fleschenberg and > to a lesser extent the Martellibot seem to somehow think > in a similar way as I do, but I seem to have an extreme > case of the disease... > > And the summaries of reasons for and against have left > out objections based on this feeling of ugliness of mixed > language. > > Interestingly, the people who seem to think a bit like that all > seem to be non native English speakers who are fluent in > English. I have read that people who move to, or become citizens of a new country often become far more patriotic and defensive of their new country, then their native-born compatriots. > While the support seems to come from people whose English > is perfectly adequate, but who are unsure to the extent that they > apologise for their "bad" English. > > Is this a pattern that you have identified? - I don't know. > > I still don't like the thought of the horrible mix of "foreign" > identifiers and English keywords, coupled with the English > sentence construction. And that, in a nutshell, is the main > reason for my rather vehement opposition to this PEP. > > The other stuff about sharing and my inability to even type > the OP's name correctly with the umlaut is kind of secondary > to this feeling of revulsion. Interesting explanation, thanks. I personally feel a lot of the reaction against the PEP involves psychological drivers like loss of control and loss of status but am not a psycologist so it would be too much work from me to try and defend, so I won't try to. I'll just say I think that making Python (significantly!!) more accessible to non-English speakers is far too imporant to both those potential new users as to Python itself, that it should not be decided by "feelings". > "Beautiful is better than ugly" "Beauty is in the eye of the beholder" From larry.bates at websafe.com Tue May 22 19:31:00 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 22 May 2007 18:31:00 -0500 Subject: using google search api for python In-Reply-To: References: Message-ID: Gerardo Herzig wrote: > Hi all. Im looking for the pyGoogle for making google searchs y a python > script. The thing is, all im founding is an AJAX api, but the > application ill use is NOT a web app. So, someone know if there is a > pure python api that i can download and use? > > Thanks! > Gerardo The server (Google) on the other end doesn't know what type of app you are. It just responds to XMLRPC requests. I haven't used the interface but I'm guessing that I would use Twisted to make XMLRPC request to Google and process the response XML payload using Elementree. -Larry From john at datavoiceint.com Tue May 8 16:19:16 2007 From: john at datavoiceint.com (HMS Surprise) Date: 8 May 2007 13:19:16 -0700 Subject: Another easy pair of questions Message-ID: <1178655556.202998.241870@e65g2000hsc.googlegroups.com> In a python Tk shell in Windows, what is the equivalent of unix's pwd? In a python Tk shell in Windows, is there an easy way to reoeat an earlier command, similar to Tcl/Tk's hist? From steve at holdenweb.com Wed May 16 16:07:36 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 16 May 2007 16:07:36 -0400 Subject: Typed named groups in regular expression In-Reply-To: <4e8efcf50705161058i206a43c7v7b1002d28058b41f@mail.gmail.com> References: <4e8efcf50705161058i206a43c7v7b1002d28058b41f@mail.gmail.com> Message-ID: Hugo Ferreira wrote: > Hi! > > Is it possible to "automagically" coerce the named groups to python types? e.g.: > >>>> type(re.match('(?P\d*)', '123').groupdict()['x']) > > > But what I'm looking forward is for the type to be 'int'. > > Cheers! > > Hugo Ferreira So apply the "int()" function to the str and it will be! 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From shuimuliang at gmail.com Sun May 27 06:29:42 2007 From: shuimuliang at gmail.com (shuimuliang at gmail.com) Date: 27 May 2007 03:29:42 -0700 Subject: How to get a dot's or pixel's RGB with PIL In-Reply-To: References: <1180240167.582601.247050@q19g2000prn.googlegroups.com> Message-ID: <1180261782.312788.129620@j4g2000prf.googlegroups.com> I got it. Pass python challenge chapter 7. From deets at nospam.web.de Wed May 30 14:32:00 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 30 May 2007 20:32:00 +0200 Subject: Appending a log file and see progress as program executes In-Reply-To: References: Message-ID: <5c5u8vF2v1pm3U2@mid.uni-berlin.de> Karim Ali schrieb: > Hi, > > I am writing a program that will take several days to execute :) and > would like to append to a log file but be able to open that file at any > time and see the errors that have occured. > > So this is what I am doing: > > ---------------------------------------------- > flog = open('out.log', 'a') > .... > when needed: > sys.stdout=flog > print "error message" > ------------------------------------------------ > > This will print directly to log. I use sys.stdout so i can quickly (in > code) change back and forth between errors displayed on screen and > errors logged.. > > This works great. The only problem is that I cant see anything in the > log file when I try to open it say with notepad while the program is > running...and this is not good at all! > > Any suggestions are appreciated. install cygwin bash, and use tail out.log Diez From nis at superlativ.dk Mon May 28 11:16:20 2007 From: nis at superlativ.dk (=?ISO-8859-1?Q?Nis_J=F8rgensen?=) Date: Mon, 28 May 2007 17:16:20 +0200 Subject: Newbie question - better way to do this? In-Reply-To: References: Message-ID: <465af249$0$90266$14726298@news.sunsite.dk> Steve Howell skrev: > --- Nis J?rgensen wrote: > >> Steve Howell skrev: >> >>> def firstIsCapitalized(word): >>> return 'A' <= word[0] <= 'Z' >> For someone who is worried about the impact of >> non-ascii identifiers, >> you are making surprising assumptions about the >> contents of data. >> > > The function there, which I don't even remotely > defend, had nothing to with the main point of the > thread. Others pointed out that correct idiom here is > word.istitle(), but the main point of the thread was > how to prevent the newbie from essentially reinventing > itertools.groupby. The subject line says "Newbie question - better way to do this". I was hinting at a better way to do what you did, which was supposedly a better way of doing what the newbie wanted. I disagree that word.istitle is the correct idiom - from the naming of the function in the original example, I would guess "word[0].isupper" would do the trick. > If you want to point out holes in my logic about the > impact of non-ascii identifiers (the above code, > though bad, does not suggest a hole in my logic; it > perhaps even adds to my case), can you kindly do it in > a thread where that's the main point of the > discussion? Will do. Nis From dzawer at gmail.com Fri May 18 10:14:20 2007 From: dzawer at gmail.com (dzawer at gmail.com) Date: 18 May 2007 07:14:20 -0700 Subject: A best approach to a creating specified http post body In-Reply-To: References: <1179486210.398916.251970@o5g2000hsb.googlegroups.com> Message-ID: <1179497660.462525.26110@o5g2000hsb.googlegroups.com> On May 18, 4:57 pm, "Dave Borne" wrote: > > I need to build a special http post body that consists of : > > name=value +\r\n strings. > > Problem is that depending on operations the number of name,value > > pairs can increase and decrease. > > Values need to be initialized at runtime, so storing premade text > > files is not possible. > > I'm not completely understanding your problems here. Can you explain > why urllib.urlencode wouldn't work? > (http://docs.python.org/lib/module-urllib.html) > > Thanks, > -Dave Hmm, I guess I meant something different by using "body"- I meant request data part and not the thing sent in ulr string. From nobody at nowhere.com Wed May 2 23:31:54 2007 From: nobody at nowhere.com (Homer J Simpson) Date: Thu, 03 May 2007 03:31:54 GMT Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> Message-ID: "Midex" wrote in message news:1178161523.615688.256120 at y80g2000hsf.googlegroups.com... > In order to appreciate just what Truthers are talking about when they > cry Treason over WTC7, you would want to see this History Channel > documentary on what they claim happened to WTC7: > http://www.youtube.com/watch?v=TVSxeJH_RCY No, it was the Men in Black. From robert.kern at gmail.com Thu May 24 13:00:38 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 24 May 2007 12:00:38 -0500 Subject: Different methods with same name but different signature? In-Reply-To: <713634.7367.qm@web37902.mail.mud.yahoo.com> References: <713634.7367.qm@web37902.mail.mud.yahoo.com> Message-ID: No. -- 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 Sun May 13 19:35:19 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 14 May 2007 09:35:19 +1000 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <46478694$0$1412$426a34cc@news.free.fr> <1hy252p.1anf7sr1p4yp12N%aleax@mac.com> Message-ID: On Sun, 13 May 2007 15:35:15 -0700, Alex Martelli wrote: > Homoglyphic characters _introduced by accident_ should not be discounted > as a risk ... > But when something similar > happens to somebody using a sufficiently fancy text editor to input > source in a programming language allowing arbitrary Unicode letters in > identifiers, the damage (the sheer waste of developer time) can be much > more substantial -- there will be two separate identifiers around, both > looking exactly like each other but actually distinct, and unbounded > amount of programmer time can be spent chasing after this extremely > elusive and tricky bug -- why doesn't a rebinding appear to "take", etc. > With some copy-and-paste during development and attempts at debugging, > several copies of each distinct version of the identifier can be spread > around the code, further hampering attempts at understanding. How is that different from misreading "disk_burnt = True" as "disk_bumt = True"? In the right (or perhaps wrong) font, like the ever-popular Arial, the two can be visually indistinguishable. Or "call" versus "cal1"? Surely the correct solution is something like pylint or pychecker? Or banning the use of lower-case L and digit 1 in identifiers. I'm good with both. -- Steven. From tenax.raccoon at gmail.com Wed May 9 14:48:57 2007 From: tenax.raccoon at gmail.com (Jason) Date: 9 May 2007 11:48:57 -0700 Subject: preferred windows text editor? In-Reply-To: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> References: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> Message-ID: <1178736537.006543.83030@y5g2000hsa.googlegroups.com> On May 9, 12:06 pm, "T. Crane" wrote: > Right now I'm using Notepad++. What are other people using? > > trevis IDLE for short scripts, PyDev under Eclipse for big Python projects, and the Python shell for basic one-offs. --Jason From fsckedagain at gmail.com Wed May 9 14:11:06 2007 From: fsckedagain at gmail.com (fscked) Date: 9 May 2007 11:11:06 -0700 Subject: path stuff Message-ID: <1178734266.858048.311740@y5g2000hsa.googlegroups.com> I am walking some directories looking for a certain filename pattern. This part works fine, but what if I want to exclude results from a certain directory being printed? eg d:\dir\mydir1\filename.txt <----------I want to see this one d:\dir\mydir2\archived\filename.txt <----------I don't want to see anything in the "archived" directory d:\dir\mydir2\filename.txt <----------Again, I do want to see this one I am having a bit of trouble figuring out how to use the path module to hack up the path to determine if I am in a subdir I care about. So either don show me the results from a certain directory or just plain skip a certain directory. From desertlinux at netscape.net Tue May 15 19:59:55 2007 From: desertlinux at netscape.net (Brian) Date: Tue, 15 May 2007 16:59:55 -0700 Subject: Python Newbie Suggestions In-Reply-To: <1179264515.958714.72880@l77g2000hsb.googlegroups.com> References: <1179264515.958714.72880@l77g2000hsb.googlegroups.com> Message-ID: <0Qr2i.101240$Fk2.48037@newsfe08.phx> What about "Learning With Python"? It was written by a high school teacher for teaching python in the classroom for absolute beginners. Best of all, it's FREE: http://www.greenteapress.com/ Byron --- garcigal at gmail.com wrote: > I'm a mechanical engineer with little experience programming. I've > used C++ and machine language for getting micro-controllers to work > and thats about it. I work allot with software developers at my job > and can read C++ code pretty good (ie. I understand whats going on). > Does anyone have any good tips or resources for someone interested in > learning PYTHON. This is purely for hobby purposes and I'd like to > expose my kids to a programing language too. If any one has any > helpful books, tips or suggestions please let me know. I have > Windows, MAC and Linux box's at my house but I'm a primarily a MAC > user. > From pillappa at hotmail.com Sun May 6 14:14:44 2007 From: pillappa at hotmail.com (pillappa at hotmail.com) Date: 6 May 2007 11:14:44 -0700 Subject: Error when using Custom Exception defined in a different python module. Message-ID: <1178475284.092656.103710@e65g2000hsc.googlegroups.com> Hi, I am hitting this error consistently and don't know why it's happening. I would like to define all exceptions for my project in one file and use them across the project. Here's a sample - exceptions.py - class MyException(StandardError): def __init__(self, error): self.myerror = error tests.py - from exceptions import * class Test: def __init__(self,filename): if filename == "": raise MyException("Raise custom error") if __name__ == "__main__" : test = Test("") When the above is run, I get the following error - NameError: global name 'MyException' is not defined Thanks loganwol From bignose+hates-spam at benfinney.id.au Sat May 19 22:12:07 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 20 May 2007 12:12:07 +1000 Subject: (Modular-)Application Framework / Rich-Client-Platform in Python References: <8ea03$464dc950$d443bb3a$5229@news.speedlinq.nl> <871whd60dx.fsf@benfinney.id.au> Message-ID: <87abw0451k.fsf@benfinney.id.au> Wildemar Wildenburger writes: > I really, really appreciate the effort you (all of you) make in > helping me and getting me on the right track, but I'm a bit > confounded by how you can be trying to convince me that the tools > I'm currently reading the docs for don't exist. I think most of us never really understood what you were looking for. Your descriptions were quite vague, and the websites you pointed to seemed to assume a great deal of understanding about Eclipse. I never got a handle on the features you wanted, so I presented my "as I understand it, you already have what you want"-type conclusions to prompt you for better descriptions of the problem. I'm glad you were able to find a solution to whatever problem it is you're trying to solve -- good luck with that :-) -- \ "Too many Indians spoil the golden egg." -- Sir Joh | `\ Bjelke-Petersen | _o__) | Ben Finney From brett_mcs at bigpond.com Thu May 24 05:45:26 2007 From: brett_mcs at bigpond.com (Brett_McS) Date: Thu, 24 May 2007 09:45:26 GMT Subject: Checking parameters prior to object initialisation Message-ID: Fairly new to Python (and loving it!) In C++ (gack!) I got used to creating a helper function with each class to check the class object initialisation parameters prior to creating the object. In Python, this would be ----------------------------------------------- import example if example.ParametersOK(a, b, c, d): newObj = example.Example(a, b, c, d) else: print "Error in parameters" ----------------------------------------------- I presume this would still be considered good practise in Python, or is there some other, preferred, method? Cheers, Brett McSweeney From steve at holdenweb.com Tue May 15 20:55:47 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 15 May 2007 20:55:47 -0400 Subject: Spotting Crashed Application In-Reply-To: <11505.3843394437$1178703827@news.gmane.org> References: <11505.3843394437$1178703827@news.gmane.org> Message-ID: Robert Rawlins - Think Blue wrote: > Hello Guys, > > > > I?ve got an application that I?ve written, and it sits in an embedded > system, from time to time the application will crash, I?m not quite sure > what?s causing this, but as we test it more and more we?ll grasp a > better understanding and fix the issues. > > > > However, until then I need a quick solution which can spot the crash and > reboot the system. Is there any generic way of writing a separate > application that?ll spot the crash in my main application? If not then i > was thinking about having my core application log itself as ?alive? > every 5 minutes or so. My new ?spotter? application can check this log, > if it?s not been written too in say 6 minutes then the main app must > have crashed, and it can reboot. > > > > Any suggestions on how best to handle this? Obviously finding the bug in > my main app is paramount, but a failsafe will never hurt. > I don't know of any pre-written functionality, but I'd recommend using a UDP socket for this. Let your application send a packet (say) every 30 seconds and have the monitoring application restart it if it doesn't hear a packet for 90 seconds. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From lisa.engblom at gmail.com Wed May 16 11:21:13 2007 From: lisa.engblom at gmail.com (Lisa) Date: 16 May 2007 08:21:13 -0700 Subject: remove all elements in a list with a particular value Message-ID: <1179328873.105705.95580@l77g2000hsb.googlegroups.com> I am reading in data from a text file. I want to enter each value on the line into a list and retain the order of the elements. The number of elements and spacing between them varies, but a typical line looks like: ' SRCPARAM 1 6.35e-07 15.00 340.00 1.10 3.0 ' Why does the following not work: line = ' SRCPARAM 1 6.35e-07 15.00 340.00 1.10 3.0 ' li = line.split(' ') for j,i in enumerate(li): if i == '': li.remove(i) After the original split I get: ['', '', '', 'SRCPARAM', '', '', '1', '6.35e-07', '15.00', '', '340.00', '', '', '1.10', '', '', '', '', '', '3.0', '', '', ''] And after the for loop I get: ['SRCPARAM', '1', '6.35e-07', '15.00', '340.00', '1.10', '', '', '', '3.0', '', '', ''] It doesn't remove all of the empty elements. Is there a better way to split the original string? Or a way to catch all of the empty elements? Thanks From joshua at eeinternet.com Thu May 24 17:08:32 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Thu, 24 May 2007 13:08:32 -0800 Subject: Module imports fine from interactive, not from script References: <46538a79$0$16264$88260bb3@free.teranews.com> Message-ID: <4655f284$0$8096$88260bb3@free.teranews.com> On Thursday 24 May 2007 08:32, Steve Holden wrote: > The directory containing the script you are executing is also added to > sys.path. Since you are executing a script called planet ... Ah! That's it. That had never occurred to me, as I was under the impression that your current *working* directory was added to sys.path, not the directory of the script. Thanks! j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE -- Posted via a free Usenet account from http://www.teranews.com From Dave.Baum at motorola.com Mon May 7 15:56:56 2007 From: Dave.Baum at motorola.com (Dave Baum) Date: Mon, 07 May 2007 14:56:56 -0500 Subject: Simulating simple electric circuits References: <5a9838F2nlbanU1@mid.individual.net> Message-ID: In article <5a9838F2nlbanU1 at mid.individual.net>, Bjoern Schliessmann wrote: > Hello all, > > I'm trying to simulate simple electric logic (asynchronous) > circuits. By "simple" I mean that I only want to know if I > have "current" or "no current" (it's quite digital) and the only > elements need to be (with some level of abstraction to my specific > problem) > > - sources (here begin currents) > - ground (here end currents) > - joints > - switches (which are able to let current pass or not, depending on > outside influence) > - loads (which can signal change in current flow to the outside -- > just like a light bulb) Are you trying to do logic simulation (digital) or analog circuit simulation? The only reason I ask is that the simulation techniques are very different, and you used both "logic" and "current" in your description, so I'm not quite sure which direction you are heading. For analog: If you are ignoring time related effects (no inductance or capacitance), then the system is solvable as a set of linear equations. Basically your circuit consists of a set of nodes and edges. Wires are edges, joints are nodes. An open switch is nothing, a closed switch is an edge. A load is an edge. You'll have to assign resistances to the edges (anything non-zero will do) in order for the equations to make sense. Then you can use Kirchoff's laws to analyze the circuit and construct the equations to solve. A good linear algebra library (numpy) will help in solving the equations. Opening or closing a switch would result in a new set of equations, and thus a new solution. You might be able to get clever and model open switches as edges with infinite resistance, which would allow you to skip the Kirchoff stuff each time a switch is flipped. You'd only have to change coefficients and solve the system of equations. However, the system of equations would be singular, so you'd have to do something like an SVD rather than an inverse. I don't want to go into too much more detail about this one because I have a hunch you are really looking at digital, but if you're interested in the analog approach let me know and I'll fill in more of the details. For digital: Event based simulation is typical here. These simulations generally are concerned with voltage, not current. A circuit consists of signals and devices. At any given time, each signal has a certain state (high/low, on/off, 9 level logic, whatever). Devices are connected to one another by signals. You'll also need events (a signal, a time, and a new state), and an event queue (events sorted by time). This is easier if each signal is driven by at most one device: 1) pop the next event off the queue 2) if the event's signal's state is the same as the new state, go to 1 3) set the event's signal's state to the new state 4) for each device that is attached to the signal, run the device's code, which should look at all of its inputs, and post new events to the queue for any outputs (do this even if the computed output is the same as the current output). These events are usually posted for some time in the future (1 simulation 'tick' is fine). 5) go to 1 This approach is pretty simple to do in Python. I wrote a sample digital simulator a while back and the core of the simulator was around 50 lines of code. Rounded out with some basic logic gates and helper functions to probe the simulation, it was around 150 lines. It was only 2 level logic and signals could only be driven by a single device. The devices that you want to model (switches, loads, etc) don't have explicit inputs and outputs, and you'll need to deal with a signal being driven from multiple sources, so it will get a bit more complicated. You will probably also need 9 level logic (or something equivalent) to deal with the fact that ground beats a source through a load when determining a node's state. The basic idea is that each signal has multiple drivers, each of which has an internal state. When a device wants to set an output, it only changes its driver's state. The signal then has code that looks at the state of all drivers and combines them in some way (this is called a resolution function). That combined state is what devices see when they read the signal. It isn't *that* complicated to implement, but if you can turn your problem into one with 2 level logic and no multiple drivers, then it will be easier to write and debug. Dave From half.italian at gmail.com Wed May 9 17:11:31 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 9 May 2007 14:11:31 -0700 Subject: Checking if string inside quotes? In-Reply-To: References: Message-ID: <1178745091.682071.128670@w5g2000hsg.googlegroups.com> On May 9, 1:39 pm, "Michael Yanowitz" wrote: > Hello: > > If I have a long string (such as a Python file). > I search for a sub-string in that string and find it. > Is there a way to determine if that found sub-string is > inside single-quotes or double-quotes or not inside any quotes? > If so how? > > Thanks in advance: > Michael Yanowitz I think the .find() method returns the index of the found string. You could check one char before and then one char after the length of the string to see. I don't use regular expressions much, but I'm sure that's a more elegant approach. This will work. You'll get in index error if you find the string at the very end of the file. s = """ foo "bar" """ findme = "foo" index = s.find(findme) if s[index-1] == "'" and s[index+len(findme)] == "'": print "single quoted" elif s[index-1] == "\"" and s[index+len(findme)] == "\"": print "double quoted" else: print "unquoted" ~Sean From richardjones at optushome.com.au Thu May 24 06:03:29 2007 From: richardjones at optushome.com.au (Richard Jones) Date: Thu, 24 May 2007 20:03:29 +1000 Subject: CP4E revival References: <1179941107.366354.101860@h2g2000hsg.googlegroups.com> Message-ID: <465562f1$0$14719$afc38c87@news.optusnet.com.au> Michael Tobis wrote: > http://tinyurl.com/yr62r3 > > seems to short-circuit some pointless hoop-jumping to get you to the > article. Hoop-jumping implemented to prevent just this kind of direct linking (and thus not saving of the PDF to local disk to view, and thus increasing the load on the server). Thanks for abusing the free service being provided to the Python Papers journal. Richard From sail0r at creepjoint.net Wed May 30 16:08:59 2007 From: sail0r at creepjoint.net (sail0r at creepjoint.net) Date: Wed, 30 May 2007 16:08:59 -0400 Subject: Off Topic: What is the good book to learn Python ? In-Reply-To: <1180549522.350380.276570@q66g2000hsg.googlegroups.com> References: <1180549522.350380.276570@q66g2000hsg.googlegroups.com> Message-ID: Katie Tam wrote: > I am new to this filed and begin to learn this langague. Can you tell > me the good books to start with ? My favorite is the O'Reilly jython book. This book is specifically about the python interpreter written in java but I have always found it to be a well written explanation of python basics in general. From tooru_honda at fast-mail.org Tue May 1 03:46:50 2007 From: tooru_honda at fast-mail.org (tooru honda) Date: Tue, 01 May 2007 15:46:50 +0800 Subject: playing sound in mac osx Message-ID: <4636F06A.8050603@fast-mail.org> Hi, I am a newbie to mac and python. Is there an easy way to play wav or mp3 sound file ? I used to use winsound module before switching to mac, but that only works for windows. Thanks Tooru P.S. I am using Mac OSX 10.4.8 and Python 2.5 From i.read.the at group.invalid Thu May 10 23:51:15 2007 From: i.read.the at group.invalid (Pom) Date: Fri, 11 May 2007 03:51:15 GMT Subject: setting extra data to a wx.textctrl Message-ID: Hello group! I have an application which uses a lot of mysql data fields, all the same data type (floats). I created a panel which executes a "SELECT * FROM tablename" and makes as much fields as needed, using de cursor.description as wx.statictext and the cursors field contents copied into wx.textctrls. At creation time, I loop over all the fields in the record and create a tuple which contains ((textctrl1, fieldname1), (textctrl2, fieldname2), ...) so I can keep track of which textctrl holds which piece of fielddata. The problem I'm having is: to know the fieldname in an text_event, I use event.GetEventObject(), then perform an iteration over the tuple and when I find a match I use the field name to update the mysqltable. When having a few fields, this is ok. But I have over 100 fields in 1 record and it really slows things down. Now my question is: should I use a python dictionary (with an object as first lookup field) ? On windows, I've seen a "Tag" property in a textbox which was meant to be used for this kind of stuff. Maybe it's better to override the wx.textctrl so I can add an extra string value? Anyone having the best solution for this ? thx! From Graham.Dumpleton at gmail.com Thu May 17 19:18:44 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: 17 May 2007 16:18:44 -0700 Subject: Is wsgi ready for prime time? In-Reply-To: References: <1179426728.846565.51390@h2g2000hsg.googlegroups.com> Message-ID: <1179441930.011502.118800@u30g2000hsc.googlegroups.com> On May 18, 5:31 am, Stefan Sonnenberg-Carstens wrote: > IMHO WSGI is _only_ a new way of talking to webservers, like apache. > It is as low-level as (f)cgi, so don't expect too much support at this > stage - > indeed a module like the cgi one in the std lib would be nice. > As google uses it (mod_wsgi), I would suspect you can use it. So people don't get the wrong impression, mod_wsgi is merely hosted on the Google code site. This does not mean that Google uses it, nor does Google have anything to do with its development. Graham From nagle at animats.com Mon May 21 02:16:24 2007 From: nagle at animats.com (John Nagle) Date: Mon, 21 May 2007 06:16:24 GMT Subject: A few questions In-Reply-To: References: Message-ID: jay wrote: > Hi, > > I'm totally new to Python and was hoping someone might be able to > answer a few questions for me: > > 1. What are your views about Python vs Perl? Do you see one as better > than the other? Python is a much cleaner language than Perl, but not as widely used. The Python language is in good shape; the libraries vary in quality. > 2. Is there a good book to start with while learning Python? I'm > currently reading 'Python Essential Reference' by David M. Beazley. So > far it looks like a pretty good book, but would like more tutorials to > work with (I've also been reading through the tutorials at 'python.org' > which has some excellent stuff!). They're all reasonably good. Python doesn't have Perl's "There's more than one way to do it" problem, so all Python books describe the same language. (Perl books tend to describe the subsections of the language that particular author likes. It takes about three different Perl books to cover every language feature.) "Learning Python" has more tutorials, but the online tutorials at "python.org" should be sufficient. This just isn't a very difficult language. If you have a computer science background, here's all you need to know: Python is a byte-code interpreted untyped procedural dynamic language with implicit declaration. Syntax is vaguely C-like. Block structure is determined by indentation. Objects use a class definition/ explicit instantiation/multiple inheritance model. Memory management is safe and managed by reference counts backed by a garbage collector. Weak references are supported. Built in data types are numerics, ASCII and Unicode strings, dynamic arrays, fixed size tuples, and hashes. Implementation speed is typically 2% of C. That's Python. > > 3. Currently, I write most of my code with Xcode (on the Mac platform) > using Applescript. Can't speak to Mac issues. Tkinter will work, although it may be aesthetically displeasing to Mac users. John Nagle From half.italian at gmail.com Mon May 28 15:47:28 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 28 May 2007 12:47:28 -0700 Subject: User input with a default value that can be modified In-Reply-To: References: Message-ID: <1180381648.351270.173400@x35g2000prf.googlegroups.com> On May 28, 11:52 am, "Etienne Hilson" wrote: > Hello the list :-) > > I do a little program that permit the user to manage list of sentences. > This program runs into a linux shell. > The user can add, modify and delete the sentences. > > What I want to do is : > > When the user want to modify one sentence, I would like to do this : > > Modify your sentence : The_sentence_appear_here_followed_by_a_cursor > > And the user can go back with the cursor, like in the bash shell, > delete, modify, and when pressing enter, the new value (or the same if > not modified) is put in my variable. > > Of course, the first think I did as a newbie was : > > new_sentence = raw_input("Modify your sentence : "old_sentence) > > But OF COURSE, stupid am I, the user cannot put the cursor back into > the old sentence ! > > I think about playing with some sophisticated keyboard exercise where > I could program a new input command with a value already appearing as > answer, but I am pretty sure that it exists already. > > What do you think about it ? > > Actually, it is quite difficult to find anything on it, because the > keywords are not very obvious (input, default answer, ...) > > Thank you for your help. > > Etienne > -- > (\__/) > (='.'=) Ceci est un petit lapin. Copiez/collez-le dans > (")_(") votre signature pour l'aider ? dominer le monde Check into the readline module. This is what I came up with. A second thread injects the text into the open readline instance. Hopefully the experts will show the _right_ way to do it. import readline, threading import time class write(threading.Thread): def __init__ (self, s): threading.Thread.__init__(self) self.s = s def run(self): time.sleep(.01) readline.insert_text(self.s) readline.redisplay() write("Edit this sentence").start() s = raw_input("prompt:") print s ~Sean From jstroud at mbi.ucla.edu Sat May 5 01:25:14 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 04 May 2007 22:25:14 -0700 Subject: Firefighters at the site of WTC7 "Move away the building is going to blow up, get back the building is going to blow up." In-Reply-To: <7hvn3358vhfo3k4iqp44167tbq6b0fnl0t@4ax.com> References: <1178161820.731367.264500@y80g2000hsf.googlegroups.com> <1hlj33p6aq838o2urk1dv6h75b5is4i2vd@4ax.com> <3TD_h.219$mR2.195@newssvr22.news.prodigy.net> <1178329932.455122.161530@u30g2000hsc.googlegroups.com> <7hvn3358vhfo3k4iqp44167tbq6b0fnl0t@4ax.com> Message-ID: Charles wrote: > On Fri, 04 May 2007 20:19:33 -0700, James Stroud > wrote: > > >>MooseFET wrote: >> >>>On May 4, 12:32 pm, James Stroud wrote: >>>[....] >>> >>> >>>>The Marxist contribution to western thought is that it put everything in >>>>terms of labor and thus allowed us to quantify the human component of >>>>economies. >>> >>> >>>No the great insight by Marx was in the selling of ducks. "Anybody >>>want to buy a duct" has done more to advance economic thinking than >>>the works of most economists. >>> >>>Economists have a vested interest in preventing people from >>>understanding economics. They are well paid and know that they >>>wouldn't be for long if people really understood what was going on. >>> >> >>You must be an economist because you provide absolutely no >>interpretation of what the hell you were saying in ghe first paragraph >>(as if you actually know what you were trying to say). Duct or duck, >>first of all. Second of all--make a point. >> >>James > > Different Marx? Oh, so Curly of the 3 stooges did more to advance physics when a vase fell on his head than all of the physics books written? Physicists don't really want you to know whats going on so they can get paid more. Oh, yes, I'm doing more for computer science by saying x=y than all of the computer books written. Knuth, eat your heart out, see how smart I am? James From stefan.behnel-n05pAM at web.de Wed May 16 06:12:38 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 16 May 2007 12:12:38 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179307919.182504.297930@q75g2000hsh.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476081.7080609@web.de> <46498514$0$6402$9b4e6d93@newsspool2.arcor-online.net> <1179288668.417582.210470@u30g2000hsc.googlegroups.com> <464AC0E0.3040107@web.de> <1179307919.182504.297930@q75g2000hsh.googlegroups.com> Message-ID: <464AD916.9020706@web.de> sjdevnull at yahoo.com wrote: > Stefan Behnel wrote: >> sjdevnull at yahoo.com wrote: >>> I even sometimes >>> read code snippets on email lists and websites from my handheld, which >>> is sadly still memory-limited enough that I'm really unlikely to >>> install anything approaching a full set of Unicode fonts. >> One of the arguments against this PEP was that it seemed to be impossible to >> find either transliterated identifiers in code or native identifiers in Java >> code using a web search. So it is very unlikely that you will need to upgrade >> your handheld as it is very unlikely for you to stumble into such code. > > Sure, if the feature isn't going to be used then it won't present > problems. Thing is, this feature *is* going to be used. Just not by projects that you are likely to stumble into. Most OpenSource projects will continue to stick to English-only, and posts to English-speaking newsgroups will also stick to English. But Closed-Source programs and posts to non-English newsgroups *can* use this feature if their developers want. And you still wouldn't even notice. Stefan From spamtrap at agharta.de Thu May 3 03:23:51 2007 From: spamtrap at agharta.de (Edi Weitz) Date: Thu, 03 May 2007 09:23:51 +0200 Subject: Microsoft's Dynamic Languages Runtime (DLR) References: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> <0T42enagIhkcNv8%stesch@parsec.no-spoon.de> Message-ID: On Thu, 3 May 2007 09:20:22 +0200, Stefan Scholl wrote: > You are not allowed to publish .NET benchmarks. :-) I'm pretty sure that only applied to their beta releases. -- Lisp is not dead, it just smells funny. Real email: (replace (subseq "spamtrap at agharta.de" 5) "edi") From gagsl-py2 at yahoo.com.ar Fri May 25 06:47:17 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 25 May 2007 07:47:17 -0300 Subject: sockets, gethostname() changing References: <1180062244.266857.300830@m36g2000hse.googlegroups.com> Message-ID: En Fri, 25 May 2007 00:04:04 -0300, 7stud escribi?: > I'm experimenting with a basic socket program(from a book), and both > the client and server programs are on my computer. In both programs, > I call socket.gethostname(), but I discovered that when I am connected > to the internet, both the client and server hang and nothing happens. > I discovered that the hostname of my computer automatically changes to > that of my isp when I'm connected to the internet, and presumably the > server program on my computer cannot listen on my isp's address(host, > port). Is there a way to make the hostname of my computer static, so > that it doesn't change to my isp's hostname when I connect to the > internet. I'm using mac os 10.4.7. Why does my computer's hostname > dynamically change in the first place? Don't use any hostname at all; use '' instead. That should bind to any interfase on your computer. -- Gabriel Genellina From nogradi at gmail.com Wed May 30 12:34:11 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Wed, 30 May 2007 18:34:11 +0200 Subject: google maps api for py? In-Reply-To: <2387F0EED10A4545A840B231BBAAC722F11AB7@slcimail1.slcgov.com> References: <2387F0EED10A4545A840B231BBAAC722F11AB7@slcimail1.slcgov.com> Message-ID: <5f56302b0705300934q18c8f997h8c3f051eb5d53d74@mail.gmail.com> > I see that the weapon of choice for google maps is javascript... Is > there anything for python? I wrote the following for finding the latitude/longitude of a location. You need to set the variable 'key' to the actual key you got from google. (Indentation might get mixed up on the way.....) HTH, Daniel ############################### # gmaps.py ############################### import urllib from time import sleep key = "here_goes_your_key" def location2latlong( query, key=key ): """Get the ( latitute, longitude ) coordinates corresponding to the query. If something goes wrong return None.""" output = 'csv' params = { } params[ 'key' ] = key params[ 'output' ] = output params[ 'q' ] = query params = urllib.urlencode( params ) try: f = urllib.urlopen( "http://maps.google.com/maps/geo?%s" % params ) except IOError: # maybe some local problem at google? let's try again sleep( 3 ) try: f = urllib.urlopen( "http://maps.google.com/maps/geo?%s" % params ) except IOError: # okay we give up return None response = f.read( ).split(',') f.close( ) try: status = response[0] accuracy = response[1] latitude = response[2] longitude = response[3] except: return None if status != '200': return None else: return latitude, longitude if __name__ == '__main__': import sys try: q = sys.argv[1] except: print 'Usage: python gmaps.py query' sys.exit( 1 ) r = location2latlong( q ) if r is not None: print r else: print 'Something went wrong.' ############################### ############################### From torriem at chem.byu.edu Mon May 21 11:16:57 2007 From: torriem at chem.byu.edu (Michael L Torrie) Date: Mon, 21 May 2007 09:16:57 -0600 Subject: List Moderator In-Reply-To: <1353asbpai1gqd6@corp.supernews.com> References: <880dece00705172218n71123b55q531ec0c5e500f208@mail.gmail.com> <880dece00705190012g4f3d3ef6v4e6c87a156708bb0@mail.gmail.com> <880dece00705191305m203bc8ep804d647c17438581@mail.gmail.com> <464F5E42.6090607@holdenweb.com> <880dece00705201305q6944986fj8f77c4b5cac09456@mail.gmail.com> <13524svhtst5dd1@corp.supernews.com> <1353asbpai1gqd6@corp.supernews.com> Message-ID: <1179760617.28714.8.camel@contra.chem.byu.edu> On Mon, 2007-05-21 at 14:24 +0000, Grant Edwards wrote: > > To quantify things for curiosity's sake, I just scanned through > the last 1000 postings in c.l.p. There was exactly 1 spam > message and two replies to spam messages complaining about > them. I'm seeing 2 messages a day, lately, to c.l.p that are blatant and a bit rude spam (and some would argue this thread is spam), out of about 200-400 messages per day. I just barely deleted one a moment ago, in fact. While that's not bad at all, my other mailing lists (gtk-list, openldap, etc) all get 0 spam per day. Also they are getting annoying mainly because they seem so preventable. They all have the same "from" address. If this was a normal mailinst list, the moderators could unsubscribe that address and prevent it from subscribing again. I'm not at all sure how moderation is working here. I am subscribed to c.l.p exclusively through the mailman mailing list, so I don't ever use the nntp part. From lucaberto at libero.it Thu May 31 04:04:05 2007 From: lucaberto at libero.it (luca72) Date: 31 May 2007 01:04:05 -0700 Subject: qt doevent Message-ID: <1180598645.635930.183950@o5g2000hsb.googlegroups.com> Hello at all I try to use qt , but i have problem, i don't find the command like wx.Yield() in wx or doevent in vb. Can you tell me the same command in qt Regards Luca From steve at holdenweb.com Sat May 19 16:29:54 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 19 May 2007 16:29:54 -0400 Subject: List Moderator In-Reply-To: <880dece00705191305m203bc8ep804d647c17438581@mail.gmail.com> References: <880dece00705172218n71123b55q531ec0c5e500f208@mail.gmail.com> <880dece00705190012g4f3d3ef6v4e6c87a156708bb0@mail.gmail.com> <880dece00705191305m203bc8ep804d647c17438581@mail.gmail.com> Message-ID: <464F5E42.6090607@holdenweb.com> Dotan Cohen wrote: > On 19/05/07, Steve Holden wrote: >> I'm sorry, but you have no idea what you are talking about. Most of what >> can be done *is* being done, which is why you see the relatively low >> spam volumes you do. > > I hope that I don't. I receive no less than 700 spams a day to my > regular address (not gmail, which I use for mailing lists), but then > again I've only twice gone over 2000 spams in a single day. I can only > imagine the efforts used to keep the list clean. Maybe spamassasin, a > few hundred procmail filters, and a last swipe with bogofilter for > good measure? > > I don't mean to be pushy, but every day I add another procmail filter > based upon what's been getting through (and they still do, I try to > err on 'false negative'). Four filters "britney", "spears", "boobs" > and "tits" would show the spammers that the moderators are serious > about keeping this list clean. > > I'll go back to reading and not writing now, at least until I get to > the point where either I feel that I can contribute, or until I get > myself real stuck. > All I am saying is that it's difficult to catch *everything* when so much of the content comes in via Usenet. These posts never touch any python.org infrastructure before being incorporated into the newsgroup content on servers all over the world. Whose procmail filters will protect you from that? You are right about some of the technologies being used, and Spambayes also enters the picture. I'm not sure we are using bogofilter. Looking at the headers in one of the messages you were writing about it appears they are being posted from Google groups, so maybe you could complain to them. Good luck with that ;-). The Python list managers know what they are doing, and they *do* keep a huge amount of spam off the list. The occasional piece gets through, but this is Usenet. It will, from time to 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 ------------------ Asciimercial --------------------- Get on the web: Blog, lens and tag your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From Usetheaddress at inthesig.com Tue May 1 16:32:11 2007 From: Usetheaddress at inthesig.com (Dom Robinson) Date: Tue, 1 May 2007 21:32:11 +0100 Subject: SEO - Search Engine Optimization - Seo Consulting References: <1177808356.681710.42980@n76g2000hsh.googlegroups.com> Message-ID: In article , bob.NGs at somewhere.com says... > You bottom posters really are a bunch of supercilious, self-righteous > bigots. > > Personally, I find bottom-posting like reading a book backwards ... it > doesn't work for me. > > And regardless of his response, Mr Bruney IS an MVP, he is clearly > knowledgeable in his subject, and his book is well enough thought of to make > me consider buying it. > > > "Sherm Pendley" wrote in message > news:m2slaik3yf.fsf at local.wv-www.com... > > "Juan T. Llibre" writes: > > > >> Top or bottom posting is a user choice. > > > > Yes, one can choose to be polite and follow established usenet > > conventions, or one can choose to be rude and self-centered. > > > > Those who choose rudeness over courtesy can expect to be called down > > for it - which is arguably rude in itself, but on usenet one reaps what > > one sows. Someone who can't deal with that, shouldn't be on usenet. > > > > sherm-- > > > > -- > > Web Hosting by West Virginians, for West Virginians: http://wv-www.net > > Cocoa programming in Perl: http://camelbones.sourceforge.net Must be because you ARE backwards. -- Dom Robinson Gamertag: DVDfever email: dom at dvdfever dot co dot uk /* http://DVDfever.co.uk (editor) /* 1132 DVDs, 347 games, 314 CDs, 110 cinema films, 42 concerts, videos & news /* antibodies, steve hillage, burning crusade, sega psp, norah jones, kylie New music charts - http://dvdfever.co.uk/music.shtml Youtube - http://www.youtube.com/profile?user=DVDfeverDom From duncan.booth at invalid.invalid Tue May 15 05:45:18 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 15 May 2007 09:45:18 GMT Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> <4648294F.2000704@web.de> <46487a6c$0$2400$426a74cc@news.free.fr> Message-ID: Anton Vredegoor wrote: > Whatever you make of my position I would appreciate if you'd not > directly conclude that I'm just being arrogant or haven't thought > about the matter if I am of a different opinion than you. Sorry, I do apologise if that came across as a personal attack on you. It certainly wasn't intended as such. I was writing about the community as a whole: I think it would be arrogant if the Python community was to decide not to support non-ascii identifiers purely because the active community of experienced users doesn't want them used in OSS software. OTOH, it may just be my own arrogance thinking such a thing. > >> Yes, any sensible widespread project is going to mandate a particular >> language for variable names and comments, but I see no reason at all >> why they all have to use English. > > Well I clearly do see a reason why it would be in their very best > interest to immediately start to use English and to interact with the > main Python community. I think the 'main Python community' is probably a very small subset of all Python developers. To be honest I expect that only a tiny percentage of OLPC users will ever do any programming, and a miniscule fraction of those will go beyond simple scripts (but I'd love to be proved wrong and in a few years be facing 50 million new Python programmers). Most of the programming which is likely to happen on these devices is not going to require input from the wider community. > >> [*] BTW, I see OLPC Nepal is looking for volunteer Python programmers >> this Summer: if anyone fancies spending 6+ weeks in Nepal this Summer >> for no pay, see >> http://www.mail-archive.com/devel at laptop.org/msg04109.html > > Thanks. I'll think about it. The main problem I see for my > participation is that I have absolutely *no* personal funds to > contribute to this project, not even to pay for my trip to that > country or to pay my rent while I'm abroad. > I think accomodation was included for the first 4 volunteers, the tricky bit would be the air fare, I've no idea how much but I suspect flights to Nepal aren't cheap. From nanodust at gmail.com Thu May 24 16:33:22 2007 From: nanodust at gmail.com (nanodust at gmail.com) Date: 24 May 2007 13:33:22 -0700 Subject: trouble converting c++ bitshift to python equivalent In-Reply-To: <135btb97ttsf975@corp.supernews.com> References: <1180037677.633613.30160@u30g2000hsc.googlegroups.com> <135btb97ttsf975@corp.supernews.com> Message-ID: <1180038802.487959.71590@u30g2000hsc.googlegroups.com> > (ord(strBuf[2])<<7) + ord(strBuf[1]) wow, thank you - works perfectly ! and much more elegant than what i was up to. thanks again... From michael at jedimindworks.com Sun May 27 02:15:44 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Sun, 27 May 2007 01:15:44 -0500 Subject: How to get a dot's or pixel's RGB with PIL In-Reply-To: <1180240167.582601.247050@q19g2000prn.googlegroups.com> References: <1180240167.582601.247050@q19g2000prn.googlegroups.com> Message-ID: On May 26, 2007, at 11:29 PM, shuimuliang at gmail.com wrote: > e.g. rtfm = (100,100) im.getpixel(rtfm) From jbmccrann at gmail.com Wed May 2 23:07:53 2007 From: jbmccrann at gmail.com (Midex) Date: 2 May 2007 20:07:53 -0700 Subject: Video: Professor of Physics Phd at Cal Tech says: 911 Inside Job In-Reply-To: <1177793419.474675.156860@y80g2000hsf.googlegroups.com> References: <1177467203.719625.93920@u32g2000prd.googlegroups.com> <1177780530.539758.275660@c35g2000hsg.googlegroups.com> <1177792809.503415.182480@o5g2000hsb.googlegroups.com> <1177793419.474675.156860@y80g2000hsf.googlegroups.com> Message-ID: <1178161673.787120.277250@n59g2000hsh.googlegroups.com> On 28 abr, 17:50, Major Quaternion Dirt Quantum wrote: > here's a question that came-up recently, > in battling with the controlled-demo advocates > at teh Promenade: > > how is it that the metal was still molten, > after weeks? > > it seems taht an additional hypothesis is required, > to explain that. because I doubt that > there was sufficient nukular material > "left-over" from a hypothetical suitcase-device. > > there are similar question, > from what I recall of Jones' report > (I just stopped at the first thing > that seemed funny, today .-) > > publications:http://www.physics.uiowa.edu/~cgrabbe/writing/ > research.html > > > > > demanding of INTELLECTUAL HONESTY. > > thus: > this was basically assuming that > floor 50 of a 100-floor building started the collapse?... > interesting analysis; I hope to look at it, again, later. > > have you seen the old analysis by the MIT Head Welder, > that I only saw a couple of weeks ago? > > > At time t=0, the top 50 floors begin to fall, independently of each > > other. The first actual impact is when floor 50 hits floor 49. On > > impact, those 2 floors fall together with an initial velocity that is > > less than that of higher floors due to conservation of momentum. Thus > > the next impact will not be floors 50,49 with floor 48 but rather it > > will be floor 51 hitting the slower moving 50,49 combo. The 3 floors > > 51,50,49 then become a unit. The initial velocity of the new 51,50,49 > > combo will be greater than the velocity of the 50-49 combo just before > > impact, but still less than that of the floors above (which are still > > in free fall). > > http://www.rwgrayprojects.com/synergetics/plates/figs/plate01.html > > thus: > "Global Warning," > an *anonymous* article in an old issue of *National Review*, > the so-called conservative mag of the grotesque Establishment > creature, > William Buckley, was a sort of benignly-spun expose > of the Mont Pelerin Society, the vehicle of British imperialist "free > trade," > free beer & free dumb, whose many "rightwing" affiliate foundations > are always in the news. the universally-newspaper-lauded-when- > he-died founding president, Mitlon Friedman, > used Sir Henry of Kiss.Ass. to conduct their first experiment > in Chile, with the help of Augusto Pinochet & Dick Nixon. > > (the fact that it was an awful failure, with the privatization > of Chile's social security, was only recently mention, but > only before Uncly Milty died.) > > I realized, much later, since it was anonymous, that > it was probably taken from The Holy Spook Economist, but > I haven't checked that hypothesis. > > yes, "Warning" was meant to evoke "warming," although > nowhere mentioned in the article, as I recall; can you say, > "emmissions trading schemes," Boys and Girl?... > can you say, "hedge funds on out-of-the-way desert islands?..." > Just Desserts Island? > > thus: > why do Dick, Borat, Osama, Harry P., Rumsfeld and Tony B. want us > to underwrite the 3rd British Invasion of Sudan, > so badly? > > anyway, Bertrand Russel published a jeremyad in the Bulletin > of the Atomic Scientists, while the USA was the only thermonukey > power, > that we should bomb them into the Stone Age; > that's your British "pacifist," whether before or after he went nuts > because of Godel's proof. > > thus: > if you can't prove that all Fermat numbers are pairwise coprime, > again! > > Darfur 'Mini-Summit'http://www.larouchepub.com/other/1998/rice_2546.html > > thus: > uh yeah; Borat wants you in Sudan, > why, Baby?... Harry Potter wants you in Iran -- > yeah, Baby; shag'US with a spoon? > > --DARFURIA CONSISTS OF ARABs & nonARABs; NEWS-ITEM: > we are marching to Darfuria, Darfuria, Darfuria! > Harry Potter IIX, ?Ordeal @ Oxford//Sudan ^ Aircraft Carrier!http://larouchepub.com/other/2007/3410caymans_hedges.html > ALgoreTHEmovieFORpresident.COM:http://larouchepub.com/eirtoc/site_packages/2007/al_gore.html I suppose you never seen this footage of WTC7 before have you? Its 100% evidence that WTC7 was controlled demolition: http://www.youtube.com/watch?v=YNN6apj5B2U From nagle at animats.com Wed May 16 18:24:59 2007 From: nagle at animats.com (John Nagle) Date: Wed, 16 May 2007 15:24:59 -0700 Subject: A new project. In-Reply-To: <1179339930.009586.258920@l77g2000hsb.googlegroups.com> References: <1179302989.142733.257910@n59g2000hsh.googlegroups.com> <1179339930.009586.258920@l77g2000hsb.googlegroups.com> Message-ID: Clement wrote: > On May 16, 1:09 pm, colin.barne... at gmail.com wrote: > >>I am interested in organizing and taking part in a project that would >>create a virtual world much like the one described in Neal >>Stephenson's 'Snow Crash'. That's a perfectly reasonable idea. It takes money and people to power it, but it's not impossible. If you have a clue. You'll need a team of 5-10 nearly full time really good core people to make it work, and probably about two years. You need at least one really good 3D programmer, at least one really good networking expert, and at least one really good artist. (I met with the core team of There when they were first starting up, and it was about that large.) Presumably you have a background in game production, or 3D graphics. If not, you need to hire an experienced game producer. Join IGDA, get to GDC, and start recruiting. You don't have to do this from a cold start. You can start from some existing code bases. Look at some of the VRML engines, or the Blender GameKit. In fact, a reasonable approach might be to start converting the Blender GameKit to multiplayer. It uses Python as a scripting language, and already has the 3D machinery, collision detection, and physics engine. What it doesn't have is scaling; it can't do a big world. There are other MMORPG engines. See http://www.devmaster.net/wiki/MMORPG_Creation_Packages for a list. This is far easier to do than it was five years ago. John Nagle From whamil1 at entergy.com Tue May 22 08:19:18 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Tue, 22 May 2007 07:19:18 -0500 Subject: Installing Python in a path that contains a blank Message-ID: <588D53831C701746A2DF46E365C018CE01D2CAA4@LITEXETSP001.etrsouth.corp.entergy.com> > From: John Machin > On 21/05/2007 11:30 PM, Konrad Hinsen wrote: > > I am trying to install Python from sources in my home directory on a Mac > > cluster (running MacOS X 10.4.8). The path to my home directory contains > > a blank, and since the installation procedure insists on getting an > > absolute path for the prefix, I cannot avoid installing to a path whose > > name contains a blank. Python does not seem to be prepared for this, as > > it uses only the part before the blank, resulting in numerous error > > messages. > > > > Does anyone know a workaround? > > > > On Windows, the workaround for pesky paths (i.e. containing blanks or > just inconveniently long) is the subst command: > > command-prompt>subst X: "C:\Documents and Settings" > > Thereafter X:\foo can be used wherever "C:\Documents and Settings\foo" > would otherwise be required. There's also short filename substitution. "C:\Documents and Settings\foo" can be replaced with "C:\docume~1\foo". In general, you take the first six non-space characters and append "~" to it. I've never run into a situation where was anything other than 1, but I'm pretty sure that you increment it if you have multiple files/directorys in the same directory that have the same first six non-space characters. This should work on any Windows long-filename system where you need 8.3 filenames for backwards compatibility. --- -Bill Hamilton From tjreedy at udel.edu Sat May 5 00:12:55 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 5 May 2007 00:12:55 -0400 Subject: Python regular expressions just ain't PCRE References: <1178323901.381993.47170@e65g2000hsc.googlegroups.com> Message-ID: "Wiseman" wrote in message news:1178323901.381993.47170 at e65g2000hsc.googlegroups.com... | I'm kind of disappointed with the re regular expressions module. I believe the current Python re module was written to replace the Python wrapping of pcre in order to support unicode. | In particular, the lack of support for recursion ( (?R) or (?n) ) is a | major drawback to me. I don't remember those being in the pcre Python once had. Perhaps they are new. |Are there any plans to support these features in re? I have not seen any. You would have to ask the author. But I suspect that this would be a non-trivial project outside his needs. tjr From artdent at freeshell.org Thu May 10 02:31:00 2007 From: artdent at freeshell.org (Jacob Lee) Date: Thu, 10 May 2007 06:31:00 +0000 (UTC) Subject: Erlang style processes for Python References: <1178759792.268979.206630@p77g2000hsh.googlegroups.com> Message-ID: On Wed, 09 May 2007 18:16:32 -0700, Kay Schluehr wrote: > Every once in a while Erlang style [1] message passing concurrency [2] > is discussed for Python which does not only imply Stackless tasklets [3] > but also some process isolation semantics that lets the runtime easily > distribute tasklets ( or logical 'processes' ) across physical > processes. Syntactically a tasklet might grow out of a generator by > reusing the yield keyword for sending messages: > > yield_expr : 'yield' ([testlist] | testlist 'to' testlist) > > where the second form is specific for tasklets ( one could also use a > new keyword like "emit" if this becomes confusing - the semantics is > quite different ) and the addition of a new keyword for assigning the > "mailbox" e.g: > > required_stmt: 'required' ':' suite > > So tasklets could be identified on a lexical level ( just like > generators today ) and compiled accordingly. I just wonder about sharing > semantics. Would copy-on-read / copy-on-write and new opcodes be needed? > What would happen when sharing isn't dropped at all but when the runtime > moves a tasklet around into another OS level thread / process it will be > pickled and just separated on need? I think it would be cleaner to > separate it completely but what are the costs? > > What do you think? > > [1] http://en.wikipedia.org/wiki/Erlang_programming_language [2] > http://en.wikipedia.org/wiki/Actor_model [3] http://www.stackless.com/ Funny enough, I'm working on a project right now that is designed for exactly that: PARLEY, http://osl.cs.uiuc.edu/parley . (An announcement should show up in clp-announce as soon as the moderators release it). My essential thesis is that syntactic sugar should not be necessary -- that a nice library would be sufficient. I do admit that Erlang's pattern matching would be nice, although you can get pretty far by using uniform message formats that can easily be dispatched on -- the tuple (tag, sender, args, kwargs) in the case of PARLEY, which maps nicely to instance methods of a dispatcher class. The questions of sharing among multiple physical processes is interesting. Implicit distribution of actors may not even be necessary if it is easy enough for two hosts to coordinate with each other. In terms of the general question of assigning actors to tasklets, threads, and processes, there are added complications in terms of the physical limitations of Python and Stackless Python: - because of the GIL, actors in the same process do not gain the advantag of true parallel computation - all tasklet I/O has to be non-blocking - tasklets are cooperative, while threads are preemptive - communication across processes is slower, has to be serialized, etc. - using both threads and tasklets in a single process is tricky PARLEY currently only works within a single process, though one can choose to use either tasklets or threads. My next goal is to figure out I/O, at which point I get to tackle the fun question of distribution. So far, I've not run into any cases where I've wanted to change the interpreter, though I'd be interested in hearing ideas in this direction (especially with PyPy as such a tantalizing platform!). -- Jacob Lee From khemkaamit at gmail.com Thu May 24 05:51:24 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Thu, 24 May 2007 15:21:24 +0530 Subject: how to use imaageop.scale In-Reply-To: <1179971908.653346.95200@d30g2000prg.googlegroups.com> References: <1179903754.084688.312200@w5g2000hsg.googlegroups.com> <1179971908.653346.95200@d30g2000prg.googlegroups.com> Message-ID: <1360b7230705240251k107bedeavf01fdcd5d9d803e1@mail.gmail.com> On 23 May 2007 18:58:28 -0700, Bruce wrote: > On May 23, 5:31 pm, "Amit Khemka" wrote: > > On 23 May 2007 00:02:34 -0700, Bruce wrote: > > > > > Hi, I want to compress a jpg file. e.g. a jpg file which has RGB band > > > (24bit per pixel), 100 * 100 size to 50 * 50 size. I > > > tried to use scale function in imageop module but failed. Any > > > suggestions about this? Thanks! > > > > Were there any exceptions/error-messasges ? > > Do you jpeg libraries installed for hadling jpeg format ? > Amit & Marc, thank you very much. Now I used PIL instead and it works > fine. > But I still don't know how to complete this simple task with imageop > module. I think imageop moudle can handle raw images only, so if you want to use imageop you will need to convert jpeg images to raw format. Cheers, -- ---- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. From rene at korteklippe.de Wed May 16 06:30:10 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Wed, 16 May 2007 12:30:10 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464ac493$0$6394$9b4e6d93@newsspool2.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649dd55$0$23144$9b4e6d93@newsspool1.arcor-online.net> <464a25e9$0$10188$9b4e6d93@newsspool4.arcor-online.net> <1179291296.561359.286230@h2g2000hsg.googlegroups.com> <464ab64f$0$10185$9b4e6d93@newsspool4.arcor-online.net> <464AB9F2.60906@web.de> <464ac189$0$20297$9b4e6d93@newsspool3.arcor-online.net> <464ac493$0$6394$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <464add30$0$6401$9b4e6d93@newsspool2.arcor-online.net> Stefan Behnel schrieb: >> Now, very special environments (what I called "rare and isolated" >> earlier) like special learning environments for children are a different >> matter. It should be ok if you have to use a specially patched Python >> branch there, or have to use an interpreter option that enables the >> suggested behaviour. For general programming, it IMO is a bad idea. > > Ok, let me put it differently. > > You *do not* design Python's keywords. You *do not* design the stdlib. You *do > not* design the concepts behind all that. You *use* them as they are. So you > can simply take the identifiers they define and use them the way the docs say. > You do not have to understand these names, they don't have to be words, they > don't have to mean anything to you. They are just tools. Even if you do not > understand English, they will not get in your way. You just learn them. I claim that this is *completely unrealistic*. When learning Python, you *do* learn the actual meanings of English terms like "open", "exception", "if" and so on if you did not know them before. It would be extremely foolish not to do so. You do care about these names and you do want to know their meaning if you want to write anything more in your life than a 10-line throw-away script. > But you *do* design your own software. You *do* design its concepts. You *do* > design its APIs. You *do* choose its identifiers. And you want them to be > clear and telling. You want them to match your (or your clients) view of the > application. You do not care about the naming of the tools you use inside. But > you do care about clarity and readability in *your own software*. I do care about the naming of my tools. I care alot. Part of why I like Python is that it resisted the temptation to clutter the syntax up with strange symbols like Perl. And I do dislike the decorator syntax, for example. Also, your distinction between "inside" and "your own" is nonsense, because the "inside" does heavily leak into the "own". It is impossible to write "your own software" with clarity and readability by your definition (i.e. in your native language). Any real Python program is a mix of identifiers you designed yourself and identifiers you did not design yourself. And I think the ones chosen by yourself are even often in the minority. It is not feasible in practice to just learn what the "other" identifiers do without understanding their names. Not for general programming. The standard library is already too big for that, and most real programs use not only the standard library, but also third party libraries that have English APIs. -- Ren? From ptmcg at austin.rr.com Thu May 17 19:46:17 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 17 May 2007 16:46:17 -0700 Subject: Regexes: How to handle escaped characters In-Reply-To: <1179443573.565202.217410@p77g2000hsh.googlegroups.com> References: <87tzubqniq.fsf@wilson.homeunix.com> <87irarqkz7.fsf@wilson.homeunix.com> <1179435962.962404.191600@y80g2000hsf.googlegroups.com> <1179440203.534490.66510@u30g2000hsc.googlegroups.com> <1179443573.565202.217410@p77g2000hsh.googlegroups.com> Message-ID: <1179445577.034717.216870@l77g2000hsb.googlegroups.com> On May 17, 6:12 pm, John Machin wrote: > > Note: "must not be *part of* any match" [my emphasis] > Ooops, my bad. See this version: from pyparsing import Regex,ParseException,col,lineno,getTokensEndLoc # fake (and inefficient) version of any if not yet upgraded to Py2.5 any = lambda lst : sum(list(lst)) > 0 def guardedSearch(pattern, text, forbidden_offsets): def offsetValidator(strng,locn,tokens): start,end = locn,getTokensEndLoc()-1 if any( start <= i <= end for i in forbidden_offsets ): raise ParseException, "can't match at offset %d" % locn regex = Regex(pattern).setParseAction(offsetValidator) return [ (tokStart,toks[0]) for toks,tokStart,tokEnd in regex.scanString(text) ] print guardedSearch(ur"o\S", u"Hollo how are you", [8,]) def guardedSearchByColumn(pattern, text, forbidden_columns): def offsetValidator(strng,locn,tokens): start,end = col(locn,strng), col(getTokensEndLoc(),strng)-1 if any( start <= i <= end for i in forbidden_columns ): raise ParseException, "can't match at col %d" % start regex = Regex(pattern).setParseAction(offsetValidator) return [ (lineno(tokStart,text),col(tokStart,text),toks[0]) for toks,tokStart,tokEnd in regex.scanString(text) ] text = """\ alksjdflasjf;sa a;sljflsjlaj ;asjflasfja;sf aslfj;asfj;dsf aslf;lajdf;ajsf aslfj;afsj;sd """ print guardedSearchByColumn("[fa];", text, [4,12,13,]) Prints: [(1, 'ol'), (15, 'ou')] [(2, 1, 'a;'), (5, 10, 'f;')] > > While we're waiting for clarification from the OP, there's a chicken- > and-egg thought that's been nagging me: if the OP knows so much about > the searched string that he can specify offsets which search patterns > should not span, why does he still need to search it? > I suspect that this is column/tabular data (a log file perhaps?), and some columns are not interesting, but produce many false hits for the search pattern. -- Paul From ramashish.lists at gmail.com Tue May 29 12:58:49 2007 From: ramashish.lists at gmail.com (Ramashish Baranwal) Date: 29 May 2007 09:58:49 -0700 Subject: SMTPAuthenticationError Message-ID: <1180457929.374281.168960@g37g2000prf.googlegroups.com> Hi, I am trying to send a mail using smtplib. My server requires me to authenticate, for this I'm using SMTP.login function. However it fails- >>> server = smtplib.SMTP(host='mail.domain', port=25) >>> server.login('username', 'password') Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/smtplib.py", line 587, in login raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (535, 'authorization failed (#5.7.0)') I am sure that I am giving the correct credentials. The same works in Thunderbird. Am I missing something here or am I supposed to use some other library for this? Thanks in advance, Ram From paul.ainsworth at baesystems.com Fri May 11 05:59:09 2007 From: paul.ainsworth at baesystems.com (Paul D Ainsworth) Date: Fri, 11 May 2007 10:59:09 +0100 Subject: 4 byte integer References: <46443344$1_1@glkas0286.greenlnk.net> Message-ID: <46443b0c$1_1@glkas0286.greenlnk.net> > > Have a look at http://aspn.activestate.com/ASPN/Cookbook/Python/ > Recipe/113799 Brilliant - thank you :) From charl.loubser at gmail.com Mon May 7 03:28:14 2007 From: charl.loubser at gmail.com (Merrigan) Date: 7 May 2007 00:28:14 -0700 Subject: long lists Message-ID: <1178522894.357829.28250@u30g2000hsc.googlegroups.com> Hi All, Firstly - thank you Sean for the help and the guideline to get the size comparison, I will definitely look into this. At the moment I actually have 2 bigger issues that needs sorting... 1. I have the script popping all the files that need to be checked into a list, and have it parsing the list for everything...Now the problem is this : The sever needs to check (at the moment) 375 files and eliminate those that don't need reuploading. This number will obviously get bigger and bigger as more files gets uploaded. Now, the problem that I'm having is that the script is taking forever to parse the list and give the final result. How can I speed this up? 2. This issue is actually because of the first one. While the script is parsing the lists and files, the connection to the ftp server times out, and I honestly must say that is is quite annoying. I know I can set the function to reconnect if it cannot find a connection, but wouldn't it just be easier just to keep the connection alive? Any idea how I can keep the connection alive? Thanks for all the help folks, I really appreciate it! From bscrivener42 at gmail.com Sat May 12 10:59:32 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: 12 May 2007 07:59:32 -0700 Subject: path stuff In-Reply-To: <1178734266.858048.311740@y5g2000hsa.googlegroups.com> References: <1178734266.858048.311740@y5g2000hsa.googlegroups.com> Message-ID: <1178981972.176092.53520@u30g2000hsc.googlegroups.com> On May 9, 1:11 pm, fscked wrote: > I am walking some directories looking for a certain filename pattern. > This part works fine, but what if I want to exclude results from a > certain directory being printed? You might find this thread helpful http://tinyurl.com/2guk3l Note how the backup dirs are excluded. Highly recommend Python Cookbook, too. rd From saif.shakeel at gmail.com Thu May 10 00:55:25 2007 From: saif.shakeel at gmail.com (saif.shakeel at gmail.com) Date: 9 May 2007 21:55:25 -0700 Subject: replacing string in xml file In-Reply-To: <1178710760.558710.262680@w5g2000hsg.googlegroups.com> References: <1178623414.092046.91120@y5g2000hsa.googlegroups.com> <46405F73.3080501@web.de> <1178624770.794888.198450@e65g2000hsc.googlegroups.com> <1178710760.558710.262680@w5g2000hsg.googlegroups.com> Message-ID: <1178772925.620297.118000@h2g2000hsg.googlegroups.com> On May 9, 4:39 pm, saif.shak... at gmail.com wrote: > On May 8, 4:46 pm, saif.shak... at gmail.com wrote: > > > > > > > On May 8, 4:30 pm, Stefan Behnel wrote: > > > > saif.shak... at gmail.com schrieb: > > > > > Hi, > > > > I need to replace a string in xml file with something else.Ex > > > > > - > > > > rate > > > > rate > > > > > > > > > > > > > > > > - > > > > > Here i have opened an xml > > > > file(small part is pasted here).I want to replace the word 'localId' > > > > with 'dataPackageID' wherever it comes in xml file.I tried this but > > > > didnt work: > > > > > import sys > > > > > file_input = raw_input("Enter The ODX File Path:") > > > > input_xml = open(file_input,'r') > > > > This should say > > > > input_xml = open(file_input,'r').read() > > > > > input_xml.replace('localId','dataPackageId') > > > > This gives error ---> AttributeError: 'file' > > > > object has no attribute 'replace' > > > > Can someone help me . > > > > Thanks > > > > Stefan- Hide quoted text - > > > > - Show quoted text - > > > There is no error now,but the string is not being replaced,It remains > > the same,should we save the opened file or something- Hide quoted text - > > > - Show quoted text - > > HI, > Thanks for the reply.that seems to work,but i was doing this > so as to attach it to a bigger code where it will be utilised before a > parsing. > > #Input file and Output file path from user > > file_input = raw_input("Enter The ODX File Path:") > > (shortname,ext)=os.path.splitext(file_input) > f_open_out=shortname+".ini" > log=shortname+".xls" > test_file=shortname+"testxml.xml" > > saveout = sys.stdout > > input_xml = open(file_input,'r') > xmlcont=input_xml.read() > xmlcont=xmlcont.replace('localId','dataPackageId') > output_file = open(test_file,"w") > output_file.write(xmlcont) > output_file.close() > > f_open=open(f_open_out, 'w') > logfile=open(log,"w") > > sys.stdout = f_open > > #Parse the input file,and check for correct ODX version > > xmldoc = minidom.parse(input_xml) > > I am opening 2 more files in addition to the file > where the new xml goes.One file is written using the sys.stdout > command as most of the output has to go there printing takes place in > many places (so cant use f_open.write) each time. > When i attach the part of replacing the string > 'localid' in xml file with something else as given above with > xmlcont=xmlcont.replace('localId','dataPackageId') > the code does not run and hangs.Can more than 3 files be opened at a > time .I dotn know what the problem is here. > Thanks- Hide quoted text - > > - Show quoted text - Hi, Cna someone help me in this ,or throw some insight . Thanks From kensmith at rahul.net Sat May 5 02:20:41 2007 From: kensmith at rahul.net (MooseFET) Date: 4 May 2007 23:20:41 -0700 Subject: Firefighters at the site of WTC7 "Move away the building is going to blow up, get back the building is going to blow up." In-Reply-To: References: <1178161820.731367.264500@y80g2000hsf.googlegroups.com> <1hlj33p6aq838o2urk1dv6h75b5is4i2vd@4ax.com> <3TD_h.219$mR2.195@newssvr22.news.prodigy.net> <1178329932.455122.161530@u30g2000hsc.googlegroups.com> Message-ID: <1178346041.557106.129670@y80g2000hsf.googlegroups.com> On May 4, 8:19 pm, James Stroud wrote: > MooseFET wrote: > > On May 4, 12:32 pm, James Stroud wrote: > > [....] > > >>The Marxist contribution to western thought is that it put everything in > >>terms of labor and thus allowed us to quantify the human component of > >>economies. > > > No the great insight by Marx was in the selling of ducks. "Anybody > > want to buy a duct" has done more to advance economic thinking than > > the works of most economists. > > > Economists have a vested interest in preventing people from > > understanding economics. They are well paid and know that they > > wouldn't be for long if people really understood what was going on. > > You must be an economist because you provide absolutely no > interpretation of what the hell you were saying in ghe first paragraph > (as if you actually know what you were trying to say). Duct or duck, > first of all. Second of all--make a point. Groucho Marx. From carl at personnelware.com Thu May 24 08:47:41 2007 From: carl at personnelware.com (Carl K) Date: Thu, 24 May 2007 07:47:41 -0500 Subject: installing cx_Oracle. Message-ID: I am trying to use this: http://python.net/crew/atuining/cx_Oracle/html/cx_Oracle.html it is a real module, right? sudo easy_install cx_Oracle did not easy_install cx_Oracle. http://www.python.org/pypi/cx_Oracle/4.3.1 doesn't give me any clue. I got the source from http://prdownloads.sourceforge.net/cx-oracle/cx_Oracle-4.3.1.tar.gz?download carl at dell17:~/a/cx_Oracle-4.3.1$ python setup.py build Traceback (most recent call last): File "setup.py", line 36, in ? oracleHome = os.environ["ORACLE_HOME"] File "/usr/lib/python2.4/UserDict.py", line 17, in __getitem__ def __getitem__(self, key): return self.data[key] KeyError: 'ORACLE_HOME' Now I don't really know whos problem this is. Carl K From showell30 at yahoo.com Sun May 27 12:48:43 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 27 May 2007 09:48:43 -0700 (PDT) Subject: ten small Python programs In-Reply-To: <4659A7B0.2020605@freakmail.de> Message-ID: <498850.58614.qm@web33505.mail.mud.yahoo.com> --- Wildemar Wildenburger wrote: > Steve Howell wrote: > > # def defines a method in Python > > def say_hello(name): > > print 'hello', name > > say_hello('Jack') > > say_hello('Jill') > > > Doesn't def define methods *xor* functions, > depending on the context? > And in this example, say_hello (*yuck*, underscores > ...) is certainly a > function. Or is it that functions are considered > "module-methods"? > Goodness, I didn't expect such a simple example to be so controversial. But please see the new version here: http://wiki.python.org/moin/SimplePrograms I changed the method name to "greet" and removed the comment, as hopefully the intent of the program will be pretty obvious to anyone that reads it. ____________________________________________________________________________________Luggage? GPS? Comic books? Check out fitting gifts for grads at Yahoo! Search http://search.yahoo.com/search?fr=oni_on_mail&p=graduation+gifts&cs=bz From gh at gregor-horvath.com Wed May 16 22:49:35 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Thu, 17 May 2007 04:49:35 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179349116.088747.167990@n59g2000hsh.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649dd55$0$23144$9b4e6d93@newsspool1.arcor-online.net> <464a25e9$0$10188$9b4e6d93@newsspool4.arcor-online.net> <1179291296.561359.286230@h2g2000hsg.googlegroups.com> <464ab64f$0$10185$9b4e6d93@newsspool4.arcor-online.net> <1179349116.088747.167990@n59g2000hsh.googlegroups.com> Message-ID: rurpy at yahoo.com schrieb: >> 2) Create a way to internationalize the standard library (and possibly >> the language keywords, too). Ideally, create a general standardized way >> to internationalize code, possibly similiar to how people >> internationalize strings today. > > Why? Or more acurately why before adopting the PEP? > The library is very usable by non-english speakers as long as > there is documentation in their native language. It would be Microsoft once translated their VBA to foreign languages. I didn't use it because I was used to "English" code. If I program in mixed cultural contexts I have to use to smallest dominator. Mixing the symbols of the programming language is confusing. Long time ago at the age of 12 I learned programming using English Computer books. Then there were no German books at all. It was not easy. It would have been completely impossible if our schools system would not have been wise enough to teach as English early. I think millions of people are handicapped because of this. Any step to improve this, is a good step for all of us. In no doubt there are a lot of talents wasted because of this wall. Gregor From thorsten at thorstenkampe.de Thu May 3 17:03:26 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Thu, 3 May 2007 22:03:26 +0100 Subject: My Python annoyances References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> <1178202431.147195.249790@u30g2000hsc.googlegroups.com> Message-ID: * Paul Boddie (3 May 2007 07:27:11 -0700) > On 3 Mai, 15:49, Ben Collver wrote: > > I installed Cygwin on a Windows machine. I try to quit from an > > interactive Python session. It tells me that on my platform, I must > > press Control-Z to exit. I press Control-Z and it makes Python a > > background process. > > Yes, Ctrl-Z exits Python in the standard Windows edition. Since Cygwin > provides a POSIX-like environment, Ctrl-D should be used instead. If > the documentation is wrong, a bug report or patch should be filed > against the software. He was using /Windows/ Python in Cygwin *chuckle*... Windows Python says Ctrl-Z because it doesn't know that it's been run from bash where Ctrl-Z is for job control. And the lesson we learn from that: if you're using Windows Python use a Windows shell. If you're using a Cygwin shell use Cygwin Python - unless you know what you're doing (which he wasn't). Thorsten From steveo at syslang.net Tue May 1 23:58:17 2007 From: steveo at syslang.net (Steven W. Orr) Date: Tue, 1 May 2007 23:58:17 -0400 (EDT) Subject: What do people use for code analysis. Message-ID: Lots of code, calls to, calls by, inheritance, multiple tasks, etc. What do people use to figure out what's happening? TIA -- 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 S.Mientki-nospam at mailbox.kun.nl Mon May 28 14:48:53 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Mon, 28 May 2007 20:48:53 +0200 Subject: ten small Python programs In-Reply-To: References: Message-ID: > >> The wxPython demo program is written as an >> interactive tutorial, >> with a few hundred examples, nicely ordered in >> groups. >> The user can view the demo, the code and the help >> text. >> The user can also change the code and see the >> results right away. >> > > Do you have a link? wxPython including demos can be downloaded from http://www.wxpython.org but there's no separate page of the demo, so I made a few screenshots: http://oase.uci.kun.nl/~mientki/data_www/pic/jalcc/python/wxpython_overview.html > >> It would even be nicer, if everybody could drop >> her/his examples >> in a standard way, so they would be automatically >> incorporated in >> something like the wxPython interactive demo. >> > > Can you elaborate? Well if you see the above demo, I've the following in mind: - create a new-demo in a special directory - add some special keywords in the new-demo, in which treenodes it should popup - on restart of the demo, the new-demo is added to the tree cheers, Stef Mientki From gatti at dsdata.it Wed May 16 04:08:36 2007 From: gatti at dsdata.it (gatti at dsdata.it) Date: 16 May 2007 01:08:36 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <4648DF39.70901@v.loewis.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179153757.844925.14230@p77g2000hsh.googlegroups.com> <4648DF39.70901@v.loewis.de> Message-ID: <1179302916.340760.177420@h2g2000hsg.googlegroups.com> Martin v. Lowis wrote: > Lorenzo Gatti wrote: >> Not providing an explicit listing of allowed characters is inexcusable >> sloppiness. > That is a deliberate part of the specification. It is intentional that > it does *not* specify a precise list, but instead defers that list > to the version of the Unicode standard used (in the unicodedata > module). Ok, maybe you considered listing characters but you earnestly decided to follow an authority; but this reliance on the Unicode standard is not a merit: it defers to an external entity (UAX 31 and the Unicode database) a foundation of Python syntax. The obvious purpose of Unicode Annex 31 is defining a framework for parsing the identifiers of arbitrary programming languages, it's only, in its own words, "specifications for recommended defaults for the use of Unicode in the definitions of identifiers and in pattern-based syntax". It suggests an orderly way to add tens of thousands of exotic characters to programming language grammars, but it doesn't prove it would be wise to do so. You seem to like Unicode Annex 31, but keep in mind that: - it has very limited resources (only the Unicode standard, i.e. lists and properties of characters, and not sensible programming language design, software design, etc.) - it is culturally biased in favour of supporting as much of the Unicode character set as possible, disregarding the practical consequences and assuming without discussion that programming language designers want to do so - it is also culturally biased towards the typical Unicode patterns of providing well explained general algorithms, ensuring forward compatibility, and relying on existing Unicode standards (in this case, character types) rather than introducing new data (but the character list of Table 3 is unavoidable); the net result is caring even less for actual usage. >> The XML standard is an example of how listings of large parts of the >> Unicode character set can be provided clearly, exactly and (almost) >> concisely. > And, indeed, this is now recognized as one of the bigger mistakes > of the XML recommendation: they provide an explicit list, and fail > to consider characters that are unassigned. In XML 1.1, they try > to address this issue, by now allowing unassigned characters in > XML names even though it's not certain yet what those characters > mean (until they are assigned). XML 1.1 is, for practical purposes, not used except by mistake. I challenge you to show me XML languages or documents of some importance that need XML 1.1 because they use non-ASCII names. XML 1.1 is supported by many tools and standards because of buzzword compliance, enthusiastic obedience to the W3C and low cost of implementation, but this doesn't mean that its features are an improvement over XML 1.0. >>> ``ID_Continue`` is defined as all characters in ``ID_Start``, plus >>> nonspacing marks (Mn), spacing combining marks (Mc), decimal number >>> (Nd), and connector punctuations (Pc). >> >> Am I the first to notice how unsuitable these characters are? > Probably. Nobody in the Unicode consortium noticed, but what > do they know about suitability of Unicode characters... Don't be silly. These characters are suitable for writing text, not for use in identifiers; the fact that UAX 31 allows them merely proves how disconnected from actual programming language needs that document is. In typical word processing, what characters are used is the editor's problem and the only thing that matters is the correctness of the printed result; program code is much more demanding, as it needs to do more (exact comparisons, easy reading...) with less (straightforward keyboard inputs and monospaced fonts instead of complex input systems and WYSIWYG graphical text). The only way to work with program text successfully is limiting its complexity. Hard to input characters, hard to see characters, ambiguities and uncertainty in the sequence of characters, sets of hard to distinguish glyphs and similar problems are unacceptable. It seems I'm not the first to notice a lot of Unicode characters that are unsuitable for identifiers. Appendix I of the XML 1.1 standard recommends to avoid variation selectors, interlinear annotations (I missed them...), various decomposable characters, and "names which are nonsensical, unpronounceable, hard to read, or easily confusable with other names". The whole appendix I is a clear admission of self-defeat, probably the result of committee compromises. Do you think you could do better? Regards, Lorenzo Gatti From martin at v.loewis.de Thu May 17 09:17:51 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 17 May 2007 15:17:51 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179247724.234869.47310@l77g2000hsb.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649BC4C.10200@web.de> <1179238847.407605.4620@w5g2000hsg.googlegroups.com> <4649C63C.1030508@web.de> <1179242328.800088.246620@h2g2000hsg.googlegroups.com> <4649D4A5.5060102@web.de> <1179247724.234869.47310@l77g2000hsb.googlegroups.com> Message-ID: <464c5600$0$26592$9b622d9e@news.freenet.de> > However, what I want to see is how people deal with such issues when > sharing their code: what are their experiences and what measures do > they mandate to make it all work properly? You can see some > discussions about various IDEs mandating UTF-8 as the default > encoding, along with UTF-8 being the required encoding for various > kinds of special Java configuration files. I believe the problem is solved when everybody uses Eclipse. You can set a default encoding for all Java source files in a project, and you check the project file into your source repository. Eclipse both provides the editor and drives the compiler, and does so in a consistent way. > Yes, it should reduce confusion at a technical level. But what about > the tools, the editors, and so on? If every computing environment had > decent UTF-8 support, wouldn't it be easier to say that everything has > to be in UTF-8? For both Python and Java, it's too much historical baggage already. When source encodings were introduced to Python, allowing UTF-8 only was already proposed. People rejected it at the time, because a) they had source files where weren't encoded in UTF-8, and were afraid of breaking them, and b) their editors would not support UTF-8. So even with Python 3, UTF-8 is *just* the default default encoding. I would hope that all Python IDEs, over time, learn about this default, until then, users may have to manually configure their IDEs and editors. With a default of UTF-8, it's still simpler than with PEP 263: you can say that .py files are UTF-8, and your editor will guess incorrectly only if there is an encoding declaration other than UTF-8. Regards, Martin From sbroscious at gmail.com Tue May 22 17:44:24 2007 From: sbroscious at gmail.com (sbroscious at gmail.com) Date: 22 May 2007 14:44:24 -0700 Subject: NOOOOB In-Reply-To: <1179829763.464614.123920@a26g2000pre.googlegroups.com> References: <1179829763.464614.123920@a26g2000pre.googlegroups.com> Message-ID: <1179870264.586288.253550@m36g2000hse.googlegroups.com> On May 22, 6:29 am, jolly wrote: > Hey guys, > > I want to begin python. Does anyone know where a good starting point > is? > > Thanks, > Jem I really liked How to Think Like a Computer Scientist learning with python foound at http://www.ibiblio.org/obp/thinkCSpy/. Unlike most paper books you'd be hard pressed to find typos (that at this level of programming you wouldn't notice) there. Also if you want another source of info try www.diveintopython.org. You can find the book on the store shelves, but why pay when you can get it for free of the net. You can view it as HTML or download the .pdf. From sinoodle at yahoo.com Wed May 9 08:23:28 2007 From: sinoodle at yahoo.com (sinoodle at yahoo.com) Date: 9 May 2007 05:23:28 -0700 Subject: Questions about bsddb Message-ID: <1178713407.968873.260950@n59g2000hsh.googlegroups.com> Hello, I need to build a large database that has roughly 500,000 keys, and a variable amount of data for each key. The data for each key could range from 100 bytes to megabytes.The data under each will grow with time as the database is being built. Are there some flags I should be setting when opening the database to handle large amounts of data per key? Is hash or binary tree recommended for this type of job, I'll be building the database from scratch, so lots of lookups and appending of data. Testing is showing bt to be faster, so I'm leaning towards that. The estimated build time is around 10~12 hours on my machine, so I want to make sure that something won't get messed up in the 10th hour. TIA, JM From mensanator at aol.com Wed May 2 16:52:35 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 2 May 2007 13:52:35 -0700 Subject: How to check if a string is empty in python? In-Reply-To: <1178138964.503290.254060@o5g2000hsb.googlegroups.com> References: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> <1178138964.503290.254060@o5g2000hsb.googlegroups.com> Message-ID: <1178139155.260722.153750@n59g2000hsh.googlegroups.com> On May 2, 3:49 pm, Basilisk96 wrote: > A simple > > if s: > print "not empty" > else: > print "empty" > > will do. How do you know that s is a string? > > -Basilisk96 From grante at visi.com Mon May 14 15:20:27 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 14 May 2007 19:20:27 -0000 Subject: Time References: <1178916216.893542.257320@y80g2000hsf.googlegroups.com> <1178916422.065108.312920@l77g2000hsb.googlegroups.com> <1178920014.621031.301860@n59g2000hsh.googlegroups.com> <1178927105.482975.174760@y5g2000hsa.googlegroups.com> <1179151205.987222.54910@k79g2000hse.googlegroups.com> <1179152573.315362.37040@u30g2000hsc.googlegroups.com> <1179152855.424498.274820@p77g2000hsh.googlegroups.com> <134hdehnrd73bef@corp.supernews.com> Message-ID: <134hdjrq1jkd4a4@corp.supernews.com> On 2007-05-14, Grant Edwards wrote: > On 2007-05-14, Gabriel Genellina wrote: >> En Mon, 14 May 2007 11:27:35 -0300, HMS Surprise >> escribi?: >> >>> On May 14, 9:22 am, HMS Surprise wrote: >>> >>> Oops +=1, should be: >>> hrMn[0] = int(hrMn[0] >>> if t[2] == 'PM': >>> hrMn[0] += 12 >>> >>> Need more starter fluid, coffee please!!! >> >> Still won't work for 12 AM nor 12 PM... > > Do you mean 12 Noon or 12 Midnight? 12AM and 12PM don't exist, > do they? http://www.astronomy.net/articles/13/ -- Grant Edwards grante Yow! I am a jelly donut. at I am a jelly donut. visi.com From enleverlesX.XmcX at XmclaveauX.com Mon May 14 15:49:42 2007 From: enleverlesX.XmcX at XmclaveauX.com (=?UTF-8?Q?M=C3=A9ta-MCI?=) Date: Mon, 14 May 2007 21:49:42 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <4648bd67$0$5110$ba4acef3@news.orange.fr> Hi! - should non-ASCII identifiers be supported? why? - would you use them if it was possible to do so? in what cases? Yes. JScript can use letters with accents in identifiers XML (1.1) can use letters with accents in tags C# can use letters with accents in variables SQL: MySQL/MS-Sql/Oralcle/etc. can use accents in fields or request etc. etc. Python MUST make up for its lost time. MCI From bj_666 at gmx.net Mon May 28 03:19:23 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 28 May 2007 09:19:23 +0200 Subject: Error in optparse documentation References: <1180302882.090651.235860@q75g2000hsh.googlegroups.com> Message-ID: In <1180302882.090651.235860 at q75g2000hsh.googlegroups.com>, Shatadal wrote: > I think the documentation should be modified so that it is made clear > that %default in the help string behaves as is claimed only in version > 2.4 and higher. Maybe something should be added for clarity but I don't think it's an error in the docs. You are reading documentation for Python 2.5 and expect everything in it to work in older versions too? Pick the right documentation from http://www.python.org/doc/versions/ Ciao, Marc 'BlackJack' Rintsch From aleax at mac.com Fri May 4 22:42:26 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 4 May 2007 19:42:26 -0700 Subject: Newbie and Page Re-Loading References: <1178275290.158007.248180@h2g2000hsg.googlegroups.com> <463b6678$0$10433$426a34cc@news.free.fr> <1178302555.479739.227920@o5g2000hsb.googlegroups.com> <1178313011.279170.292200@u30g2000hsc.googlegroups.com> Message-ID: <1hxltav.y0wenquohjqeN%aleax@mac.com> Miki wrote: ... > > Is there a lightweight Https Server I could run locally (WINXP), which > > would run .py scripts, without lots of installation modifications ? > http://lighttpd.net. > Make sure "mod_cgi" is uncommented, set your document root and set > right python interpreter in cgi.assign For https, you do need to do substantial homework, though -- no two ways about it, since you'll need to get SSL certificates, etc etc. There are reasonably simple instructions for the purpose at , but they're for Linux -- I don't know how they change when you want to serve https on Xp. Alex From larry at theclapp.org Wed May 23 12:51:32 2007 From: larry at theclapp.org (Larry Clapp) Date: Wed, 23 May 2007 12:51:32 -0400 Subject: The Concepts and Confusions of Prefix, Infix, Postfix and Fully Functional Notations References: <1179936917.652372.24780@q69g2000hsb.googlegroups.com> Message-ID: ["Followup-To:" header set to comp.lang.lisp.] On 2007-05-23, Xah Lee wrote: > The Concepts and Confusions of Prefix, Infix, Postfix and Fully > Functional Notations > > Xah Lee, 2006-03-15 Xah, why do you post year-old essays to newsgroups that couldn't care less about them? From __peter__ at web.de Mon May 21 03:12:42 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 21 May 2007 09:12:42 +0200 Subject: getting output from a command into a list to work with References: Message-ID: Anthony Irwin wrote: > I would like to run the command below and have each line from the > output stored as an element in a list. > > find /some/path/ -maxdepth 1 -type f -size +100000k -exec ls -1 '{}' \ > > The reason for this is so I can then work on each file in the > following manner > > var = command > > for i in var: > # do stuff to file code here > > not sure the best way to get the output of the command so each line of > output is one element in the list. from subprocess import Popen, PIPE for line in Popen("find ...", shell=True, stdout=PIPE).stdout: # do stuff or if you don't need shell expansion for line in Popen(["find", "/some/path", ...], stdout=PIPE).stdout: # do stuff See http://docs.python.org/lib/module-subprocess.html for more. Peter From eric.brunel at pragmadev.com Tue May 15 02:59:45 2007 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Tue, 15 May 2007 08:59:45 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179160242.787344.48060@h2g2000hsg.googlegroups.com> Message-ID: On Mon, 14 May 2007 18:30:42 +0200, wrote: [snip] > Can a discussion about support for non-english identifiers (1) > conducted in a group where 99.9% of the posters are fluent > speakers of english (2), have any chance of being objective > or fair? Agreed. > Although probably not-sufficient to overcome this built-in > bias, it would be interesting if some bi-lingual readers would > raise this issue in some non-english Python discussion > groups to see if the opposition to this idea is as strong > there as it is here. Done on the french Python newsgroup. -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From g_teodorescu at yahoo.com Mon May 14 04:39:10 2007 From: g_teodorescu at yahoo.com (g_teodorescu at yahoo.com) Date: 14 May 2007 01:39:10 -0700 Subject: How to do basic CRUD apps with Python In-Reply-To: <1179098458.333666.307750@e65g2000hsc.googlegroups.com> References: <1179098458.333666.307750@e65g2000hsc.googlegroups.com> Message-ID: <1179131950.358056.208630@q75g2000hsh.googlegroups.com> walterbyrd a scris: > With PHP, libraries, apps, etc. to do basic CRUD are everywhere. Ajax > and non-Ajax solutions abound. > > With Python, finding such library, or apps. seems to be much more > difficult to find. > > I thought django might be a good way, but I can not seem to get an > answer on that board. > > I would like to put together a CRUD grid with editable/deletable/ > addable fields, click on the headers to sort. Something that would > sort-of looks like an online spreadsheet. It would be nice if the > fields could be edited in-line, but it's not entirely necessary. > > Are there any Python libraries to do that sort of thing? Can it be > done with django or cherrypy? > > Please, don't advertise your PHP/Ajax apps. SqlAlchemy - SqlSoup - PyQt4 (fragment) example: import sys from PyQt4.Qt import * from PyQt4 import uic from avc.avcqt4 import * from sqlalchemy.ext.sqlsoup import SqlSoup from ui_db import Ui_DbForm class DbForm(QWidget,AVC): def __init__(self, parent=None): QWidget.__init__(self,parent) self.ui = Ui_DbForm() self.ui.setupUi(self) # current index self.crtIndex = 0 self.crtPk = 0 # avc variables, same names as form widgets (lineEdit, combo, etc....) self.edtId = 0 self.edtFirstName = "" self.edtLastName = "" self.edtSalary = 0.0 self.connect(self.ui.btnQuit, SIGNAL("clicked()"), qApp, SLOT("quit()")) self.connect(self.ui.btnFirst, SIGNAL("clicked()"), self.goFirst) self.connect(self.ui.btnPrior, SIGNAL("clicked()"), self.goPrior) self.connect(self.ui.btnNext, SIGNAL("clicked()"), self.goNext) self.connect(self.ui.btnLast, SIGNAL("clicked()"), self.goLast) self.connect(self.ui.btnSave, SIGNAL("clicked()"), self.doSave) self.connect(self.ui.btnAdd, SIGNAL("clicked()"), self.doAdd) self.connect(self.ui.btnDel, SIGNAL("clicked()"), self.doDel) # connection: 'postgres://user:password at address:port/db_name' self.db = SqlSoup('postgres://postgres:postgres at localhost:5432/ testdb') self.goFirst() def goFirst(self): self.crtIndex = 0 self.doRead(self.crtIndex) def goPrior(self): if self.crtIndex > 0: self.crtIndex = self.crtIndex - 1 else: self.crtIndex = 0 self.doRead(self.crtIndex) def goNext(self): maxIndex = self.db.person.count() - 1 if self.crtIndex < maxIndex: self.crtIndex = self.crtIndex + 1 else: self.crtIndex = maxIndex self.doRead(self.crtIndex) def goLast(self): maxIndex = self.db.person.count() - 1 self.crtIndex = maxIndex self.doRead(self.crtIndex) def doSave(self): if self.crtPk == 0: # aflu pk-ul si adaug o inregistrare goala newPk = self.db.engine.execute("select nextval('person_id_seq')").fetchone()[0] self.crtPk = newPk self.db.person.insert(id=self.crtPk, firstname='', lastname='', salary=0.0) self.db.flush() person = self.db.person.selectone_by(id=self.crtPk) person.firstname = self.edtFirstName person.lastname = self.edtLastName person.salary = self.edtSalary self.db.flush() def doAdd(self): self.crtPk = 0 self.edtId = self.crtPk self.edtFirstName = "" self.edtLastName = "" self.edtSalary = 0.0 # inregistrarea trebuie salvata explicit # prin apasarea butonului "Save" def doDel(self): mk = self.db.person.selectone_by(id=self.crtPk) self.db.delete(mk) self.db.flush() self.goNext() def doRead(self, index): person = self.db.person.select() self.edtId = person[index].id self.edtFirstName = person[index].firstname self.edtLastName = person[index].lastname self.edtSalary = person[index].salary # invariant pt. toate operatiile, mai putin adaugare inregistrare # pk-ul nu se poate modifica prin edtId !!! self.crtPk = person[index].id if __name__ == "__main__": app = QApplication(sys.argv) # QApplication.setStyle(QStyleFactory.create("Cleanlooks")) QApplication.setStyle(QStyleFactory.create("Plastique")) form = DbForm() form.avc_init() form.show() sys.exit(app.exec_()) From kinch1967 at gmail.com Sat May 19 22:46:34 2007 From: kinch1967 at gmail.com (bullockbefriending bard) Date: 19 May 2007 19:46:34 -0700 Subject: regex matching question In-Reply-To: <464FA8B7.9070408@lexicon.net> References: <1179595319.239229.262160@l77g2000hsb.googlegroups.com> <464F86F0.8080100@lexicon.net> <1179620336.327038.253920@h2g2000hsg.googlegroups.com> <464FA8B7.9070408@lexicon.net> Message-ID: <1179629194.818363.52220@p47g2000hsd.googlegroups.com> > > No way? Famous last words :-) > > C:\junk>type showargs.py > import sys; print sys.argv > > C:\junk>\python25\python > 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 subprocess > >>> subprocess.call('\\python25\\python showargs.py teehee\n') > ['showargs.py', 'teehee\n'] can't argue with that :) back to \Z From bbxx789_05ss at yahoo.com Sat May 26 20:18:23 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 26 May 2007 17:18:23 -0700 Subject: sockets, gethostname() changing In-Reply-To: <1180123450.448644.11230@x35g2000prf.googlegroups.com> References: <1180062244.266857.300830@m36g2000hse.googlegroups.com> <1180123450.448644.11230@x35g2000prf.googlegroups.com> Message-ID: <1180225103.694825.93590@g4g2000hsf.googlegroups.com> I figured something out that succeeded in making the hostname constant, and it allows me to run the socket programs without error. I'm posting what I did for future seekers. This is for mac os 10.4.7: 1) In System Preferences>Sharing, there is a name entered there: Computer Name: John Smiths computer But underneath that is this text: Other computers on your local subnet can access your computer at John-Smiths-computer.local Copy the name John-Smiths-computer.local exactly as written. Notice the added dashes and the extension. If you want, you can change the name by entering something else in the text box to the right of "Computer Name:". Then if you click outside the text box elsewhere to move the focus away from the text box, the text underneath the text box will update with the new name, and that is the exact name you need to use for step 2. 2) In the file /etc/hostconfig, at the bottom I added the line: HOSTNAME=John-Smiths-computer.local The name entered there has to be the exact same name as the name in step 1. The hostconfig file is read only unless you are logged in using the root account(which you are never supposed to do). In any case, you can use the sudo command to momentarily become the superuser, which will enable you to edit hostcofig. If you are logged in as the root account, then you'll be able to edit hostconfig without having to use the sudo command. I used the cd command to change directories to /etc: $ cd /etc Then I used vi to edit the hostconfig file $ sudo vi hostconfig Hold your breath because you don't want to mess anything up when you have root privileges, although I don't think you can get in much trouble while editing a text file. Then save the file. 3) Restart your computer. I think there must be a way to reload the hostconfig file with out having to restart, but I couldn't figure out which command to use to accomplish that. After restarting, the hostname part of my prompt in Terminal stayed constant whether I was connected to the internet or not. And I could run the socket programs in my original post using gethostname()--whether I was connected to the internet or not. From steve at holdenweb.com Thu May 31 16:37:43 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 31 May 2007 16:37:43 -0400 Subject: c[:]() In-Reply-To: <003301c7a3ab$f2bdf960$240110ac@Muse> References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> <135tobve86qj808@corp.supernews.com> <135tru124pie2b3@corp.supernews.com> <135tv1bjqgbmsc9@corp.supernews.com> <003301c7a3ab$f2bdf960$240110ac@Muse> Message-ID: Warren Stringer wrote: >>>> c[:] holds many behaviors that change dynamically. >>> I've absolutely no clue what that sentence means. If c[:] does >>> behave differently than c, then somebody's done something >>> seriously weird and probably needs to be slapped around for >>> felonious overriding. > > I'm still a bit new at this, was wondering why c[:]() doesn't work, and > implicitly wondering why it *shouldn't* work. > >>>> So c[:]() -- or the more recent go(c)() -- executes all those >>>> behaviors. No it doesn't. See below. > > Oops meant to say do(c)(), not "go", which matches a prior post. > >>> Still no clue. >>> >>>> This is very useful for many performers. >>> What are "performers"? > > Real people, like musicians, and their proxies in code that passes around > real-time events that may be rendered, recorded, and played back. > >>>> The real world example that I'm working one is a collaborative >>>> visual music performance. So c can contain wrapped MIDI events >>>> or sequencer behaviors. c may get passed to a scheduler to >>>> execute those events, or c may get passed to a pickler to >>>> persist the performance. >>> I still don't see how c[:] is any different from c. >>> >> It isn't. The OP is projecting a wish for a function call on a list to >> be interpreted as a call on each member of the list with the same >> arguments. The all-members slice notation is a complete red herring. > > Just looked up "red herring wiki" hope I wasn't being misleading -- at least > not intentionally. c[:] is the simplest case for a broad range of behaviors. > Perhaps, I should have said c[selector()]() ??? but, no, that makes the > question more complex ... still > >> It would require a pretty fundamental re-think to give such a construct >> sensible and consistent semantics, I think. > > What do you mean? > > If c[:]() works, the so does this, using real world names > > orchestra[:].pickle() > orchestra[conductor()].sequence() > > Though, I'm already starting to prefer: > > do(orchestra).pickle() > do(orchestra(conductor)).sequence() > Yes, dammit, but c[:]() *DOESN'T WORK* unless you have made some pretty crufty changes to the underlying object. > Perhaps, this is what you mean by "sensible and consistent semantics" > > I just read Alex Martelli's post in the "rats! Varargs" thread about how > list and tupples are implemented. I want to understand implementation before > suggesting changes. Maybe c[:]() isn't so simple to fix, after all? > > This is what I'm having difficulty understanding. You said, in your original post (which, by the way, hijacked another thread about something completely different): > I want to call every object in a tupple, like so: > [By the way, that's "tuple", not "tupple"] > #------------------------------------------ > def a: print 'a' > def b: print 'b' > c = (a,b) > >>>> >>>c[:]() # i wanna > TypeError: 'tupple' object is not callable > >>>> >>>c[0]() # expected > a >>>> >>>c[:][0] # huh? > a This is what I just don't believe. And, of course, the use of "tupple" above tells us that this *wasn't" just copied and pasted from an interactive session. >>>> >>> [i() for i in c] # too long and ...huh? > a > b > [None,None] > #------------------------------------------ This is also clearly made up. In a later email you say: > why does c[:][0]() work but c[:]() does not? The reason for this is that c[:][0] is a function, a single item from a tuple of functions. c[:], however, is a tuple of functions, and cannot be called as a function itself. No matter how much you would like it to be. Python's chief virtue is obviousness, and this behavior would be very non-obvious. You also don't explain when Python should do if you happen to have something other than a function (say a string or a floating-point number) in the tuple. You also said: > Why does c[0]() has exactly the same results as c[:][0]() ? The reason for this is that c is exactly the same as c[:]. The slicing notation "[:]" tells the interpreter to use a tuple consisting of everything in the tuple to which it's applied. Since the interpreter knows that tuples are immutable (can't be changed), it just uses the same tuple -- since the immutability there's no way that a difference could arise between the tuple and a copy of the tuple, Python doesn't bother to make a copy. This behavior is *not* observed with lists, because lists are mutable. I realise you are trying to find ways to make Python more productive for you, and there's nothing wrong with that. But consider the following, which IS copied and pasted: >>> def a(): ... print "A" ... >>> def b(): ... print "B" ... >>> c = (a, b) >>> c (, ) >>> c[:] (, ) >>> c[0]() A >>> c[1]() B >>> c() Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object is not callable >>> c[:]() Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object is not callable >>> I think the fundamental mistake you have made is to convince yourself that c[:]() is legal Python. It isn't, it never has been. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From facundo at taniquetil.com.ar Wed May 2 09:13:28 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Wed, 2 May 2007 13:13:28 +0000 (UTC) Subject: More urllib timeout issues. References: Message-ID: Steve Holden wrote: > 1) There is work afoot to build timeout arguments into network libraries > for 2.6, and I know Facundo Batista has been involved, you might want to > Google or email Facundo about that. Right now (in svn trunk) httplib, ftplib, telnetlib, etc, has a timeout argument. If you use it, the socket timeout will be set (through s.settimeout()). What behaviour has the socket after setting it the timeout, is beyond of these changes, though. BTW, I still need to make the final step here, that is adding a timeout argument to urllib2.urlopen(). Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From wildemar at freakmail.de Sun May 27 11:45:52 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Sun, 27 May 2007 17:45:52 +0200 Subject: ten small Python programs In-Reply-To: <409218.34160.qm@web33506.mail.mud.yahoo.com> References: <409218.34160.qm@web33506.mail.mud.yahoo.com> Message-ID: <4659A7B0.2020605@freakmail.de> Steve Howell wrote: > # def defines a method in Python > def say_hello(name): > print 'hello', name > say_hello('Jack') > say_hello('Jill') > Doesn't def define methods *xor* functions, depending on the context? And in this example, say_hello (*yuck*, underscores ...) is certainly a function. Or is it that functions are considered "module-methods"? W From khemkaamit at gmail.com Thu May 24 08:35:26 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Thu, 24 May 2007 18:05:26 +0530 Subject: Web Archtecture using tow layers in Phyton In-Reply-To: References: Message-ID: <1360b7230705240535r7bd41143kfc8b70191a86ab83@mail.gmail.com> On 5/23/07, Wagner Garcia Campagner wrote: > Hello, > > I need to develop an web applications that meet the following requirements: > > - 2 layers: the first one is the user interface (browser) and the second one > is the interaction with the operacional system of the server. > - the second layer must be developed using Python. > > I'd like to know if it is possible to implement this system... making the > second layer using python and the first layer using another web technologies > like AJAX for example. Yes, It is very much possible and you will find the quite a few of such impementations . > Does anybody have any experience in developing python web applications? > Maybe send me some links or documentation about it... Search this news-group or web for "python web framework" and you can choose one based on your specific needs. ( some names that often pop up are: django, cherrypy, webware, pylons etc) > The final goal is to make diferent user interfaces (layer 1) that can > integrate with the second layer... for example, one web interface and one > local interface using python+qt (example)... i don't know if this is > possible and how can this be implemented... any help is aprreciated... Read the documentation of the framework ( if any) you choose to work with you may find templating system useful. For standalone app you can look at wxPython, which can communicate to your server at some port. Cheers, -- ---- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. From nsjmetzger at gmail.com Wed May 2 17:57:40 2007 From: nsjmetzger at gmail.com (nsjmetzger at gmail.com) Date: 2 May 2007 14:57:40 -0700 Subject: Cannot execute Windows commands via Python in 64-bit Message-ID: <1178143060.952025.85520@h2g2000hsg.googlegroups.com> I have a script that runs fine in Windows 2003 (32-bit). It basically calls the Windows defrag command. When I try the exact same code on Windows 2003 (64-bit) I get the following message: C:\Scripts>autodefrag.py Starting defragment: defrag -v C: >>c:/Scripts/DEFRAG20070502.log 'defrag' is not recognized as an internal or external command, operable program or batch file. I have tried defrag.exe and even giving it the full path to defrag.exe. Always the same result. Here is the python code that is generating this error: cmd = "defrag -v C: >>c:/Scripts/DEFRAG20070502.log" print "Starting defragment: ", cmd errorlevel = os.system(cmd) Anyone know what the heck is going on and how to fix it? This code works fine on my 32-bit windows machines. Thanks. From mail at microcorp.co.za Thu May 10 04:07:59 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 10 May 2007 10:07:59 +0200 Subject: Change serial timeout per read References: <1178754931.060029.135800@w5g2000hsg.googlegroups.com> Message-ID: <016601c792da$e799f160$03000080@hendrik> wrote: > I'm writing a driver in Python for an old fashioned piece of serial > equipment. Currently I'm using the USPP serial module. From what I can > see all the serial modules seem to set the timeout when you open a > serial port. This is not what I want to do. I need to change the > timeout each time I do a "read" on the serial port, depending on > which part of the protocol I've got to. Sometimes a return character > is expected within half a second, sometimes within 2 seconds, and > sometimes within 20 seconds. How do I do this in USPP, or Pyserial, or > anything else? Currently I'm working in Windows, but I'd prefer a > platform independent solution if possible... Yikes! you will probably have to make the port non blocking, and roll your own using different time.sleep(n) values between invocations to port.read(1) calls Unless you can afford to close and open the port each time - but that way leads to missed characters... - Hendrik From aasava at gmail.com Sun May 6 08:48:19 2007 From: aasava at gmail.com (Savatage4ever) Date: 6 May 2007 05:48:19 -0700 Subject: All what you are looking for and much more Message-ID: <1178455699.061553.86250@y80g2000hsf.googlegroups.com> urmania http://urmania.ipbfree.com/ application | movies | games | mp3 | ebooks From rampeters at gmail.com Thu May 10 10:02:49 2007 From: rampeters at gmail.com (johnny) Date: 10 May 2007 07:02:49 -0700 Subject: newb: Python Module and Class Scope Message-ID: <1178805769.658287.178240@q75g2000hsh.googlegroups.com> Can a class inside a module, access a method, outside of class, but inside of the module? Eg. Can instance of class a access main, if so how? What is the scope of "def main()" interms of class A? myModule: class A: main() def main(): thnx. From mail at microcorp.co.za Wed May 9 02:09:14 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 9 May 2007 08:09:14 +0200 Subject: Towards faster Python implementations - theory References: <1210i.7468$2v1.2505@newssvr14.news.prodigy.net> Message-ID: <013d01c79210$5e441280$03000080@hendrik> "John Nagle" wrote: 8<---------------- summary of existing work and thinking ------------------ > The point here is that we don't need language changes or declarations > to make Python much faster. All we need are a few restrictions that > insure that, when you're doing something unusual, the compiler can > tell. > I am relatively new on this turf, and from what I have seen so far, it would not bother me at all to tie a name's type to its first use, so that the name can only be bound to objects of the same type as the type of the object that it was originally bound to. But maybe I am missing the point of dynamism. Would an implementation of the above break lots of stuff in practice? It seems to me that it could have the effect of a declaration without the wart of actually doing it. - Hendrik From iclt at gmx.at Mon May 28 07:51:34 2007 From: iclt at gmx.at (Eisl Thomas) Date: Mon, 28 May 2007 13:51:34 +0200 Subject: FTP not Returning (Python on Series 60 Nokia) References: mailman.3808.1143618713.27775.python-list@python.org Message-ID: <465AC246.9070605@gmx.at> Hi! Do you already have found a solution for the FTP.storbinary hang-up-problem? I am writing a program who connects himself a lot of times to a FTP-Server, but in about 1 of 100 cases, it gets stuck in the storbinary command although the connection seems to work. I have already tried to set a timeout with ftpserver.sock.settimeout(60), but it doesn't work either... Thx for your answer! Greetz from Austria From http Sun May 13 13:49:09 2007 From: http (Paul Rubin) Date: 13 May 2007 10:49:09 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <7xabw8aa22.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > So, please provide feedback, e.g. perhaps by answering these > questions: > - should non-ASCII identifiers be supported? why? No, and especially no without mandatory declarations of all variables. Look at the problems of non-ascii characters in domain names and the subsequent invention of Punycode. Maintaining code that uses those identifiers in good faith will already be a big enough hassle, since it will require installing and getting familiar with keyboard setups and editing tools needed to enter those characters. Then there's the issue of what happens when someone tries to slip a malicious patch through a code review on purpose, by using homoglyphic characters similar to the way domain name phishing works. Those tricks have also been used to re-insert bogus articles into Wikipedia, circumventing administrative blocks on the article names. > - would you use them if it was possible to do so? in what cases? I would never insert them into a program. In existing programs where they were used, I would remove them everywhere I could. From vdicarlo at gmail.com Fri May 11 10:13:28 2007 From: vdicarlo at gmail.com (vdicarlo) Date: 11 May 2007 07:13:28 -0700 Subject: append In-Reply-To: <46438251$0$5908$426a34cc@news.free.fr> References: <1178816546.689849.255070@y5g2000hsa.googlegroups.com> <46438251$0$5908$426a34cc@news.free.fr> Message-ID: <1178892807.960948.307130@l77g2000hsb.googlegroups.com> > > the reference material. I want to know about list >> operations such as > > append. I've been struggling myself to assemble and learn just the right combination of quick references. Here is some of what I've found. For a quick search for the syntax and a simple example of a particular method or function, the single most efficient source for me has been the keyword search page for the Python Library Reference, Language Reference, and Python/C API manuals that you can find from a link on the official documentation page at http://www.python.org/doc/ or directly at http://starship.python.net/crew/theller/pyhelp.cgi Full text searches (not limited to keywords like the resource above) of the Python Library Reference can also be done at http://www.zvon.org/other/python/PHP/search.php Other handy references are: Dive into Python at http://diveintopython.org/toc/index.html The Python 2.5 Quick Reference at http://rgruet.free.fr/PQR25/PQR2.5.html Last, but far from least, the one resource that I most wish I had known about when I started with Python is the screencast tutorial site at www.showmedo.com. There are two excellent free screencasts on Python resources at http://tinyurl.com/2qkuht and lots of other Python tutorials, most free and some for a modest fee. In particular, the 9th installment of the paid series called Python Newbies on XP at http://tinyurl.com/3ayhwt is about how to use the help functions built into Python Idle. From afriere at yahoo.co.uk Thu May 10 02:46:34 2007 From: afriere at yahoo.co.uk (Asun Friere) Date: 9 May 2007 23:46:34 -0700 Subject: elegant python style for loops In-Reply-To: <5afrsmF2o97gcU1@mid.uni-berlin.de> References: <1178776272.535735.166540@h2g2000hsg.googlegroups.com> <5afrsmF2o97gcU1@mid.uni-berlin.de> Message-ID: <1178779594.588153.49620@n59g2000hsh.googlegroups.com> On May 10, 4:20 pm, "Diez B. Roggisch" wrote: > for a, b in zip(lista, listb): > ... You don't even need the for loop nowadays. Just pass the zipped list to a dictionary constructor thusly: newdict = dict(zip(listKeys,listValues)) Asun From benedict.verheyen at gmail.com Wed May 30 10:33:52 2007 From: benedict.verheyen at gmail.com (Benedict Verheyen) Date: Wed, 30 May 2007 16:33:52 +0200 Subject: Key Listeners In-Reply-To: <163f0ce20705300519m4404bc22m75f31549252c702@mail.gmail.com> References: <1180491273.446164.281990@q75g2000hsh.googlegroups.com> <1180510259.914953.225420@h2g2000hsg.googlegroups.com> <465d64c4$0$7452$426a74cc@news.free.fr> <163f0ce20705300519m4404bc22m75f31549252c702@mail.gmail.com> Message-ID: kaens schreef: >> > > What, he wants to know if there's a way in python to capture > keystrokes, and do something with them depending on what they are. > > I mean, it's very unlikely that you would ask for something called a > "key listener" if you didn't want to do something like: > > if keypress == 'a': > do somem > > right? Even if you're looking to do it the java way, all of the > listener functionality more or less boils down to "wait for and report > keys being pressed". > > He could have been less ambiguous, but I don't think that he was > asking the wrong question per se. > > Not to mention asking the OP "what's a key listener" isn't going to > make them think about the question they asked - it makes it seem like > you don't know what a key listener is (and frankly, I think that if > you have done any work with doing stuff on different keystrokes, > you'll figure out what is meant by key listener pretty quickly, even > if you haven't heard the term before) That's how it came across for me too. Couldn't have said it better kaens. Benedict From joshua at eeinternet.com Mon May 21 19:28:46 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Mon, 21 May 2007 15:28:46 -0800 Subject: model browser References: Message-ID: <46521edd$0$16328$88260bb3@free.teranews.com> On Sunday 20 May 2007 10:55, Daniel Nogradi wrote: > Are there other options I overlooked? > > Daniel There is a CRUD template for TG: http://docs.turbogears.org/1.0/CRUDTemplate Might be what you're looking for. j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE -- Posted via a free Usenet account from http://www.teranews.com From michael at stroeder.com Mon May 21 02:22:19 2007 From: michael at stroeder.com (=?ISO-8859-2?Q?Michael_Str=F6der?=) Date: Mon, 21 May 2007 08:22:19 +0200 Subject: Python Web Programming - looking for examples of solid high-traffic sites In-Reply-To: References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> Message-ID: John Nagle wrote: > Sure they do. I have a complex web site, "http://www.downside.com", > that's implemented with Perl, Apache, and MySQL. It automatically reads > SEC > filings and parses them to produce financial analyses. It's been > running for seven years, and hasn't been modified in five, except [..] Well, how can you be then sure that you don't have any security hole in there? Ciao, Michael. From bj_666 at gmx.net Fri May 25 09:51:39 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 25 May 2007 15:51:39 +0200 Subject: Reading a file and resuming reading. References: Message-ID: In , Karim Ali wrote: > Simple question. Is it possible in python to write code of the type: > > ----------------------------- > while not eof <- really want the EOF and not just an empty line! > readline by line > end while; > ----------------------------- while True: line = f.readline() if not line: break # Do something with `line`. > What I am using now is the implicit for loop after a readlines(). I don't > like this at all as a matter of opinion (my background is C++). Both look ugly to Pythonistas too. Files are iterable: for line in f: # Do something with `line`. > But also, in case for one reason or another the program crashes, I want to > be able to rexecute it and for it to resume reading from the same position > as it left. If a while loop like the one above can be implemented I can do > this simply by counting the lines! for line_nr, line in enumerate(f): # Do something with `line_nr` and `line`. Ciao, Marc 'BlackJack' Rintsch From srikrishnamohan at gmail.com Wed May 23 13:37:00 2007 From: srikrishnamohan at gmail.com (km) Date: Wed, 23 May 2007 23:07:00 +0530 Subject: Inheriting from Python list object(type?) In-Reply-To: <1179939516.574991.194470@u30g2000hsc.googlegroups.com> References: <1179939516.574991.194470@u30g2000hsc.googlegroups.com> Message-ID: Hi, u have the answer in ur question itself :) u dont need to redefine list methods again - just inherit from the builtin-list-type. try this with new style classes: #### code ### class Point(list): def __init__(self,x,y): super(Point, self).__init__() self.x = x self.y = y p = Point(2,3) print dir(p) print type(p) #### code #### regards KM ---------------------------------------------------------------------------------------------- On 23 May 2007 09:58:36 -0700, Mangabasi wrote: > > Howdy, > > I would like to create a Point class that lets me use Point instances > like the following example. > > >>> p = Point(3, 4) > >>> p.x > 3 > >>> p.y > 4 > >>> p.z > 1 > >>> p[0] > 3 > >>> p[1] > 4 > >>> p[1] = 5 > >>> p.y > 5 > >>> > > other than the x, y, z attributes, these instances should behave like > regular Python lists. I have created something like : > > class Point: > def __init__(self, x, y, z = 1): > self.list = [x, y, z] > > def __repr__(self): > return str(self.list) > > def __str__(self): > return str(self.list) > > def __getattr__(self, name): > if name == 'x': > return self.list[0] > elif name == 'y': > return self.list[1] > elif name == 'z': > return self.list[2] > else: > return self.__dict__[name] > > def __setattr__(self, name, value): > if name == 'x': > self.list[0] = value > elif name == 'y': > self.list[1] = value > elif name == 'z': > self.list[2] = value > else: > self.__dict__[name] = value > > def __getitem__(self, key): > return self.list[key] > > def __setitem__(self, key, value): > self.list[key] = value > > def __getslice__(self, i, j): > return self.list[i : j] > > def __setslice__(self, i, j, s): > self.list[i : j] = s > > def __contains__(self, obj): > if obj in self.list: > return True > else: > return False > > > There must be a way to inherit from the list type without having to > redefine all the methods and attributes that regular lists have. > > i.e. > > class Point(list): > ... > > > Can someone provide an example? > > Thanx in advance > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From JohnRoth1 at jhrothjr.com Fri May 18 21:26:32 2007 From: JohnRoth1 at jhrothjr.com (John Roth) Date: 18 May 2007 18:26:32 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46473267$0$31532$9b622d9e@news.freenet.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <1179537992.586692.94630@e65g2000hsc.googlegroups.com> On May 13, 9:44 am, "Martin v. L?wis" wrote: > PEP 1 specifies that PEP authors need to collect feedback from the > community. As the author of PEP 3131, I'd like to encourage comments > to the PEP included below, either here (comp.lang.python), or to > python-3... at python.org > > In summary, this PEP proposes to allow non-ASCII letters as > identifiers in Python. If the PEP is accepted, the following > identifiers would also become valid as class, function, or > variable names: L?ffelstiel, chang?, ??????, or ??? > (hoping that the latter one means "counter"). I notice that Guido has approved it, so I'm looking at what it would take to support it for Python FIT. The actual issue (for me) is translating labels for cell columns (and similar) into Python identifiers. After looking at the firestorm, I've come to the conclusion that the old methods need to be retained not only for backwards compatability but also for people who want to translate existing fixtures. The guidelines in PEP 3131 for standard library code appear to be adequate for code that's going to be contributed to the community. I will most likely emphasize those in my documentation. Providing a method that would translate an arbitrary string into a valid Python identifier would be helpful. It would be even more helpful if it could provide a way of converting untranslatable characters. However, I suspect that the translate (normalize?) routine in the unicode module will do. John Roth Phthon FIT From lesande at gmail.com Thu May 31 08:39:03 2007 From: lesande at gmail.com (Lee Sander) Date: 31 May 2007 05:39:03 -0700 Subject: file reading by record separator (not line by line) In-Reply-To: <1180614374.027569.235540@g4g2000hsf.googlegroups.com> References: <1180614374.027569.235540@g4g2000hsf.googlegroups.com> Message-ID: <1180615143.228557.258760@g4g2000hsf.googlegroups.com> I wanted to also say that this file is really huge, so I cannot just do a read() and then split on ">" to get a record thanks lee On May 31, 1:26 pm, Lee Sander wrote: > Dear all, > I would like toreada really hugefilethat looks like this: > > > name1.... > > line_11 > line_12 > line_13 > ...>name2 ... > > line_21 > line_22 > ... > etc > > where line_ij is just a free form text on that line. > > how can ireadfileso that every time i do a "read()" i get exactly > onerecord > up to the next ">" > > many thanks > Lee From stargaming at gmail.com Fri May 18 02:04:23 2007 From: stargaming at gmail.com (Stargaming) Date: Fri, 18 May 2007 08:04:23 +0200 Subject: How to convert a number to binary? In-Reply-To: <1179445546.307017.275850@p77g2000hsh.googlegroups.com> References: <1179444832.775573.55830@y80g2000hsf.googlegroups.com> <1179445546.307017.275850@p77g2000hsh.googlegroups.com> Message-ID: Lyosha schrieb: > On May 17, 4:40 pm, Michael Bentley wrote: > >>On May 17, 2007, at 6:33 PM, Lyosha wrote: >> >> >>>Converting binary to base 10 is easy: >>> >>>>>>int('11111111', 2) >>> >>>255 >> >>>Converting base 10 number to hex or octal is easy: >>> >>>>>>oct(100) >>> >>>'0144' >>> >>>>>>hex(100) >>> >>>'0x64' >> >>>Is there an *easy* way to convert a number to binary? >> >>def to_base(number, base): >> 'converts base 10 integer to another base' >> >> number = int(number) >> base = int(base) >> if base < 2 or base > 36: >> raise ValueError, "Base must be between 2 and 36" >> if not number: >> return 0 >> >> symbols = string.digits + string.lowercase[:26] >> answer = [] >> while number: >> number, remainder = divmod(number, base) >> answer.append(symbols[remainder]) >> return ''.join(reversed(answer)) >> >>Hope this helps, >>Michael > > > That's way too complicated... Is there any way to convert it to a one- > liner so that I can remember it? Mine is quite ugly: > "".join(str((n/base**i) % base) for i in range(20) if n>=base**i) > [::-1].zfill(1) > Wrote this a few moons ago:: dec2bin = lambda x: (dec2bin(x/2) + str(x%2)) if x else '' Regards, Stargaming From p.f.moore at gmail.com Thu May 24 12:23:15 2007 From: p.f.moore at gmail.com (Paul Moore) Date: 24 May 2007 09:23:15 -0700 Subject: Module imports fine from interactive, not from script In-Reply-To: <46538a79$0$16264$88260bb3@free.teranews.com> References: <46538a79$0$16264$88260bb3@free.teranews.com> Message-ID: <1180023795.116203.16990@h2g2000hsg.googlegroups.com> On 23 May, 02:20, "Joshua J. Kugler" wrote: > Yes, I've read this:http://mail.python.org/pipermail/python-list/2006-August/395943.html > That's not my problem. > > I installed PlanetPlanet via the > package's "setup.py install" command (as root). planet.py will not run, > however, giving me this error: > > Traceback (most recent call last): > File "/usr/local/bin/planet.py", line 167, in ? > main() > File "/usr/local/bin/planet.py", line 124, in main > planet.logging.basicConfig() > AttributeError: 'module' object has no attribute 'logging' Your problem is that your script is called planet.py, the same as the module you're trying to import. So from the script, "import planet" finds the script itself (the script's directory is always added to sys.path), and importing it as planet rather than importing the planet module from site-packages. The simplest fix is to not call the driver script "planet.py". It's not exactly "terribly simple", but it is quite a common mistake (I've certainly made it more than once...) Paul. From steve at REMOVE.THIS.cybersource.com.au Sun May 27 19:40:02 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 28 May 2007 09:40:02 +1000 Subject: What's the best way to iniatilize a function References: <7NmdncRrFaG3WMTbnZ2dnUVZ_gWdnZ2d@comcast.com> Message-ID: On Sun, 27 May 2007 10:51:46 -0700, Jack wrote: > I have a set of functions to wrap a library. For example, > > mylib_init() > mylib_func() > mylib_exit() > > or > > handle = mylib_init() > mylib_func(handle) > mylib_exit(handle) > > In order to call mylib_func(), mylib_init() has to be called once. > When it's done, or when program exits, mylib_exit() should > be called once to free resources. Sounds like a module to me. Write it as a module. Python will call your initialization code, once, the first time you import it. Python will handle the garbage collection of your resources when your module goes away. Modules are automatically singletons. # mylib wrapper(?) module # Initialize a bunch of data DATA = range(1000000) def func(): return DATA[0] # or something useful... Note that mylib.func() doesn't need to check that it is initialized, because if it isn't, it can't be called! That is to say, if some of your initialization code fails, an exception will be raised and the module will not be imported. Note two gotchas: (1) Python can automatically free most data structures and close open files, but if your needs are more sophisticated, this approach may not be suitable. (2) Module imports are cached. Calling "import mylib" imports the module, but calling "del mylib" doesn't free it because of the cache. Calling "del mylib; del sys.modules['mylib']" should remove the cache, allowing Python's normal garbage collection to free your resources, but note the above caveats regarding the types of resources that Python can automatically free. > I can list all three functions in a module and let the > application manage the init call and exit call. Or, better, > to have the wrapper function manage these calls. I'm currently > using a singleton class (see below.) It seems to work fine. Why do you care that it is a singleton? Surely the important thing is that all the instances share the same state, not that there is only one instance? The easiest way to ensure all instances share the same state is to put all the data you care about into class attributes instead of instance attributes: class MyLib(object): DATA = range(100000) # initialized when the class is defined def func(self): return self.DATA[0] Note that there are no __init__ or __new__ methods needed. If you don't want the (trivial) expense of creating new instances just to call the func method, use a class method that doesn't need an instance: class MyLib(object): DATA = range(100000) # initialized when the class is defined @classmethod def func(cls): return cls.DATA[0] See also the source to the random module for another way to expose a class-based interface as if it were a set of functions. > My questions here are: > > 1. every time I call the function: > > MyLib().func() > > part of the object creation code is called, at least to check if > there is an existing instance of the class, then return it. So it > may not be very efficient. Is there a better way? Yes. The caller should save the instance and reuse it, the same as any other expensive instance: obj = MyLib() obj.func() obj.func() > 2. what's the right way to call mylib_exit()? I put it in __del__(self) > but it is not being called in my simple test. instance.__del__ is only called when there are no references to the instance. instance = MyLib() another = instance data = [None, 1, instance] something = {"key": instance} del another # __del__ will not be called, but name "another" is gone del instance # __del__ still not called, but name "instance" is gone data = [] # __del__ still not called something.clear() # now __del__ will be called! It isn't easy to keep track of all the places you might have a reference to something, but Python can do it much better than you can. -- Steven. From Roka100 at gmail.com Fri May 25 07:51:35 2007 From: Roka100 at gmail.com (Jia Lu) Date: 25 May 2007 04:51:35 -0700 Subject: How to do this in python with regular expressions Message-ID: <1180093895.743196.75510@b40g2000prd.googlegroups.com> Hi all I'm trying to parsing html with re module. html = """
DATA1DATA2DATA3DATA4
DATA5DATA6DATA7DATA8
""" I want to get DATA1-8 from that string.(DATA maybe not english words.) Can anyone tell me how to do it with regular expression in python? Thank you very much. From horpner at yahoo.com Mon May 21 09:59:54 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 21 May 2007 13:59:54 GMT Subject: Python compared to other language References: <1179753682.661307.186540@y18g2000prd.googlegroups.com> Message-ID: On 2007-05-21, user2048 at yahoo.com wrote: >> Python is a strongly typed but dynamic language ... > > In the "A few questions" thread, John Nagle's summary of Python > begins "Python is a byte-code interpreted untyped procedural > dynamic language with implicit declaration. " > > Is Python strongly typed or untyped? It's strongly typed (only a handful of type conversions are automatic), and dynamically typed (no type declarations for identifiers are needed, types are checked at run time, not compile time). -- Neil Cerutti The doctors X-rayed my head and found nothing. --Dizzy Dean From carsten at uniqsys.com Fri May 4 00:39:56 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 04 May 2007 00:39:56 -0400 Subject: I wish that [].append(x) returned [x] In-Reply-To: <4638fa2e$0$16322$88260bb3@free.teranews.com> References: <46379a41$0$25252$88260bb3@free.teranews.com> <1178053211.209905.154030@h2g2000hsg.googlegroups.com> <4638e263$0$16368$88260bb3@free.teranews.com> <4638fa2e$0$16322$88260bb3@free.teranews.com> Message-ID: <1178253596.3522.22.camel@localhost.localdomain> On Wed, 2007-05-02 at 13:45 -0800, Joshua J. Kugler wrote: > On Wednesday 02 May 2007 12:05, Tobiah wrote: > > > > >> In addition to the above good advice, in case you are submitting a query > >> to a DB-API compliant SQL database, you should use query parameters > >> instead of building the query with string substitution. > > > > I tried that a long time ago, but I guess I found it to be > > more awkward. I imagine that it is quite a bit faster that way? > > I'm using MySQLdb. > > The issue is not speed, it's security. Query parameters are automatically > escaped to prevent SQL injection attacks. In addition to the important security factor, on many databases, using query parameters will also result in a speed increase. It just so happens that MySQLdb is not one of them. The wording that query parameters are "escaped" implies that handling query parameters is a string formatting exercise and that query parameters are stuffed into the query string as properly escaped literals. That is not always the case. In many databases, the lowlevel database API provides a particular mechanism for binding parameter values to placeholders without "injecting" them into the query string. This saves the client from constructing literals and it saves the server from parsing those literals. It also allows the server to reuse the query string without re-parsing it, because the query string doesn't change if the parameters are transmitted separately. The resulting speedup can be quite significant, as demonstrated for example with an IBM Informix database: # querytest.py class Tester(object): def __init__(self): import informixdb conn = informixdb.connect("ifxtest") self.cur = conn.cursor() self.cur.execute("create temp table t1(a int, b int)") self.counter = 0 def with_params(self): self.counter += 1 self.cur.execute("insert into t1 values(?,?)", (self.counter,self.counter*2) ) def without_params(self): self.counter += 1 self.cur.execute("insert into t1 values(%s,%s)" % (self.counter,self.counter*2) ) [carsten at localhost python]$ python -mtimeit -s "from querytest import Tester; t=Tester()" 't.with_params()' 10000 loops, best of 3: 146 usec per loop [carsten at localhost python]$ python -mtimeit -s "from querytest import Tester; t=Tester()" 't.without_params()' 1000 loops, best of 3: 410 usec per loop I think those numbers speak for themselves. -Carsten From muhamad.abbas at yahoo.co.uk Wed May 2 06:46:32 2007 From: muhamad.abbas at yahoo.co.uk (muhamad.abbas) Date: Wed, 02 May 2007 10:46:32 -0000 Subject: Calling Exe from Python Message-ID: Hello Folks, This is what i am required to do. Call an executable from my python script, and when the executable is finished running, i should continue with my python script. I have tried "os.exec()" but it calls the executable and never returns to the calling python script. I tried "os.fork" it will start an independent process, since logic of my program depends on the results of executable. I am unable to figure, how to do it. Hope you folks would help me. ~JinBaba From gherron at islandtraining.com Wed May 30 02:27:27 2007 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 29 May 2007 23:27:27 -0700 Subject: Key Listeners In-Reply-To: <1180491273.446164.281990@q75g2000hsh.googlegroups.com> References: <1180491273.446164.281990@q75g2000hsh.googlegroups.com> Message-ID: <465D194F.3010507@islandtraining.com> Mike wrote: > Are there key listeners for Python? Either built in or third party? > > (As always on forums like this, you're most likely to get answers if you define your terms. A little Goggling informs me that in Java a key listener is a Java term for a component that generates an event when the keyboard is used. ) Yes, every GUI I've ever used from Python (Tk/Tcl, wxPython, Gtk++, Win32 API, ...) has a way to catch keyboard events. But you're going to have to tell us which OS and which GUI you're interested in before you get a more detailed answer. Gary Herron From walterbyrd at iname.com Wed May 2 16:48:45 2007 From: walterbyrd at iname.com (walterbyrd) Date: 2 May 2007 13:48:45 -0700 Subject: Can I use Python instead of Joomla? Message-ID: <1178138925.498663.252920@o5g2000hsb.googlegroups.com> If I wanted to build a website with forums, news feeds, galleries, event calander, document managment, etc. I do so in Joomla easily. But, I would perfer to use django/python, if that would be at all practical. I suppose I could put python scripts into django, if those scripts exist. From matt at exemail.com.au Mon May 28 04:52:08 2007 From: matt at exemail.com.au (Matt van de Werken) Date: Mon, 28 May 2007 18:52:08 +1000 Subject: gui application on cross platform In-Reply-To: <1180332092.551838.258440@z28g2000prd.googlegroups.com> References: <1180332092.551838.258440@z28g2000prd.googlegroups.com> Message-ID: <465a9839$0$4609$61c65585@un-2park-reader-01.sydney.pipenetworks.com.au> james_027 wrote: > Hi, > > I am using delphi to develop gui application, and wish to make a shift > to python. here are some of my question/concern... > > 1. is python develop gui application a cross platform? just like java > swing? > 2. delphi makes things easy for me like coding for a specific event on > a specific component, could it be the same for python? > 3. are there cool library of component like in delphi available for > python that will make database application more usesable? > 4. where do I start the learning curve? I did some research and I > don't know which one to take among wxwdiget, pygtk, and etc. > > I'm also going down this path, and have decided on python + wxWidgets + boa as the RAD tool. From the tutorial, it seems pretty easy to use, except for some minor annoyances on both windows and linux platforms. Under windows, for some inexplicable reason the "dialogs" tab is not present, while under linux, I can't seem to drag components around the frame after placement. Cheers, mvdw From steven at REMOVE.THIS.cybersource.com.au Sun May 13 22:46:17 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 14 May 2007 02:46:17 -0000 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <20070513160046.GC29172@v.igoro.us> <7x646wa9wz.fsf@ruckus.brouhaha.com> <7xfy608bkk.fsf@ruckus.brouhaha.com> Message-ID: On Sun, 13 May 2007 17:59:23 -0700, Paul Rubin wrote: > Steven D'Aprano writes: >> > It certainly does apply, if you're maintaining a program and someone >> > submits a patch. In that case you neither click nor type the >> > character. You'd normally just make sure the patched program passes >> > the existing test suite, and examine the patch on the screen to make >> > sure it looks reasonable. The phishing possibilities are obvious. >> >> Not to me, I'm afraid. Can you explain how it works? A phisher might be >> able to fool a casual reader, but how does he fool the compiler into >> executing the wrong code? > > The compiler wouldn't execute the wrong code; it would execute the code > that the phisher intended it to execute. That might be different from > what it looked like to the reviewer. How? Just repeating in more words your original claim doesn't explain a thing. It seems to me that your argument is, only slightly exaggerated, akin to the following: "Unicode identifiers are bad because phishers will no longer need to write call_evil_func() but can write call_?v??_func() instead." Maybe I'm naive, but I don't see how giving phishers the ability to insert a call to ?unction() in some module is any more dangerous than them inserting a call to function() instead. If I'm mistaken, please explain why I'm mistaken, not just repeat your claim in different words. -- Steven. From amidzic.branko at gmail.com Wed May 9 14:09:28 2007 From: amidzic.branko at gmail.com (amidzic.branko at gmail.com) Date: 9 May 2007 11:09:28 -0700 Subject: Inheritance problem Message-ID: <1178734168.255175.248800@e51g2000hsg.googlegroups.com> I'm trying to solve a problem using inheritance and polymorphism in python 2.4.2 I think it's easier to explain the problem using simple example: class shortList: def __init__(self): self.setList() def setList(self): a = [1,2,3] print a class longList(shortList): def __init__(self): shortList.setList() self.setList() def setList(self): a.extend([4,5,6]) print a def main(): a = raw_input('Do you want short or long list? (s/l)') if a.upper() == 'S': lst = shortList() else: lst = longList() lst.setList() if __name__ == '__main__': main() After that I'm getting a message: TypeError: unbound method setList() must be called with shortList instance as first argument (got nothing instead) Where is the problem? Thanks in advance... From bdesth.quelquechose at free.quelquepart.fr Sun May 13 18:27:06 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 14 May 2007 00:27:06 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464762B6.701@web.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> Message-ID: <46478694$0$1412$426a34cc@news.free.fr> Stefan Behnel a ?crit : > Martin v. L?wis schrieb: > >>PEP 1 specifies that PEP authors need to collect feedback from the >>community. As the author of PEP 3131, I'd like to encourage comments >>to the PEP included below, either here (comp.lang.python), or to >>python-3000 at python.org >> >>In summary, this PEP proposes to allow non-ASCII letters as >>identifiers in Python. If the PEP is accepted, the following >>identifiers would also become valid as class, function, or >>variable names: L?ffelstiel, chang?, ??????, or ??? >>(hoping that the latter one means "counter"). >> >>I believe this PEP differs from other Py3k PEPs in that it really >>requires feedback from people with different cultural background >>to evaluate it fully - most other PEPs are culture-neutral. >> >>So, please provide feedback, e.g. perhaps by answering these >>questions: >>- should non-ASCII identifiers be supported? why? >>- would you use them if it was possible to do so? in what cases? > > > > To make it clear: this PEP considers "identifiers written with non-ASCII > characters", not "identifiers named in a non-english language". You cannot just claim that these are two totally distinct issues and get away with it. The fact is that not only non-english identifiers are a bad thing when it comes to sharing and cooperation, and it's obvious that non-ascii glyphs can only make things work - since it's obvious that people willing to use such a "feature" *wont* do it to spell english identifiers anyway. > While the first is already allowed as long as the transcription uses only > ASCII characters, the second is currently forbidden and is what this PEP is about. > > Now, I am not a strong supporter (most public code will use English > identifiers anyway) but we should not forget that Python supports encoding > declarations in source files and thus has much cleaner support for non-ASCII > source code than, say, Java. So, introducing non-ASCII identifiers is just a > small step further. I would certainly not qualify this as a "small" step. > Disallowing this does *not* guarantee in any way that > identifiers are understandable for English native speakers. I'm not an English native speaker. And there's more than a subtle distinction between "not garantying" and "encouraging". > It only guarantees > that identifiers are always *typable* by people who have access to latin > characters on their keyboard. A rather small advantage, I'd say. > > The capability of a Unicode-aware language to express non-English identifiers > in a non-ASCII encoding totally makes sense to me. It does of course make sens (at least if you add support for non-english non-ascii translation of the *whole* language - keywords, builtins and the whole standard lib included). But it's still a very bad idea IMHO. From ross at biostat.ucsf.edu Fri May 11 20:53:26 2007 From: ross at biostat.ucsf.edu (Ross Boylan) Date: Fri, 11 May 2007 17:53:26 -0700 Subject: logging module and threading Message-ID: <20070512005326.GM13408@iron.psg.net> I would like my different threads to log without stepping on each other. Past advice on this list (that I've found) mostly says to send the messages to a Queue. That would work, but bypasses the logging module's facilities. The logging module itself is "thread-safe", but I think that just means that individual output is protected. If I have, in temporarly sequence: thread 1: warning("A") thread 2: info("something") thread 1: warning("B") then I think I'll get them output in this order. It's thread-safe in that the log will not end up with an entry like A some B thing (I think). But I want to get, for example, A B something What I would like is for each thread to emit a chunk of log messages when it finishes a unit of work. It looks as if I might be able to use a MemoryHandler to accumulate the log locally and then flush it into the main log (I'd like to send it to the main logger, but it looks as if I must send it to a specific handler). Would something like the following work? class MyThread (threading.Thread): def __init__(self): # do I need the next line? threading.Thread.__init__(self) self._log = logging.getLogger(self.getName()) # flush into main log self._log = logging.MemoryHandler(9999999, , # default flushlevel logging.getLogger().handlers[1] ) def run(self): j = getjob() while j: # do stuff # log like this self._log.info("some message") # when done self._log.flush() j = getjob() I'm also puzzled by how the logger hierarchy works. The docs say that everything that is logged by the kids is also logged by the parent. That would seem to defeat what I'm trying to do above, since the parent would get each logged event right away. However, logging.getLogger("a").error("test") produces only a single log message indicating an associated object of "a". The docs lead me to expect that I'd see one message from "a" and another from root. When I add handlers (e.g., FileHandlers) I do get the message recorded by each. Can anyone explain what's going on? Thanks. Ross Boylan From len-l at telus.net Thu May 31 01:34:17 2007 From: len-l at telus.net (Lenard Lindstrom) Date: Thu, 31 May 2007 05:34:17 GMT Subject: New-style classes and special methods In-Reply-To: References: Message-ID: Raj B wrote: > > Yes, special methods populate the slots in the structures which Python > > uses to represent types. Objects/typeobject.c in the Python source > > distribution does the hard work, particularly in function type_new > > > > Thanks for that quick response. I am quite comfortable with C code and > am trying to understand exactly what happens when a new-style class is > created, and then instantiated. > > I have been reading typeobject.c and type_new() inside it in detail, and > there are a few issues I am trying to figure out. > > I can see a lot of *SLOT() macros in the file that seem to set the slots > to appropriate values. What I am having trouble figuring out is the > connection i.e. at what point during construction of the class object in > type_new() are those slots allotted? Is it the tp_alloc() function which > does this? The place to start is the PyType_Type tp_new slot function type_new(). The second to last statement is a call to fixup_slot_dispatchers(). This function goes through the dictionary looking for special methods and adds the appropriate slot functions. This gets very involved. I had to use the Visual Studio debugger to follow what was happening when trying to figure out what happens when assigning a special method to a class after it is declared. > > Is there some kind of descriptor or other mechanism connecting special > method names with their slots in the object representation? (e.g. > "__call__" with type->tp_call) There is a special tp_call slot function, slot_tp_call(), that calls the user defined __call__. The same goes for other special methods. Descriptors only come into play with extension types. In this case if a slot function is found a descriptor is added to make the slot function accessible from Python as a special method. > > Also, what happens when a class inherits from multiple classes with > their own __call__ methods? Where and how is it decided which __call__ > goes into the tp_call slot? > As Alex Martelli mentioned, __call__ is found using the method resolution order. The tp_call slot function slot_tp_call() uses lookup_method(), a variation of PyObject_GetAttribute(), to finding the appropriate Python method. Its all documented in the C file. > I'm sure I'll eventually figure it out if I stare at the code hard > enough, but would totally appreciate any help I can get :) > Just ask. -- Lenard Lindstrom From DustanGroups at gmail.com Sun May 6 07:53:23 2007 From: DustanGroups at gmail.com (Dustan) Date: 6 May 2007 04:53:23 -0700 Subject: Did you read about that? In-Reply-To: <1178446711.502374.286790@l77g2000hsb.googlegroups.com> References: <1178446711.502374.286790@l77g2000hsb.googlegroups.com> Message-ID: <1178452403.114975.249050@u30g2000hsc.googlegroups.com> On May 6, 5:18 am, happy wrote: > you can take a look for this web sites > > http://www.imanway.com/vb/forumdisplay.php?f=90 > > http://www.geocities.com/islamone_l/index.htm > > or read this > > ================================================== > > What is Islam? > > ABOUT THE WORDS "ISLAM" AND "MUSLIM" > > The name of this religion is Islam, the root of which is S-L-M, which > means peace. The word "Salam," derived from the same root, may also > mean greeting one another with peace. > > One of the beautiful names of God is that He is Peace. But Islam means > more than that: it means submission to the One God, and it means > living in peace with the Creator -- peace within one's self, peace > with other people, and peace with the environment. > > Thus, Islam is a total system of living. A Muslim is supposed to live > in peace and harmony with all these segments. It follows that a Muslim > is any person, anywhere in the world, whose obedience, allegiance, and > loyalty are to God, the Lord of the Universe. > > IS "MUSLIM" THE SAME AS ARAB? > > The followers of Islam are called Muslims. Muslims are not to be > confused with Arabs. > > Muslims may be Arabs, Turks, Persians, Indians, Pakistanis, > Malaysians, Indonesians, Europeans, Africans, Americans, Chinese, or > other nationalities. > > An Arab could be a Muslim, a Christian, a Jew or an atheist. Any > person who adopts the Arabic language is called an Arab. > > The language of the Qur'an (the Holy Book of Islam) is Arabic. Muslims > all over the world try to learn or improve their Arabic, so that they > may be able to read the Qur'an and understand its meaning. They pray > in the language of the Qur'an, Arabic. Islamic supplications to God > could be (and are) delivered in any language. > > There are one billion Muslims in the world; there are about 200 > million Arabs. Among those two hundred million Arabs, approximately > ten percent are not Muslims. Thus Arab Muslims constitute only about > twenty percent of the Muslim population of the world. > - > > ALLAH THE ONE AND THE ONLY GOD > > "Allah" was the Arabic word for God long before the birth of Muhammad, > peace be upon him. > > Muslims believe that Allah is the name of the One and Only God. He is > the Creator of all human beings. He is the God for the Christians, the > Jews, the Muslims, the Buddhists, the Hindus, the atheists, and all > others. Muslims worship God, whose name is Allah. They put their trust > in Him and they seek His help and His guidance. > > MUHAMMAD > > Muhammad was chosen by God to deliver His Message of Peace, namely > Islam. He was born in 570 C.E. (Common Era) in Makkah, Arabia. He was > entrusted with the Message of Islam when he was at the age of forty > years. The revelation that he received is called the Qur'an, while the > message is called Islam. > > Muhammad is the very last Prophet of God to mankind. He is the final > Messenger of God. His message was and is still to the Christians, the > Jews and the rest of mankind. He was sent to those religious people to > inform them about the true mission of Jesus, Moses, Jacob, Isaac, and > Abraham. > > Muhammad is considered to be the summation and the culmination of all > the prophets and messengers that came before him. He purified the > previous messages from adulteration and completed the Message of God > for all humanity. He was entrusted with the power of explaining, > interpreting and living the teaching of the Qur'an. > > ISLAM AND NON-MUSLIMS > > Muslims are required to respect all those who are faithful and God > conscious people, namely those who received messages. Christians and > Jews are called People of the Book. Muslims are asked to call upon the > People of the Book for common terms, namely, to worship One God, and > to work together for the solutions of the many problems in the > society. > > Christians and Jews lived peacefully with Muslims throughout centuries > in the Middle East and other Asian and African countries. The second > Caliph, Umar, chose not to pray in the church in Jerusalem, so as not > to give later Muslims an excuse to take it over. Christians entrusted > the Muslims, and as such the key of the Church in Jerusalem is still > in the hands of the Muslims. > > When Jews fled from Spain during the Inquisition, they were welcomed > by the Muslims. They settled in the heart of the Islamic Caliphate. > They enjoyed positions of power and authority. Throughout the Muslim > world, churches, synagogues and missionary schools were built within > the Muslim neighborhoods. These places were protected by Muslims > during bad times and good, and have continued to receive this > protection during the contemporary crises in the Middle East > > =============================================================== > What is the Qur'?n? > > The Qur'?n is the name given to Allah's speech that He revealed to His > servant and Messenger Muhammad (peace be upon him); speech that is > recited as an act of worship, is miraculous, and cannot be imitated by > man. It is the name of Allah's Book, and no other book is called by > this name. > > The connection between the Creator and his Creation is by way of His > Messengers, and these Messengers only know what Allah wants from them > by way of revelation, either directly or indirectly. The rational mind > cannot dismiss the possibility of revelation, since nothing is > difficult for the all-powerful Creator > > revelation is a communication between two beings: one that speaks, > commands, and gives, and another who is addressed, commanded, and > receives. Prophet Muhammad (peace be upon him) - as with every Prophet > - never confused himself with the One who gave the revelation to him. > As a human being, he felt his weakness before Allah, feared Allah's > wrath if he should disobey, and hoped for Allah's mercy. > > Proves why it is impossible that Mohammad (Pbuh) wrote the Quran : > 1. No matter how brilliant or insightful a person might be, there is > no way that he could discuss the happenings of nations lost to > antiquity, issues of belief and Divine Law, the rewards and > punishments of Heaven and Hell, and future events, all in such great > detail without any contradiction and with a most perfect style and > literary form. The Prophet (peace be upon him) had never once read a > book nor met with any historian > 2. The Qur'?n makes to the disbelievers a stern challenge that they > will never be able to produce a chapter similar to it. Such a > challenge would never have come from the Messenger (peace be upon him) > 3. The Qur'?n, in some places, sternly rebukes Muhammad (peace be upon > him) where he acted upon his own judgment in something and did not > decide on what is best. The Qur'?n clarified the truth and showed the > error of the Prophet (peace be upon him). > 4. Many verses of the Qur'?n begin with the imperative verb "Say!" As > a matter of fact, this occurs more than three hundred times, > addressing Muhammad (peace be upon him) and directing him with respect > to what he should say. He, thus, did not follow his own desires; he > followed only what was revealed to him. > 5. Complete harmony exists between what the Qur'?n says regarding the > physical world and what has been discovered by modern science. This > has been a source of amazement for a number of contemporary western > researchers. > ==================================================== > Who was Muhammad? > > Muhammad (peace be upon him) was born in Makkah in the year 570, > during the period of history Europeans called the Middle Ages. > Muhammad was the son of Aamenah and Abdullah, from the tribe of > Quraysh. He was a direct descendant of Ishmael, the eldest son of > prophet Abraham. Muhammad's father died just before he was born, and > his mother passed away when he was six. He was raised by this > grandfather, the chief of Makkah; and upon his grandfather's death, > Muhammad came under the care of his uncle, Abu Talib. > > Muhammad was a shepherd in his youth. As he grew up, he became known > for his truthfulness, generosity, and sincerity; earning the title of > al Amin, the trustworthy one. Muhammad was frequently called upon to > arbitrate disputes and counsel his fellow Makkans. > > At age 25, Muhammad married Khadijah, an honorable and successful > businesswoman. They were blessed with two sons and four daughters. It > was an ideal marriage and they lived a happy family life. > > Muhammad was of a contemplative nature and had long detested the > decadence and cruelty of his society. It became his habit to meditate > from time to time in the cave of Hira' near the summit of Jabal an- > Nur, the "Mountain of Light" on the outskirts of Makkah. > How did Muhammad become a Messenger of God? > > At the age of 40, while engaged in a meditative retreat, Muhammad > received his first revelation from God through the Archangel Gabriel. > This revelation, which continued for twenty three years, is known as > the Qur'an > > Muhammad began to share the revelations he received from God with the > people of Makkah. They were idol worshippers, and rejected Muhammad's > call to worship only One God. They opposed Muhammad and his small > group of followers in every way. These early Muslims suffered bitter > persecution. > > In 622, God gave the Muslim community the command to emigrate. This > event, the hijrah or migration, in which they left Makkah for the city > of Madinah, some 260 miles to the North, marks the beginning of the > Muslim calendar. > > Madinah provided Muhammad and the Muslims a safe and nurturing haven > in which the Muslim community grew. After several years, the Prophet > and his followers returned to Makkah and forgave their enemies. Then, > turning their attention to the Ka'bah (the sanctuary that Abraham > built), they removed the idols and rededicated it to the worship of > the One God. Before the Prophet died at the age of 63, most of the > people of Arabia had embraced his message. In less than a century, > Islam had spread to Spain in the west, as far east as China. >>> for message in op.profile: # http://preview.tinyurl.com/yvu55k if message.isSpam(): print "SPAM!" else: print "This guy's not spamming all the time..." SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! >>> try: print len(op.inbox) except MemoryError: print "owch!" owch! >>> for message in op.inbox: if message.isSpam(): print "SPAM!" else: print "This guy's getting legitimate emails!" SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! SPAM! [Ctrl-C] From rw at smsnet.pl Sun May 6 16:24:16 2007 From: rw at smsnet.pl (Rob Wolfe) Date: Sun, 06 May 2007 22:24:16 +0200 Subject: tkinter - label widget text selection References: <1178478118.170827.196310@e65g2000hsc.googlegroups.com> Message-ID: <87lkg1r98v.fsf@merkury.smsnet.pl> rahulnag22 at yahoo.com writes: > Hi, > I guess this is a very trivial question -- > I am using a label widget to display text (black font in a white > background color). I am trying to use my mouse to scroll over the > displayed text to select it, but tkinter does not allow me to do it. > Is there a method/option to do this. Try to use an entry widget in read-only state: import Tkinter as Tk root = Tk.Tk() ent = Tk.Entry(root, state='readonly', readonlybackground='white', fg='black') var = Tk.StringVar() var.set('Some text') ent.config(textvariable=var, relief='flat') ent.pack() root.mainloop() -- HTH, Rob From showell30 at yahoo.com Sun May 27 21:26:09 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 27 May 2007 18:26:09 -0700 (PDT) Subject: itertools.groupby In-Reply-To: <1180313441.598026.198230@d30g2000prg.googlegroups.com> Message-ID: <267952.80323.qm@web33502.mail.mud.yahoo.com> --- Raymond Hettinger wrote: > > FWIW, I wrote those docs. Suggested improvements > are > welcome; however, I think they already meet a > somewhat > high standard of quality: > I respectfully disagree, and I have suggested improvements in this thread. Without even reading the doc, I completely understand the motivation for this function, and I understand its implementation from reading email threads where it was discussed, but when I go back a couple days later to read the docs, I find it hard to grok how to actually use the module. You provided a bunch of points that clarify what you did specify correctly in the documentation, and I'm not going to attempt to refute them individually. I'm simply going to agree with the original poster that the docs as written are hard to understand, and I'll leave it to you to make your own judgment upon re-reading the docs. It could come down to simply needing a better motivating example. My suggestions mostly come down to providing better example code (I provided some in a separate reply), but I think you could also clarify the main use case (aggregating a stream of data) and the main limitation (requirement to sort by key since the iteration could be infinite)--which I know you mention, but you maybe could emphasize it more. > This is most complex itertool in the module. I > believe > the docs for it can be usable, complete, and > precise, > but not idiot-proof. > Agreed, of course, that nothing can be idiot-proof, and I understand the limitations myself, and I understand groupby's power. > The groupby itertool came-out in Py2.4 and has had > remarkable > success (people seem to get what it does and like > using it, and > there have been no bug reports or reports of > usability problems). > All in all, that ain't bad (for what 7stud calls a > poster child). > I agree that "poster child" is way too strong, but please don't disregard 7stud completely just because he exaggerates a tad. I've had minor usability problems with groupby, and I just haven't reported them. I'm still on 2.3 for most of my day-to-work work, but I've been sufficiently intrigued by the power of groupby() to try it out in a later version. I really mean all of these suggestions constructively. It's a great function to have in Python, and I think the documentation's mostly good, just could be even better. ____________________________________________________________________________________ Don't get soaked. Take a quick peak at the forecast with the Yahoo! Search weather shortcut. http://tools.search.yahoo.com/shortcuts/#loc_weather From pete.losangeles at gmail.com Tue May 15 18:18:18 2007 From: pete.losangeles at gmail.com (MisterPete) Date: 15 May 2007 15:18:18 -0700 Subject: inherit from file and create stdout instance? Message-ID: <1179267498.154549.58370@h2g2000hsg.googlegroups.com> How can I inherit from file but stil create an instance that writes to stdout? ----------- I'm writing a file-like object that has verbosity options (among some other things). I know I could just set self.file to a file object rather than inheriting from file. I started with something like this (simplified for clarity): class Output(object): def __init__(self, file=sys.stdout, verbosity=1): self.verbosity = verbosity self.file = file def write(self, string, messageVerbosity=1): if messageVerbosity <= self.verbosity: self.file.write(string) ... but it is frustrating me that if I try to inherit from file it works fine for regular files but I can't figure out a clean way to instantiate an object that writes to stdout using sys.stdout. something like the following: class Output(object): def __init__(self, file=sys.stdout, verbosity=1): self.verbosity = verbosity self.file = file def write(self, string, messageVerbosity=1): if messageVerbosity <= self.verbosity: self.file.write(string) ... I hope that's clear. Is it just a bad idea to inherit from file to create a class to write to stdout or am I missing something? Any insight is appreciated. Thanks, Pete From deets at nospam.web.de Thu May 10 02:20:01 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 10 May 2007 08:20:01 +0200 Subject: elegant python style for loops In-Reply-To: <1178776272.535735.166540@h2g2000hsg.googlegroups.com> References: <1178776272.535735.166540@h2g2000hsg.googlegroups.com> Message-ID: <5afrsmF2o97gcU1@mid.uni-berlin.de> ian.team.python at saltmob.com schrieb: > To step through a list, the python style is avoid an explicit index. > But what if the same hidden index is to be used for more than one list > > for example:- > for key,value in listKeys,listValues : > newdict[key]=value > > won't work as it is a tuple of lists, as opposed to a list of tuples. > Is there an elegant solution to this? Is there a way to merge lists > into a list of tuples to allow moving through multiple lists, or is > the for i in range(len(listkeys)): the only solution? > > Any suggestions? for a, b in zip(lista, listb): ... Diez From etienne.hilson at gmail.com Mon May 28 14:52:11 2007 From: etienne.hilson at gmail.com (Etienne Hilson) Date: Mon, 28 May 2007 20:52:11 +0200 Subject: User input with a default value that can be modified Message-ID: <194d520c0705281152t1bffe328k651181cf7d5a2004@mail.gmail.com> Hello the list :-) I do a little program that permit the user to manage list of sentences. This program runs into a linux shell. The user can add, modify and delete the sentences. What I want to do is : When the user want to modify one sentence, I would like to do this : Modify your sentence : The_sentence_appear_here_followed_by_a_cursor And the user can go back with the cursor, like in the bash shell, delete, modify, and when pressing enter, the new value (or the same if not modified) is put in my variable. Of course, the first think I did as a newbie was : new_sentence = raw_input("Modify your sentence : "old_sentence) But OF COURSE, stupid am I, the user cannot put the cursor back into the old sentence ! I think about playing with some sophisticated keyboard exercise where I could program a new input command with a value already appearing as answer, but I am pretty sure that it exists already. What do you think about it ? Actually, it is quite difficult to find anything on it, because the keywords are not very obvious (input, default answer, ...) Thank you for your help. Etienne -- (\__/) (='.'=) Ceci est un petit lapin. Copiez/collez-le dans (")_(") votre signature pour l'aider ? dominer le monde From saif.shakeel at gmail.com Tue May 15 02:00:42 2007 From: saif.shakeel at gmail.com (saif.shakeel at gmail.com) Date: 14 May 2007 23:00:42 -0700 Subject: removing spaces between 2 names Message-ID: <1179208842.114189.233060@e65g2000hsc.googlegroups.com> Hi, Suppose i have a string stored in variable,how do i remove the space between them,like if i have the name: "USDT request" in a variable.i need "USDTrequest",without any space . Thanks From gherron at islandtraining.com Mon May 7 03:25:36 2007 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 07 May 2007 00:25:36 -0700 Subject: Newbie prob: How to write a file with 3 threads? In-Reply-To: <1178522026.763041.319940@e65g2000hsc.googlegroups.com> References: <1178440537.257526.40980@y5g2000hsa.googlegroups.com> <1178485944.755068.321740@y5g2000hsa.googlegroups.com> <1178522026.763041.319940@e65g2000hsc.googlegroups.com> Message-ID: <463ED470.2010202@islandtraining.com> est wrote: > On May 7, 5:12 am, MRAB wrote: > >> On May 6, 9:51 am, Marc 'BlackJack' Rintsch wrote:> In <1178440537.257526.40... at y5g2000hsa.googlegroups.com>, est wrote: >> >>>> I need to write a file using 3 threads simutaniously, e.g. Thread 1 >>>> write the first byte of test.bin with an "a", second thread write the >>>> second byte "b", third thread write the third byte "c". Anyone could >>>> give a little example on how to do that? >>>> >>> Simplest solution is: don't do that. Write from one thread and send the >>> date from the other threads via a `Queue.Queue` to the writing thread. >>> Send the number of the thread with the data so the writer thread knows in >>> which order the data has to be written. >>> >> [snip] >> Or have a `Queue.Queue` for each source thread and make the writer >> thread read from each in turn. >> > > > I'll try Queue.Queue, thank you. I didn't expect that multithread > write a file is so troublesome > As a general rule, *ALL* multithread operations are at least that troublesome, and most are far more so. Pessimistically-yours, Gary Herron From bj_666 at gmx.net Fri May 4 11:13:50 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 04 May 2007 17:13:50 +0200 Subject: How do I get type methods? References: <1178220806.664557.245780@c35g2000hsg.googlegroups.com> <1178253260.075515.43810@q75g2000hsh.googlegroups.com> <1178283588.694886.204250@c35g2000hsg.googlegroups.com> <1178289484.265718.198060@c35g2000hsg.googlegroups.com> Message-ID: In <1178289484.265718.198060 at c35g2000hsg.googlegroups.com>, Thomas Nelson wrote: > On May 4, 7:59 am, yavanna... at yahoo.com wrote: >> Let me retype my question: what I 'dir()' in case of 'pyuno' type >> instance? >> Or in case of 'dict' type instance? Or in case of any other new python >> type? > >>>> class Foo: > ... def f(self,x): > ... print x+1 > ... def g(self,x): > ... print x-1 > ... >>>> dir(Foo) > ['__doc__', '__module__', 'f', 'g'] > > Is this not what you want? These are the only methods in the Foo > class. The OPs problem is, there is no access to the class or type because there is no name. You can get just instances from a factory function. Ciao, Marc 'BlackJack' Rintsch From antroy at gmail.com Tue May 15 10:27:23 2007 From: antroy at gmail.com (Ant) Date: 15 May 2007 07:27:23 -0700 Subject: HappyDoc, Jython and docstrings In-Reply-To: <1179227276.205531.86230@u30g2000hsc.googlegroups.com> References: <1179227276.205531.86230@u30g2000hsc.googlegroups.com> Message-ID: <1179239243.902193.128730@h2g2000hsg.googlegroups.com> On May 15, 12:07 pm, Ant wrote: > Hi All, > > I'm looking to provide online python documentation for several jython > modules: does anyone know if there are tools to create documentation > from docstrings that work in Jython? Jython doesn't provide the pydoc > module. > > I've looked into HappyDoc, which is supposed to work on jython as well Actually - don't worry. I've discovered Epydoc, which seems to work fine for jython source using the --parse-only flag. Cheers, -- Ant... http://antroy.blogspot.com/ From jzgoda at o2.usun.pl Fri May 18 06:53:43 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 18 May 2007 12:53:43 +0200 Subject: (Modular-)Application Framework / Rich-Client-Platform in Python In-Reply-To: <878xbm5s56.fsf@benfinney.id.au> References: <878xbm5s56.fsf@benfinney.id.au> Message-ID: Ben Finney napisa?(a): >> Thanks for the effort, but I think I'm not well understood. I'm not >> looking for a GUI framework (which, by the way, is most likely to be >> wxPython), but for a pure plugin architecture. A >> rich-client-platform, as it is sometimes called. Nothing specific >> about anythin in particular, just something that runs plugins. Like >> Eclipse does these days. > > I've never used Eclipse (beyond proving that it runs on various > computers). Can you please describe what behaviour you're looking for? The key is not "Eclipse" itself, but the whole Eclipse Platform. See http://wiki.eclipse.org/index.php/Rich_Client_Platform -- Jarek Zgoda "We read Knuth so you don't have to." From NikitaTheSpider at gmail.com Wed May 30 23:11:31 2007 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Wed, 30 May 2007 23:11:31 -0400 Subject: How to parse usenet urls? References: <1180573018.786188.220260@h2g2000hsg.googlegroups.com> Message-ID: In article <1180573018.786188.220260 at h2g2000hsg.googlegroups.com>, "snewman18 at gmail.com" wrote: > I'm trying to parse newsgroup messages, and I need to follow URLs in > this format: news://some.server. I can past them into a newsreader > with no problem, but I want to do it programatically. > > I can't figure out how to follow these links - anyone have any ideas? Are you aware of nntplib? http://docs.python.org/lib/module-nntplib.html -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From MrJean1 at gmail.com Thu May 3 10:58:19 2007 From: MrJean1 at gmail.com (MrJean1) Date: 3 May 2007 07:58:19 -0700 Subject: 32 OS on 64-bit machine In-Reply-To: <1178183424.548438.303170@y80g2000hsf.googlegroups.com> References: <1178183424.548438.303170@y80g2000hsf.googlegroups.com> Message-ID: <1178204299.233068.59730@p77g2000hsh.googlegroups.com> $ python Python 2.5c1 (r25c1:51305, Sep 12 2006, 08:39:50) [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-54)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import platform >>> print platform.processor() x86_64 >>> print platform.architecture() ('64bit', 'ELF') >>> This is an Opteron box running 64-bit RedHat Enterprise Lunix release 3 update 7, not 32-bit. $ uname -a Linux localhost.localdomain 2.4.21-40.EL #1 Thu Feb 2 22:20:41 EST 2006 x86_64 x86_64 x86_64 GNU/Linux /Jean Brouwers On May 3, 2:10 am, SamG wrote: > If anyone has a x86_64 machine and is running a 32bit OS on top of > that.... could you tell me what output would you get for the following > program > > #====================== > import platform > print platform.processor() > print platform.architecture() > #====================== > > Thanks in advance > : )~ From thomas.guest at gmail.com Mon May 21 15:24:43 2007 From: thomas.guest at gmail.com (tag) Date: 21 May 2007 12:24:43 -0700 Subject: doctest environment question In-Reply-To: References: <1179762737.153434.143030@b40g2000prd.googlegroups.com> Message-ID: <1179775483.685881.236940@x18g2000prd.googlegroups.com> On 21 May, 18:53, Peter Otten <__pete... at web.de> wrote: > The doctest code is executed in a module without a __name__, it seems. > Unfortunately (in this case) the builtin module serves as a fallback > helping out with its own name: > > >>> __name__ > '__main__' > >>> del __name__ > >>> __name__ > > '__builtin__' > > What to do about it? doctest could be changed to execute code snippets in a > module with a name and a sys.modules entry though I don't see much benefit > here. Peter, thanks for the quick response, but I don't quite understand what you're saying. I don't want to change doctest -- I want to find a way to make my example pass using doctest. doctest.testfile comes with lots of parameters, and I suspect if I knew how to do it I could pass in the correct parameters to make this example work. It's not what I actually want to document/test, it's a minimal example which demonstrates the problem. Thanks again. > > Peter From gerardo.maldonado at gmail.com Tue May 15 19:22:16 2007 From: gerardo.maldonado at gmail.com (Gerard M) Date: 15 May 2007 16:22:16 -0700 Subject: Issue with MySQLdb wrapper Message-ID: <1179271336.065217.75980@k79g2000hse.googlegroups.com> Hi guys I have a big problem with this wrapper im using Ubuntu 7.04 and I want to install python-MySQLdb, I used synaptics and it is installed, but when I try to do >>> import MySQLdb and I get this error: Traceback (most recent call last): File "", line 1, in File "MySQLdb/__init__.py", line 19, in import _mysql ImportError: No module named _mysql so I tried to download it from the site and install it from the .tar file but I failed because when I run #~/Desktop/MySQL-python-1.2.2$ python setup.py install I get this output: This script requires setuptools version 0.6c5 to run (even to display help). I will attempt to download it for you (from http://cheeseshop.python.org/packages/2.5/s/setuptools/), but you may need to enable firewall access for this script first. I will start the download in 15 seconds. (Note: if this machine does not have network access, please obtain the file http://cheeseshop.python.org/packages/2.5/s/setuptools/setuptools-0.6c5-py2.5.egg and place it in this directory before rerunning this script.) --------------------------------------------------------------------------- Downloading http://cheeseshop.python.org/packages/2.5/s/setuptools/setuptools-0.6c5-py2.5.egg Traceback (most recent call last): File "setup.py", line 5, in import ez_setup; ez_setup.use_setuptools() File "/home/gerardo/Desktop/MySQL-python-1.2.2/ez_setup.py", line 85, in use_setuptools import setuptools; setuptools.bootstrap_install_from = egg zipimport.ZipImportError: can't decompress data; zlib not available I dont know whats that zlib, I installed some libraries with zlib using synaptics, but still no luck :(, thanks for your help From steven.bethard at gmail.com Sun May 13 12:59:18 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 13 May 2007 10:59:18 -0600 Subject: package rating system for the Cheese Shop In-Reply-To: <1179001410.386588.35730@e51g2000hsg.googlegroups.com> References: <1178995430.511788.161150@e51g2000hsg.googlegroups.com> <1179001410.386588.35730@e51g2000hsg.googlegroups.com> Message-ID: cbtube03 at gmail.com wrote: > On May 12, 2:49 pm, Steven Bethard wrote: >> cbtub... at gmail.com wrote: >>> Is there a package rating system for the Cheese Shop, like how Perl >>> has cpanratings (http://cpanratings.perl.org/)? >> I don't know CPAN, but maybe this is what you're looking for: >> >> http://www.cheeserater.com/ >> >> ? >> >> STeVe > > Thanks for the link STeVe. Yes, this is the sort of thing I was > looking for. Looks like there's no way to actually leave comments on a > package though; just a (+) or (-) rating. No way to say something > like, "I like x, y, and z about this package, but n, m, and especially > o need to get fixed" though. > > One strength of cpanratings is you can leave those comments. A well- > written review comment, like "I used this package, and here's how it > worked out ... If you need , you might try y> instead of this one." is much more valuable than a thumbs-up or > thumbs-down. It might be worth sending those comments to whoever maintains that site. Looks like either "Jacob Kaplan-Moss" (http://www.jacobian.org/) or "Jeff Croft" (http://www.jeffcroft.com/) STeVe From ready.or.special3 at gmail.com Mon May 14 14:13:31 2007 From: ready.or.special3 at gmail.com (ready.or.special3 at gmail.com) Date: 14 May 2007 11:13:31 -0700 Subject: =// Homeland Security on High Alert!! Message-ID: <1179166411.536148.186120@w5g2000hsg.googlegroups.com> http://freewindowsvista.blogspot.com/ - With a class action lawsuit looming, three politicians question the head of the Department of Homeland Security about the lost hard drive. The laptop was never found... From Graham.Dumpleton at gmail.com Tue May 1 01:28:49 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: 30 Apr 2007 22:28:49 -0700 Subject: re-importing modules In-Reply-To: References: <8%pZh.18192$Kd3.76@newssvr27.news.prodigy.net> <1177962288.575008.48490@q75g2000hsh.googlegroups.com> <1177967919.968338.3300@l77g2000hsb.googlegroups.com> Message-ID: <1177997329.701861.143290@e65g2000hsc.googlegroups.com> On May 1, 2:17 pm, Steven D'Aprano wrote: > On Tue, 01 May 2007 00:32:20 +0000, John Nagle wrote: > > kyoso... at gmail.com wrote: > > >>>In addition to the warning that reload() does not recursively reload > >>>modules that the reloaded module depends on, be warned that reloading a > >>>module does not magically affect any functions or objects from the old > >>>version that you may be holding on to. > > > Maybe reloading modules should be deprecated. The semantics > > are awful, and it interferes with higher-performance implementations. > > I'd hate for reload to disappear, it is great for interactive > development/debugging, at least under some circumstances. (If you have > complex and tangled class hierarchies, it might not be powerful enough.) > > As for the semantics being awful, I disagree. reload() does exactly > what it claims to do, no more, no less. I wouldn't expect reload(module1) > to reload modules 2 through 5 just because they were imported by module1. > If I wanted them reloaded, I'd say so. That it doesn't reload a parent when a child changes may be fine in an interactive debugger, but can cause problems if not done where automatic reloading is being done in a long running web application where you want to avoid server restarts. For that very reason, the new importer in mod_python 3.3 tracks parent/child relationships between modules and is able to import a parent module when a child changes. The new importer does a lot more besides that as well, including distinguishing modules by full path rather than purely by name. For some details on the mod_python importer see documentation for import_module() in: http://www.modpython.org/live/current/doc-html/pyapi-apmeth.html To understand why the new importer does some of the things it does, it may be helpful to read all the problems the previous importer was causing: http://www.dscpl.com.au/wiki/ModPython/Articles/ModuleImportingIsBroken Getting module importing with reloading working is frightfully tricky in an application where multiple threads corresponding to concurrent web requests are executing as one can't be reloading on top of modules where code may be executing, one must also avoid triggering a reload of a specific module half way through a request where the same module is encountered twice and lots, plus lots of other gotchas. Graham From gagsl-py2 at yahoo.com.ar Fri May 4 00:54:54 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 04 May 2007 01:54:54 -0300 Subject: Replacement for HTMLGen? References: <463a70b1$0$16345$88260bb3@free.teranews.com> Message-ID: En Thu, 03 May 2007 21:23:42 -0300, Joshua J. Kugler escribi?: > I found http://dustman.net/andy/python/HyperText, but it's not listed in > Cheeseshop, and its latest release is over seven years ago. Granted, I > know HTML doesn't change (much) but it's at least nice to know something > you're going to be using is maintained. I use HyperText, and if it's not maintained so much, it's because it does not have to change. BTW, it's amazing how much can you get from so many classes with just a "pass" statement. -- Gabriel Genellina From pollastri at iriti.cnr.it Fri May 25 05:12:14 2007 From: pollastri at iriti.cnr.it (Fabrizio Pollastri) Date: Fri, 25 May 2007 11:12:14 +0200 Subject: method override inside a module Message-ID: <4656A86E.5040602@iriti.cnr.it> Hello, I am trying to override a method of a class defined into an imported module, but keeping intact the namespace of the imported module. For example, let suppose import module_X and in module_X is defined something like class A: ... def method_1(): ... ... I wish to override method_1 with a new function and to call the overrided method inside my application with the same name of the original method like ... module_X.method_1() ... Thanks in advance for any help. Regards, F. Pollastri. From stefan.behnel-n05pAM at web.de Tue May 15 02:23:43 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 15 May 2007 08:23:43 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <7xd512onsx.fsf@ruckus.brouhaha.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1hy2qg3.iqfvwnrvr9kjN%aleax@mac.com> <46482624.6050507@web.de> <7xd512onsx.fsf@ruckus.brouhaha.com> Message-ID: <464951EF.7030900@web.de> Paul Rubin wrote: > Stefan Behnel writes: >> But then, where's the problem? Just stick to accepting only patches that are >> plain ASCII *for your particular project*. > > There is no feature that has ever been proposed for Python, that cannot > be supported with this argument. If you don't like having a "go to" > statement added to Python, where's the problem? Just don't use it in > your particular project. "go to" is not meant for clarity, nor does it encourage code readability. But that's what this PEP is about. Stefan From sjdevnull at yahoo.com Mon May 7 13:36:14 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 7 May 2007 10:36:14 -0700 Subject: how do you implement a reactor without a select? In-Reply-To: <1178543812.260333.39280@w5g2000hsg.googlegroups.com> References: <1178543812.260333.39280@w5g2000hsg.googlegroups.com> Message-ID: <1178559374.393874.113460@l77g2000hsb.googlegroups.com> Michele Simionato wrote: > Notice that I copied the Twisted terminology, but > I did not look at Twisted implementation because I did not want to > use a select (I assume that the GUI mainloops do not use it either). > The trick I use is to store the actions to perform (which are > callables identified by an integer) in an event dictionary and > to run them in the mainlooop if the current time is greater than > the scheduled time. > I had to add a time.sleep(.001) call in the default_action to avoid > consuming 100% > of the CPU in the loop. Busy-looping like that is ugly and inefficient, even with the sleep thrown in. Most GUI main loops _do_ use either select() or poll(). When Xt/GTK/ Qt/etc have function like "gtk_add_input" which takes an fd that you'll get notified about if it's written to while you're in the main loop, that's just adding another fd to the select() loop. There are other ways to wait for events on an fd, but they tend to be less portable. Depending on your Unix flavor, epoll, /dev/poll, kqueues, kevent, queued realtime signals, or something else might be available from the OS (but probably not from Python without futzing with ctypes or writing an extension). If you want details, check out http://www.kegel.com/c10k.html The alternatives usually aren't really faster unless you have hundreds of connections, though--select/poll have major portability advantages, so go with them unless you have a compelling reason. From listserver at tdw.net Fri May 4 07:06:04 2007 From: listserver at tdw.net (Tim Williams) Date: Fri, 4 May 2007 12:06:04 +0100 Subject: How to check if a string is empty in python? In-Reply-To: References: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> <1178138964.503290.254060@o5g2000hsb.googlegroups.com> <1178139155.260722.153750@n59g2000hsh.googlegroups.com> <463a31c0$0$6845$c3e8da3@news.astraweb.com> <1178224237.326531.254130@o5g2000hsb.googlegroups.com> Message-ID: <9afea2ac0705040406r2cc0fee1lf03eac4dd7c50a34@mail.gmail.com> On 4 May 2007 03:02:37 -0700, Jaswant wrote: > This is a simple way to do it i think > > > s=hello > > >>> if(len(s)==0): > .... print "Empty" > .... else: > .... print s > .... > hello Not as simple as " If not s: " and nowhere near as simple as " print s or 'Empty' " :) :) >>> s = '' >>> print s or 'Empty' Empty >>> s = 'hello' >>> print s or 'Empty' hello >>> From ed at leafe.com Mon May 28 21:12:13 2007 From: ed at leafe.com (Ed Leafe) Date: Mon, 28 May 2007 21:12:13 -0400 Subject: gui application on cross platform In-Reply-To: <1180332092.551838.258440@z28g2000prd.googlegroups.com> References: <1180332092.551838.258440@z28g2000prd.googlegroups.com> Message-ID: <79D09063-A8B4-4373-A15E-A5CC909DE622@leafe.com> On May 28, 2007, at 2:01 AM, james_027 wrote: > I am using delphi to develop gui application, and wish to make a shift > to python. here are some of my question/concern... > > 1. is python develop gui application a cross platform? just like java > swing? wxPython is probably the best cross-platform GUI toolkit available for Python. That's why we chose it for our primary UI toolkit for Dabo. > 2. delphi makes things easy for me like coding for a specific event on > a specific component, could it be the same for python? Not in Python per se, but I know exactly what you mean. I come from the Visual FoxPro world, which is very similar to Delphi. I stumbled upon Python, and quickly discovered that it was far and away the best language I've programmed in in over 3 decades of coding. Yet it lacked anything like the power of GUI development that tools such as Delphi or Visual FoxPro offered. So along with my partner Paul McNett, we set out to create such a tool, and that is Dabo. > 3. are there cool library of component like in delphi available for > python that will make database application more usesable? One word: Dabo. We do database apps. > 4. where do I start the learning curve? I did some research and I > don't know which one to take among wxwdiget, pygtk, and etc. Check out our collection of screencasts to see what Dabo can do for you (http://dabodev.com/documentation). Post messages to the dabo- users list to get answers to any questions you might have (sign up at http://leafe.com/mailman/listinfo/dabo-users). There are a ton of web frameworks out there. But for Python, there is only one desktop app framework: Dabo. -- Ed Leafe -- http://leafe.com -- http://dabodev.com From basilisk96 at gmail.com Tue May 1 18:09:00 2007 From: basilisk96 at gmail.com (Basilisk96) Date: 1 May 2007 15:09:00 -0700 Subject: Removing the continous newline characters from the pythong string In-Reply-To: <1178056233.225222.163330@p77g2000hsh.googlegroups.com> References: <1178055012.135278.104430@p77g2000hsh.googlegroups.com> <1178056233.225222.163330@p77g2000hsh.googlegroups.com> Message-ID: <1178057340.432353.216130@p77g2000hsh.googlegroups.com> What was I thinking? split() will only work if you have no other whitespace characters in the string. A regex like "[\n\r]+" is indeed much more appropriate and robust. Cheers -Basilisk96 From thomas.guest at gmail.com Tue May 22 07:56:29 2007 From: thomas.guest at gmail.com (tag) Date: 22 May 2007 04:56:29 -0700 Subject: doctest environment question In-Reply-To: References: <1179762737.153434.143030@b40g2000prd.googlegroups.com> <1179775483.685881.236940@x18g2000prd.googlegroups.com> <1179818466.394663.222390@k79g2000hse.googlegroups.com> Message-ID: <1179832319.597782.166310@z28g2000prd.googlegroups.com> On 22 May, 10:11, "Gabriel Genellina" wrote: > The version given by Peter Otten may do what you want, but I'd consider if > you really need an announce_function in the first place, given all the > other ways you already have to do the same thing. > Implicitely rebinding globals does not look good. Thanks for the advice Gabriel. The use case I have is that I'd like to be able to decorate classes and even modules in this way: >>> import announce >>> import spam >>> announce.announce_module(spam) Here, "announce.announce_module" has a look in "spam", finds all the functions and instancemethods, and decorates them (rebinds them) by announcing calls to these functions and instancemethods. It's something I've found useful, though clearly the behaviour of "spam" has been drastically changed. I'd appreciate advice on better ways to achieve this kind of thing, or why it doesn't look good. From mail at timgolden.me.uk Tue May 8 06:18:38 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 08 May 2007 11:18:38 +0100 Subject: Can Python Parse an MS SQL Trace? In-Reply-To: <1178547517.938939.201490@w5g2000hsg.googlegroups.com> References: <1178544236.856685.288740@y80g2000hsf.googlegroups.com> <1178547517.938939.201490@w5g2000hsg.googlegroups.com> Message-ID: <46404E7E.50102@timgolden.me.uk> kyosohma at gmail.com wrote: > On May 7, 8:34 am, Tim Golden wrote: >> kyoso... at gmail.com wrote: >>> Can Python parse a trace file created with MS SQL's profiler? There >>> are a few thousand lines in the trace file and I need to find the >>> insert statements and the stored procedures. Unfortunately, I am not >>> an SQL guru and was hoping Python could help. >>> Mike >> Mike, >> >> Can I suggest that, since the answer is more to >> do with parsing and less to do with MSSQL (which >> simply generated the output) that you post an example >> of a trace file to some web location to see if anyone >> wants to pick up the challenge? >> >> I'm not at work so I don't have access to MSSQL, but >> I seem to remember that you can output/save as XML, >> which may make things easier (or at least interest a >> different group of people in having a look). >> >> I'm quite certain it can by done by Python; I did >> consider it myself a couple of months back, but my >> colleague spotted the problem before I'd really got >> into the code! >> >> TJG > > Good point. Unfortunately, I think our SQL Server must be too old for > xml (we have version 8). The only save options I see is Trace > Template, Trace File, Trace Table and SQL Script. Yes, you're right; I have clients installed for SQL 2000 & 2005 and it's only under 2005 that I have the XML output option. The .trc file format is pretty much opaque binary, and the .sql output only gives you the SQL statements issued - not the events they're associated with. One obvious way is to save it to a table and to interrogate that table. I find that kind of thing a bit cumbersome, but if XML's not an option, it might be the only way. (FWIW, I find XML cumbersome too, but that might just be lack of practice ;) Running a standard trace and saving to a table, this is the structure which resulted: CREATE TABLE [trace_output] ( [RowNumber] [int] IDENTITY (1, 1) NOT NULL , [EventClass] [int] NULL , [TextData] [ntext] COLLATE SQL_Latin1_General_CP1_CS_AS NULL , [NTUserName] [nvarchar] (128) COLLATE SQL_Latin1_General_CP1_CS_AS NULL , [ClientProcessID] [int] NULL , [ApplicationName] [nvarchar] (128) COLLATE SQL_Latin1_General_CP1_CS_AS NULL , [LoginName] [nvarchar] (128) COLLATE SQL_Latin1_General_CP1_CS_AS NULL , [SPID] [int] NULL , [Duration] [bigint] NULL , [StartTime] [datetime] NULL , [Reads] [bigint] NULL , [Writes] [bigint] NULL , [CPU] [int] NULL , PRIMARY KEY CLUSTERED ( [RowNumber] ) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO Seems like you might be able to do something with it. (Possibly just dumping it straight back out to CSV or XML if that's easier for you than db querying) TJG From grante at visi.com Tue May 8 11:02:06 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 08 May 2007 15:02:06 -0000 Subject: File Name Format References: Message-ID: <134147e2gsg6v35@corp.supernews.com> On 2007-05-08, Anand wrote: > How do I convert programmatically the file names from WIN32 to UNIX format? You don't need to. AFAIK, all legal WIN32 filenames are legal UNIX file names. > A code snippet would be of great help. As would an example of what you're trying to do. -- Grant Edwards grante Yow! JAPAN is a WONDERFUL at planet -- I wonder if we'll visi.com ever reach their level of COMPARATIVE SHOPPING ... From bj_666 at gmx.net Thu May 10 11:30:16 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 10 May 2007 17:30:16 +0200 Subject: trouble with generators References: Message-ID: In , Hans-Peter Jansen wrote: > class Gen(object): > def records(self, cls): > for i in range(3): > setattr(cls, "id", "%s%s" % (cls.__doc__, i)) > yield cls > > [?] > > class GenA(Gen): > def __init__(self): > self.genB = GenB() > > def records(self): > for a in Gen.records(self, A()): Here you create an instance of `A` and pass that *instance* and not the *class*. If you would pass the class here, you must create objects in `Gen.records()`. Ciao, Marc 'BlackJack' Rintsch From phd at phd.pp.ru Thu May 3 09:29:06 2007 From: phd at phd.pp.ru (Oleg Broytmann) Date: Thu, 3 May 2007 17:29:06 +0400 Subject: SQLObject 0.7.6 Message-ID: <20070503132906.GB9945@phd.pp.ru> Hello! I'm pleased to announce the 0.7.6 release of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.7.6 News and changes: http://sqlobject.org/docs/News.html What's New ========== News since 0.7.5 ---------------- Bug Fixes --------- * Fixed a longstanding bug with .select() ignoring 'limit' parameter. * Fixed a bug with absent comma in JOINs. * Fixed sqlbuilder - .startswith(), .endswith() and .contains() assumed their parameter must be a string; now you can pass an SQLExpression: Table.q.name.contains(func.upper('a')), for example. * Fixed a longstanding bug in sqlbuilder.Select() with groupBy being a sequence. * Fixed a bug with Aliases in JOINs. * Yet another patch to properly initialize MySQL connection encoding. * Fixed a minor comparison problem in test_decimal.py. Docs ---- * Added documentation about 'validator' Col constructor option. * More documentation about orderBy. For a more complete list, please see the news: http://sqlobject.org/docs/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From laurent.pointal at wanadoo.fr Thu May 3 13:55:37 2007 From: laurent.pointal at wanadoo.fr (Laurent Pointal) Date: Thu, 03 May 2007 19:55:37 +0200 Subject: [ANN] Update to Python Quick Reference Card (for Python 2.4) (v0.67) References: <4bnh33pb644j9qsvij3citqrpb2bmqlsu4@4ax.com> <4638e8a8$0$27396$ba4acef3@news.orange.fr> <1hxiay0.17x1upmcmvc46N%aleax@mac.com> Message-ID: <463a20cc$0$25950$ba4acef3@news.orange.fr> Alex Martelli wrote: > Laurent Pointal wrote: > >> Casey Hawthorne wrote: >> >> > PC-cillin flagged this as a dangerous web site. >> >> Maybe PC-cillin tag as dangerous all sites about Python, the famous >> snake. >> >> >> PS. And why does it tag my laboratory work page as dangerous ? It's pure >> HTML, I worked to have even no javascript, readable with lynx. > > It's an excellent quick-reference card, BTW (though I don't quite > understand why even-numbered pages are flipped upside-down). At work I print it on horizontal A4/USLetter, with recto-back, and with binding (reliure in french) on small side of paper. With ad-hoc folding, it would make a little book with one column width... any publisher in the newsgroup ? A+ Laurent. From alan.franzoni_invalid at geemail.invalid Wed May 23 07:19:44 2007 From: alan.franzoni_invalid at geemail.invalid (Alan Franzoni) Date: Wed, 23 May 2007 13:19:44 +0200 Subject: Basic Class/Instance Question References: <1179918439.085344.171330@u30g2000hsc.googlegroups.com> Message-ID: <1vodj8x0pt1ow$.wi599psulrjv.dlg@40tude.net> Il 23 May 2007 04:07:19 -0700, Siah ha scritto: > Ready to go insane here. Class A, taking on a default value for a __init__ is a function, taking a default value of [], which is a list, which is a mutable object. That said, you should remember that this means that such default value is 'shared' between all instances. If you don't want that, do something like: def __init__(self, defaultvalue=None): if defaultvalue is None: defaultvalue=[] http://docs.python.org/tut/node6.html#SECTION006710000000000000000 -- Alan Franzoni - Togli .xyz dalla mia email per contattarmi. Remove .xyz from my address in order to contact me. - GPG Key Fingerprint (Key ID = FE068F3E): 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From inq1ltd at verizon.net Tue May 29 10:59:00 2007 From: inq1ltd at verizon.net (jim-on-linux) Date: Tue, 29 May 2007 10:59:00 -0400 Subject: python unix install, sqlite3 In-Reply-To: <1180443141.119281.304880@q66g2000hsg.googlegroups.com> References: <1180443141.119281.304880@q66g2000hsg.googlegroups.com> Message-ID: <200705291059.00555.inq1ltd@verizon.net> On Tuesday 29 May 2007 08:52, Simon wrote: > I installed the source code on unix for python > 2.5.1. The install went mainly okay, except for > some failures regarding: _ssl, _hashlib, > _curses, _curses_panel. > > No errors regarding sqlite3. > However, when I start python and do an import > sqlite3 I get: > > /ptmp/bin/> python > Python 2.5.1 (r251:54863, May 29 2007, > 05:19:30) [GCC 3.3.2] on sunos5 > Type "help", "copyright", "credits" or > "license" for more information. > > >>> import sqlite3 > I'm using python 2.5 on linux and it works fine Try; import sqlite3 in place of from sqlite3 import * jim-on-linux http://www.inqvista.com > Traceback (most recent call last): > File "", line 1, in > File > "/ptmp/Python-2.5.1/lib/python2.5/sqlite3/__ini >t__.py", line 24, in > from dbapi2 import * > File > "/ptmp/Python-2.5.1/lib/python2.5/sqlite3/dbapi >2.py", line 27, in > from _sqlite3 import * > ImportError: No module named _sqlite3 From sturlamolden at yahoo.no Wed May 2 17:40:21 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 2 May 2007 14:40:21 -0700 Subject: Lazy evaluation: overloading the assignment operator? In-Reply-To: References: <1178133344.415521.118710@n76g2000hsh.googlegroups.com> Message-ID: <1178142021.745136.207810@l77g2000hsb.googlegroups.com> On May 2, 9:46 pm, Stargaming wrote: > > del tmp2 > > y = tmp3 # tmp3 gets evaluated as assignment is overloaded > > To allow lazy evaluation, you need overloading of the assignment > operator? No I don't. I could for example delay evaluation until some data from y is requested, say when x = y[5] is executed. However, that can allow mutual dependencies between unevaluated expressions. These can be complicated to resolve, and is an issue similar to to that of cyclic dependencies in reference counting. With an overloaded assignment operator, we would avoid this as assignments are natural places to flush lazy evaluations. No dangling unevaluated expression would be produced, and thus there would be no strange bugs of this sort. > Where should you overload it? y is less than None when you do > that assignment. In this case, I am not suggesting overloading y = but rather overloading = tmp3 That is, when a variable is bound to an object, a method is called (e.g. __get__) and the variable gets the return value output from that function instead. It is analogous to the __get__ method of descriptors. COnsider happens when we call a = someObject.someProperty and someProperty has a __get__ method. Even if a is less than None, we still get a call to __get__. On the other hand, if y had been bound to a value before hand, it would be meaningful to call a method called __set__ on y when y = tmp3 is executed. Just like someObject.someProperty = value would call __set__ on someProperty if it had one. Obviously if someObject.someProperty had been unbound, there would have been no call to __set__. So I am suggesting generalising __set__ and __get__ to overload the assignment operator. This would be an example: class Foo(object): def __init__(self): self.value = None def __set__(self,value): ''' overloads bar = value after bar = Foo()''' self.value = value def __get__(self): ''' overloads obj = bar after bar = Foo()''' return self.value So it is just a generalization of the already existing descriptors. It even makes descriptors and properties easier to understand. > I don't really see the need for overloading here. > Following the binding rules, __mul__ would (even without any hackery) be > evaluated before __add__. Yes, but at the cost of generating several temporary arrays and looping over the same memory several times. If the assignment operator could be overloaded, we could avoid the temporary objects and only have one loop. For numerical code, this can mean speed ups in the order of several magnitudes. Sturla Molden > > > > Should there be a PEP to overload the assignment operator? > > If -- after this discussion -- community seems to like this feature, you > could try to come up with some patch and a PEP. But not yet. > > > In terms of > > syntax, it would not be any worse than the current descriptor objects > > - but it would make lazy evaluation idioms a lot easier to implement. > > -- > Stargaming From johnjsal at NOSPAMgmail.com Tue May 8 15:05:18 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 08 May 2007 15:05:18 -0400 Subject: Suggestions for how to approach this problem? Message-ID: <4640ca5b$0$23392$c3e8da3@news.astraweb.com> I figured I might give myself a little project to make my life at work easier, so here's what I want to do: I have a large list of publication citations that are numbered. The numbers are simply typed in with the rest of the text. What I want to do is remove the numbers and then put bullets instead. Now, this alone would be easy enough, with a little Python and a little work by hand, but the real issue is that because of the way these citations were typed, there are often line breaks at the end of each line -- in other words, the person didn't just let the line flow to the next line, they manually pressed Enter. So inserting bullets at this point would put a bullet at each line break. So I need to remove the line breaks too, but of course not *all* of them because each reference still needs a line break between it. So I'm hoping I could get an idea or two for approaching this. I figure regular expressions will be needed, and maybe it would be good to remove the line breaks first and *not* remove a line break that comes before the numbers (because that would be the proper place for one), and then finally remove the numbers. Thanks. From deets at nospam.web.de Tue May 1 17:14:12 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 01 May 2007 23:14:12 +0200 Subject: How can I get the ascii code of a charter in python? In-Reply-To: <1178053581.390873.65850@n76g2000hsh.googlegroups.com> References: <1178053581.390873.65850@n76g2000hsh.googlegroups.com> Message-ID: <59pot5F2jtk6gU1@mid.uni-berlin.de> tedpottel at gmail.com schrieb: > Hi, > a python newbe needs some help, > > I read the python doc at > http://docs.python.org/lib/module-curses.ascii.html > > I tried > Import curses.asciicurses.ascii > Print ascii('a') > > I get an error saying module curses.ascii8 does not exsist. > > How can I get the ascii code of a charter in python? ord('A') == 65 Diez From thomas.guest at gmail.com Tue May 22 07:57:29 2007 From: thomas.guest at gmail.com (tag) Date: 22 May 2007 04:57:29 -0700 Subject: doctest environment question In-Reply-To: References: <1179762737.153434.143030@b40g2000prd.googlegroups.com> <1179775483.685881.236940@x18g2000prd.googlegroups.com> <1179818466.394663.222390@k79g2000hse.googlegroups.com> Message-ID: <1179832577.759863.164860@z24g2000prd.googlegroups.com> On 22 May, 10:11, "Gabriel Genellina" wrote: > The version given by Peter Otten may do what you want, but I'd consider if > you really need an announce_function in the first place, given all the > other ways you already have to do the same thing. > Implicitely rebinding globals does not look good. Thanks for the advice Gabriel. The use case I have is that I'd like to be able to decorate classes and even modules in this way: import announce import spam announce.announce_module(spam) ... code which calls into spam module Here, "announce.announce_module" has a look in "spam", finds all the functions and instancemethods, and decorates them (rebinds them) by announcing calls to these functions and instancemethods. It's something I've found useful, though clearly the behaviour of "spam" has been drastically changed. I'd appreciate advice on better ways to achieve this kind of thing, or why it doesn't look good. From sjmachin at lexicon.net Sat May 19 19:23:28 2007 From: sjmachin at lexicon.net (John Machin) Date: Sun, 20 May 2007 09:23:28 +1000 Subject: regex matching question In-Reply-To: <1179595319.239229.262160@l77g2000hsb.googlegroups.com> References: <1179595319.239229.262160@l77g2000hsb.googlegroups.com> Message-ID: <464F86F0.8080100@lexicon.net> On 20/05/2007 3:21 AM, bullockbefriending bard wrote: > first, regex part: > > I am new to regexes and have come up with the following expression: > ((1[0-4]|[1-9]),(1[0-4]|[1-9])/){5}(1[0-4]|[1-9]),(1[0-4]|[1-9]) > > to exactly match strings which look like this: > > 1,2/3,4/5,6/7,8/9,10/11,12 > > i.e. 6 comma-delimited pairs of integer numbers separated by the > backslash character + constraint that numbers must be in range 1-14. Backslash? Your example uses a [forward] slash. Are you sure you don't want to allow for some spaces in the data, for the benefit of the humans, e.g. 1,2 / 3,4 / 5,6 / 7,8 / 9,10 / 11,12 ? > > i should add that i am only interested in finding exact matches (doing > some kind of command line validation). > > this seems to work fine, although i would welcome any advice about how > to shorten the above. it seems to me that there should exist some > shorthand for (1[0-4]|[1-9]) once i have defined it once? > > also (and this is where my total beginner status brings me here > looking for help :)) i would like to add one more constraint to the > above regex. i want to match strings *iff* each pair of numbers are > different. e.g: 1,1/3,4/5,6/7,8/9,10/11,12 or > 1,2/3,4/5,6/7,8/9,10/12,12 should fail to be matched by my final > regex whereas 1,2/3,4/5,6/7,8/9,10/11,12 should match OK. > > any tips would be much appreciated - especially regarding preceding > paragraph! > > and now for the python part: > > results = "1,2/3,4/5,6/7,8/9,10/11,12" > match = re.match("((1[0-4]|[1-9]),(1[0-4]|[1-9])/){5}(1[0-4]|[1-9]), > (1[0-4]|[1-9])", results) Always use "raw" strings for patterns, even if you don't have backslashes in them -- and this one needs a backslash; see below. For clarity, consider using "mobj" or even "m" instead of "match" to name the result of re.match. > if match == None or match.group(0) != results: Instead of if mobj == None .... use if mobj is None ... or if not mobj ... Instead of the "or match.group(0) != results" caper, put \Z (*not* $) at the end of your pattern: mobj = re.match(r"pattern\Z", results) if not mobj: HTH, John From manatlan at gmail.com Sat May 12 09:34:48 2007 From: manatlan at gmail.com (manatlan) Date: 12 May 2007 06:34:48 -0700 Subject: Dynamic subclassing ? Message-ID: <1178976888.443891.116090@y80g2000hsf.googlegroups.com> I've got an instance of a class, ex : b=gtk.Button() I'd like to add methods and attributes to my instance "b". I know it's possible by hacking "b" with setattr() methods. But i'd like to do it with inheritance, a kind of "dynamic subclassing", without subclassing the class, only this instance "b" ! In fact, i've got my instance "b", and another class "MoreMethods" class MoreMethods: def sayHello(self): print "hello" How could i write ... "b = b + MoreMethods" so "b" will continue to be a gtk.Button, + methods/attributs of MoreMethods (it's what i call "dynamic inheritance") ...so, things like this should work : - b.set_label("k") - b.sayHello() I can't find the trick, but i'm pretty sure it's possible in an easy way. Help is welcome thanx From siona at chiark.greenend.org.uk Wed May 30 08:29:27 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 30 May 2007 13:29:27 +0100 (BST) Subject: Rats! vararg assignments don't work References: Message-ID: <33t*jU1Lr@news.chiark.greenend.org.uk> samwyse wrote: >> samwyse wrote: >>>I thought that I'd try this: >>> first, *rest = arglist >>>Needless to say, it didn't work. > [ ... ] >My use-case is (roughtly) this: > first, *rest = f.readline().split() > return dispatch_table{first}(*rest) first, rest = f.readline().split(None, 1) return dispatch_table{first}(*rest.split()) -- \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 aleax at mac.com Mon May 14 02:00:17 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 13 May 2007 23:00:17 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <1hy2qg3.iqfvwnrvr9kjN%aleax@mac.com> Aldo Cortesi wrote: > Thus spake Steven D'Aprano (steven at REMOVE.THIS.cybersource.com.au): > > > If you're relying on cursory visual inspection to recognize harmful code, > > you're already vulnerable to trojans. > > What a daft thing to say. How do YOU recognize harmful code in a patch > submission? Perhaps you blindly apply patches, and then run your test suite on > a quarantined system, with an instrumented operating system to allow you to > trace process execution, and then perform a few weeks worth of analysis on the > data? > > Me, I try to understand a patch by reading it. Call me old-fashioned. I concur, Aldo. Indeed, if I _can't_ be sure I understand a patch, I don't accept it -- I ask the submitter to make it clearer. Homoglyphs would ensure I could _never_ be sure I understand a patch, without at least running it through some transliteration tool. I don't think the world of open source needs this extra hurdle in its path. Alex From maxm at mxm.dk Fri May 25 07:33:11 2007 From: maxm at mxm.dk (Max M) Date: Fri, 25 May 2007 13:33:11 +0200 Subject: Xml parser In-Reply-To: References: Message-ID: <4656c97c$0$52158$edfadb0f@dread11.news.tele.dk> ashish skrev: > Hi All, > > I want to know weather is there any api available in python for parsing > xml(XML parser) I have had very good succes with lxml -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From cjames at callone.net Mon May 14 09:49:48 2007 From: cjames at callone.net (c james) Date: Mon, 14 May 2007 08:49:48 -0500 Subject: multi threaded SimpleXMLRPCServer In-Reply-To: <46483122.2030901@swsoft.com> References: <46483122.2030901@swsoft.com> Message-ID: I use a variation of the following. Clean and straight forward. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/425043 Vyacheslav Maslov wrote: > Hi, all! > > I need multi threaded version of SimpleXMLRPCServer. Does python library > already have implementation of this one? Or i need to implement multi > threading by myself? > > Which way is the simpliest? From marco.colombo at gmail.com Tue May 15 11:20:31 2007 From: marco.colombo at gmail.com (Marco Colombo) Date: 15 May 2007 08:20:31 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179236673.893122.28800@w5g2000hsg.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> Message-ID: <1179242431.660213.10840@k79g2000hse.googlegroups.com> On 15 Mag, 15:44, George Sakkis wrote: > After 175 replies (and counting), the only thing that is clear is the > controversy around this PEP. Most people are very strong for or > against it, with little middle ground in between. I'm not saying that > every change must meet 100% acceptance, but here there is definitely a > strong opposition to it. Accepting this PEP would upset lots of people > as it seems, and it's interesting that quite a few are not even native > english speakers. > > George I see very few people against this PEP. Most objections are against: 1) the use of non-English words for indentifiers; 2) embedding non-ASCII characters in source files (PEP263); 3) writing unreadable code (for English-speaking readers). None of the above is covered by this PEP. Let's face that identifiers are just a small part of the information conveyed by a program source. All the rest can *already* be totally unreadable to an English speaker, or even undisplayable on his monitor. There's no real reason to force ASCII-only identifiers UNLESS we also force ASCII-only programs. I doubt any program containing Chinese comments, with Chinese characters, (which we allow), Chinese strings (which we allow), identifiers that are Chinese words, written with ASCII characters, (which we allow) is made any LESS readable by writing those identifiers with Chinese characters too. But it *is* more readable to someone speaking Chinese! For sure it's easier for them to read their words with their own glyphs instead of being forced to spell them with a foreign alphabet. .TM. From showell30 at yahoo.com Sun May 27 10:02:58 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 27 May 2007 07:02:58 -0700 (PDT) Subject: totally lost newbie In-Reply-To: Message-ID: <313388.5424.qm@web33509.mail.mud.yahoo.com> --- Marc 'BlackJack' Rintsch wrote: > > Maybe it's easier to use a key function instead of a > compare function. A > key function receives an element and must return > something that is then > sorted and the element ends up where the computed > key is in the sorted > list. Little example for sorting a list of strings > first by length and > strings of the same length by alphabetical order: > > def key_func(item): > return (len(item), item) > > data = ['viking', 'spam', 'parrot', 'ham', 'eric'] > data.sort(key=key_func) > print data > Marc, when did the key feature get introduced, 2.4 or 2.5? I'm asking on behalf of the newbie, who's going to struggle with your solution if he's still running 2.3. ____________________________________________________________________________________Fussy? Opinionated? Impossible to please? Perfect. Join Yahoo!'s user panel and lay it on us. http://surveylink.yahoo.com/gmrs/yahoo_panel_invite.asp?a=7 From thorsten at thorstenkampe.de Tue May 15 09:24:03 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 15 May 2007 14:24:03 +0100 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476081.7080609@web.de> <46498514$0$6402$9b4e6d93@newsspool2.arcor-online.net> <4649882E.3060005@web.de> <46499940$0$10199$9b4e6d93@newsspool4.arcor-online.net> <46499BF9.30209@web.de> <4649a2c1$0$10193$9b4e6d93@newsspool4.arcor-online.net> <4649A429.3010406@web.de> <4649ae4a$0$20289$9b4e6d93@newsspool3.arcor-online.net> <4649AF84.7010208@web.de> <4649b22c$0$20289$9b4e6d93@newsspool3.arcor-online.net> Message-ID: * Ren? Fleschenberg (Tue, 15 May 2007 15:14:20 +0200) > Stefan Behnel schrieb: > > That's easy to prevent: just keep your fingers from projects that work with > > them and make sure that projects you start do not use them. > > You keep bringing up that argument that completely neglects reality. The > same argument can be used to justify anything else (including the > opposite of your position: Don't like the fact that Python does not > support non-ASCII identifiers? Pick another language!). Let's introduce > gotos and all other kinds of funny stuff -- after all, noone is forced > to work on a project that uses it! You are right, except that using the correct characters for words is not a "funny thing". Using Polish diacritics (for example) for identifier names just makes sense for a project that already uses polish comments and polish names for their code. You will never get in touch with that. Using the right charset for these polish words doesn't change a bit in your ability to debug or understand this code. From iddw at hotmail.com Wed May 30 20:29:20 2007 From: iddw at hotmail.com (Dave Hansen) Date: 30 May 2007 17:29:20 -0700 Subject: Is PEP-8 a Code or More of a Guideline? In-Reply-To: References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <87abvqpl6v.fsf@benfinney.id.au> Message-ID: <1180571360.883706.244950@q66g2000hsg.googlegroups.com> Apologies for jumping into the thread late. On May 27, 3:25 pm, Roy Smith wrote: > Ben Finney wrote: > > Is C no longer a "major" language? The long-standing convention there > > is for lower_case_with_underscores. > > Which dates back to the days of ASR-33's which only had one case (upper The date is about right (actually, a little early: ASR-33, 1965; C, about 1970), but you can't program C on an ASR-33. Keywords are all lower case, and always have been. "IF" is a syntax error... > case, as a matter of fact). Does nobody else remember C compilers which > accepted \( and \) for { and }? I don't, but modern conforming compilers are supposed to accept ??< or <% for { and ??> or %> for }. Makes it awful hard to read, though, IMHO. Regards, -=Dave P.S. CamelCase sucks. ;-) From saif.shakeel at gmail.com Mon May 14 05:56:17 2007 From: saif.shakeel at gmail.com (saif.shakeel at gmail.com) Date: 14 May 2007 02:56:17 -0700 Subject: Element tree errors Message-ID: <1179136577.691598.229270@o5g2000hsb.googlegroups.com> HI, The following code is for replacing the strings localid with "datapackageid" in an xml document.: from xml.etree.ElementTree import ElementTree as et file_input = raw_input("Enter The ODX File Path:") (shortname,ext)=os.path.splitext(file_input) test_file=shortname+"testxml.xml" input_xml = open(file_input,'r') tree = et.parse(input_xml) for t in tree.getiterator("SERVICEPARAMETER"): if t.get("Semantics") == "localId": t.set("Semantics", "dataPackageID") tree.write(test_file) The python ver is 2.5.there is no module error now,but when i run i get this error: Traceback (most recent call last): File "C:\Documents and Settings\pzchfr\Desktop\test.py", line 12, in tree = et.parse(input_xml) TypeError: unbound method parse() must be called with ElementTree instance as first argument (got file instance instead) I am passing the input file from user to be parsed which seems to be incorrect,Can someone help me. Thanks From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu May 24 06:11:58 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 24 May 2007 12:11:58 +0200 Subject: Checking parameters prior to object initialisation In-Reply-To: References: Message-ID: <465564ca$0$19174$426a34cc@news.free.fr> Brett_McS a ?crit : > Fairly new to Python (and loving it!) > > In C++ (gack!) I got used to creating a helper function with each class to > check the class object initialisation parameters prior to creating the > object. > > In Python, this would be > ----------------------------------------------- > import example > > if example.ParametersOK(a, b, c, d): > newObj = example.Example(a, b, c, d) > else: > print "Error in parameters" > ----------------------------------------------- > > I presume this would still be considered good practise in Python, I don't think so. > or is > there some other, preferred, method? If you really have to check, do it in the object's initializer (the __init__ method), and raise an exception if necessary. From nick at craig-wood.com Thu May 17 07:30:05 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 17 May 2007 06:30:05 -0500 Subject: A bug in cPickle? References: <1179335180.786851.209900@y80g2000hsf.googlegroups.com> Message-ID: Victor Kryukov wrote: > The following behavior is completely unexpected. Is it a bug or a by- > design feature? > > from pickle import dumps > from cPickle import dumps as cdumps > > print dumps('1001799')==dumps(str(1001799)) > print cdumps('1001799')==cdumps(str(1001799)) > > >>>>output:>>>> > True > False Does it matter since it is decoded properly? >>> import pickle >>> import cPickle >>> cPickle.dumps('1001799') "S'1001799'\np1\n." >>> pickle.dumps('1001799') "S'1001799'\np0\n." >>> pickle.loads(pickle.dumps('1001799')) '1001799' >>> pickle.loads(cPickle.dumps('1001799')) '1001799' >>> cPickle.loads(pickle.dumps('1001799')) '1001799' >>> cPickle.loads(cPickle.dumps('1001799')) '1001799' >>> -- Nick Craig-Wood -- http://www.craig-wood.com/nick From aisaac at american.edu Fri May 4 23:48:53 2007 From: aisaac at american.edu (Alan Isaac) Date: Sat, 05 May 2007 03:48:53 GMT Subject: change of random state when pyc created?? Message-ID: This may seem very strange, but it is true. If I delete a .pyc file, my program executes with a different state! In a single directory I have module1 and module2. module1 imports random and MyClass from module2. module2 does not import random. module1 sets a seed like this:: if __name__ == "__main__": random.seed(314) main() I execute module1.py from the (Windows) shell. I get a result, let's call it result1. I execute it again. I get another result, say result2. Running it again and again, I get result2. Now I delete module2.pyc. I execute module1.py from the shell. I get result1. I execute it again; I get result2. >From then on I get result2, unless I delete module.pyc again, in which case I once again get result1. Can someone explain this to me? Thank you, Alan Isaac From duncan.booth at invalid.invalid Mon May 7 08:01:32 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 7 May 2007 12:01:32 GMT Subject: Bastion/rexec use cases? References: <1178534949.324994.60870@l77g2000hsb.googlegroups.com> Message-ID: Paul Miller wrote: > Bastion and rexec have been deprecated since Python 2.2, so it seems > we (the Python community) have gotten along well enough without them. > Have these modules not been reimplemented because: > > a) There are no valid use cases for them. > b) Doing so would be difficult and prone to breakage as new features > are introduced into the language. > c) Nobody has any idea how to do it. > d) Nobody cares. > e) Guido thinks it's a bad idea. > > or, some combination of these? > > I think it is mostly 'b' plus partly nobody cares sufficiently to put the time, money and effort behind it. The recent release of Silverlight means that there is now a way to run Python in a secure sandbox. At present it is only available for Windows and Mac, but hopefully the Mono community will be able to overcome that deficiency (also of course you don't get all of the standard Python libraries): see http://www.mono-project.com/Moonlight for the current state of the Mono based Silverlight implementation. From kyosohma at gmail.com Fri May 11 09:28:33 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 11 May 2007 06:28:33 -0700 Subject: setting extra data to a wx.textctrl In-Reply-To: References: Message-ID: <1178890113.188436.228450@h2g2000hsg.googlegroups.com> On May 10, 10:51 pm, Pom wrote: > Hello group! > > I have an application which uses a lot of mysql data fields, all the > same data type (floats). > > I created a panel which executes a "SELECT * FROM tablename" and makes > as much fields as needed, using de cursor.description as wx.statictext > and the cursors field contents copied into wx.textctrls. > > At creation time, I loop over all the fields in the record and create a > tuple which contains ((textctrl1, fieldname1), (textctrl2, fieldname2), > ...) so I can keep track of which textctrl holds which piece of fielddata. > > The problem I'm having is: > > to know the fieldname in an text_event, I use event.GetEventObject(), > then perform an iteration over the tuple and when I find a match I use > the field name to update the mysqltable. > When having a few fields, this is ok. But I have over 100 fields in 1 > record and it really slows things down. > > Now my question is: should I use a python dictionary (with an object as > first lookup field) ? > > On windows, I've seen a "Tag" property in a textbox which was meant to > be used for this kind of stuff. Maybe it's better to override the > wx.textctrl so I can add an extra string value? > > Anyone having the best solution for this ? > > thx! Both of your ideas seem sound to me. You could also look into using statically assigned IDs that increment by one. Then you could just increment or decrement by one and look up the field by ID. Of course, that might get ugly and there are some IDs that are supposedly reserved. But it's an idea. Also, I've heard that Dabo (http://dabodev.com/) is good for database work. You might look at that. To get the quickest and most on target answers to wxPython questions, I recommend the wxPython users-group mailing list: http://www.wxpython.org/maillist.php Mike From howe.steven at gmail.com Tue May 15 18:15:37 2007 From: howe.steven at gmail.com (Steven Howe) Date: Tue, 15 May 2007 15:15:37 -0700 Subject: Python Newbie Suggestions In-Reply-To: <1179264515.958714.72880@l77g2000hsb.googlegroups.com> References: <1179264515.958714.72880@l77g2000hsb.googlegroups.com> Message-ID: <464A3109.1040308@gmail.com> garcigal at gmail.com wrote: > I'm a mechanical engineer with little experience programming. I've > used C++ and machine language for getting micro-controllers to work > and thats about it. I work allot with software developers at my job > and can read C++ code pretty good (ie. I understand whats going on). > Does anyone have any good tips or resources for someone interested in > learning PYTHON. This is purely for hobby purposes and I'd like to > expose my kids to a programing language too. If any one has any > helpful books, tips or suggestions please let me know. I have > Windows, MAC and Linux box's at my house but I'm a primarily a MAC > user. > > I found "Learning Python" O'Reilly pretty good. It's pretty dogeared now. It's ISBN number is:1-56592-464-9. That's edition 1from the last century. sph -- HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 From steve at holdenweb.com Sat May 19 09:12:32 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 19 May 2007 09:12:32 -0400 Subject: which is the comprehencive module for postgresql? In-Reply-To: References: Message-ID: Gabriel Genellina wrote: > En Sat, 19 May 2007 02:25:11 -0300, krishnakant Mane > escribi?: > >> some times having many choices often confuses the users. >> can some one plese tell me which is the most comprehencive, well >> documented and widely used and tested module to connect from python to >> postgresql database? I looked around PYPgsql but there seams to be >> very little documentation. > > I've never used Postgresql with Python so I can't recommend any, but see > this wiki page: > http://wiki.python.org/moin/PostgreSQL > I'd recommend psycopg2 - I have used it quite a bit, it seems well-written and well-supported. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From steven.bethard at gmail.com Sat May 26 16:03:48 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 26 May 2007 14:03:48 -0600 Subject: PyPI bdist_wininst upload failing Message-ID: I just tried to upload new versions of the argparse module to PyPI, but it seems like I can no longer upload Windows installers: $ setup.py sdist bdist_wininst upload ... running upload Submitting dist\argparse-0.8.0.zip to http://www.python.org/pypi Server response (200): OK Submitting dist\argparse-0.8.0.win32.exe to http://www.python.org/pypi Upload failed (400): Bad Request Anyone know what I'm doing wrong? (I've always been able to upload bdist_wininst packages to PyPI in the past.) STeVe From larry.bates at websafe.com Wed May 2 18:41:39 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 02 May 2007 17:41:39 -0500 Subject: Python COM and Delphi callback Message-ID: I have a Python COM object working. I want to pass to it a Delphi callback function (showing progress) that I can call periodically. I've Googled until I'm cross-eyed and I'm getting nowhere. Anybody out there that could give me a push in the right direction. I tried passing pointer to my callback function using @ operator in Delph, but when I compile Delphi complains. Here is a snip of my Delphi code: function Callback(total: integer; position: integer): boolean; stdcall; begin WriteLn('In Callback, total=' + IntToStr(total) + ' position=' + IntToStr(position)); result := True; end; . . In program . // // Set callback function in wsAPI to be called for each block // that is uploaded. oC contains instance of COM object and // works perfectly. oC has a method called WSset_callback that // expects a callback function as an argument. I have the // callback working perfectly in pure-Python code. // oC.WSset_callback(@Callback); When I compile I get: [Pascal Error] wsAPICOM.dpr(151) E2281 Type not allowed in Variant Dispatch call. Thanks in advance for any assistance. Regards, Larry From mensanator at aol.com Sun May 13 12:26:06 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 13 May 2007 09:26:06 -0700 Subject: Interesting list Validity (True/False) In-Reply-To: References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> <1178914190.166662.285410@p77g2000hsh.googlegroups.com> <1178915791.584216.293130@l77g2000hsb.googlegroups.com> <1178918808.091358.233740@o5g2000hsb.googlegroups.com> <1179017740.656323.209590@e51g2000hsg.googlegroups.com> <1179020634.130689.171960@o5g2000hsb.googlegroups.com> Message-ID: <1179073565.933957.174250@o5g2000hsb.googlegroups.com> On May 13, 8:57?am, Carsten Haese wrote: > On Sat, 2007-05-12 at 18:43 -0700, mensana... at aol.com wrote: > > > That doesn't explain what you mean. How does "if arg==True" test whether > > > "a list is a boolean"? > > > >>> type(sys.argv) > > > > >>> type(True) > > > > All right, so what you meant was "Assuming that arg is a list, 'if > arg==True' will always fail because lists never compare equal to any > boolean." > > > Actually, it's this statement that's non-sensical. > > > > > "if arg==True" tests whether the object known as arg is equal to the > > object known as True. > > > > > [snip examples of "surprising" equality tests...] > > The statement I made is simply the meaning of "if arg==True" by > definition, so I don't see how it can be nonsensical. Because you didn't allow for exceptions, which are prominently pointed out in the Python docs. > > The problem is that you consider equality tests in Python to be > nonsensical because they don't fit with your opinion of what equality > should mean. No, it has nothing to do with what it means. 1, [1], (1,) and mpz(1) are all different types and all mathmatically the same. Yet 1 and mpz(1) compare equal but (1,) and [1] do not. The later fails due to type mis-match, the former does not despite type mis-match due to the fact they are the same mathematically. I'm not saying the situation is wrong, what I'm saying is that somone who doesn't understand why arg==True is failing should be told ALL the rules, not just the easy ones. > > Regards, > > -- > Carsten Haesehttp://informixdb.sourceforge.net From gherron at islandtraining.com Thu May 10 02:24:11 2007 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 09 May 2007 23:24:11 -0700 Subject: elegant python style for loops In-Reply-To: <1178776272.535735.166540@h2g2000hsg.googlegroups.com> References: <1178776272.535735.166540@h2g2000hsg.googlegroups.com> Message-ID: <4642BA8B.3060908@islandtraining.com> ian.team.python at saltmob.com wrote: > To step through a list, the python style is avoid an explicit index. > But what if the same hidden index is to be used for more than one list > > for example:- > for key,value in listKeys,listValues : > newdict[key]=value > > won't work as it is a tuple of lists, as opposed to a list of tuples. > Is there an elegant solution to this? Is there a way to merge lists > into a list of tuples to allow moving through multiple lists, or is > the for i in range(len(listkeys)): the only solution? > > Any suggestions? > > Yes. The builtin function zip does just that: merging separate lists into a list of tuples. See: http://docs.python.org/lib/built-in-funcs.html#l2h-81 Gary Herron From josiah.carlson at sbcglobal.net Mon May 21 21:22:50 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Mon, 21 May 2007 18:22:50 -0700 Subject: A few questions In-Reply-To: <1179768939.695708.299940@u36g2000prd.googlegroups.com> References: <1179768939.695708.299940@u36g2000prd.googlegroups.com> Message-ID: Christopher Arndt wrote: > I have a few quibles with your summary of Python's properties: > On 21 Mai, 08:16, John Nagle wrote: >> Memory management >> is safe and managed by reference counts backed by a garbage collector. >> Weak references are supported. Built in data types are numerics, ASCII >> and Unicode strings, dynamic arrays, fixed size tuples, and hashes. > > Python lists are much more than arrays. More like a linked list. > You forgot sets. And functions, classes, methods, instances.... (see > above) Python lists are implemented as C arrays that are resized as necessary. - Josiah From half.italian at gmail.com Wed May 23 15:36:20 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 23 May 2007 12:36:20 -0700 Subject: Parallel/distributed generator In-Reply-To: <1179943256.575473.62610@q66g2000hsg.googlegroups.com> Message-ID: <1179948980.173325.262610@d30g2000prg.googlegroups.com> On May 23, 11:00 am, George Sakkis wrote: > I'm looking for any existing packages or ideas on how to implement the > equivalent of a generator (in the Python sense, i.e.http://www.python.org/dev/peps/pep-0255/) in a parallel/distributed > way. As a use case, imagine a function that generates a range of > primes. I'd like to be able to do something along the following lines: > > def iterprimes(start=1, end=None): > # ... > yield prime > > # rpc-related initialization > ... > rpc_proxy = some_rpc_lib(iterprimes, start=1e6, end=1e12) > for prime in proxy: > print prime > > Is there any module out there that does anything close to this ? > > George Parellel Python? http://www.parallelpython.com/content/view/17/31/#SUM_PRIMES I've never used it, but looks like it does what you are looking for. ~Sean From michael.forbes at gmail.com Mon May 7 20:35:31 2007 From: michael.forbes at gmail.com (Michael) Date: 7 May 2007 17:35:31 -0700 Subject: Why are functions atomic? In-Reply-To: <1hxltle.haomya7z5hdwN%aleax@mac.com> References: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> <1178044821.864741.235260@o5g2000hsb.googlegroups.com> <1178063341.779617.289690@o5g2000hsb.googlegroups.com> <1178065685.161372.81790@y80g2000hsf.googlegroups.com> <1178083318.404304.76100@q75g2000hsh.googlegroups.com> <1178260571.160570.299160@p77g2000hsh.googlegroups.com> <1178308503.420603.158120@e65g2000hsc.googlegroups.com> <1hxltle.haomya7z5hdwN%aleax@mac.com> Message-ID: <1178584531.712503.110460@e65g2000hsc.googlegroups.com> On May 4, 7:54 pm, a... at mac.com (Alex Martelli) wrote: > Michael wrote: > > Thus, whenever I need to pass information to a function, I use default > > arguments now. Is there any reason not to do this other than the fact > > that it is a bit more typing? > > You're giving your functions a signature that's different from the one > you expect it to be called with, and so making it impossible for the > Python runtime to diagnose certain errors on the caller's part. ... > The miniscule "optimization" of giving a function an argument it's not > _meant_ to have somewhat breaks this part of the "Zen of Python", and > thus I consider it somewhat unclean. That is a pretty good reason in some contexts. Usually, the arguments I pass are values that the user might like to change, so the kwarg method often serves an explicit purpose allowing parameters to be modified, but I can easily imagine cases where the extra arguments should really not be there. I still like explicitly stating the dependencies of a function, but I suppose I could do that with decorators. Thanks, Michael. From bbxx789_05ss at yahoo.com Wed May 16 03:34:58 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 16 May 2007 00:34:58 -0700 Subject: setting an attribute Message-ID: <1179300898.223314.76430@y80g2000hsf.googlegroups.com> "When you bind (on either a class or an instance) an attribute whose name is not special...you affect only the __dict__ entry for the attribute(in the class or instance, respectively)." In light of that statement, how would one explain the output of this code: class Test(object): x = [1, 2] def __init__(self): self.x[0] = 10 print Test.__dict__ #{.....'x':[1,2]....} t = Test() print t.x #[10, 2] print t.__dict__ #{} print Test.__dict__ #{.....'x':[10,2]...} It looks to me like self.x[0] is binding on an instance whose attribute name is not special, yet it doesn't affect any __dict__ entry for the attribute in the instance--instead it is affecting a __dict__ entry for the attribute in the class. From carsten at uniqsys.com Thu May 10 01:06:33 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 10 May 2007 01:06:33 -0400 Subject: change of random state when pyc created?? In-Reply-To: References: <5ae25fF2oggbqU1@mid.uni-berlin.de> Message-ID: <20070510043535.M77513@uniqsys.com> On Thu, 10 May 2007 12:46:05 +1000, Steven D'Aprano wrote > It is natural to expect two runs of any program to give the same > result if there are (1) no random numbers involved; (2) the same > input data; (3) and no permanent storage from run to run. Which of those three categories does time.time() fall into? What about id("hello")? -Carsten From phd at phd.pp.ru Thu May 3 09:44:08 2007 From: phd at phd.pp.ru (Oleg Broytmann) Date: Thu, 3 May 2007 17:44:08 +0400 Subject: SQLObject 0.8.3 Message-ID: <20070503134408.GB10781@phd.pp.ru> Hello! I'm pleased to announce the 0.8.3 release of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.8.3 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.8.2 ---------------- Bug Fixes --------- * Fixed a longstanding bug with .select() ignoring 'limit' parameter. * Fixed a bug with absent comma in JOINs. * Fixed sqlbuilder - .startswith(), .endswith() and .contains() assumed their parameter must be a string; now you can pass an SQLExpression: Table.q.name.contains(func.upper('a')), for example. * Fixed a longstanding bug in sqlbuilder.Select() with groupBy being a sequence. * Fixed a bug with Aliases in JOINs. * Yet another patch to properly initialize MySQL connection encoding. * Fixed a minor comparison problem in test_decimal.py. Docs ---- * Added documentation about 'validator' Col constructor option. * Added an answer and examples to the FAQ on how to use sqlmeta.createSQL. * More documentation about orderBy. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From kib2 at free.fr Sat May 26 01:40:48 2007 From: kib2 at free.fr (tool69) Date: Sat, 26 May 2007 07:40:48 +0200 Subject: NLTK: Natural language processing in Python In-Reply-To: References: Message-ID: <4657c877$0$19912$426a74cc@news.free.fr> NLTK seems very interesting, and the tutorial are very well done. Thanks for it ! Kib? From sickcodemonkey at gmail.com Sat May 19 23:26:25 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Sat, 19 May 2007 23:26:25 -0400 Subject: interesting dict bug In-Reply-To: <82d28c40705191940m261a12f5n9e118f871ad21971@mail.gmail.com> References: <2adc542f0705191927u799da2ak9e884cef53f15979@mail.gmail.com> <82d28c40705191940m261a12f5n9e118f871ad21971@mail.gmail.com> Message-ID: <2adc542f0705192026u7ed269d6k17c27fecd576d9ff@mail.gmail.com> Ahhh thank you so much! I just added a ".encode('utf-8')" to the variables causing problems and that resolved my issue. Much appreciated! .dave On 5/19/07, Jeff McNeil wrote: > > Filename is a unicode string. See > http://www.diveintopython.org/xml_processing/unicode.html or > http://docs.python.org/tut/node5.html#SECTION005130000000000000000. > > 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. > >>> s = "string" > >>> unicode(s) > u'string' > >>> > > You're not seeing the 'u' in the 'print filename' line as it isn't > actually part of the data. You will see it in the 'print params2' > output, though, as I believe it relies on the string object's __repr__ > function, which will include the unicode specifier. > > -Jeff > > On 5/19/07, Sick Monkey wrote: > > Here is a segment of some code that I have. > > CODE: > > -------------- > > print filename > > params2 = > > > {'filename':filename,'id3title':title,'id3artist':artist,'id3album':album,'id3year':year,'id3track':track,'id3genre':genre,'uname':username,'password':password,'filesToUpload':open(file, > > 'rb')} > > print params2 > > ---------------- > > OUTPUT: > > 01.mp3 > > {'password': u'XXX', 'id3year': '2002', 'id3album': 'album, 'id3title': > > 'Lose Yourself', 'filename': u'01.mp3', 'uname': u'', 'id3genre': > > 'Soundtrack', 'id3artist': 'Eminem', 'filesToUpload': > u'/Users/ozdon/Music/test2/01- eminemhhh.mp3', mode 'rb' at 0x106a5c0>, > > 'id3track': 'Unknown'} > > -------------- > > Does anyone know how the random " u' " is getting into the params2 or > know > > how to around this? > > > > I am using Python 2.5 on MacOSX. > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From daniele.varrazzo at gmail.com Mon May 7 10:42:10 2007 From: daniele.varrazzo at gmail.com (Daniele Varrazzo) Date: 7 May 2007 07:42:10 -0700 Subject: problem with quoted strings while inserting into varchar field of database. In-Reply-To: References: <1178475772.423687.118800@e65g2000hsc.googlegroups.com> <1178526655.933789.294700@h2g2000hsg.googlegroups.com> <1178530363.516882.228380@l77g2000hsb.googlegroups.com> <1178548015.856661.308070@u30g2000hsc.googlegroups.com> Message-ID: <1178548930.494072.92040@q75g2000hsh.googlegroups.com> > Ashes on my head. My fault: the difference is hard to spot indeed in the rather long line of the example. I should have been more explicit stating that the differences were: 1. missing explicit quotes around the placeholders (they are part of the escaped values), 2. no % operator: two parameters are passed instead. Best regards, -- Daniele From nejtak... Tue May 29 12:34:42 2007 From: nejtak... (Troels Thomsen) Date: Tue, 29 May 2007 18:34:42 +0200 Subject: Scope - import and globals References: <1180455769.891470.116360@p47g2000hsd.googlegroups.com> Message-ID: <465c5623$0$52109$edfadb0f@dread11.news.tele.dk> "HMS Surprise" skrev i en meddelelse news:1180455769.891470.116360 at p47g2000hsd.googlegroups.com... > > In the file snippet below the value for the global hostName is > determined at runtime. Functions imported from the parent baseClass > file such as logon also need access to this variable but cannot see it > the with the implementation I have attempted here. > > Also, functions in this file and in the imported parent class need > PyHttpTestCase. Does there need to be an import statement in both > files? > If a file needs an import, make the import! Dont rely on other file's imports , in general, imho. Not sure excactly what you are doing, but are you sure you dont want an instance variable instead of a global ? self.hostName = "blah" And then a getHostName() method in the class ? regards Troels From afriere at yahoo.co.uk Mon May 21 02:05:31 2007 From: afriere at yahoo.co.uk (Asun Friere) Date: 20 May 2007 23:05:31 -0700 Subject: Unable to strip \n characters In-Reply-To: References: <1179658203.040541.220800@p77g2000hsh.googlegroups.com> Message-ID: <1179727531.061286.139560@x35g2000prf.googlegroups.com> On May 20, 10:49 pm, Michael Bentley wrote: > On May 20, 2007, at 7:41 AM, Michael Bentley wrote: > > > (upload.strip()) > > Oops: (upload.strip(),) or upload.strip() Superfluous though the braces around your original were, it should still run ... ie. (a) == a From steven.bethard at gmail.com Tue May 22 14:34:56 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 22 May 2007 12:34:56 -0600 Subject: converting text and spans to an ElementTree In-Reply-To: <1179847659.770231.115490@r3g2000prh.googlegroups.com> References: <1179847659.770231.115490@r3g2000prh.googlegroups.com> Message-ID: attn.steven.kuo at gmail.com wrote: > On May 21, 11:02 pm, Steven Bethard wrote: >> I have some text and a list of Element objects and their offsets, e.g.:: >> >> >>> text = 'aaa aaa aaabbb bbbaaa' >> >>> spans = [ >> ... (etree.Element('a'), 0, 21), >> ... (etree.Element('b'), 11, 18), >> ... (etree.Element('c'), 18, 18), >> ... ] >> >> I'd like to produce the corresponding ElementTree. So I want to write a >> get_tree() function that works like:: >> >> >>> tree = get_tree(text, spans) >> >>> etree.tostring(tree) >> '
aaa aaa aaabbb bbbaaa' >> >> Perhaps I just need some more sleep, but I can't see an obvious way to >> do this. Any suggestions? > > It seems you're looking to construct an Interval Tree: > > http://en.wikipedia.org/wiki/Interval_tree No, I'm looking to construct an ElementTree from intervals. ;-) Could you elaborate on how an Interval Tree would help me? STeVe From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue May 15 16:03:23 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 15 May 2007 22:03:23 +0200 Subject: Simulating simple electric circuits References: <5a9838F2nlbanU1@mid.individual.net> <5ae44aF2ku9rtU1@mid.individual.net> <5ak3u9F2odts2U1@mid.individual.net> <1178974027.175679.51130@k79g2000hse.googlegroups.com> <5aruivF2osbvdU1@mid.individual.net> Message-ID: <5aui0bF2pf8unU1@mid.individual.net> Bjoern Schliessmann wrote: > I suspect that this is a dead end though, because in more complex > designs the creation of circuits becomes cumbersome. Also, for the > system I want to model, the circuits are OOH very complex and OTOH > I don't have access to all circuit diagrams. :( So I think I'll > try next to transfer my problem to digital two-level logic. Erm, no. Doesn't work. I'll still stick with the circuit approach ... Regards, Bj?rn -- BOFH excuse #367: Webmasters kidnapped by evil cult. From gagsl-py2 at yahoo.com.ar Wed May 9 22:02:54 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 09 May 2007 23:02:54 -0300 Subject: path stuff References: <1178734266.858048.311740@y5g2000hsa.googlegroups.com> Message-ID: En Wed, 09 May 2007 15:11:06 -0300, fscked escribi?: > I am walking some directories looking for a certain filename pattern. > This part works fine, but what if I want to exclude results from a > certain directory being printed? Using os.walk you can skip undesired directories entirely: for dirpath, dirnames, filenames in os.walk(starting_dir): if "archived" in dirnames: dirnames.remove("archived") # process filenames, typically: for filename in filenames: fullfn = os.path.join(dirpath, filename) ... -- Gabriel Genellina From showell30 at yahoo.com Sun May 27 15:17:29 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 27 May 2007 12:17:29 -0700 (PDT) Subject: ten small Python programs In-Reply-To: Message-ID: <382474.67546.qm@web33503.mail.mud.yahoo.com> --- Steven Bethard wrote: > > > > Maybe this is the first good example that > motivates a > > hyperlink to alternatives. Would you accept the > idea > > that we keep my original example on the > SimplePrograms > > page, but we link to a UnitTestingPhilosophies > page, > > and we show your alternative there? Or vice > versa, > > show your example on the first page, but then show > > mine on the hyperlinked page? > > Sure. Either way is fine. > Ok, for now, I'm taking no action, let's let the unit testing discussion progress a little. Despite my saying early that I don't want to debate it, I do want to discuss it :), as it is near in dear to my heart. ____________________________________________________________________________________Yahoo! oneSearch: Finally, mobile search that gives answers, not web links. http://mobile.yahoo.com/mobileweb/onesearch?refer=1ONXIC From a.schmolck at gmail.com Sun May 13 18:46:31 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: Sun, 13 May 2007 23:46:31 +0100 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: "Martin v. L?wis" writes: > PEP 1 specifies that PEP authors need to collect feedback from the > community. As the author of PEP 3131, I'd like to encourage comments > to the PEP included below, either here (comp.lang.python), or to > python-3000 at python.org > > In summary, this PEP proposes to allow non-ASCII letters as > identifiers in Python. If the PEP is accepted, the following > identifiers would also become valid as class, function, or > variable names: L?ffelstiel, chang?, ??????, or ??? > (hoping that the latter one means "counter"). > > I believe this PEP differs from other Py3k PEPs in that it really > requires feedback from people with different cultural background > to evaluate it fully - most other PEPs are culture-neutral. > > So, please provide feedback, e.g. perhaps by answering these > questions: > - should non-ASCII identifiers be supported? Yes. > why? Because not everyone speaks English, not all languages can losslessly transliterated ASCII and because it's unreasonable to drastically restrict the domain of things that can be conveniently expressed for a language that's also targeted at a non-professional programmer audience. I'm also not aware of any horror stories from languages which do already allow unicode identifiers. > - would you use them if it was possible to do so? Possibly. > in what cases? Maybe mathematical code (greek letters) or code that is very culture and domain specific (say code doing Japanese tax forms). 'as From jmg3000 at gmail.com Wed May 16 02:59:07 2007 From: jmg3000 at gmail.com (jmg3000 at gmail.com) Date: 15 May 2007 23:59:07 -0700 Subject: Issue with MySQLdb wrapper In-Reply-To: <1179271336.065217.75980@k79g2000hse.googlegroups.com> References: <1179271336.065217.75980@k79g2000hse.googlegroups.com> Message-ID: <1179298747.936795.217180@l77g2000hsb.googlegroups.com> On May 15, 7:22 pm, Gerard M wrote: > Hi guys I have a big problem with this wrapper im using Ubuntu 7.04 > and I want to install python-MySQLdb, I used synaptics and it is > installed, but when I try to do>>> import MySQLdb > > and I get this error: > > Traceback (most recent call last): > File "", line 1, in > File "MySQLdb/__init__.py", line 19, in > import _mysql > ImportError: No module named _mysql Looks like the install of MySQLdb is botched up. You might try and use the Ubuntu package management tool to check your installation for correctness. If that tells you everything is ok and it's still busted, you might try to uninstall, then reinstall MySQLdb. If that still doesn't work, you probably should ask about this on one of the Ubuntu forums. > so I tried to download it from the site and install it from the .tar > file but I failed because when I run > > #~/Desktop/MySQL-python-1.2.2$ python setup.py install > > [snip] In general, my guess is that, unless you have a good reason not to, you should probably not install fairly standard python packages by- hand like that on Ubuntu. There should be an Ubuntu package for what you need, and if there is, you should stick with that. If it fails, the Ubuntu folks will want to know about it. ---John From Leo.Kislov at gmail.com Tue May 8 01:15:37 2007 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 7 May 2007 22:15:37 -0700 Subject: invoke user's standard mail client In-Reply-To: <1178571606.190151.233580@y5g2000hsa.googlegroups.com> References: <1178266064.922925.125760@y80g2000hsf.googlegroups.com> <1178513538.133114.81940@p77g2000hsh.googlegroups.com> <1178571606.190151.233580@y5g2000hsa.googlegroups.com> Message-ID: <1178601337.953718.16280@u30g2000hsc.googlegroups.com> On May 7, 2:00 pm, "luc.saf... at gmail.com" wrote: > On May 7, 10:28 am, "Gabriel Genellina" > wrote: > > > > > Get the pywin32 package (Python for Windows extensions) from sourceforge, > > install it, and look into the win32comext\mapi\demos directory. > > Thanks for the hint, Gabriel. > Wow, that's heavily spiced code! When I invoke mapisend.py I get: > > Traceback (most recent call last): > File "mapisend1.py", line 85, in > SendEMAPIMail(SendSubject, SendMessage, SendTo, > MAPIProfile=MAPIProfile) > File "mapisend1.py", line 23, in SendEMAPIMail > mapi.MAPIInitialize(None) > pywintypes.com_error: (-2147467259, 'Unspecified error', None, None) > > But what is a MAPI profile? It's an abstraction of incoming and outgoing mail accounts. In UNIX terms it's kind of like running local sendmail that forwards mail to another server and fetchmail that fetches mail from external inboxes, e.g. it's a proxy between you and outgoing/incoming mail server. > I left this variable blank. Do I need MS > Exchange Server to run this demo? No, but you need an account on some mail server and some email program should create a MAPI profile to represent that account on your local computer. As I understand creation of MAPI profiles is not a common practice among non-Microsoft products, for example my computer with Lotus Notes doesn't have any MAPI profiles. -- Leo From nagle at animats.com Wed May 2 01:17:33 2007 From: nagle at animats.com (John Nagle) Date: Wed, 02 May 2007 05:17:33 GMT Subject: Why are functions atomic? In-Reply-To: <463816a9$0$9276$9b622d9e@news.freenet.de> References: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> <1178044821.864741.235260@o5g2000hsb.googlegroups.com> <1178063341.779617.289690@o5g2000hsb.googlegroups.com> <1178065685.161372.81790@y80g2000hsf.googlegroups.com> <463816a9$0$9276$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote: > Michael schrieb: > >>A bit more info, but still no clear picture about why functions are >>mutable but have immutable copy symantics. There are arguments why >>functions should be immutable, but the decision was to make user- >>defined functions mutable. My question is still: why the present >>ummutable copy symantics? > > > The answer is really really simple. The implementation of copy predates > mutability. When the copy code was written, functions *were* immutable. > When functions became mutable, the copy code was not changed, and > nobody noticed or complained. That's probably an indication that mutable functions don't get used all that much. Are there any instances of them in the standard Python libraries? John Nagle From mail at microcorp.co.za Thu May 10 03:54:25 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 10 May 2007 09:54:25 +0200 Subject: Towards faster Python implementations - theory References: <1210i.7468$2v1.2505@newssvr14.news.prodigy.net><1178705421.711371.182770@e65g2000hsc.googlegroups.com> Message-ID: <016501c792da$e6d086e0$03000080@hendrik> "John Nagle" wrote: > Paul Boddie wrote: > > On 9 May, 08:09, "Hendrik van Rooyen" wrote: > > > >>I am relatively new on this turf, and from what I have seen so far, it > >>would not bother me at all to tie a name's type to its first use, so that > >>the name can only be bound to objects of the same type as the type > >>of the object that it was originally bound to. > > > > > > But it's interesting to consider the kinds of names you could restrict > > in this manner and what the effects would be. In Python, the only kind > > of name that can be considered difficult to arbitrarily modify "at a > > distance" - in other words, from outside the same scope - are locals, > > and even then there are things like closures and perverse > > implementation-dependent stack hacks which can expose local namespaces > > to modification, although any reasonable "conservative Python" > > implementation would disallow the latter. > > Modifying "at a distance" is exactly what I'm getting at. That's the > killer from an optimizing compiler standpoint. The compiler, or a > maintenance programmer, looks at a block of code, and there doesn't seem > to be anything unusual going on. But, if in some other section of > code, something does a "setattr" to mess with the first block of code, > something unusual can be happening. This is tough on both optimizing > compilers and maintenance programmers. > > Python has that capability mostly because it's free in an > "everything is a dictionary" implementation. ("When all you have > is a hash, everything looks like a dictionary".) But that limits > implementation performance. Most of the time, nobody is using > "setattr" to mess with the internals of a function, class, or > module from far, far away. But the cost for that flexibility is > being paid, unnecessarily. > > I'm suggesting that the potential for "action at a distance" somehow > has to be made more visible. > > One option might be a class "simpleobject", from which other classes > can inherit. ("object" would become a subclass of "simpleobject"). > "simpleobject" classes would have the following restrictions: > > - New fields and functions cannot be introduced from outside > the class. Every field and function name must explicitly appear > at least once in the class definition. Subclassing is still > allowed. > - Unless the class itself uses "getattr" or "setattr" on itself, > no external code can do so. This lets the compiler eliminate the > object's dictionary unless the class itself needs it. > > This lets the compiler see all the field names and assign them fixed slots > in a fixed sized object representation. Basically, this means simple objects > have a C/C++ like internal representation, with the performance that comes > with that representation. > > With this, plus the "Shed Skin" restrictions, plus the array features of > "numarray", it should be possible to get computationally intensive code > written in Python up to C/C++ levels of performance. Yet all the dynamic > machinery of Python remains available if needed. > > All that's necessary is not to surprise the compiler. > If this is all it takes, I would even be happy to have to declare which things could be surprising - some statement like: x can be anything Would that help? It kind of inverts the logic - and states that if you want what is now the default behaviour, you have to ask for it. - Hendrik From necmettin.begiter at gmail.com Tue May 8 16:03:47 2007 From: necmettin.begiter at gmail.com (Necmettin Begiter) Date: Tue, 8 May 2007 23:03:47 +0300 Subject: chdir() In-Reply-To: <1178652809.436141.176900@u30g2000hsc.googlegroups.com> References: <1178652809.436141.176900@u30g2000hsc.googlegroups.com> Message-ID: <200705082303.47249.necmettin.begiter@gmail.com> On Tuesday 08 May 2007 22:54:39 HMS Surprise wrote: > WindowsError: [Error 123] The filename, directory name, or volume > label syntax is incorrect: 'c:\twill'. > > What is wrong with the syntax? Try 'c:\\twill' because the '\' character is the escape character. Eg: \n is new-line (aka crlf) \t is tab etc. To understand how these work, try this: print 'hello\nworld' and you get: hello world From toby at tobiah.org Wed May 2 16:05:08 2007 From: toby at tobiah.org (Tobiah) Date: Wed, 02 May 2007 13:05:08 -0700 Subject: I wish that [].append(x) returned [x] In-Reply-To: References: <46379a41$0$25252$88260bb3@free.teranews.com> <1178053211.209905.154030@h2g2000hsg.googlegroups.com> Message-ID: <4638e263$0$16368$88260bb3@free.teranews.com> > In addition to the above good advice, in case you are submitting a query > to a DB-API compliant SQL database, you should use query parameters > instead of building the query with string substitution. I tried that a long time ago, but I guess I found it to be more awkward. I imagine that it is quite a bit faster that way? I'm using MySQLdb. -- Posted via a free Usenet account from http://www.teranews.com From nagle at animats.com Fri May 11 12:04:35 2007 From: nagle at animats.com (John Nagle) Date: Fri, 11 May 2007 16:04:35 GMT Subject: Towards faster Python implementations - theory In-Reply-To: References: <1210i.7468$2v1.2505@newssvr14.news.prodigy.net> <1178804728.527486.196400@y80g2000hsf.googlegroups.com> Message-ID: Tim Golden wrote: > sturlamolden wrote: > >> On May 8, 5:53 pm, John Nagle wrote: >> >>> The point here is that we don't need language changes or >>> declarations >>> to make Python much faster. All we need are a few restrictions that >>> insure that, when you're doing something unusual, the compiler can >>> tell. > > I doubt if anyone disputes the gist of what you're > saying[*], viz that Python could be made faster by using > technique (a), (b) or (c) which have been successful elsewhere. At least > that it's worth investgating. > > But the relevant bit of your last paragraph is at the start: > "We should...". Unless someone or someones has the time, > inclination, money, backing, wherewithal etc. to implement > this or any other measure of speeding-up, it's all > pie-in-the-sky. Useful, maybe, as discussion of what > options are viable, but a project of this magnitude > doesn't just happen in some developer's lunchbreak. Focusing may help. Between Jython, PyPy, and Shed Skin, enough effort has been put in to produce something better than CPython, but none of those efforts resulted in something more useable than CPython. There's a "commercial grade Python" from ActiveState, but that's CPython in a cardboard box, I think. Another problem is that if the language is defined as "whatever gets put in CPython", that discourages other implementations. The language needs to be standards-based. John Nagle From exarkun at divmod.com Mon May 21 09:39:51 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 21 May 2007 09:39:51 -0400 Subject: howto check does module 'asdf' exist? (is available for import) In-Reply-To: <1179753436.736228.321400@x35g2000prf.googlegroups.com> Message-ID: <20070521133951.30678.476073400.divmod.quotient.3295@ohm> On 21 May 2007 06:17:16 -0700, dmitrey wrote: >howto check does module 'asdf' exist (is available for import) or no? >(without try/cache of course) >Thx in advance, D. > You could use twisted.python.modules: $ python Python 2.4.3 (#2, Oct 6 2006, 07:52:30) [GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from twisted.python.modules import getModule >>> from sys import modules >>> 'Numeric' in modules False >>> getModule('Numeric') PythonModule<'Numeric'> >>> 'Numeric' in modules False >>> Jean-Paul From mail at microcorp.co.za Thu May 31 02:48:48 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 31 May 2007 08:48:48 +0200 Subject: Tkinter Listbox - Different Text colors in one listbox References: <1180458123.139727.182500@d30g2000prg.googlegroups.com> <1180526692.171952.310950@w5g2000hsg.googlegroups.com> Message-ID: <016701c7a353$81043c60$03000080@hendrik> wrote: > On May 29, 2:02 pm, rahulna... at yahoo.com wrote: > > Hi, > > Is it possible to havedifferentitems in alistboxindifferentcolors? Or is it justonecolor for all items in alistbox? > > Thanks > > Rahul > > from Tkinter import * > > root = Tk() > l = Listbox(root) > l.pack() > for x in range(10): > l.insert(END, x) > l.itemconfig(2, bg='red', fg='white') > l.itemconfig(4, bg='green', fg='white') > l.itemconfig(5, bg='cyan', fg='white') > root.mainloop() > > You can _only_ configurate 'background', 'foreground', > 'selectbackground', 'selectforegroud', not font :( Live and learn, - was not aware you could do this - thanks, nice one. - Hendrik From madhurrajn at gmail.com Sat May 5 07:18:26 2007 From: madhurrajn at gmail.com (Madhur) Date: 5 May 2007 04:18:26 -0700 Subject: Problem with Closing TCP connection Message-ID: <1178363905.984741.124810@u30g2000hsc.googlegroups.com> Dear All, I am currently developing a tool using Python 2.4.2 which will be used as a sink to pump TCP messages. During which i have observed that the TCP close interface provided by Python is not closing the connection. This i confirmed by looking at the ethereal logs, which show proper 3 way FIN ACK Handshake. But the netstat reports TIME_WAIT state for the TCP connection, which is hindering the messages to be pumped later. I would like to know whether the problem exists Python close and is there is turnaround? to the mentioned problem. Thanks, Madhur From bearophileHUGS at lycos.com Tue May 22 06:29:03 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 22 May 2007 03:29:03 -0700 Subject: Fastest Way To Iterate Over A Probability Simplex In-Reply-To: <4652b323$1@news.bezeqint.net> References: <4652b323$1@news.bezeqint.net> Message-ID: <1179829743.120449.148390@r3g2000prh.googlegroups.com> On May 22, 11:19 am, Efrat Regev: > I want to iterate over all > such vectors under the constraint that the granularity of > each component is at most some delta. You can think of this like your sum is an integer>=1 and the single "probabilities" are integers>=1 So given the sum, like 6, you can find all the parts of it, and then find all the permutations of such parts. Eppstein has given code for the parts of an integer, and you can can find the iterable permutations code on the cookbook. But the number of such possible vectors grows very quickly... http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/218332 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/474124 Bye, bearophile From tfb+google at tfeb.org Fri May 4 05:17:21 2007 From: tfb+google at tfeb.org (Tim Bradshaw) Date: 4 May 2007 02:17:21 -0700 Subject: Why stay with lisp when there are python and perl? In-Reply-To: <1178270006.399908.275470@y5g2000hsa.googlegroups.com> References: <1178155239.007219.205020@y5g2000hsa.googlegroups.com> <1178219732.127815.3260@y80g2000hsf.googlegroups.com> <463a9668$0$8719$ed2619ec@ptn-nntp-reader02.plus.net> <1178270006.399908.275470@y5g2000hsa.googlegroups.com> Message-ID: <1178270240.960248.68800@p77g2000hsh.googlegroups.com> On May 4, 10:13 am, Tim Bradshaw wrote: > Anyway the experience of writing in Python was kind of interesting. > [...] So one of the things I learned was "use a > language with a decent compiler"[*] I think. Bugger, I did not realise until too late that this was going to comp.lang.python as well. I should therefore add a caveat: Use a language with a high-performance (this is what I meant by "decent") compiler if that kind of performance matters to you. It did to us, but there are very many cases where it does not. In other words, despite appearances I'm not particularly trying to slag off Python. From maric at aristote.info Wed May 23 19:22:04 2007 From: maric at aristote.info (Maric Michaud) Date: Thu, 24 May 2007 01:22:04 +0200 Subject: Basic Class/Instance Question In-Reply-To: References: <1179921235.622391.230150@h2g2000hsg.googlegroups.com> Message-ID: <4654CC9C.2000207@aristote.info> Alan Franzoni a ?crit : > Il 23 May 2007 04:53:55 -0700, Siah ha scritto: > > [cut] > > No. > > It's because the *body* of the function gets evaluated every time the > function is called, while the *definition* of the function gets evaluated > just once, when the function is 'declared'. > > Your issue arises when the default value of the function (which is part of > the definition, not of the body) is a mutable object, because it's the very > same default value that gets modified at each time. > > That is. Jython doesn't have the same rules about optimisation of common literals : maric at redflag2:~$ jython Jython 2.1 on java1.4.2-03 (JIT: null) Type "copyright", "credits" or "license" for more information. >>> () is () 0 >>> 1 is 1 1 >>> def f(d=()) : return d ... >>> f() is f() 1 From paul at boddie.org.uk Tue May 15 07:04:55 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 15 May 2007 04:04:55 -0700 Subject: time format In-Reply-To: <1179224967.959750.21490@l77g2000hsb.googlegroups.com> References: <1179224967.959750.21490@l77g2000hsb.googlegroups.com> Message-ID: <1179227095.719906.214290@e65g2000hsc.googlegroups.com> On 15 May, 12:29, Alchemist wrote: > > How can I format a ctime() object? > Can anyone give me (or lead me to) an example of a solution to my > problem? Use time.strftime. See... http://docs.python.org/lib/module-time.html#tex2html122 Paul From rene at korteklippe.de Sat May 19 15:12:44 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Sat, 19 May 2007 21:12:44 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464C5185.4060302@v.loewis.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <464ab2f9$0$23146$9b4e6d93@newsspool1.arcor-online.net> <464ABA99.8080208@web.de> <464abecb$0$6403$9b4e6d93@newsspool2.arcor-online.net> <464C5185.4060302@v.loewis.de> Message-ID: <464f4c2c$0$10196$9b4e6d93@newsspool4.arcor-online.net> Martin v. L?wis schrieb: >>> Then get tools that match your working environment. >> Integration with existing tools *is* something that a PEP should >> consider. This one does not do that sufficiently, IMO. > > What specific tools should be discussed, and what specific problems > do you expect? Systems that cannot display code parts correctly. I expect problems with unreadable tracebacks, for example. Also: Are existing tools that somehow process Python source code e.g. to test wether it meets certain criteria (pylint & co) or to aid in creating documentation (epydoc & co) fully unicode-ready? -- Ren? From jgodoy at gmail.com Mon May 7 18:45:41 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Mon, 07 May 2007 19:45:41 -0300 Subject: No module named urllib References: <1178575589.059564.226060@q75g2000hsh.googlegroups.com> <87tzuop8s2.fsf@gmail.com> <1178577562.498615.222340@e51g2000hsg.googlegroups.com> Message-ID: <87ps5cp816.fsf@gmail.com> HMS Surprise writes: > Perhaps I should have put qoutes in my sentence. Or I should have read it slowly. ;-) > I get the "no module message named urllib". Can you please import sys print sys.path and put the answer here on the newsgroup? -- Jorge Godoy From vmaslov at swsoft.com Fri May 25 23:32:26 2007 From: vmaslov at swsoft.com (Vyacheslav Maslov) Date: Sat, 26 May 2007 10:32:26 +0700 Subject: Large Amount of Data In-Reply-To: References: Message-ID: <4657AA4A.70902@swsoft.com> Larry Bates wrote: > Jack wrote: >> Thanks for the replies! >> >> Database will be too slow for what I want to do. >> >> "Marc 'BlackJack' Rintsch" wrote in message >> news:pan.2007.05.25.18.03.09.688008 at gmx.net... >>> In , Jack wrote: >>> >>>> I need to process large amount of data. The data structure fits well >>>> in a dictionary but the amount is large - close to or more than the size >>>> of physical memory. I wonder what will happen if I try to load the data >>>> into a dictionary. Will Python use swap memory or will it fail? >>> What about putting the data into a database? If the keys are strings the >>> `shelve` module might be a solution. >>> >>> Ciao, >>> Marc 'BlackJack' Rintsch >> > Purchase more memory. It is REALLY cheap these days. Not a solution at all. What about if amount of data exceed architecture memory limits? i.e. 4Gb at 32bit. Better solution is to use database for data storage/processing -- Vyacheslav Maslov From kapelner at stanford.edu Sun May 27 03:17:38 2007 From: kapelner at stanford.edu (way4thesub) Date: Sun, 27 May 2007 00:17:38 -0700 (PDT) Subject: Color Segmentation w/ PIL? In-Reply-To: <1174549126.754309.317260@n76g2000hsh.googlegroups.com> References: <1174549126.754309.317260@n76g2000hsh.googlegroups.com> Message-ID: <10822775.post@talk.nabble.com> I don't know of any in Python, but an open source image processing package in Java has been developed at Stanford University - http://www.gemident.net GemIdent . GemIdent was originally designed to segment cells from miscroscopic images and, more generally, can identify objects of interest and do color image segmentation. Maybe some of the code can I apply to your project and you can bridge the gap using Jython. Adam MooMaster wrote: > > I'm trying to write a Digital Image Processing program using the PIL > library, and upon consultation of the Handbook I see that it seems to > have built in functions to run Edge Detection (in the ImageFilter > module), but I don't see anything about Segmentation. Are there any > built-in tools to do this operation? Has anyone done this operation > with PIL in the past that can lead me in the right direction? > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/Color-Segmentation-w--PIL--tf3445941.html#a10822775 Sent from the Python - python-list mailing list archive at Nabble.com. From carsten at uniqsys.com Tue May 8 22:40:15 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 8 May 2007 22:40:15 -0400 Subject: String parsing In-Reply-To: <1178676374.081202.74850@e51g2000hsg.googlegroups.com> References: <1178672992.522463.228620@l77g2000hsb.googlegroups.com> <1178676374.081202.74850@e51g2000hsg.googlegroups.com> Message-ID: <20070509023431.M72158@uniqsys.com> On 8 May 2007 19:06:14 -0700, HMS Surprise wrote > Thanks for posting. Could you reccommend an HTML parser that can be > used with python or jython? BeautifulSoup (http://www.crummy.com/software/BeautifulSoup/) makes HTML parsing easy as pie, and sufficiently old versions seem to work with Jython. I just tested this with Jython 2.2a1 and BeautifulSoup 1.x: Jython 2.2a1 on java1.5.0_07 (JIT: null) Type "copyright", "credits" or "license" for more information. >>> from BeautifulSoup import BeautifulSoup >>> soup = BeautifulSoup("""""") >>> print soup.first('input', {'name':'LastUpdated'}).get('value') 1178658863 Hope this helps, -- Carsten Haese http://informixdb.sourceforge.net From toby at tobiah.org Wed May 2 15:24:06 2007 From: toby at tobiah.org (Tobiah) Date: Wed, 02 May 2007 12:24:06 -0700 Subject: bitwise shift? In-Reply-To: <462FEE8B.2030701@lexicon.net> References: <462FEE8B.2030701@lexicon.net> Message-ID: <4638d8c5$0$16290$88260bb3@free.teranews.com> John Machin wrote: > On 26/04/2007 7:10 AM, Sherm Pendley wrote: > >> Shift left is *not* the same as multiplying by k. It is the same as >> multi- >> plying by 2^k. > > Where I come from, ^ is the exclusive-or operator. Of course YMMV in WV :-) desktops:toby:ga> bc bc 1.06 Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc. This is free software with ABSOLUTELY NO WARRANTY. For details type `warranty'. 2^3 8 -- Posted via a free Usenet account from http://www.teranews.com From grante at visi.com Thu May 24 10:57:16 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 24 May 2007 14:57:16 -0000 Subject: Python and GUI References: <1179761984.704369.116310@b40g2000prd.googlegroups.com> <4651CDBC.1070508@ulmcnett.com> Message-ID: <135b9ucc5tn0p9f@corp.supernews.com> On 2007-05-24, Brian Blais wrote: > I'd like to ask the Python community about this, because it > seems to me that there is a real need that is not being met > very effectively. [...] "...but wx is written in C++ and > definitely shows, even in the Python port". It's just not > very pythonic. > > Then there is Dabo, which I personally have had problems with. > [...] I haven't tried Dabo, so I can't comment. > Finally, consider wax (http://zephyrfalcon.org/labs/wax.html). > In my view, this is *exactly* what python needs, and its not > being maintained anymore as far as I can tell. What I like > about it is: > > 1) it is small...I can include the entire wax distribution in > my app with only a 780k footprint. > > 2) it is a very thin layer on wx, so when something doesn't > quite work, I can immediately fall back onto wx, mixing and > matching wax and wx objects. it's just that the wax > objects have more pythonic calling and use properties I did try wax, and I liked it. It seemed much more "Pythonic" than bare wxPython, and resulted in cleaner, easier-to-read code. When I tried it, it was still early in its development, and there were still parts of it that needed to be fleshed out (a lot of stuff was still unwrapped). I contributed a little bit of code (wrapping one or two more things), but I didn't have enough time at that point to wrap and debug all the things I needed, so I switched back to plain wxPython (I had a mixture of wax and wx for a little while, but I that annoyed me too much). > Is there a reason that the port of wxPython doesn't include > wax, or something similar? It would seem pretty > straightforward, when porting the wx to Python, to simply > include such a wrapper. I wish I were more clever, and had > more time, to take over the maintenance of wax because I think > it is the most straightforward, practical, and pythonic > solution out there. > > Do others think like me here? Yes. I thought wax was a good idea, and there was a a good start on an implementation. -- Grant Edwards grante Yow! My nose feels like a at bad Ronald Reagan movie ... visi.com From sturlamolden at yahoo.no Thu May 3 05:39:44 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 3 May 2007 02:39:44 -0700 Subject: Lazy evaluation: overloading the assignment operator? In-Reply-To: <4639636b$0$14016$c30e37c6@lon-reader.news.telstra.net> References: <1178133344.415521.118710@n76g2000hsh.googlegroups.com> <59scumF2lqg76U1@mid.uni-berlin.de> <4639636b$0$14016$c30e37c6@lon-reader.news.telstra.net> Message-ID: <1178185184.795457.253500@h2g2000hsg.googlegroups.com> On May 3, 6:22 am, Charles Sanders wrote: > y = a*b+c*d # Returns a proxy object > > x = y[4] # Computes x = a[4]*b[4] + c[4]*d[4] > > v = y.eval() # Evaluates all elements, returning Xarray > > z = ((a+b)*(c+d)).eval() # Also evaluates all elements When I suggested this on the NumPy mailing list, I too suggested using the indexing operator to trigger the computations. But I am worried that if an expression like y = a*b+c*d returns a proxy, it is somehow possible to mess things up by creating cyclically dependent proxies. I may be wrong about this, in which case __getitem__ et al. will do the job. > Whether it would be any faster is doubtful, but it would eliminate > the temporaries. The Numexpr compiler in SciPy suggests that it can. It parses an expression like 'y = a*b+c*d' and evaluates it. Numexpr is only a slow prototype written in pure Python, but still it can sometimes give dramatical speed-ups. Here we do not even need all the machinery of Numexpr, as Python creates the parse tree on the fly. Inefficiency of binary operators that return temporary arrays is mainly an issue when the arrays in the expression is too large to fit in cache. RAM access can be very expensive, but cache access is usually quite cheap. One also avoids unnecessary allocation and deallocation of buffers to hold temporary arrays. Again, it is mainly an issue when arrays are large, as malloc and free can be rather efficient for small objects. From w.m.gardella.sambeth at gmail.com Wed May 9 22:13:45 2007 From: w.m.gardella.sambeth at gmail.com (w.m.gardella.sambeth at gmail.com) Date: 9 May 2007 19:13:45 -0700 Subject: Parameter checking on an interfase In-Reply-To: <46422822$0$29857$426a74cc@news.free.fr> References: <1178682591.359947.240390@y80g2000hsf.googlegroups.com> <46422822$0$29857$426a74cc@news.free.fr> Message-ID: <1178763225.199074.173740@n59g2000hsh.googlegroups.com> On 9 mayo, 17:42, Bruno Desthuilliers wrote: > w.m.gardella.samb... at gmail.com a ?crit : > > > > > Hi all, > > I am more or less new to Python, and currently am making my > > first "serious" program. The application is a Clinical History manager > > (for my wife) which stores its data on a sqlite database. After > > googling on this newsgroup, I have read several threads where is > > stated that the LBYL way of testing parameters is not a pythonic way > > to work, and that is preferable catch the exceptions generated trying > > to use an invalid parameter passed to a function. > > Although I am generally following this approach, the problem I > > see is that sqlite docs states clearly that the engine does not check > > that the data types passed to the SQL sentences matches the types > > declared for the column, and lets any kind of information to be put in > > any column of the table. When I code the "business objects" of the > > application (don't know if this is the exact term for a layer that > > will isolate the application from the raw database, letting me change > > it in a future if necessary), > > business objects and databases are not necessarily related. And business > objects are much more than a "database abstraction layer" - they are the > "model" part of the MVC triad, and are the heart of your application's > logic. As such, they are of course in charge of validating their own > state wrt/ business rules. > > > I realize that if I pass arguments of > > wrong type (say, a numeric ID instead of the patient name), the DB > > engine will accept that gladly, and I will finish with data that could > > not be consistently retrievable if I use the DB from another program > > (no one right now, but I think of, perhaps, statistical trends on > > diseases and treatments). > > In this case, could be reasonable add type checking LBYL style > > on the methods, so if passed data is of wrong type, it generates a > > adequate exception to be catched by the caller? > > This is more a problem of validation/conversion of values than strictly > a typing problem IMHO. As someone said : "be liberal about what you > accept and strict about what you send". > > > In this way, the rest > > of the app (mostly GUI) can be coded EAFP style. As programming > > background, as you can guess, I have made some programming in C, VBA > > and JavaScript (quite procedurally). > > I hope that you can bring me some light about this kind of > > design, so I can improve my coding and get the Python way faster. > > I strongly encourage you to have a look at SQLAlchemy (a hi-level > RDBMS/python interface and an ORM) and Elixir (an ActiveRecord-like > declarative layer on top of SQLAlchemy), and FormEncode (an in/out > validation/conversion package). > > http://www.sqlalchemy.org/http://elixir.ematia.de/ > > FWIW, I'm actually working on using the second to add > validation/conversion to the first:http://groups.google.com/group/sqlelixir/browse_thread/thread/af7b2d0... Hi all: First of all I give Bruno many thanks for the definition of business objects, because plugs a big hole on my concepts. And after reading your messages, I reach to the conclussion that the best I can do with my program is to unittest more (against my own dumbness) the classes that will call the interfase, and take out all the type checking code from the callees. And in the event that the program could grow/evolve in something more serious, change the RDBMS to another more fit to the task. Thank you very much and May Entropy be benevolent with you. Walter From bdesth.quelquechose at free.quelquepart.fr Sun May 20 15:09:05 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 20 May 2007 21:09:05 +0200 Subject: Python Web Programming - looking for examples of solid high-traffic sites In-Reply-To: References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> <464da0a9$0$25891$426a74cc@news.free.fr> Message-ID: <46509274$0$23130$426a74cc@news.free.fr> John Nagle a ?crit : > Bruno Desthuilliers wrote: > >> John Nagle a ?crit : >> >>> Victor Kryukov wrote: >>> >>>> Hello list, >>>> >>>> our team is going to rewrite our existing web-site, which has a lot of >>>> dynamic content and was quickly prototyped some time ago. >>> >>> >>> ... >>> >>>> Our main requirement for tools we're going to use is rock-solid >>>> stability. As one of our team-members puts it, "We want to use tools >>>> that are stable, has many developer-years and thousands of user-years >>>> behind them, and that we shouldn't worry about their _versions_." The >>>> main reason for that is that we want to debug our own bugs, but not >>>> the bugs in our tools. >>> >>> >>> >>> You may not be happy with Python, then. >> >> >> >> John, I'm really getting tired of your systemic and totally >> unconstructive criticism. If *you* are not happy with Python, by all >> means use another language. > > > Denying the existence of the problem won't fix it. > Neither will keeping on systematically criticizing on this newsgroup instead of providing bug reports and patches. > As a direct result of this, neither the Linux distro builders like > Red Hat nor major hosting providers provide Python environments that > just work. That's reality. > I've been using Python for web applications (Zope, mod_python, fast cgi etc) on Gentoo and Debian for the 4 or 5 past years, and it works just fine. So far, I've had much more bugs and compatibility problems with PHP (4 and 5) than with Python. From Josef.Dalcolmo at gmx.net Thu May 3 10:26:47 2007 From: Josef.Dalcolmo at gmx.net (Josef Dalcolmo) Date: Thu, 3 May 2007 14:26:47 +0000 (UTC) Subject: getmtime in 2.5 reports GMT instead of local time Message-ID: Hello, I have tried this only on Windows XP. in Python 2.4 os.path.getmtime() used to return an integer representing the local time. in Python 2.5 os.path.getmtime() reports a float representing the GMT of the file's modification time. Since I could not find any documentation to this behavioural change, I am asking here: was this change intentional? Is it going to stay? Windows reports the same time for the file as Python 2.4 used to. So I am tempted to call this a bug, but wanted some feedback from the developers, before filing a bug report. If you want to test this, make sure your local time differs from GMT, then do: import os, time print time.ctime(os.path.getmtime('foo.txt')) on a file foo.txt, once with Python 2.4 then with Python 2.5, and you should see what I mean. - Josef From eric.brunel at pragmadev.com Tue May 15 03:09:30 2007 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Tue, 15 May 2007 09:09:30 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <7x4pmg716p.fsf@ruckus.brouhaha.com> <4648EC26.8020907@v.loewis.de> Message-ID: On Tue, 15 May 2007 07:15:21 +0200, ZeD wrote: > Neil Hodgson wrote: > >> Ada 2005 allows Unicode identifiers and even includes the constant >> '?' in Ada.Numerics. ^^^ > this. is. cool. Yeah, right... The problems begin... Joke aside, this just means that I won't ever be able to program math in ADA, because I have absolutely no idea on how to do a 'pi' character on my keyboard. Still -1 for the PEP... -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From orl at gmx.de Tue May 29 10:34:22 2007 From: orl at gmx.de (=?ISO-8859-1?Q?Orlando_D=F6hring?=) Date: Tue, 29 May 2007 16:34:22 +0200 Subject: [B,IX] = sort(A,...) - Order for sort()-function Message-ID: <8cc339d80705290734r3c0e3828vd53e1b80de89527@mail.gmail.com> Dear community, I want to use the sort function to sort a (nested) list. General information can be found below. http://www.python.org/doc/2.4.2/lib/typesseq-mutable.html http://wiki.python.org/moin/HowTo/Sorting http://www.python.org/doc/2.4.4/whatsnew/node12.html I want to solve the following problem. Given a list I do not only want to retrieve the sorted list but also the position of the original elements (IX below). The example is taken from Matlab syntax: http://www.mathworks.com/access/helpdesk/help/techdoc/ref/sort.html '[B,IX] = sort(A,...) also returns an array of indices IX, where size(IX) == size(A). If A is a vector, B = A(IX). If A is an m-by-n matrix, then each column of IX is a permutation vector of the corresponding column of A, such that for j = 1:n B(:,j) = A(IX(:,j),j); end' -- A = [ 3 7 5 0 4 2 ]; # in Python: A = [[3,7,5],[0,4,2]] [B,IX] = sort(A,2) # sort by rows B = 3 5 7 0 2 4 IX = 1 3 2 1 3 2 # first line: 3 was formerly in the first position, 5 formerly in position 3, 7 formerly in position 2 # second line: similiarly Yours, Orlando -- -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.rawlins at thinkbluemedia.co.uk Wed May 2 01:43:31 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Wed, 2 May 2007 06:43:31 +0100 Subject: Dynamic File Name Open() Message-ID: <001c01c78c7c$d14657f0$73d307d0$@rawlins@thinkbluemedia.co.uk> Chaps, I'm trying to open a file using open() but the name of the file is created dynamically as a variable, but also has part of a static path. For instance, the file may be called 'dave' and will always be in '/my/files/here/'. Now I've tried a few combinations of getting this to work, such as. Path = '/my/files/here/%s' % (name) Open(Path, 'r') But that does work, can anyone enlighten me on the best way to do this? Thanks, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From arkanes at gmail.com Tue May 1 11:44:47 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 1 May 2007 10:44:47 -0500 Subject: re-importing modules In-Reply-To: References: <8%pZh.18192$Kd3.76@newssvr27.news.prodigy.net> <1177962288.575008.48490@q75g2000hsh.googlegroups.com> <1177967919.968338.3300@l77g2000hsb.googlegroups.com> Message-ID: <4866bea60705010844p37a06326kcba7b5757fcb25e3@mail.gmail.com> On 5/1/07, John Nagle wrote: > Steven D'Aprano wrote: > > I'd hate for reload to disappear, it is great for interactive > > development/debugging, at least under some circumstances. (If you have > > complex and tangled class hierarchies, it might not be powerful enough.) > > > > As for the semantics being awful, I disagree. reload() does exactly > > what it claims to do, no more, no less. > > It's more complicated than that. See > > http://arcknowledge.com/lang.jython.user/2006-01/msg00017.html > > Exactly what reloading should do is still an open question for some of > the hard cases. > > "reload" as a debug facility is fine. > Trouble comes from production programs which use it as a > reinitialization facility. > > Reloading a module with multiple threads running gets > complicated. It works in CPython because CPython doesn't have > real concurrency. Insisting that it work like CPython implies > an inefficient locking model. > > John Nagle > -- Not really. The problem is when people attempt to overload the current, existing reload() semantics (which are sensible and simple once you understand that they don't attempt magic, although people tend to expect the magic and they're non-intuitive in that manner). There shouldn't be any problem implementing reload() in anything that implements import. The problem is with the fancier, magical imports that people keep expecting reload() to be, and thats what both the links you've provided are attempting to write. There's potentially a place for that sort of reload(), but it clearly can't have the semantics that the current reload does, and it suffers from all the same problems that hotpatching systems always have - that it's not always clear how they should work or what they should do, and you need a very tight specification of how they will work in all the corner cases, including threading. But that's got nothing to do with the current reload(), which is simple, straightforward, and easily implemented. The GIL isn't important in this respect - there's nothing complicated about reload() that isn't also complicated about import. You either have thread-local modules (which is probably stupid, because it can result in all sorts of crazy behavior if you pass objects defined in different versions of the same module between threads) or you serialize import and access to sys.modules (or whatever your underlying implementation of the module cache is). From cesar.gomes at gmail.com Sun May 13 15:36:52 2007 From: cesar.gomes at gmail.com (Cesar G. Miguel) Date: 13 May 2007 12:36:52 -0700 Subject: Basic question In-Reply-To: <1hy0cy8.eg6p1p135hbo3N%aleax@mac.com> References: <1178986686.510137.195490@p77g2000hsh.googlegroups.com> <1178991933.421386.58500@u30g2000hsc.googlegroups.com> <1178992910.318929.77790@e51g2000hsg.googlegroups.com> <1178995630.925969.207740@w5g2000hsg.googlegroups.com> <1hy0cy8.eg6p1p135hbo3N%aleax@mac.com> Message-ID: <1179085012.596034.24500@p77g2000hsh.googlegroups.com> On May 12, 8:13 pm, a... at mac.com (Alex Martelli) wrote: > Cesar G. Miguel wrote: > > > On May 12, 3:40 pm, Dmitry Dzhus wrote: > > > > Actually I'm trying to convert a string to a list of float numbers: > > > > str = '53,20,4,2' to L = [53.0, 20.0, 4.0, 2.0] > > > > str="53,20,4,2" > > > map(lambda s: float(s), str.split(',')) > > > > Last expression returns: [53.0, 20.0, 4.0, 2.0] > > > -- > > > Happy Hacking. > > > > Dmitry "Sphinx" Dzhushttp://sphinx.net.ru > > > Nice! > > As somebody else alredy pointed out, the lambda is supererogatory (to > say the least). > > > The following also works using split and list comprehension (as > > suggested in a brazilian python forum): > > > ------------------- > > L = [] > > file = ['5,1378,1,9', '2,1,4,5'] > > str='' > > for item in file: > > L.append([float(n) for n in item.split(',')]) > > The assignment to str is useless (in fact potentially damaging because > you're hiding a built-in name). > > L = [float(n) for item in file for n in item.split(',')] > > is what I'd call Pythonic, personally (yes, the two for clauses need to > be in this order, that of their nesting). > > Alex Yes, 'str' is unnecessary. I just forgot to remove it from the code. From jianbing.chen at gmail.com Fri May 4 17:30:06 2007 From: jianbing.chen at gmail.com (jianbing.chen at gmail.com) Date: 4 May 2007 14:30:06 -0700 Subject: behavior difference for mutable and immutable variable in function definition Message-ID: <1178314206.701824.291560@n59g2000hsh.googlegroups.com> Hi, Can anyone explain the following: Python 2.5 (r25:51908, Apr 9 2007, 11:27:23) [GCC 4.1.1 20060525 (Red Hat 4.1.1-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> def foo(): ... x = 2 ... >>> foo() >>> def bar(): ... x[2] = 2 ... >>> >>> bar() Traceback (most recent call last): File "", line 1, in File "", line 2, in bar NameError: global name 'x' is not defined Thanks, Jianbing From tinaweb at bestemselv.com Thu May 3 01:25:31 2007 From: tinaweb at bestemselv.com (Tina I) Date: Thu, 03 May 2007 07:25:31 +0200 Subject: how update a qListView in backgroud In-Reply-To: References: Message-ID: Reinaldo Carvalho wrote: > Hi, > > I programming with qt module and i have a qWidgetTab with a qListView > inside, and i need update the qListView every 5 seconds, how do this > on transparent mode to user. I do a function to update, but i dont > know call then. > > I will start this update when user select this tab, and stop whe user > leave this tab. I need a thread ot something else? > Assuming PyQt4 here: Check out QTimer. Have it start when the user selects the tab and have it timeout every five seconds calling the update function. Tina From fdu.xiaojf at gmail.com Mon May 14 22:23:00 2007 From: fdu.xiaojf at gmail.com (fdu.xiaojf at gmail.com) Date: Tue, 15 May 2007 10:23:00 +0800 Subject: How to calculate definite integral with python Message-ID: <46491984.4070908@gmail.com> I'm trying to do some integral calculation. I have searched the web, but haven't found any useful information. Will somebody point me to the right resources on the web for this job ? Thanks a lot. ps. Can numpy be used for this job?* * From dundeemt at gmail.com Mon May 7 23:25:59 2007 From: dundeemt at gmail.com (dundeemt) Date: 7 May 2007 20:25:59 -0700 Subject: ANN: Omaha Python Users Group Meeting, May 10 Message-ID: <1178594759.063491.124600@l77g2000hsb.googlegroups.com> It's time for another get together! May 10, 2007 - 7pm Door Prize: + There will be a door prize for this meeting! Topics: + Testing in Python: Nosetest + Lightning Talks (subprocess, cheetah) Discuss possible additional monthly lunch meeting Location: Reboot The User 13416 A Street Omaha, NE 68144 Refreshments: + Pizza and Pop sponsored by DM&T. Please make sure and mail the list with toppings and flavor requests for the meeting. From adamurbas at hotmail.com Fri May 11 21:47:27 2007 From: adamurbas at hotmail.com (adamurbas at hotmail.com) Date: 11 May 2007 18:47:27 -0700 Subject: need help with python Message-ID: <1178934447.719778.197150@h2g2000hsg.googlegroups.com> ya so im pretty much a newb to this whole python thing... its pretty cool but i just started today and im already having trouble. i started to use a tutorial that i found somewhere and i followed the instructions and couldnt get the correct results. heres the code stuff... temperature=input("what is the temperature of the spam?") if temperature>50: print "the salad is properly cooked." else: print "cook the salad some more." ya i was trying to do that but when i told it what the spams temperature was, it just turned off... well it wasnt working at all at first until i realized that i hadnt been following the instructions completely correctly and that i was supposed to type that code up in a notepad then save and open with python... so ya thats when it asked me what temperature the spam was and i typed a number then it just closed itself... im not really sure what went wrong... itd be real nice if someone would be like a mentor or something... From ruiligc at earthlink.net Tue May 1 06:47:02 2007 From: ruiligc at earthlink.net (Ray) Date: Tue, 01 May 2007 10:47:02 GMT Subject: python TK scrollbar problem In-Reply-To: References: Message-ID: James Stroud wrote: > > You are not binding to the Scrollbar.set() method nor are you assigning > the Scrollbar a command. You should try to emulate this: > > http://www.pythonware.com/library/tkinter/introduction/x7583-patterns.htm > > You need to also determine exactly what it is you want to scroll. You > probably don't want to scroll frame_grid as that contains your > scrollbar. Google "tkinter scrolled frame". Here is an example: > > http://mail.python.org/pipermail/python-list/2007-February/427886.html > > So, a suggestion would be to create a new frame to hold frame_grid and > yscroll and then use yscroll to scroll frame_grid. > > James entry do not have .yview and yscrollcommand. I will try to scroll frame_grid with a new frame. thanks Ray From tony.meyer at gmail.com Thu May 31 17:56:58 2007 From: tony.meyer at gmail.com (Tony Meyer) Date: 31 May 2007 14:56:58 -0700 Subject: Python 2.5.1 broken os.stat module In-Reply-To: References: Message-ID: <1180648618.295955.68600@x35g2000prf.googlegroups.com> On Jun 1, 9:16 am, "Joe Salmeri" wrote: > I just upgraded from Python 2.4.2 to Python 2.5.1 and have found some > unexpected behavior that appears to be a bug in the os.stat module. Have you read this thread? http://groups.google.com/group/comp.lang.python/browse_thread/thread/890eef2197c6f045/5466283a8253cafb?lnk=gst&q=getmtime&rnum=3#5466283a8253cafb I suspect that it explains your problem. Cheers, Tony From saif.shakeel at gmail.com Thu May 10 07:21:35 2007 From: saif.shakeel at gmail.com (saif.shakeel at gmail.com) Date: 10 May 2007 04:21:35 -0700 Subject: replacing string in xml file--revisited In-Reply-To: <1178787310.006875.204040@w5g2000hsg.googlegroups.com> References: <1178783809.444544.79640@w5g2000hsg.googlegroups.com> <1178787310.006875.204040@w5g2000hsg.googlegroups.com> Message-ID: <1178796095.060439.40240@y5g2000hsa.googlegroups.com> On May 10, 1:55 pm, half.ital... at gmail.com wrote: > On May 10, 12:56 am, saif.shak... at gmail.com wrote: > > > > > > > Hi, > > I need to replace a string in xml file with something else.Ex > > > - > > rate > > rate > > > > > > > > - > > > Here i have opened an xml > > file(small part is pasted here).I want to replace the word 'localId' > > with 'dataPackageID' wherever it comes in xml file.I have asked this > > before and got a code: > > input_file = open(filename) > > xmlcontents = input_file.read() > > input_file.close() > > xmlcontents = xmlcontents.replace("spam", "eggs") > > output_file = open(filename,"w") > > output_file.write(xmlcontents) > > output_file.close() > > > Although this works alone it is nto > > working when i handle multiple file I/O.Is there a alternative to do > > this.(maybe without read() operation) > > Thanks > > After reading your post again, this might be better: > > #!/usr/bin/env python > > from elementtree import ElementTree as et > tree = et.parse("testxml.xml") > > for t in tree.getiterator("SERVICEPARAMETER"): > if t.get("Semantics") == "localId": > t.set("Semantics", "dataPackageID") > > tree.write("output.xml") > > ~Sean- Hide quoted text - > > - Show quoted text - which module should be imported for above to work,it says ImportError: No module named elementtree Thanks From Glich.Glich at googlemail.com Sat May 19 11:40:24 2007 From: Glich.Glich at googlemail.com (Glich) Date: 19 May 2007 08:40:24 -0700 Subject: Start In-Reply-To: <1179588413.987135.241210@e65g2000hsc.googlegroups.com> References: <1179588413.987135.241210@e65g2000hsc.googlegroups.com> Message-ID: <1179589224.627849.282280@u30g2000hsc.googlegroups.com> I got started here: http://showmedo.com/videos/python From infocat at earthlink.net Mon May 28 23:08:34 2007 From: infocat at earthlink.net (Frank Swarbrick) Date: Mon, 28 May 2007 21:08:34 -0600 Subject: Is PEP-8 a Code or More of a Guideline? In-Reply-To: References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> Message-ID: <5c1jpkF2tl0ilU1@mid.individual.net> Roy Smith wrote: > I really like lisp's convention of using dashes instead of underscores, > i.e. ip-address and snmp-manager. I think the only reason most languages > don't use that is the parsing ambiguity, but if you required white space > around all operators, then "ip-address" would unambiguously be a variable > name and "ip - address" would be a subtraction expression. Then you'd really love COBOL! :-) Frank COBOL programmer for 10+ years From mikeminer53 at hotmail.com Wed May 23 12:45:28 2007 From: mikeminer53 at hotmail.com (mkPyVS) Date: 23 May 2007 09:45:28 -0700 Subject: Resizing listbook's listview pane In-Reply-To: <1179932659.180278.72990@w5g2000hsg.googlegroups.com> Message-ID: <1179938728.318264.273840@g4g2000hsf.googlegroups.com> On May 23, 9:04 am, kyoso... at gmail.com wrote: > Which Python gui toolkit are you using? Tkinter, wxPython, pyQT? Are > you wanting the resize to happen programmatically, when the user > changes the app's size, both or what? > > More details would be helpful. > > Mike Sorry, copied from wxpython submit as well.. I'm using wxpython 2.8... Primariy I want the resize to happen programatically during object creation/post creation... I can worry about app size changes later. Thanks, From mblume at socha.net Sat May 19 10:36:44 2007 From: mblume at socha.net (Martin Blume) Date: Sat, 19 May 2007 16:36:44 +0200 Subject: Execute commands from file References: <1179320782.594398.67980@u30g2000hsc.googlegroups.com> <464b370c$0$3808$5402220f@news.sunrise.ch> <1179387023.005808.60670@o5g2000hsb.googlegroups.com> <464c7e99$0$3814$5402220f@news.sunrise.ch> <464ee1b6$0$3812$5402220f@news.sunrise.ch> Message-ID: <464f0b7c$0$3812$5402220f@news.sunrise.ch> "Steve Holden" schrieb > > I simply meant that the whole source has to be presented > to the exec statement and not chunked into lines. > That's what I meant: With exec open(f).read() it is not broken into several exec invocations. > > I was probably just a little over-zealous in pursuing > correct English usage, in which case please accept > my apology. > The apology is on my part, I didn't explain my thinking clearly enough. Thanks for your explanations. Makes my newbie understanding of Python much more robust. Regards Martin From john at datavoiceint.com Tue May 8 22:19:12 2007 From: john at datavoiceint.com (HMS Surprise) Date: 8 May 2007 19:19:12 -0700 Subject: String parsing In-Reply-To: References: <1178672992.522463.228620@l77g2000hsb.googlegroups.com> Message-ID: <1178677152.478615.79170@y80g2000hsf.googlegroups.com> Yes it could, after I isolate that one string. Making sure I that I isolate that complete line and only that line is part of the problem. thanks for posting. jh From Dave.Baum at motorola.com Wed May 9 13:49:12 2007 From: Dave.Baum at motorola.com (Dave Baum) Date: Wed, 09 May 2007 12:49:12 -0500 Subject: Simulating simple electric circuits References: <5a9838F2nlbanU1@mid.individual.net> <5ae44aF2ku9rtU1@mid.individual.net> Message-ID: In article <5ae44aF2ku9rtU1 at mid.individual.net>, Bjoern Schliessmann wrote: > Sounds more familiar than the analog approach. Maybe I misunderstood > something ... but I can't transfer my problem to this way of > thinking yet. My biggest problem is the fact that relays aren't > really interested in voltage, but current. > > Also, I find it difficult to transfer this circuit logic to boolean > logic I can contruct logic gates from. Sometimes, electric circuits > are used in different directions. Yep, the traditional digital simulation techniques don't apply very well to things like switches and relays. Going with a different approach is probably cleaner. > > I set up the mentioned "controller" which, at the beginning, tries > out all possible ways through the network and saves them. So, for > every possible circuit it knows which switches must be closed and > which relays will work if it's "on". In theory, it should now be > possible to try out every path, tell the relays if they have > voltage/current, and let the relays report back in to the > controller if their status changes so it can again test the > circuits that may have changed. I haven't tried out the last step, > but I will in the next days. Is there any logic error in my > strategy? Sounds reasonable. Depending on the size of your network, I might not worry too much about precomputing and saving information. If your circuit has loops in it (where the output of a later relay circles back to an earlier relay's coil), then it is possible for the circuit to oscillate, so you might have to be careful about this. For example, if your basic simulation flow was: 1) set initial conditions (switches, etc) 2) let power flow through the system 3) determine which relays will be thrown 4) if any relays have changed state, go to 2 Then an oscillating circuit would never quit. You might want to put a limit on the number of iterations through the loop, or logic that explicitly checks for oscillation. Or you could analyze the circuit ahead of time to see whether it has oscillation or not. Dave From manstey at csu.edu.au Sun May 20 20:49:12 2007 From: manstey at csu.edu.au (manstey) Date: 20 May 2007 17:49:12 -0700 Subject: subclassing list question Message-ID: <1179708552.839036.114950@b40g2000prd.googlegroups.com> Hi, I have a simple class that subclasses a list: class CaListOfObj(list): """ subclass of list """ def __init__(self, *args, **kwargs): list.__init__(self, *args, **kwargs) a= CaListOfObj([1,2,3]) Is it possible to have a method in the class that is called EVERY time a is modified? Thanks From nagle at animats.com Thu May 17 12:35:15 2007 From: nagle at animats.com (John Nagle) Date: Thu, 17 May 2007 09:35:15 -0700 Subject: Python Web Programming - looking for examples of solid high-traffic sites In-Reply-To: References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> Message-ID: Jarek Zgoda wrote: > Victor Kryukov napisa?(a): > > >>Our main requirement for tools we're going to use is rock-solid >>stability. As one of our team-members puts it, "We want to use tools >>that are stable, has many developer-years and thousands of user-years >>behind them, and that we shouldn't worry about their _versions_." The >>main reason for that is that we want to debug our own bugs, but not >>the bugs in our tools. > > > I don't think you find anything even remotely resembling that idea here. > Moreover, I don't think you find it elsewhere. Maybe even such tools do > not exist in nature? Sure they do. I have a complex web site, "http://www.downside.com", that's implemented with Perl, Apache, and MySQL. It automatically reads SEC filings and parses them to produce financial analyses. It's been running for seven years, and hasn't been modified in five, except once when the NASDAQ changed the format of their ticker symbol file. It's not that useful at this point, because its purpose was to predict failing dot-coms, but it's still running and doing a sizable amount of work every day to update itself. John Nagle From tavares at fe.up.pt Thu May 10 13:54:18 2007 From: tavares at fe.up.pt (tavares at fe.up.pt) Date: 10 May 2007 10:54:18 -0700 Subject: Symposium "Computational Methods in Image Analysis" within the USNCCM IX Congress - Submission ENDS in 5 days Message-ID: <1178819658.771291.170990@p77g2000hsh.googlegroups.com> ------------------------------------------------------------------------------------------------------------------------------------------- (Apologies for cross-posting) Symposium "Computational Methods in Image Analysis" National Congress on Computational Mechanics (USNCCM IX) San Francisco, CA, USA, July 22 - 26 2007 http://www.me.berkeley.edu/compmat/USACM/main.html We would appreciate if you could distribute this information by your colleagues and co-workers. ------------------------------------------------------------------------------------------------------------------------------------------- Dear Colleague, Within the National Congress on Computational Mechanics (USNCCM IX), to be held in San Francisco, CA, USA, July 22 - 26 2007, we are organizing the Symposium "Computational Methods in Image Analysis". Examples of some topics that will be considered in that symposium are: Image acquisition, Image processing and analysis, Image segmentation, 3D Vision, Motion analysis, Pattern recognition, Objects recognition, Medical imaging and Tools and applications. Due to your research activities in those fields, we would like to invite you to submit an abstract and participate in the symposium "Computational Methods in Image Analysis". For instructions and submission, please access to the congress website at: http://www.me.berkeley.edu/compmat/USACM/main.html. Please note, when submitting your abstract you should select "053 - Computational Methods in Image Analysis". Important dates: - Deadline for abstract submissions (EXTENDED): May 15, 2007 - Final selection of abstracts: May 22, 2007 - Deadline for early registration (EXTENDED!): June 1, 2007 - Deadline for regular registration: July 15, 2007 Kind regards, Jo?o Manuel R. S. Tavares Renato Natal Jorge Yongjie Zhang Dinggang Shen (Symposium organizers) From ggrabler at gmail.com Sat May 5 15:45:20 2007 From: ggrabler at gmail.com (Georg Grabler) Date: Sat, 05 May 2007 19:45:20 +0000 Subject: Python Binding Message-ID: Hello everybody. There's a C library which i'd like to have python bindings for. I havn't known anything before about how to write python bindings for a C library. I succeeded now by using distutils to write the first bindings for functions and similar. Now, it seems as something is blocking my brain. For the library, i need "custom" types, so types defined in this library (structures), including pointers and similar. I've been thinking about what i will need to represent this lists in python. I thought about creating an external python object, providing "information" i get from the list in C structures which can be converted. Basically, it are list of packages, which have several attributes (next, prev, etc). But i don't know how to supply a proper list from the binding / object written in C. Any suggestions or hints about this? Thank you, Georg From gagsl-py2 at yahoo.com.ar Sat May 19 17:43:50 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 19 May 2007 18:43:50 -0300 Subject: dislin titlin and string decode References: <1179572181.557824.213350@k79g2000hse.googlegroups.com> <1179610131.799695.244180@p77g2000hsh.googlegroups.com> Message-ID: En Sat, 19 May 2007 18:28:51 -0300, luis escribi?: > The problem was the value of dislin.chacod. This must be 'ISO1' not > the default ('STANDAR') I used to use DISLIN some time ago, but now I use PyChart most of the time. Its convoluted interfase (mostly due to Fortran support, I guess) makes it rather "ugly" to use from Python. (And has a very strange licence, btw.) -- Gabriel Genellina From aahz at pythoncraft.com Wed May 30 17:50:57 2007 From: aahz at pythoncraft.com (Aahz) Date: 30 May 2007 14:50:57 -0700 Subject: Resize image NO PIL!! References: <1180406398.615904.22230@g4g2000hsf.googlegroups.com> Message-ID: In article <1180406398.615904.22230 at g4g2000hsf.googlegroups.com>, cbmeeks wrote: > >My stupid host (pair.com) doesn't have PIL installed and I'm too much >of a stupid newbie to figure out how to get it to work with them >(access denied while installing it, of course). > >Also, they don't have any python interface setup for GD. > >Anyway, I don't know what my options are. I'm thinking: > >1) Find another host with mod_python, PIL, and other Python goodies webfaction.com -- I almost went with pair.com because they're reliable, but I decided to choose a provider that supports Python. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From devicerandom at gmail.com Thu May 24 12:49:46 2007 From: devicerandom at gmail.com (massimo s.) Date: 24 May 2007 09:49:46 -0700 Subject: of destructors, open files and garbage collection In-Reply-To: References: <1180021256.619953.80500@q66g2000hsg.googlegroups.com> Message-ID: <1180025386.880262.230470@q66g2000hsg.googlegroups.com> > It will delete the *name* `item`. It does nothing to the object that was > bound to that name. If the name was the only reference to that object, it > may be garbage collected sooner or later. Read the documentation for the > `__del__()` method for more details and why implementing such a method > increases the chance that the object *won't* be garbage collected! > > Relying on the `__del__()` method isn't a good idea because there are no > really hard guaranties by the language if and when it will be called. Ok, I gave a look at the docs and, in fact, relying on __del__ doesn't look like a good idea. Changing the code as to add an explicit method that closes dangling filehandles is easy. It would be somehow nice because -since that method would be added to a plugin API- it *forces* people writing plugins to ensure a way to close their dangling files, and this may be useful for a lot of future purposes. However I'd also like to track references to my objects -this would help debugging a lot. How can I do that? From facundo at taniquetil.com.ar Wed May 30 09:05:33 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Wed, 30 May 2007 13:05:33 +0000 (UTC) Subject: Malformed big5 reading bug References: <84fb38e30705291212t12e3f668x66927a918926e761@mail.gmail.com> Message-ID: tsuraan wrote: > Python enters some sort of infinite loop when attempting to read data from a > malformed file that is big5 encoded (using the codecs library). This > behaviour can be observed under Linux and FreeBSD, using Python 2.4 and 2.5. > A really simple example illustrating the bug follows: > ... > be a good but to have out there so a future version of python can > (hopefully) fix this. Please, file a bug in SourceForge, with the example and everything. Thanks! -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From tjandacw at yahoo.com Mon May 14 16:18:01 2007 From: tjandacw at yahoo.com (timw.google) Date: 14 May 2007 13:18:01 -0700 Subject: os.listdir() doesn't work ?? In-Reply-To: References: Message-ID: <1179173881.163830.54930@n59g2000hsh.googlegroups.com> On May 14, 4:09 pm, Stef Mientki wrote: > hello, > > I want to find all files with the extension "*.txt". > From the examples in "Learning Python, Lutz and Asher" and > from the website I see examples where you also may specify a wildcard filegroup. > > But when I try this > files = os.listdir('D:\\akto_yk\\yk_controle\\*.txt') > > I get an error message > > WindowsError: [Errno 123] The filename, directory name, or volume label syntax is incorrect: > 'D:\\akto_yk\\yk_controle\\*.txt/*.*' > > What am I doing wrong ? > > thanks, > Stef Mientki You want the glob module http://docs.python.org/lib/module-glob.html import glob glob.glob('*.txt') From steven at REMOVE.THIS.cybersource.com.au Tue May 15 04:54:40 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 15 May 2007 08:54:40 GMT Subject: Sorting troubles References: <1179158708.433792.127150@h2g2000hsg.googlegroups.com> <1179161396.220858.86150@q75g2000hsh.googlegroups.com> <1179204326.945346.38590@q75g2000hsh.googlegroups.com> Message-ID: On Mon, 14 May 2007 21:45:26 -0700, seyensubs wrote: > Ah, I see, just slicing it like that.. nice! But after doing some timing > tests, the version that's in place and using partitions is about twice > faster than the non hybrid qSort. The hybrid one, with insertionsSort > used for smaller lists works faster, but in a weird way. When given > lists of 2000, the best bet to is to set the threshold to 14, but when > given a list of 40000, 14 is slow, but a threshold of 200(less or more > is slower, again) makes it about 8 times faster than a normal qSort, and > 4 times faster than an in-place qSort, using a self -defined > partitioning alg. > > Making a hybrid out of the in-place partitioned qSort makes it a bit > faster, but not by much compared to the other hybrid which uses list > comprehensions. > > Teach said that the optimal threshold in hybrids is 14-16, but guess he > wasn't so right after all =\\ The overhead of using insertion sort on a > longer list turns out to be faster than just piling on recursions, when > confronted with bigger lists. Teach may have been thinking of languages where comparing items is fast and moving data is slow; Python is the opposite, comparisons invoke a whole bucket-full of object-oriented mechanism, while moving data just means moving pointers. It needs to be said, just in case... this is a good learning exercise, but don't use this in real code. You aren't going to get within a bull's roar of the performance of the built-in sort method. Tim Peter's "timsort" is amazingly powerful; you can read about it here: http://pythonowns.blogspot.com/2002_07_28_pythonowns_archive.html#79780508 http://svn.python.org/projects/python/trunk/Objects/listsort.txt -- Steven. From antroy at gmail.com Thu May 10 03:57:52 2007 From: antroy at gmail.com (Ant) Date: 10 May 2007 00:57:52 -0700 Subject: preferred windows text editor? In-Reply-To: <1178749301.768963.278070@w5g2000hsg.googlegroups.com> References: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> <1178749301.768963.278070@w5g2000hsg.googlegroups.com> Message-ID: <1178783872.463067.297280@o5g2000hsb.googlegroups.com> On May 9, 11:21 pm, BartlebyScrivener wrote: ... > I too vote for VIM. I use it on both Windows XP and Debian Etch. I > can't find anything it doesn't do. I also use Vim (well, GVim). The only thing I find missing is an integrated console for running code snippets/entire scripts. The runscript plugin is OK, but lacks interactive use. I have been thinking about some way of interacting with a Python shell using sockets to send snippets directly to the shell from Vim, but haven't had time to get very far. What method of executing code snippets in a Python shell do other Vim users use? Other than just copy/paste? From default at defaulter.net Thu May 3 08:36:12 2007 From: default at defaulter.net (default) Date: Thu, 03 May 2007 08:36:12 -0400 Subject: Firefighters at the site of WTC7 "Move away the building is going to blow up, get back the building is going to blow up." References: <1178161820.731367.264500@y80g2000hsf.googlegroups.com> Message-ID: <1hlj33p6aq838o2urk1dv6h75b5is4i2vd@4ax.com> On 2 May 2007 20:10:20 -0700, Midex wrote: >LIES LIES LIES LIES LIES Trying to understand the World Trade Center events is like waking up to act fifteen of a long Greek Tragedy. It needs a complex fabric of description to give a full picture. In explaining this crisis, we will be showing how the situation rests on layers of historical developments, layers of crises and solutions. shamelessly taken from: http://www.againstsleepandnightmare.com/ASAN/ASAN7/ASAN7.html The World After September 11th, 2001 The Old Mole By the time you read this, a crisis different from September 11th may well be foremost in people's minds. Read on. For us today, all the crises merge to one and we can see the form of Enron's Collapse or the Iraq War within September 11th and vice-versa. Now, beyond the death and destruction, the horror of an event like September 11th is the horror of losing control of your world. This feeling is an extension of the ordinary experience of being a resident of modern capitalist society. Here, work, commuting, shopping, and television are transmitted to you in ways that are beyond any individual or collective control. Damn good read. -- ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From nagle at animats.com Wed May 2 13:58:43 2007 From: nagle at animats.com (John Nagle) Date: Wed, 02 May 2007 10:58:43 -0700 Subject: Python un-plugging the Interpreter In-Reply-To: References: <1hwu415.1yyvbo61efn1uqN%aleax@mac.com> Message-ID: Jorgen Grahn wrote: > On Wed, 25 Apr 2007 08:05:01 +0200, Hendrik van Rooyen wrote: > >>"Jorgen Grahn" wrote: > Eric Raymond's "The Art of Unix Programming" sums up the threading > criticism, I think: > > http://catb.org/~esr/writings/taoup/html/multiprogramchapter.html What that really reflects is that threads came late to UNIX. The locking primitives weren't standardized for years, signals took a decade to settle down, interprocess message passing was weak and still is, and some parts of the context, like the current directory, are per-process while they should be per-thread. To this day, threading remains an afterthought in the UNIX/Linux/C world. This really isn't a Python topic, but if you want to see threading and interprocess communication done right, look at QNX 6. True message passing, well defined semantics for thread cancellation, the ability to time out any system call that blocks, and defined atomic operations are all there. All the thread machinery that has to work right is well worked out and well documented. John Nagle From signs2443 at fedexkinkos.com Wed May 30 05:41:32 2007 From: signs2443 at fedexkinkos.com (Signs & Graphics Center) Date: Wed, 30 May 2007 05:41:32 -0400 Subject: A REAL money maker. IT WORKS!!!! Message-ID: <465D46CC.13217F75@fedexkinkos.com> was up man does this stuff realy works From steven.bethard at gmail.com Sun May 27 11:55:01 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 27 May 2007 09:55:01 -0600 Subject: PyPI bdist_wininst upload failing In-Reply-To: References: <1180249872.007145.48030@a26g2000pre.googlegroups.com> Message-ID: Gabriel Genellina wrote: > En Sun, 27 May 2007 12:19:03 -0300, Steven Bethard > escribi?: > >> Also, I couldn't get the StringIO code from there to work: >> >> >>> import StringIO >> >>> content = open('argparse-0.8.0.win32.exe').read() > > Use open("...","rb").read() - the "b" is important on Windows. Ahh, great. Thanks. So any ideas why distutils is generating a bdist_wininst installer with file names like: lib/argparse-0.8.0-py2.5.egg-info lib/argparse.py instead of what John Machin had: PURELIB/xlrd-0.6.1a4-py2.5.egg-info PURELIB/xlrd/biffh.py The ones with 'lib' instead of 'PURELIB' will get rejected by the safe_zipnames regular expression in verify_filetype.py: re.compile(r'(purelib|platlib|headers|scripts|data).+', re.I) Is there something I need to do when running 'setup.py bdist_wininst' to get 'PURELIB' instead of 'lib'? STeVe From gagsl-py2 at yahoo.com.ar Mon May 21 10:12:11 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 21 May 2007 11:12:11 -0300 Subject: TIFF to PDF References: <1179687595.142454.23850@z24g2000prd.googlegroups.com> <1179744141.027494.60590@r3g2000prh.googlegroups.com> <4651A444.9040901@cc.umanitoba.ca> Message-ID: En Mon, 21 May 2007 10:53:08 -0300, Brian van den Broek escribi?: > Gabriel Genellina said unto the world upon 05/21/2007 07:01 AM: >> En Mon, 21 May 2007 07:42:21 -0300, revuesbio >> escribi?: >> >>> os.system('"C:\Program Files\GnuWin32\bin\tiff2pdf.exe" -o C:\test.pdf >>> C:\test.TIF') >> >> \ is used as a escape character in strings. >> Use either \\ or a raw string, that is: >> > Better still, use / as the path separator. That works fine on both > windows and *nixes. But unfortunately / does not always work, specially for arguments to internal commands: py> os.system("type c:/windows/win.ini") La sintaxis del comando no es correcta. [invalid syntax] 1 py> os.system(r"type c:\windows\win.ini") [Compatibility] _3DPC=0x00400000 _BNOTES=0x224000 ... -- Gabriel Genellina From horpner at yahoo.com Thu May 24 15:52:29 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 24 May 2007 19:52:29 GMT Subject: converting text and spans to an ElementTree References: Message-ID: On 2007-05-24, Neil Cerutti wrote: > On 2007-05-23, Steven Bethard wrote: > You mean... I left out the hard part? Shucks. I had really > hoped it didn't matter. > >> * the recursive (or stack) part assigns children to parents >> * the non-recursive part assigns text or tail to the previous element >> (note that's previous in a sequential sense, not a recursive sense) >> >> I'm sure I could implement this recursively, passing around >> annother appropriate argument, but it wasn't obvious to me >> that the code would be any cleaner. > > Moreover, it looks like you have experience in writing that > sort of code. I'd have never even attempted it without > recursion, but that's merely exposing one of my limitations. ;) You'll be happy to know I found a way to salvage my simple recursive solution, and make it generate an ElementTree! def get_tree(text, spans): """ >>> text = 'aaa aaa aaabbb bbbaaa' >>> spans = [ ... (etree.Element('a'), 0, 21), ... (etree.Element('b'), 11, 18), ... (etree.Element('c'), 18, 18), ... ] I'd like to produce the corresponding ElementTree. So I want to write a get_tree() function that works like:: >>> etree.tostring(get_tree(text, spans)) 'aaa aaa aaabbb bbbaaa' """ def helper(text, spans): if not spans: return '' else: head, tail = spans[0], spans[1:] elem, start, end = head if tail: _, follow_start, follow_end = tail[0] else: follow_start, follow_end = (end, end) if end > start: return ("<%s>%s%s%s" % (elem.tag, text[start:follow_start], helper(text, tail), text[follow_end:end], elem.tag)) else: return "<%s />%s" % (elem.tag, helper(text, tail)) return etree.XML(helper(text, spans)) But at least I learned just a *little* about XML and Python during this arduous process. ;) -- Neil Cerutti The concert held in Fellowship Hall was a great success. Special thanks are due to the minister's daughter, who labored the whole evening at the piano, which as usual fell upon her. --Church Bulletin Blooper From JarodEvans at gmail.com Tue May 29 15:32:01 2007 From: JarodEvans at gmail.com (JarodEvans at gmail.com) Date: 29 May 2007 12:32:01 -0700 Subject: Speex bindings for python 2.5 In-Reply-To: <1180466922.114571.46410@d30g2000prg.googlegroups.com> References: <1180466922.114571.46410@d30g2000prg.googlegroups.com> Message-ID: <1180467121.238065.111720@r19g2000prf.googlegroups.com> On 29 mai, 21:28, JarodEv... at gmail.com wrote: > Hello, > > For a personal project, I need to use speex with Python on Win32, but > pyspeex is compiled for python 2.2. > > Could somebody try to compile pyspeex for python 2.5 please ? > > Thanx a lot for your help. I forgot to give the url : http://www.freenet.org.nz/python/pySpeex/ Thanks. From Graham.Dumpleton at gmail.com Mon May 21 04:26:56 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: 21 May 2007 01:26:56 -0700 Subject: mod_python performs several magnitudes slower than PHP? In-Reply-To: <46514F9F.2060004@tilanus.com> References: <1179616996.948606.319670@q75g2000hsh.googlegroups.com> <4dM3i.3287$y_7.725@newssvr27.news.prodigy.net> <1179625827.647353.50840@p77g2000hsh.googlegroups.com> <46514F9F.2060004@tilanus.com> Message-ID: <1179736016.540211.164230@x35g2000prf.googlegroups.com> On May 21, 5:51 pm, Winfried Tilanus wrote: > On 05/20/2007 Graham Dumpleton wrote: > > Hi, > > > A more suitable example for comparison would have been: > > And are there any benchmarks with this new version available? Just > curious... Unless someone else posts that specific example comparing it to PHP on the same system, then you might instead look at: http://www.modpython.org/pipermail/mod_python/2007-May/023654.html This shows the original posters Python example compared to another way of doing it, not what I posted, which would be even quicker, ie., using Python itself to do the buffering. Do note that such benchmarks are pretty meaningless as you will never achieve such throughputs once you actually load on top your Django, TurboGears, Pylons or other mega web framework application. Such applications are huge and carry a lot of overhead which dwarfs any overhead of mod_python itself. Graham From kensmith at rahul.net Fri May 4 21:52:12 2007 From: kensmith at rahul.net (MooseFET) Date: 4 May 2007 18:52:12 -0700 Subject: Firefighters at the site of WTC7 "Move away the building is going to blow up, get back the building is going to blow up." In-Reply-To: References: <1178161820.731367.264500@y80g2000hsf.googlegroups.com> <1hlj33p6aq838o2urk1dv6h75b5is4i2vd@4ax.com> <3TD_h.219$mR2.195@newssvr22.news.prodigy.net> Message-ID: <1178329932.455122.161530@u30g2000hsc.googlegroups.com> On May 4, 12:32 pm, James Stroud wrote: [....] > The Marxist contribution to western thought is that it put everything in > terms of labor and thus allowed us to quantify the human component of > economies. No the great insight by Marx was in the selling of ducks. "Anybody want to buy a duct" has done more to advance economic thinking than the works of most economists. Economists have a vested interest in preventing people from understanding economics. They are well paid and know that they wouldn't be for long if people really understood what was going on. From dustin at v.igoro.us Wed May 2 00:38:27 2007 From: dustin at v.igoro.us (dustin at v.igoro.us) Date: Tue, 1 May 2007 23:38:27 -0500 Subject: pre-PEP: Standard Microthreading Pattern In-Reply-To: References: <20070501205820.GE11383@v.igoro.us> Message-ID: <20070502043827.GE14710@v.igoro.us> On Tue, May 01, 2007 at 08:34:39PM -0400, Terry Reedy wrote: > Sounds like a good idea to me. Travis Oliphant has spent over a year on > http://www.python.org/dev/peps/pep-3118/ > so array-making-using programs can better operate together. I hope you > have the same patience and persistance. I hope so too! This is still only a pre-PEP, so there's a long way to go. > | .. [2] PEP 342, "Coroutines via Enhanced Generators", van Rossum, Eby > | (http://www.python.org/peps/pep-0342) > > This gave 404 Not Found while this works (/dev added): > http://www.python.org/dev/peps/pep-0342/ I'm going to assume these are related to the noises I'm hearing about ongoing funniness with the website. If someone is wiser than me, please speak up! > | .. [3] PEP 355, "Simple Generators", Schemenauer, Peters, Hetland > | (http://www.python.org/peps/pep-0342) > > 255, not 355 or 342 again: > http://www.python.org/dev/peps/pep-0255/ Thanks -- good catch! Dustin From steven.bethard at gmail.com Sat May 26 22:33:04 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 26 May 2007 20:33:04 -0600 Subject: ten small Python programs In-Reply-To: <1180229019.873381.52800@m36g2000hse.googlegroups.com> References: <1180229019.873381.52800@m36g2000hse.googlegroups.com> Message-ID: Paul McGuire wrote: > I ***love*** this "10 Little Programs" idea! As soon as I get a > breathing space, I'm going to add a "10 Little Parsers" page to the > pyparsing wiki! > > On May 26, 2:38 pm, Steven Bethard wrote: >> >> Though the code should probably follow PEP 8 guidelines, e.g. >> under_scores instead of camelCase for object and method names: >> >> http://www.python.org/dev/peps/pep-0008/ >> > > Really? Underscore-separated words preferred over camel case? What > is the rationale for this? Rationale? It's a style guide. There is no rationale. ;-) > If we want to just say "well, PEP-8 says such and such," I think this > is an area where the thinking has possibly evolved since 2001. I really don't think so. If anything, it's gotten more strict. PEP 8 used to allow either camelCase or under_scores. Now it only allows the latter. > I guess pyparsing with its mixedCase functions and attributes is > doomed for the Dunce Corner. Too bad for BeautifulSoup, cElementTree, > and wxPython that are also at variance with this canon of Python > coding style. Many (if not all) of these modules were written before the most recent incarnation of PEP 8. Thus, they fall under the second good reason "to break a particular rule": (2) To be consistent with surrounding code that also breaks it Of course, for new code, such as that in this thread, there's no reason to break from the PEP 8 guidelines. STeVe From gagsl-py2 at yahoo.com.ar Wed May 2 03:22:48 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 02 May 2007 04:22:48 -0300 Subject: os.path.join References: <1178072869.844914.59010@u30g2000hsc.googlegroups.com> <1178083903.677905.32710@c35g2000hsg.googlegroups.com> <1178089436.202973.148650@h2g2000hsg.googlegroups.com> Message-ID: En Wed, 02 May 2007 04:03:56 -0300, escribi?: > On May 1, 11:10 pm, "Gabriel Genellina" > wrote: >> The right usage is os.path.join(*pathparts) > > Wow. What exactly is that * operator doing? Is it only used in > passing args to functions? Does it just expand the list into > individual string arguments for exactly this situation? Or does it > have other uses? When calling a function, it is used to pass a sequence as positional arguments. Similarly, **values is used to pass a dictionary as keyword arguments. When defining a function, *args receives the remaining positional arguments not already bound to another parameter; and **kwargs receives the remaining keyword arguments not already bound to another parameter. [There is nothing special on the *args and **kwargs names, only the * and ** are important] See section 4.7 on the Python Tutorial http://docs.python.org/tut/node6.html#SECTION006700000000000000000 and specially section 4.7.4 Unpacking Argument Lists. For a more technical description (but sometimes necesary) read the Python Reference Manual http://docs.python.org/ref/calls.html -- Gabriel Genellina From cbmeeks at gmail.com Mon May 28 22:39:58 2007 From: cbmeeks at gmail.com (cbmeeks) Date: 28 May 2007 19:39:58 -0700 Subject: Resize image NO PIL!! Message-ID: <1180406398.615904.22230@g4g2000hsf.googlegroups.com> I have created an image hosting site and when a user uploads an image, I want a service to run on the server to create a few thumbnails while the user does other things. My stupid host (pair.com) doesn't have PIL installed and I'm too much of a stupid newbie to figure out how to get it to work with them (access denied while installing it, of course). Also, they don't have any python interface setup for GD. Anyway, I don't know what my options are. I'm thinking: 1) Find another host with mod_python, PIL, and other Python goodies 2) use PHP to create the thumbnails 3) Open the images into a buffer and try to do the calculations myself I'm thinking I might have to go with 1. I want the script to run as a service so I don't know how well number 2 would work and I certainly don't want number 3 (on a time-line here). Any suggestions? Thanks cbmeeks http://www.signaldev.com From noagbodjivictor at gmail.com Wed May 2 16:35:47 2007 From: noagbodjivictor at gmail.com (noagbodjivictor at gmail.com) Date: 2 May 2007 13:35:47 -0700 Subject: How to check if a string is empty in python? Message-ID: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> How to check if a string is empty in python? if(s == "") ?? From dtgeadamo at yahoo.com Wed May 2 12:51:18 2007 From: dtgeadamo at yahoo.com (Viewer T.) Date: 2 May 2007 09:51:18 -0700 Subject: Logic for Chat client Message-ID: <1178124678.168359.170760@e65g2000hsc.googlegroups.com> Could anyone kindly give me a comprehensive logic guide to creating a peer-to-peer chat program with Python. I would really appreciat a comprehensive guide and links to any modules I would need that are not in the standard library. From stefan.sonnenberg at pythonmeister.com Sat May 19 09:31:50 2007 From: stefan.sonnenberg at pythonmeister.com (Stefan Sonnenberg-Carstens) Date: Sat, 19 May 2007 15:31:50 +0200 Subject: Writelines() a bit confusing In-Reply-To: <1179578195.565952.244110@u30g2000hsc.googlegroups.com> References: <1179578195.565952.244110@u30g2000hsc.googlegroups.com> Message-ID: <464EFC46.8090902@pythonmeister.com> aiwarrior schrieb: > If file.WriteLines( seq ) accepts a list and it says it writes lines, > why does it write the whole list in a single line. Be cause of that > the reverse of file.writelines(seq) is not file.readlines(). > Are the assumptions i made correct? If yes why is this so? > > I find a function called writelines not actualy writing the list in > lines wierd. > > [code] > something = ['re','ri','ro'] > f.writelines( something ) > something_else = f.readlines() > [/code] > In this case the list something_else will be diffrent from something > > Please see this: >>> help(f.writelines) Help on built-in function writelines: writelines(...) writelines(sequence_of_strings) -> None. Write the strings to the file. Note that newlines are not added. The sequence can be any iterable object producing strings. This is equivalent to calling write() for each string. so you'd want this: f.writelines([x+os.linesep for x in strings]) or something similar. Why ? Ask the originator of this function. One explanation: If you do this: f1 = file('file1') f2 = file('file2','w') f2.writelines(f1.readlines()) f1.close() ; f2.close() all is how it should be. From claird at lairds.us Tue May 1 07:21:44 2007 From: claird at lairds.us (Cameron Laird) Date: Tue, 1 May 2007 11:21:44 +0000 Subject: Python-URL! - weekly Python news and links (Apr 30) References: <1177963548_23061@sp12lax.superfeed.net> <961ig4-hti.ln1@lairds.us> <1177974549_23503@sp12lax.superfeed.net> Message-ID: <8fkjg4-r5s.ln1@lairds.us> In article <1177974549_23503 at sp12lax.superfeed.net>, Roger Upole wrote: > >"Cameron Laird" wrote in message >news:961ig4-hti.ln1 at lairds.us... >> In article <1177963548_23061 at sp12lax.superfeed.net>, >> Roger Upole wrote: >>>Cameron Laird wrote: >>>> QOTW: "That is just as feasible as passing a cruise ship through a phone >>>> line." - Carsten Haese, on transporting a COM object across a network. >>>> Less vividly but more formally, as he notes, "A COM object represents a >>>> connection to a service or executable that is running on one computer. >>>> Transferring that connection to another computer is impossible." >>>> >>> >>>While this is indeed a nice turn of phrase, in substance it's incorrect. >>>You can marshal a live COM object and unmarshal it on a different >>>machine. >> . >> . >> . >> ... but the *references* in that object are unlikely to be >> meaningful on the second machine (or, in many cases, on the >> original machine, if at a sufficiently later time). > >In practice, you can marshal and unmarshal an object as complex >as Excel.Application which contains references to literally hundreds >of objects. . . . This surprises me; it's different from my experience. There's a lot I have to learn about COM and DCOM, though, so I thank you for the correction. The larger point, which you aptly reinforced, is that "Python-URL!"'s aim is not so much to teach facts as to provoke thought. We're successful when conversations like this ensue. From duncan.booth at invalid.invalid Tue May 8 12:54:18 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 8 May 2007 16:54:18 GMT Subject: changing a var by reference of a list References: <5abcj4F2nv0p0U1@mid.uni-berlin.de> Message-ID: "Jorgen Bodde" wrote: > I will try this approach. The idea was that I could give a list to the > SQL execute command, so that the results coming back would > automatically be assigned to variables. > Don't forget that in Python a function can return multiple results (or rather can return a sequence). That means you can do something like: varA, varB = doSomething() where doSomething would execute your SQL and return two results. From mhellwig at xs4all.nl Sun May 6 09:26:46 2007 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Sun, 06 May 2007 15:26:46 +0200 Subject: Did you read about that? In-Reply-To: <1178457498.639373.157350@y80g2000hsf.googlegroups.com> References: <1178446711.502374.286790@l77g2000hsb.googlegroups.com> <1178452403.114975.249050@u30g2000hsc.googlegroups.com> <1178457498.639373.157350@y80g2000hsf.googlegroups.com> Message-ID: <463dd72e$0$331$e4fe514c@news.xs4all.nl> Dustan wrote: > On May 6, 8:20 am, Steven D'Aprano > wrote: >> On Sun, 06 May 2007 04:53:23 -0700, Dustan wrote: >>> SPAM! >>> SPAM! >>> SPAM! >>> SPAM! >>> SPAM! >>> SPAM! >>> SPAM! >>> SPAM! >> Gosh, you think so? I'm glad we had you around to tell us, otherwise we >> might have thought it was about Python programming. >> >> Actually, many of us wouldn't even have seen it in the first place, >> because our ISPs do a good job of filtering out obvious spam before we >> even see it. And then people like you come along, and reply to it, and we >> see the reply -- complete with the original spam. > > Well, sorry. I didn't realize I'd get whacked around for making a > joke. > >> -- >> Steven. > Aren't jokes supposed to be funny? -- mph http://martinphellwig.blogspot.com/ From wildemar at freakmail.de Fri May 18 14:10:49 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Fri, 18 May 2007 20:10:49 +0200 Subject: (Modular-)Application Framework / Rich-Client-Platform in Python In-Reply-To: <1179503315.889565.166710@q75g2000hsh.googlegroups.com> References: <1179485905.764950.124000@p77g2000hsh.googlegroups.com> <1179503315.889565.166710@q75g2000hsh.googlegroups.com> Message-ID: <464DEC29.1040103@freakmail.de> Peter Wang wrote: > Actually, just this week, we completed a major SVN reorganization and > from this point forward, all of the libraries in ETS will be released > as eggs. In fact, eggs have been available for a long time for python > 2.4, and now we have them for python 2.5 as well. > > I'm not sure, but you guys seem a bit Windows-centric. I have yet to find out if the egg-approach actually works for Linux (and Mac, though I don't use it) as well. I've seen some mentioning of binary dependencies, which makes me frown a bit. We'll just see. > The "Eclipse in python" you're looking for is actually called > Envisage, and it is part of ETS: https://svn.enthought.com/enthought/wiki/Envisage > > The "Dev Guide" has some tutorials etc.: https://svn.enthought.com/enthought/wiki/EnvisageDevGuide > > Yeah, I've been reading through that for the past couple of hours, seems pretty sweet and reasonably simple. I can see your reorg, by the way: The example .py files are not where they're advertised to be. Better be quick with that, even solid software with buggy documentation is buggy software ... ;) > Chime in on the mailing list if you have any questions. It's pretty > active and many people on it have lots of experience with Envisage. > I'm almost sure I will :) c.u. /w From hanser at club-internet.fr Wed May 16 01:55:26 2007 From: hanser at club-internet.fr (Pierre Hanser) Date: Wed, 16 May 2007 07:55:26 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179291296.561359.286230@h2g2000hsg.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649dd55$0$23144$9b4e6d93@newsspool1.arcor-online.net> <464a25e9$0$10188$9b4e6d93@newsspool4.arcor-online.net> <1179291296.561359.286230@h2g2000hsg.googlegroups.com> Message-ID: <464a9cbe$0$21144$7a628cd7@news.club-internet.fr> rurpy at yahoo.com a ?crit : > On May 15, 3:28 pm, Ren? Fleschenberg wrote: >> We all know what the PEP is about (we can read). The point is: If we do >> not *need* non-English/ASCII identifiers, we do not need the PEP. If the >> PEP does not solve an actual *problem* and still introduces some >> potential for *new* problems, it should be rejected. So far, the >> "problem" seems to just not exist. The burden of proof is on those who >> support the PEP. it *does* solve a huge problem: i have to use degenerate french, with orthographic mistakes, or select in a small subset of words to use only ascii. I'm limited in my expression, and I ressent this everyday! This is true, even if commercial french programmers don't object the pep because they have to use english in their own work. This is something i really cannot understand. it's a problem of everyday, for million people! and yes sometimes i publish code (rarely), even if it uses french identifiers, because someone looking after a real solution *does* prefer an existing solution than nothing. -- Pierre From dotancohen at gmail.com Fri May 11 15:39:35 2007 From: dotancohen at gmail.com (Dotan Cohen) Date: Fri, 11 May 2007 22:39:35 +0300 Subject: stealth screen scraping with python? In-Reply-To: <1178911975.308104.297380@n59g2000hsh.googlegroups.com> References: <1178911975.308104.297380@n59g2000hsh.googlegroups.com> Message-ID: <880dece00705111239k20b23d3fm55f66af8eb2118be@mail.gmail.com> On 11 May 2007 12:32:55 -0700, different.engine at gmail.com wrote: > Folks: > > I am screen scraping a large volume of data from Yahoo Finance each > evening, and parsing with Beautiful Soup. > > I was wondering if anyone could give me some pointers on how to make > it less obvious to Yahoo that this is what I am doing, as I fear that > they probably monitor for this type of activity, and will soon ban my > IP. > > -DE > So long as you are sending a regular http request, as from a browser, then they will have no way of knowing. Just keep your queries down to no more than once every 3-5 seconds and you should be fine. Rotate your IP, too, if you can. Dotan Cohen http://lyricslist.com/lyrics/artist_albums/110/carmen_eric.html http://what-is-what.com/what_is/eula.html From dibanders at yahoo.com Thu May 3 14:29:49 2007 From: dibanders at yahoo.com (Dave Lim) Date: Thu, 3 May 2007 11:29:49 -0700 (PDT) Subject: problem with py2exe and microsoft speech SDK 5.1 Message-ID: <440422.1656.qm@web33510.mail.mud.yahoo.com> Hello, this is my first time in the mailing list so bear with me. Basically what I did was I followed this site: http://surguy.net/articles/speechrecognition.xml So I installed microsoft speech SDK 5.1 and then used pythonwin COM MakePy utility for it and it worked out fine. However, I need to compile my program into a .exe and I have no idea how to make this work. I tried using py2exe but I get the error: Traceback (most recent call last): File "simple-speech-recognition.py", line 57, in ? TypeError: Error when calling the metaclass bases cannot create 'NoneType' instances If anybody knows a good solution to this problem I would very much appreciate it if you can guide me to the right path / solution. Thank you very much! -Dave Lim __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From jnadiaz at yahoo.com Wed May 30 22:48:08 2007 From: jnadiaz at yahoo.com (jnadiaz at yahoo.com) Date: 30 May 2007 19:48:08 -0700 Subject: THE UNIVERSAL GOD BODY Message-ID: <1180579688.172008.44460@g4g2000hsf.googlegroups.com> THE UNIVERSAL GOD BODY http://groups.yahoo.com/group/Multidimensionalman/ Introduction to The Universal God Body: We have now established that our bodies consist of 4 Personality Bodies and 4 Spiritual Bodies. We have also established that the life which exists in the cellular, plant, and animal kingdoms have the same structure. The higher dimensions are in some cases only potential, but it is a characteristic of all life forms that all these dimensions form part of their structure. Now let us consider a further 4 dimensions those of Gaia, Planet Earth, the Solar Logos and all Suns, the Milky Way Galaxy and all other Galaxies, and the Big Bang Universe. We can safely assume that these 4 upper levels of life have activated progressively higher levels, or Dimensions. And since we, humans, are part of their "Multidimensional Bodies", these upper levels are available to us. THE UNIVERSAL GOD BODY: Once we are in the God Body all we need to join with these 4 Upper Spiritual Bodies, is to express our intent in a way that is visible to the Spiritual world, where the necessary connections will be made by our friends, who love us immensely as we all know. So what we will do is to move into these 4 upper dimensions, through Their Crown Chakra, while we are in our God Body, and express our intent from there. Gaia :Visualize our Earth with all the area of space surrounding Her. See Her in all Her Glory, with all Her Multidimensional Bodies surrounding Her. The North Pole is Her Crown Chakra. Go to this Porthole and walk into Her Spiritual Body. You will now send your powerful telepathic message: "We want union with Gaia's Spiritual Body" As you send out this request You will feel it being fulfilled, you will feel yourself floating, as part of the outer Spiritual Body surrounding and penetrating the Earth. Solar System: See the huge, complete, Solar System's Spiritual Bodies enveloping the whole system, extending beyond the Dwarf Planets, and covering it right round, with the Crown Chakra rising vertically above the Sun. Now go to this Crown Chakra and see yourself walking into the Spiritual Body "We want UNION with You" will go out your powerful telepathic request. You will now feel yourself floating above and right round the whole System. You are now in your second Upper Spiritual Dimension. Milky Way Galaxy Now visualize the Milky Way Galaxy with its huge Halo enveloping it. The Crown Chakra rises upwards into the Halo from the Galactic centre. Walk through this Galactic Centre and through the Halo into the Spiritual Dimension. " We now want Union with our Galactic Spiritual Body". See this huge Spiritual Body which has now become the third of your Upper Spiritual Bodies. Send your Love and immense appreciation Big-Bang Universe. Now we want to add the Spiritual Body of our Big Bang Universe to our Spiritual Bodies. Visualize this whole Universe, starting from its original Big Bang and expanding until it reaches its present state of expansion. See it all in your mind's eye and send out your intent with a powerful telepathic message: "I want Union with the Spiritual Body of our Big Bang Universe" Just as the Aether, the Pre-atomic, and the Molecular Dimensions are constituents of our total body, so these 4 Upper Dimensions are also part of our Multidimensional Body. Once Union is effected, we become our Universal God Body, and we can train ourselves to feel our total United Body every time we say: I AM MY UNIVERSAL GOD BODY Joe Zaidan http://groups.yahoo.com/group/Multidimensionalman/ From steveo at syslang.net Wed May 23 09:46:41 2007 From: steveo at syslang.net (Steven W. Orr) Date: Wed, 23 May 2007 09:46:41 -0400 (EDT) Subject: Decorator question Message-ID: I just discovered decorators. Very cool. My question is that I can't figure out how to make a decorator not be restricted to a function so it would also work on a method. Here's my code: def g(expr): def rpt(func): def wrapper(t): for ii in range(expr): print ii, func(t) wrapper.__name__ = func.__name__ wrapper.__dict__ = func.__dict__ wrapper.__doc__ = func.__doc__ return func return wrapper return rpt @g(20) def f(s): print 's="%s"'%s f('Hello') It works fine, but now I want to apply the same decorator to a class method. class KK: # @g(20) This obviously doesn't work. def f(self, s): print 's= %s'%s k = KK() k.f('Hello') Is there a trick I need? TIA -- 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 wilder.usenet at gmail.com Thu May 3 13:38:31 2007 From: wilder.usenet at gmail.com (J) Date: 3 May 2007 10:38:31 -0700 Subject: NewB: Glob Question Message-ID: <1178213910.976263.207630@e65g2000hsc.googlegroups.com> Greetings Group- I'm trying to put together a pattern matching script that scans a directory tree for tif images contained in similar folder names, but running into a NewB problem already. Is it the way I'm trying to join multiple paths? Any help would be greatly appericated. Thanks, J! import glob, sys, os topdir = sys.argv[1] tifFilter = '*.tif' dirFilter = '**' tifList = glob.glob(os.path.join(topdir, tifFilter)) tifList = tifList + glob.glob(os.path.join(topdir, dirFilter, tifFilter)) for tif in tifList: print os.basename(tif) + " is in " + os.dirname(tif) From bbxx789_05ss at yahoo.com Thu May 24 14:33:55 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 24 May 2007 11:33:55 -0700 Subject: How can I time a method of a class in python using Timeit In-Reply-To: <1180031029.147000.55680@m36g2000hse.googlegroups.com> References: <1180020970.039576.319230@m36g2000hse.googlegroups.com> <1180027843.322955.57280@q75g2000hsh.googlegroups.com> <1180028334.650900.283930@m36g2000hse.googlegroups.com> <1180028476.396282.316330@q69g2000hsb.googlegroups.com> <1180031029.147000.55680@m36g2000hse.googlegroups.com> Message-ID: <1180031635.924444.103180@q69g2000hsb.googlegroups.com> On May 24, 12:23 pm, "silverburgh.me... at gmail.com" wrote: > On May 24, 12:41 pm, 7stud wrote: > > > > > Actually, you can do this: > > > class Dog(object): > > def aFunction(self): > > result = 20 + 2 > > def run(self): > > #do stuff > > aFunction() > > #do other stuff > > import timeit > > > t = timeit.Timer("d.aFunction()", "from __main__ import Dog; d = > > Dog()") > > print t.timeit() > > > Since you only want to time aFunction(), you can call it directly. > > Can 't = timeit.Timer()' run inside a thread? > And I have multiple threads running this 't = timeit.Time()' function? __main__ is a thread isn't it? However, timeit() runs in it's own scope, so you need to import anything you need into that scope using the setup parameter for the Timer() constructor. From daniele.varrazzo at gmail.com Mon May 7 13:53:19 2007 From: daniele.varrazzo at gmail.com (Daniele Varrazzo) Date: 7 May 2007 10:53:19 -0700 Subject: Latest errors on pickled objects and blob datatypes in mysql In-Reply-To: References: Message-ID: <1178560399.519293.27880@y80g2000hsf.googlegroups.com> On 7 Mag, 19:08, "krishnakant Mane" wrote: > hello, > finally the errors for my sql query have changed so I have even > changed the thread subject because I feel now that this is not doable > in mysql and this seams to be a bug, ither in python or the MySQLdb > module or perhaps both. And why not also a bug in MySQL? Or a neutrino hitting your CPU changing a 0 into an 1? Doesn't the Occam razor suggest it may be your fault? :) > my table is called testobj and the blob field is called obj. > now following is my query with the cursor named CSRInsert. > CSRInsert.execute("insert into testobj (obj) values (?);",(pickled_object)) > the error is, > "type error, not all arguments formatted during string formatting ". > > can some one now figure out what could be the problem? Please, read the fine manual. if you had read the DBAPI documentation as previously suggested, you would know that you MUST use "%s" placeholder, not "?" (because MySQLdb.paramstyle == 'format'). Just replace the placeholder in your sql string and keep passing sql and values as two distinct arguments. The second argument of the execute() method MUST be a tuple (or a mapping for named parameters, but let's stick to the positional ones). "(pickled_object)" is not a tuple, it is just an object in parenthesis. To represent a tuple with a single argument you must write "(pickled_object,)", notice the trailing comma. Try: CSRInsert.execute("insert into testobj (obj) values (%s);", (pickled_object,)) -- Daniele From mensanator at aol.com Mon May 14 14:41:21 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 14 May 2007 11:41:21 -0700 Subject: Interesting list Validity (True/False) In-Reply-To: References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> <1178914190.166662.285410@p77g2000hsh.googlegroups.com> <1178915791.584216.293130@l77g2000hsb.googlegroups.com> <1178918808.091358.233740@o5g2000hsb.googlegroups.com> <1179017740.656323.209590@e51g2000hsg.googlegroups.com> <1179020634.130689.171960@o5g2000hsb.googlegroups.com> <1179031812.090768.248750@l77g2000hsb.googlegroups.com> Message-ID: <1179168081.603409.39970@e51g2000hsg.googlegroups.com> On May 13, 8:24 am, Steven D'Aprano wrote: > On Sat, 12 May 2007 21:50:12 -0700, mensana... at aol.com wrote: I intended to reply to this yesterday, but circumstances (see timeit results) prevented it. > >> > Actually, it's this statement that's non-sensical. > > >> > > >> > "if arg==True" tests whether the object known as arg is equal to the > >> > object known as True. > >> > > > >> Not at all, it makes perfect sense. X == Y always tests whether the > >> argument X is equal to the object Y regardless of what X and Y are. > > > Except for the exceptions, that's why the statement is wrong. > > But there are no exceptions. Sec 2.2.3: Objects of different types, *--->except<---* different numeric types and different string types, never compare equal; > X == Y tests for equality. If it returns > True, then the objects are equal by definition. That's what equal means in > Python. > > One can abuse the technology to give nonsensical results: > > class EqualToEverything(object): > def __eq__(self, other): > return True > > >>> x = EqualToEverything() > >>> x == 1.0 > True > >>> x == [2.9, "hello world"] > > True > > but that's no different from any language that allows you to override > operators. > > >> > None of these four examples are "equal" to any other. > > >> That's actually wrong, as you show further down. > > > No, it's not, as I show further down. > > But you show no such thing. > > Or, to put it another way: > > Did! Did not! Did! Did not! Did! Did not! ... > > >> >>>> a = 1 > >> >>>> b = (1,) > >> >>>> c = [1] > >> >>>> d = gmpy.mpz(1) > > [snip] > > >> >>>> a==d > >> > True > > >> See, a and d are equal. > > > No, they are not "equal". > > Of course they are. It says so right there: "a equals d" is true. Ok, but they are an exception to the rule "different types compare False". > > > Ints and mpzs should NEVER > > be used together in loops, even though it's legal. > > Why ever not? If you need an mpz value in order to do something, and no > other data type will do, what would you suggest? Just give up and say > "Don't do this, because it is Bad, m'kay?" It's not the mpzs you shouldn't use, its the ints. I also stessed "in loops". Replacing an integer literal with a variable still requires a coercion, so it doesn't matter if n + 1 occurs outside a loop. > > > The ints > > ALWAYS have to be coerced to mpzs to perform arithmetic > > and this takes time...LOTS of it. > > Really? Just how much time? Can't say, had to abort the following. Returns the count of n/2 and 3n+1 operations [1531812, 854697]. import gmpy def collatz(a): ONE = gmpy.mpz(1) TWO = gmpy.mpz(2) TWE = gmpy.mpz(3) a = gmpy.mpz(a) t = 0 u = 0 done = 0 while done==0: f = gmpy.scan1(a,0) if f>0: a = a >> f u += f else: if a==1: done = 1 else: a = a*TWE + ONE t += 1 return [u,t] def collatz2(a): t = 0 u = 0 done = 0 while done==0: f = gmpy.scan1(a,0) if f>0: a = a >> f u += f else: if a==1: done = 1 else: a = a*3 + 1 t += 1 return [u,t] def test(): collatz(2**177149-1) def test2(): collatz2(2**177149-1) if __name__=='__main__': from timeit import Timer t = Timer("a = test()", "from __main__ import test") u = Timer("b = test2()", "from __main__ import test2") print t.timeit(10) print u.timeit(10) ## 723.430377542 ## *ABORTED after 20 hours* > > timeit.Timer("x == y", "import gmpy; x = 1; y = gmpy.mpz(1)").repeat() > timeit.Timer("x == y", "x = 1; y = 1").repeat() > > I don't have gmpy installed here, Good Lord! How do you solve a Linear Congruence? :-) > so I can't time it, but I look forward > to seeing the results, if you would be so kind. I had a lot of trouble with this, but I think I finally got a handle on it. I had to abort the previous test after 20+ hours and abort a second test (once I figured out to do your example) on another machine after 14+ hours. I had forgotten just how significant the difference is. import timeit ## t = timeit.Timer("a == b", "a = 1; b = 1") ## u = timeit.Timer("c == d", "import gmpy; c = 1; d = gmpy.mpz(1)") ## t.repeat() ## [0.22317417437132372, 0.22519314605627253, 0.22474588250741367] ## u.repeat() ## [0.59943819675405763, 0.5962260566636246, 0.60122920650529466] Unfortunately, this is not a very useful test, since mpz coercion appears to vary ny the size of the number involved. Although changing t to ## t = timeit.Timer("a == b", "a = 2**177149-1; b = 2**177149-1") still produces tractable results ## t.repeat() ## [36.323597552202841, 34.727026758987506, 34.574566320579862] the same can't be said for mpz coercion: ## u = timeit.Timer("c == d", "import gmpy; c = 2**177149-1; d = gmpy.mpz(2**177149-1)") ## u.repeat() ## *ABORTED after 14 hours* So I changed it to (using yet a third machine) for i in xrange(8): e = 2*i*100 n = 2**e-1 r = 'a = %d; b = %d' % (n,n) s = 'import gmpy; a = %d; b = gmpy.mpz(%d)' % (n,n) print 'For 2**e-1',e t = timeit.Timer("a == b",r) u = timeit.Timer("a == b",s) print t.repeat() print u.repeat() print which clearly shows the growth rate of the mpz coercion. ## int==int vs. int==mpz ## ## For 2**e-1 0 ## [0.054264941118974445, 0.054553378257723141, 0.054355515455681791] ## [0.16161957500399435, 0.16188363643198839, 0.16197491752897064] ## ## For 2**e-1 200 ## [0.093393746299376912, 0.093660961833065492, 0.092977494572419439] ## [1.0425794607193544, 1.0436544844503342, 1.0451038279715417] ## ## For 2**e-1 400 ## [0.10496130299527184, 0.10528292779203152, 0.10497603593951155] ## [2.2687503839249636, 2.2685411490493506, 2.2691453463783233] ## ## For 2**e-1 600 ## [0.11724617625774236, 0.11701867087715279, 0.11747874550051129] ## [3.616420796797021, 3.617562537946073, 3.6152373342355801] ## ## For 2**e-1 800 ## [0.13156379733273482, 0.1310266632832402, 0.13168082630802047] ## [5.2398534562645089, 5.2389728893525458, 5.2353889230364388] ## ## For 2**e-1 1000 ## [0.153719968797283, 0.15383679852633492, 0.15352625633217798] ## [6.967458038928207, 6.9640038947002409, 6.9675019294931388] ## ## For 2**e-1 1200 ## [0.16716219584402126, 0.16743472335786436, 0.16782637005291434] ## [11.603391791430532, 11.601063020084396, 11.603106936964878] ## ## For 2**e-1 1400 ## [0.179120966908215, 0.17908259508838853, 0.17934175430681876] ## [14.753954507946347, 14.755623642634944, 14.756064585859164] And, just for laughs, I compared mpzs to mpzs, s = 'import gmpy; a = gmpy.mpz(%d); b = gmpy.mpz(%d)' % (n,n) which ended up faster than comparing ints to ints. ## int==int vs. mpz==mpz ## ## For 2**e-1 0 ## [0.054301433257206225, 0.054502401293220933, 0.054274144039999611] ## [0.12487657446828507, 0.099130500653189346, 0.094799646619862565] ## ## For 2**e-1 200 ## [0.10013419046813476, 0.10156139134030695, 0.10151083166511599] ## [0.091683807483012414, 0.091326269489948375, 0.091261281378934411] ## ## For 2**e-1 400 ## [0.10716937998703036, 0.10704403530042028, 0.10705119312788414] ## [0.099165500324245093, 0.097540568227742153, 0.10131808159697742] ## ## For 2**e-1 600 ## [0.12060785142996777, 0.11720683828159517, 0.11800506010281886] ## [0.11328210449149934, 0.1146064679843235, 0.11307050873582014] ## ## For 2**e-1 800 ## [0.12996358680839437, 0.13021352430898236, 0.12973684081916526] ## [0.12344120825932059, 0.11454960385710677, 0.12339954699673861] ## ## For 2**e-1 1000 ## [0.15328649918703752, 0.15362917265815135, 0.15313422618208516] ## [0.12753811336359666, 0.12534907002753748, 0.12588097104350471] ## ## For 2**e-1 1200 ## [0.16756264696760326, 0.16747118166182684, 0.167885034915086] ## [0.12162660501311073, 0.13368267591470051, 0.13387503876843265] ## ## For 2**e-1 1400 ## [0.17867761017283623, 0.17829534684824377, 0.17826312158720281] ## [0.13718761665773815, 0.13779106963280441, 0.13708166276632738] > > Even if it is terribly slow, that's just an implementation detail. What > happens when Python 2.7 comes out (or Python 3.0 or Python 99.78) and > coercion from int to mpz is lightning fast? Would you then say "Well, > int(1) and mpz(1) used to be unequal, but now they are equal?". Are you saying I should be unconcerned about implementation details? That it's silly of me to be concerned about implementation side effects due to mis-matched types? > > Me, I'd say they always were equal, but previously it used to be slow to > coerce one to the other. So, when you're giving advice to the OP you don't feel any need to point this out? That's all I'm trying to do, supply some "yes, but you should be aware of..." commentary. > > > The absolute stupidest > > thing you can do (assuming n is an mpz) is: > > > while n >1: > > if n % 2 == 0: > > n = n/2 > > else: > > n = 3*n + 1 > > Oh, I can think of much stupider things to do. > > while len([math.sin(random.random()) for i in range(n)[:]][:]) > 1: > if len( "+" * \ > int(len([math.cos(time.time()) for i in \ > range(1000, n+1000)[:]][:])/2.0)) == 0: > n = len([math.pi**100/i for i in range(n) if i % 2 == 1][:]) > else: > s = '+' > for i in range(n - 1): > s += '+' > s += s[:] + ''.join(reversed(s[:])) > s += s[:].replace('+', '-')[0:1] > n = s[:].count('+') + s[:].count('-') > > > You should ALWAYS do: > > > ZED = gmpy.mpz(0) > > ONE = gmpy.mpz(1) > > TWO = gmpy.mpz(2) > > TWE = gmpy.mpz(3) > > > while n >ONE: > > if n % TWO == ZED: > > n = n/TWO > > else: > > n = TWE*n + ONE > > > This way, no coercion is performed. > > I know that algorithm, but I don't remember what it is called... The Collatz Conjecture. If true, it means the while loop terminates for any n. > > In any case, what you describe is a local optimization. Its probably a > good optimization, but in no way, shape or form does it imply that mpz(1) > is not equal to 1. It's a different type. It is an exception to the "different types compare False" rule. That exception is not without cost, the type mis-match causes coercion. > > >> > And yet a==d returns True. So why doesn't b==c > >> > also return True, they both have a 1 at index position 0? > > >> Why should they return true just because the contents are the same? > > > Why should the int 1 return True when compared to mpz(1)? > > Because they both represent the same mathematical number, where as a list > containing 1 and a tuple containing 1 are different containers. Even if > the contents are the same, lists aren't equal to tuples. > > > a = [1] > > b = [1] > > > returns True for a==b? > > That's because both are the same kind of container, and they both have the > same contents. > > > After all, it returns false if b is [2], > > so it looks at the content in this case. So for numerics, > > it's the value that matters, not the type. And this creates > > a false sense of "equality" when a==d returns True. > > There's nothing false about it. Ask any mathematician, does 1 equal 1.0, > and they will say "of course". And if you ask any mathematician, he'll say that (1,) is equal to [1]. That's the difference between a mathematician and a programmer. A programmer will say "of course not, the int has to be coered." > > >> A bag > >> of shoes is not the same as a box of shoes, even if they are the same > >> shoes. > > > Exactly. For the very reason I show above. The fact that the int > > has the same shoes as the mpz doesn't mean the int should be > > used, it has to be coerced. > > Ints are not containers. An int doesn't contain values, an int is the > value. > > Numeric values are automatically coerced because that's more practical. > That's a design decision, and it works well. And I'm not saying it shouldn't be that way. But when I wrote my Collatz Functions library, I wasn't aware of the performance issues when doing millions of loop cycles with numbers having millions of digits. I only found that out later. Would I have gotten a proper answer on this newgroup had I asked here? Sure doesn't look like it. BTW, in reviewing my Collatz Functions library, I noticed a coercion I had overlooked, so as a result of this discussion, my library is now slightly faster. So some good comes out of this argument after all. > > As for gmpy.mpz, since equality tests are completely under the control of > the class author, the gmpy authors obviously wanted mpz values to compare > equal with ints. And they chose to do a silent coercion rather than raise a type exception. It says right in the gmpy documentation that this coercion will be performed. What it DOESN'T say is what the implications of this silent coercion are. > > >> Since both lists and tuples are containers, neither are strings or > >> numeric types, so the earlier rule applies: they are different types, so > >> they can't be equal. > > > But you can't trust a==d returning True to mean a and d are > > "equal". > > What does it mean then? It means they are mathematically equivalent, which is not the same as being programatically equivalent. Mathematical equivalency is what most people want most of the time. Not all of the people all of the time, however. For example, I can calculate my Hailstone Function parameters using either a list or a tuple: >>> import collatz_functions as cf >>> print cf.calc_xyz([1,2]) (mpz(8), mpz(9), mpz(5)) >>> print cf.calc_xyz((1,2)) (mpz(8), mpz(9), mpz(5)) But [1,2]==(1,2) yields False, so although they are not equal, they ARE interchangeable in this application because they are mathematically equivalent. > > > To say the comparison means the two objects are > > equal is misleading, in other words, wrong. It only takes one > > turd to spoil the whole punchbowl. > > >> gmpy.mpz(1) on the other hand, is both a numeric type and a custom class. > >> It is free to define equal any way that makes sense, and it treats itself > >> as a numeric type and therefore says that it is equal to 1, just like 1.0 > >> and 1+0j are equal to 1. > > > They are equal in the mathematical sense, but not otherwise. > > Since they are mathematical values, what other sense is meaningful? > > > And to think that makes no difference is to be naive. > > I never said that there was no efficiency differences. Comparing X with Y > might take 0.02ms or it could take 2ms depending on how much work needs > to be done. I just don't understand why you think that has a bearing on > whether they are equal or not. The bearing it has matters when you're writing a function library that you want to execute efficiently. > > -- > Steven. From jjl at pobox.com Wed May 30 15:57:13 2007 From: jjl at pobox.com (John J. Lee) Date: Wed, 30 May 2007 19:57:13 GMT Subject: Is PEP-8 a Code or More of a Guideline? References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <1180254338.292249.29520@h2g2000hsg.googlegroups.com> <87ps4lazor.fsf@pobox.com> Message-ID: <87hcpuozix.fsf@pobox.com> Steven Bethard writes: > John J. Lee wrote: [...] > > Even as a native English speaker, some of these are tricky -- > > e.g. urllib has a private class named "addinfourl". "What's this > > 'fourl' we're adding in?" > > (In fact, the method adds attributes named "info" and "url". Even > > though I've read that name hundreds of times, my brain always insists > > on reading it "add in fourl".) > > This is the worst of both worlds: inconsistent and hard to > > understand. > > Sounds like a good candidate for a rename in Python 3000. The point was the general issue, not the particular case. The problems associated with this naming style do not go away when bad cases like "addinfourl" go away: 1. Other runtogether names are less tricky than "addinfourl", but the issue is still there. These names (e.g. "getitem") are considered good Python standard library style. This particular point involves a trade-off and is debatable, I accept. More important, and less debatable: 2. The runtogether style makes *many* names hard to remember because of the runtogether / kept_apart choice. 3. The style introduces tiresome inconsistency in naming decisions. John From bblais at bryant.edu Tue May 22 21:38:15 2007 From: bblais at bryant.edu (Brian Blais) Date: Tue, 22 May 2007 21:38:15 -0400 Subject: Cherrypy setup questions Message-ID: <46539B07.1070808@bryant.edu> Hello, I'd like to start trying out some cherrypy apps, but I've been having some setup problems. I think I need some bone-head simple example to clear my understanding. :) I'm on a system running Apache, that I don't have root access to. I will be publishing the html/image/python files in a directory off of my current web page, and running the app as a user on the system. I'd like to be able to specify the base url for the app, especially if I have more than one app. I've read the docs, but am getting confused with the config file information, and exactly how to set it up. I'm using CherryPy 3.0.1, the latest I know. Some questions I have: 1) can I configure cherrypy to look at requests only off a base url, like: http://www.provider.com:8080/~myusername/apps and ignore all other requests below that url, like http://www.provider.com:8080/~someotherguy or http://www.provider.com:8080/~myusername 2) If you run (as in Unix): cd app1 python mycherrypyapp1.py & cd ../app2 python mycherrypyapp2.py & Does this start 2 cherrypy servers, trying to both fight for port 8080, or is there only one, and the two apps share it? Are there any examples that show such a setup? I didn't see a CherryPy mailing list, so I'm posting here, but if there is somewhere else better I'd be glad to know! thanks, Brian Blais -- ----------------- bblais at bryant.edu http://web.bryant.edu/~bblais From rbonvall at gmail.com Tue May 15 17:04:11 2007 From: rbonvall at gmail.com (Roberto Bonvallet) Date: 15 May 2007 14:04:11 -0700 Subject: removing spaces between 2 names In-Reply-To: <1179212094.912104.9170@e65g2000hsc.googlegroups.com> References: <1179208842.114189.233060@e65g2000hsc.googlegroups.com> <1179212094.912104.9170@e65g2000hsc.googlegroups.com> Message-ID: <1179263051.252215.88170@e65g2000hsc.googlegroups.com> half.ital... at gmail.com wrote: > s = "jk hij ght" > print "".join(s.split(" ")) "".join(s.split()) is enough. -- Roberto Bonvallet From a.schmolck at gmail.com Sun May 27 10:00:30 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: Sun, 27 May 2007 15:00:30 +0100 Subject: matplotlib, usetex References: Message-ID: Bill Jackson writes: > Alexander Schmolck wrote the following on 05/25/2007 02:33 PM: >> I have no idea whether this will resolve your problem, but you could try >> updating to 0.90 (BTW what happens if you do axis([0,128,0,128])). > > The problem appears to be with a matplotlibrc file. If I delete the > matplotlibrc file, then I am able to plot perfectly. Thus, it appears that I > am unable to specify usetex from my configuration file. Why is this > happening? > > ---- ~/.matplotlib/matplotlibrc ---- > text.usetex : True > > ---- test.py ---- > import matplotlib > import pylab > matplotlib.rc('text', usetex=True) I think it might be a good habit to develop to call ``rc`` before ``import pylab`` -- some things won't take effect otherwise (this doesn't affect all parameters and will likely be eventually fixed in general, but notably it does currently affect some latex-related stuff, such as font choice). > pylab.plot(range(10)) > pylab.show() > > > Running 'python test.py' with the above matplotlibrc causes the errors in my > original post. Deleting matplotlibrc resolves the problem. I can't see any problem with you matplotlibrc; what happens if you swap around the lines as I suggested above? Maybe it just appears to work, because the usetex really does have no affect above, and you really are not using latex? I have been using matplotlib with latex for fonts handling for some time now (and I've even submitted a patch to ameliorate the rc problem mentioned above), but the latex stuff has changed somewhat over time, and still has some rough edges -- so for not immediately obvious problems with the latex handling of an older version of matplotlib you're much more likely to find someone who has the relevant details mentally available on the matplotlib-disc list are much better than here; so I'd recommend you give it a try again (yeah sf is a pain). cheers, 'as From ptmcg at austin.rr.com Thu May 17 20:01:29 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 17 May 2007 17:01:29 -0700 Subject: How to convert a number to binary? In-Reply-To: <1179445546.307017.275850@p77g2000hsh.googlegroups.com> References: <1179444832.775573.55830@y80g2000hsf.googlegroups.com> <1179445546.307017.275850@p77g2000hsh.googlegroups.com> Message-ID: <1179446488.865118.42320@y80g2000hsf.googlegroups.com> On May 17, 6:45 pm, Lyosha wrote: > That's way too complicated... Is there any way to convert it to a one- > liner so that I can remember it? Mine is quite ugly: > "".join(str((n/base**i) % base) for i in range(20) if n>=base**i)[::-1].zfill(1) > Howzis? "".join(map(str,[ int(bool(n & 2**i)) for i in range(20) if n>2**i ] [::-1])) Uses: - integer & to test for bit high or low, returns 2**i - bool(int) to evaluate boolean value of integers - zero -> False, nonzero -> True - int(bool) to convert True->1 and False->0 -- Paul From turbana at gmail.com Wed May 2 18:56:41 2007 From: turbana at gmail.com (Ian Clark) Date: Wed, 2 May 2007 15:56:41 -0700 Subject: curses mystical error output In-Reply-To: <17977.2867.158091.217653@montanaro.dyndns.org> References: <17977.2867.158091.217653@montanaro.dyndns.org> Message-ID: On 5/2/07, skip at pobox.com wrote: > I have a fairly simple curses app which is giving me this error: > > addstr() returned ERR > > I'm trapping it and continuing. I can see that *some* of my addstring calls > succeed. This one happens to be > > screen.addstr(row, 39, "|") > > where row is 3. You might be trying to write to a section that is currently off screen. Seems to me when I was doing some curses stuff that when I tried to write to one more row than could be fit onto my terminal that error would come up. Try doing the following code and make sure that you can enough space to draw it. >>> (height, width) = screen.getmaxyx() Ian From exarkun at divmod.com Wed May 2 12:29:20 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 2 May 2007 12:29:20 -0400 Subject: ascii to unicode line endings In-Reply-To: <1178122765.162546.59680@l77g2000hsb.googlegroups.com> Message-ID: <20070502162920.19381.667447983.divmod.quotient.7582@ohm> On 2 May 2007 09:19:25 -0700, fidtz at clara.co.uk wrote: >The code: > >import codecs > >udlASCII = file("c:\\temp\\CSVDB.udl",'r') >udlUNI = codecs.open("c:\\temp\\CSVDB2.udl",'w',"utf_16") > >udlUNI.write(udlASCII.read()) > >udlUNI.close() >udlASCII.close() > >This doesn't seem to generate the correct line endings. Instead of >converting 0x0D/0x0A to 0x0D/0x00/0x0A/0x00, it leaves it as 0x0D/ >0x0A > >I have tried various 2 byte unicode encoding but it doesn't seem to >make a difference. I have also tried modifying the code to read and >convert a line at a time, but that didn't make any difference either. > >I have tried to understand the unicode docs but nothing seems to >indicate why an seemingly incorrect conversion is being done. >Obviously I am missing something blindingly obvious here, any help >much appreciated. Consider this simple example: >>> import codecs >>> f = codecs.open('test-newlines-file', 'w', 'utf16') >>> f.write('\r\n') >>> f.close() >>> f = file('test-newlines-file') >>> f.read() '\xff\xfe\r\x00\n\x00' >>> And how it differs from your example. Are you sure you're examining the resulting output properly? By the way, "\r\0\n\0" isn't a "unicode line ending", it's just the UTF-16 encoding of "\r\n". Jean-Paul From myheartinamerica at gmail.com Mon May 21 09:39:00 2007 From: myheartinamerica at gmail.com (myheartinamerica) Date: 21 May 2007 06:39:00 -0700 Subject: full screen graphics Message-ID: <1179754739.658332.122200@b40g2000prd.googlegroups.com> Hello, I need to run a particular graphics application over and over again with a different command line to get benchmarks on the applications performance (frame rates and similar data). I am running the following within a while loop that parses out a different command line from a configuration file. ############ def runCommand(command): """runCommand(command) Parameters: command -- the full string of the command to execute """ print command try: childProcess = subprocess.Popen(command) done = False while not done: returnCode = childProcess.poll() if (returnCode != None): done = True else: # sleep for 10 seconds before checking again time.sleep(10) except KeyboardInterrupt: print 'KeyboardInterrupt received. Trying to kill Wolf2.exe' print '>TASKKILL /F /T /PID ', childProcess.pid killCommand = ''.join(('TASKKILL /F /T /PID ', str(childProcess.pid))) killSubProcess = subprocess.Popen(killCommand) killSubProcess.wait() sys.exit(0) except OSError, (errno, strerror): print 'OS Error (%s): %s' % (errno, strerror) print 'Above error occurred while executing the following:' print command except WindowsError, (errno, strerror): print 'MS Windows Error (%s): %s' % (errno, strerror) print 'Above error occurred while executing the following:' print command ########## The problem lies in that the second time the application is run, it doesn't grab focus and go full screen, but sits paused. It will not continue running until I click on the minimized application in the taskbar. Is there any way to force it to grab focus? I am running on Win32 with Python 2.5.1. Your help in this matter is greatly appreciated, Mick Charles Beaver From whamil1 at entergy.com Wed May 16 08:21:44 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Wed, 16 May 2007 07:21:44 -0500 Subject: tkFileDialog.askopenfilename() Message-ID: <588D53831C701746A2DF46E365C018CE01D2CA9B@LITEXETSP001.etrsouth.corp.entergy.com> > From: rahulnag22 at yahoo.com > > Hi, > When I call tkFileDialog.askopenfilename() , the dialog box opens with > the current directory as the default directory. Is it possible to open > the dialog box with a directory other than the current directory. Can > we pass in a user defined starting directory. > Thanks > Rahul > This link has a decent amount of info about the various dialog modules. http://www.pythonware.com/library/tkinter/introduction/x1164-data-entry.htm --- -Bill Hamilton From rowen at cesmail.net Thu May 24 15:32:11 2007 From: rowen at cesmail.net (Russell E. Owen) Date: Thu, 24 May 2007 12:32:11 -0700 Subject: Python and GUI References: <1179761984.704369.116310@b40g2000prd.googlegroups.com> Message-ID: In article <1179761984.704369.116310 at b40g2000prd.googlegroups.com>, sdoty044 at gmail.com wrote: > Just wondering on what peoples opinions are of the GUIs avaiable for > Python? > > All I am doing is prompting users for some data (listbox, radio > buttons, text box, ect...). Then I will have some text output, maybe > a scrolling text message as things are happening. > > I have some minor things I need to do, for example, if Checkbutton X > is clicked, I need to disable TextBox Y, and I would like to display > the scrolling text (output) > > Ultimately, is it worth downloading and learning some of the packages > avaiable for Python, or should I just stick to the Tkinter stuff that > is included. > > More specifically, has anyone used the Qt stuff for python, easy to > use? My opinion is that Tkinter is perfect for the job you describe. It is easy to use, fairly pythonic (an issue with some competing toolkits) and does not require any fancy installation. If you want a very professional and "native" look then you have to work harder. Options include Tkinter with tile, wxPython, PyQt and several others. -- Russell From rajb at rice.edu Wed May 30 11:55:42 2007 From: rajb at rice.edu (Raj B) Date: Wed, 30 May 2007 10:55:42 -0500 Subject: New-style classes and special methods Message-ID: > Yes, special methods populate the slots in the structures which Python > uses to represent types. Objects/typeobject.c in the Python source > distribution does the hard work, particularly in function type_new Thanks for that quick response. I am quite comfortable with C code and am trying to understand exactly what happens when a new-style class is created, and then instantiated. I have been reading typeobject.c and type_new() inside it in detail, and there are a few issues I am trying to figure out. I can see a lot of *SLOT() macros in the file that seem to set the slots to appropriate values. What I am having trouble figuring out is the connection i.e. at what point during construction of the class object in type_new() are those slots allotted? Is it the tp_alloc() function which does this? Is there some kind of descriptor or other mechanism connecting special method names with their slots in the object representation? (e.g. "__call__" with type->tp_call) Also, what happens when a class inherits from multiple classes with their own __call__ methods? Where and how is it decided which __call__ goes into the tp_call slot? I'm sure I'll eventually figure it out if I stare at the code hard enough, but would totally appreciate any help I can get :) Thanks again! Raj From thorsten at thorstenkampe.de Tue May 15 14:41:04 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 15 May 2007 19:41:04 +0100 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> <4648294F.2000704@web.de> <46487a6c$0$2400$426a74cc@news.free.fr> Message-ID: * Duncan Booth (15 May 2007 17:30:58 GMT) > Donn Cave wrote: > > [Spanish in Brazil? Not as much as you might think.] > > Sorry temporary[*] brain failure, I really do know it is Portugese. Yes, you do. Spanish is what's been used in the United States, right? Thorsten From grante at visi.com Thu May 17 00:12:45 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 17 May 2007 04:12:45 -0000 Subject: In a text file: how do I tell the EOF, from a blank line? References: <1179368197.929029.134400@p77g2000hsh.googlegroups.com> Message-ID: <134nlhtgg55qg9d@corp.supernews.com> On 2007-05-17, walterbyrd wrote: > How do I test for the end of a file, in such a why that python can > tell the EOF from a blank line? This has already been explained to you by at least 5 different people -- complete with examples. -- Grant Edwards grante Yow! Uh-oh!! I forgot at to submit to COMPULSORY visi.com URINALYSIS! From mcbooczech at gmail.com Sun May 27 17:53:11 2007 From: mcbooczech at gmail.com (Petr Jakes) Date: 27 May 2007 14:53:11 -0700 Subject: Help with PySMS In-Reply-To: <1180264285.477306.137830@r19g2000prf.googlegroups.com> References: <1180264285.477306.137830@r19g2000prf.googlegroups.com> Message-ID: <1180302791.160909.91570@k79g2000hse.googlegroups.com> Maybe you can try python binding for gammu, which works great for me. HTH Petr Jakes http://cihar.com/gammu/python/ From jjl at pobox.com Mon May 28 08:51:55 2007 From: jjl at pobox.com (John J. Lee) Date: Mon, 28 May 2007 12:51:55 GMT Subject: Ancient projectiles (was: Muzzle Velocity (was: High resolution sleep (Linux)) References: <1178274122.142071.91740@y5g2000hsa.googlegroups.com> <3f0mi4-mj8.ln1@lairds.us> Message-ID: <87lkf9az6a.fsf@pobox.com> Roy Smith writes: > In article <3f0mi4-mj8.ln1 at lairds.us>, claird at lairds.us (Cameron Laird) > wrote: > > > Hmmm; now you've got me curious. What *were* the first > > composite projectiles? > > Fetchez la Vache! :-) From robert.rawlins at thinkbluemedia.co.uk Mon May 21 04:25:57 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Mon, 21 May 2007 09:25:57 +0100 Subject: Restart Linux System Message-ID: <002d01c79b81$aa748d40$ff5da7c0$@rawlins@thinkbluemedia.co.uk> Hello Guys, I'm looking to restart a Linux system from my python application. What's the best way to achieve this, is there something in the OS module? Thanks, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From mcPas.De.Spam at mclaveauPas.De.Spam.com Tue May 1 12:22:56 2007 From: mcPas.De.Spam at mclaveauPas.De.Spam.com (Michel Claveau) Date: Tue, 01 May 2007 18:22:56 +0200 Subject: SilverLight, a new way for Python? Message-ID: Hi! SilverLight ("MS flash killer"), is a plug-in for InternetExplorer (Win), FireFox (Win), and Safari (Mac). The release 1.1-Alpha come with JScript & Python (or ironPython?) See : http://www.microsoft.com/silverlight/default.aspx http://www.microsoft.com/silverlight/why-compelling.aspx http://silverlight.net/Default.aspx http://www.microsoft.com/silverlight/install.aspx Perhaps SilverLight is a new substitute for Python-Active-Scripting in IE. Perhaps SilverLight is the begin for new GUI style (vectors + XAML). Perhaps SilverLight is the start for a new IDE (plug-in for VS-2005 or Expression are availables). But, I don't had try SilverLight... Who had try it? -- @-salutations Michel Claveau From steven at REMOVE.THIS.cybersource.com.au Mon May 7 01:30:29 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 07 May 2007 05:30:29 -0000 Subject: CGI python use "under a curse" References: <1178512216.246621.38960@p77g2000hsh.googlegroups.com> Message-ID: On Sun, 06 May 2007 21:30:16 -0700, Adrian Smith wrote: > The support guy looked at it and gave me this: > > Traceback (most recent call last): > File "python1.cgi", line 6, in ? > print form["essay"].value > File "/usr/local/lib/python2.4/cgi.py", line 559, in __getitem__ raise > KeyError, key > KeyError: 'essay' > > (http://www.profusehost.net/forum/support/10894-cgi-blink.html) > > He says I have a syntax error, though I'm b*ed if I can see where it > could be. Can anyone here suggest anything? Oh lordy lordy lordy, you've got one fine example of incompetence in action. >From the support forum: [quote] Quote: perl python1.cgi \Semicolon seems to be missing at python1.cgi line 3. syntax error at python1.cgi line 4, near "form " Execution of python1.cgi aborted due to compilation errors. Quote: perl -p python1.cgi Semicolon seems to be missing at python1.cgi line 3. syntax error at python1.cgi line 4, near "form " Execution of python1.cgi aborted due to compilation errors. [end quote] The "administrator" John is trying to execute a Python script with Perl. I notice that you pointed that out to him, and his response was: [quote] Sorry for delay. if we try to run this script by python we will get same error. python -t python1.cgi Content-type: text/html Traceback (most recent call last): File "python1.cgi", line 6, in ? print form["essay"].value File "/usr/local/lib/python2.4/cgi.py", line 559, in __getitem__ raise KeyError, key KeyError: 'essay' we can test perl or cgi scripts using perl command. PLease fix syntax error so it will work fine. [end quote] It is NOT the same error. There are NO syntax errors in the script, there is a runtime error. The so-called administrator is wrong: you can't use Perl to test just any old CGI scripts. They have to be written in Perl. I see from the source code on your page that you have a line: You have two lines in your cgi script: form = cgi.FieldStorage() print form["essay"].value Having never done cgi programming, I'm not sure what the problem is, but after reading help(cgi) I'll take a stab in the dark and say try this: print form.value It might also help for you to try this: print form.keys() Good luck with the "admins" at your hosting company. -- Steven. From desertlinux at netscape.net Tue May 15 20:12:01 2007 From: desertlinux at netscape.net (Brian) Date: Tue, 15 May 2007 17:12:01 -0700 Subject: Newbie Question: Getting a list of files Message-ID: Hello, I am currently working on putting together a free, open source, anti-spyware program for the Mac (and eventually for other OS's too.) However, there's one thing that I am currently trying to figure out: How do I, in Python, obtain a recursive list of files in a specified directory, including the subdirectories, etc? For example, in the old MS-DOS days, we could specify at the command prompt "DIR /S" and this would provide a listing of all files, including those in subdirectories, no matter how far down the branch they were. How can this be done with Python? P.S. I have been searching Google, but haven't found the answer yet. Any info appreciated! Dusty --- From david at boddie.org.uk Mon May 14 08:37:55 2007 From: david at boddie.org.uk (David Boddie) Date: 14 May 2007 05:37:55 -0700 Subject: GUI tutorial In-Reply-To: <1179104242.701176.160180@e65g2000hsc.googlegroups.com> References: <1179104242.701176.160180@e65g2000hsc.googlegroups.com> Message-ID: <1179146275.584873.230940@p77g2000hsh.googlegroups.com> On May 14, 2:57 am, BartlebyScrivener wrote: > On May 13, 12:51 pm, John K Masters > wrote: > > > Can someone point me in the direction of a good tutorial on programming > > python with a GUI? > > Alan Gauld added a gui programming tutorial to his main course. > > http://www.freenetpages.co.uk/hp/alan.gauld/ > > It's a frame page so I can't link directly, but select "GUI > Programming" under Advanced Topics on the left. It may be worth pointing out that the information about licensing on that page is a little vague and inaccurate in places. PyGTK is actually licensed under the GNU LGPL, not the GPL, and both PyQt and PyGTK can be used to create commercial applications as long as those applications are not closed source. David From mikeb at mitre.org Wed May 2 10:50:11 2007 From: mikeb at mitre.org (Mike Brenner) Date: Wed, 02 May 2007 10:50:11 -0400 Subject: What do people use for code analysis. Message-ID: <4638A523.2020605@mitre.org> On the one hand, I would like better graphical code analysis tools. On the other hand, I would like to mention a different kind of code analysis. A "Return on Investment" (ROI) philosophy would analyze the code by how much it costs to change the code. To do this, you can add up all the costs. The main cost pays for analyzing the dataflows to determine the impact of the change. The secondary costs pays for the backlogs, the things that you put off paying for in the past: - the number of branches in the code not covered by automatic tests, - the number of API parameters without tested examples, - the dataflows without documented preconditions and postconditions, - the hours of developer overtime not being paid, - the cost of opening up the configuration management to a change, - the number of platform-dependent features, - the number of reviewer comments not kept, etc. Notice that such things as code size, inheritance, multiple tasks, calls, etc., don't add cost! Code costs almost nothing compared to the true value, the data and the dataflows. Mike Brenner Steven wrote: > Lots of code, calls to, calls by, inheritance, multiple tasks, etc. > What do people use to figure out what's happening? From kyosohma at gmail.com Fri May 25 11:05:14 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 25 May 2007 08:05:14 -0700 Subject: Xml parser In-Reply-To: References: <46557351.9050205@motorola.com> Message-ID: <1180105514.877352.170380@p77g2000hsh.googlegroups.com> On May 25, 7:04 am, "Amit Khemka" wrote: > On 5/24/07, ashish wrote: > > > Hi All, > > > I want to know weather is there any api available in python for parsing > > xml(XML parser) > > Checkout cElementTree . > > Cheers, > > -- > ---- > Amit Khemka -- onyomo.com > Home Page:www.cse.iitd.ernet.in/~csd00377 > Endless the world's turn, endless the sun's Spinning, Endless the quest; > I turn again, back to my own beginning, And here, find rest. And don't forget about Beautiful Soup: http://www.crummy.com/software/BeautifulSoup/ Mike From ian.team.python at saltmob.com Thu May 10 04:00:55 2007 From: ian.team.python at saltmob.com (ian.team.python at saltmob.com) Date: 10 May 2007 01:00:55 -0700 Subject: elegant python style for loops In-Reply-To: <1178779594.588153.49620@n59g2000hsh.googlegroups.com> References: <1178776272.535735.166540@h2g2000hsg.googlegroups.com> <5afrsmF2o97gcU1@mid.uni-berlin.de> <1178779594.588153.49620@n59g2000hsh.googlegroups.com> Message-ID: <1178784055.673575.173600@u30g2000hsc.googlegroups.com> thank you everybody....very well answered.....just one question remains.... where do i find documentation on zip ...i was looking for a function like this, but could not even find a relevant list of functions!! From __peter__ at web.de Wed May 23 10:04:51 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 23 May 2007 16:04:51 +0200 Subject: Decorator question References: Message-ID: Steven W. Orr wrote: > I just discovered decorators. Very cool. My question is that I can't > figure out how to make a decorator not be restricted to a function so it > would also work on a method. > > Here's my code: > @g(20) > def f(s): > print 's="%s"'%s > f('Hello') Here you are calling f() with one string argument. > It works fine, but now I want to apply the same decorator to a class > method. > > class KK: > # @g(20) This obviously doesn't work. > def f(self, s): > print 's= %s'%s > > k = KK() > k.f('Hello') Here you are calling KK.f() with two arguments (an implicit KK instance and the explicit "Hello" string). Both calls are channeled through wrapper(t) which expects exactly one parameter. > Is there a trick I need? Change wrapper() to accept an arbitrary number of arguments: > def g(expr): > def rpt(func): def wrapper(*args): > for ii in range(expr): > print ii, func(*args) > wrapper.__name__ = func.__name__ > wrapper.__dict__ = func.__dict__ > wrapper.__doc__ = func.__doc__ > return func > return wrapper > return rpt Peter From paul at boddie.org.uk Wed May 9 11:41:52 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 9 May 2007 08:41:52 -0700 Subject: String parsing In-Reply-To: References: <1178672992.522463.228620@l77g2000hsb.googlegroups.com> Message-ID: <1178725312.394037.201820@q75g2000hsh.googlegroups.com> On 9 May, 06:42, Dennis Lee Bieber wrote: > [HTMLParser-based solution] Here's another approach using libxml2dom [1] in HTML parsing mode: import libxml2dom # The text, courtesy of Dennis. sample = """ """ # Parse the string in HTML mode. d = libxml2dom.parseString(sample, html=1) # For all input fields having the name 'LastUpdated', # get the value attribute. last_updated_fields = d.xpath("//input[@name='LastUpdated']/@value") # Assuming we find one, print the contents of the value attribute. print last_updated_fields[0].nodeValue Paul [1] http://www.python.org/pypi/libxml2dom From larry.bates at websafe.com Fri May 18 16:17:10 2007 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 18 May 2007 15:17:10 -0500 Subject: Python compared to other language In-Reply-To: References: Message-ID: scott wrote: > Hi all, > > I have been looking at the various programming languages available. > I have programed in Basic since I was a teenager and I also have a basic > understanding of C, but I want something better. > > Can anybody tell me the benefits and weaknesses of using Python? > Search the archives, this question has been covered many times. That said I'm going to list some benefits below: Python is Portable - C is probably the only more portable language Python is Powerful - You can write everything from simple scripts to daemons, Windows Services, Windows COM objects, web frameworks, GUI or console programs. Again only C has that much range. On Windows, Delphi comes close, but try to move a Delphi program to Macintosh or even to Linux. I've merely copied Python programs from one OS to another and they have run without so much as a single change. Python has strong standard library - The standard library contains many modules that you would have to purchase with other languages. This adds to portability because many features are standard and don't require additions. Python is maintainable - Python coerces you into writing better code. >From the required indention of blocks to the rich built in data types it provides a programmer with tools that you use over and over. I've gone back to programs that I wrote 5+ years ago an it was remarkable how quickly I could remember what I was doing. Python is a strongly typed but dynamic language - I have always hated the fact that you have to define everything in other languages. In Python you define something when you need it and the definition is implicit in hat you point to with a variable name. The introspection that Python provides also lets you do some really powerful things because you can make your code self-aware. While compiled languages have their place, give me Python for my daily work. If I find myself needing more performance in my code, I isolate that code into an external C library and call it from Python. The data types that are provided by Python (lists, tuples, dictionaries) are exactly what programmers need. If you don't have a datatype that you want, its easy to create one using Python classes. Python has strong group of helpful users - This list is amazing. Post a question and you get not one but several answers to even the most complex of inquiries. This list provides the BEST technical support of any language I've ever used in my 30+ years of programming many different languages. Python allows me to get really good at one language - Since I can do almost anything that I can dream up in Python, I find I write almost 100% of my code in Python. This means that I am getting better at Python not learning lots of other languages which I will never know well. I hope you find the information at least helpful. Regards, Larry From martin at v.loewis.de Sun May 20 14:41:39 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 20 May 2007 20:41:39 +0200 Subject: Python compared to other language In-Reply-To: <1hycp1k.1g93oj9ezbinxN%aleax@mac.com> References: <1179540061.598417.13870@y80g2000hsf.googlegroups.com> <1hybvdz.1qnlesglcv0vcN%aleax@mac.com> <1179556574.341550.229190@q23g2000hsg.googlegroups.com> <1hycp1k.1g93oj9ezbinxN%aleax@mac.com> Message-ID: <46509663.20208@v.loewis.de> > PHP was definitely born _for_ webpages; Ruby wasn't, just like Perl or > Python weren't, it just became very popular for webpages when Rails > appeared. In this kind of discussion, I get always reminded that Perl stands for "Practical Extraction and Report Language". So Perl _clearly_ is for generating reports :-) FWIW, I think the main purpose of Python is to do testing on distributed operating systems :-) Regards, Martin From jstroud at mbi.ucla.edu Mon May 7 23:35:23 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 07 May 2007 20:35:23 -0700 Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? In-Reply-To: <1178351229.212479.237050@l77g2000hsb.googlegroups.com> References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> <08qk33t594ih0ulmjmev90d22lkfnotgoe@4ax.com> <1178351229.212479.237050@l77g2000hsb.googlegroups.com> Message-ID: Tonico wrote: > On May 4, 2:08 am, quasi wrote: > >>On Fri, 04 May 2007 09:37:37 +1200, Gib Bogle >> >> wrote: >> >>>Ah, so the firefighters were in on the conspiracy! >> >>No, but the firefighters are very much aware that there is more to >>9/11 than has been officially revealed. >> >>This is even more true at Pentagon. The firefighters there brought >>dogs trained to search for survivors and/or remains and found nothing. >> >>quasi > > **************************************************** > Ah, Quasi, Midex and the other conspiratorers! You're the living proof > that (gullible) idiots don't disappear: there just are new ones every > time. > Regards > Tonio > > Conspiracy theorists at least have thought behind their crazy ideas--but you just come up with monkey talk insults. Good job monkey. Monkey can't think of something to say but monkey talk? That's ok, here's a banana, monkey. Waiting for monkey response, monkey. From gh at gregor-horvath.com Fri May 18 07:10:19 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Fri, 18 May 2007 13:10:19 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de><1179160242.787344.48060@h2g2000hsg.googlegroups.com> <1179258692.237438.110860@p77g2000hsh.googlegroups.com> <464ad4a2$0$23143$9b4e6d93@newsspool1.arcor-online.net><464C34DB.4010903@v.loewis.de> <008901c79880$0282a260$03000080@hendrik> Message-ID: Hendrik van Rooyen schrieb: > I suppose that this "one language track" - mindedness of mine > is why I find the mix of keywords and German or Afrikaans so > abhorrent - I cannot really help it, it feels as if I am eating a > sandwich, and that I bite on a stone in the bread. - It just jars. Please come to Vienna and learn the local slang. You would be surprised how beautiful and expressive a language mixed up of a lot of very different languages can be. Same for music. It's the secret of success of the music from Vienna. It's just a mix up of all the different cultures once living in a big multicultural kingdom. A mix up of Python key words and German identifiers feels very natural for me. I live in cultural diversity and richness and love it. Gregor From martin at v.loewis.de Tue May 29 01:34:01 2007 From: martin at v.loewis.de (=?GB2312?B?Ik1hcnRpbiB2LiBMbyJ3aXMi?=) Date: Tue, 29 May 2007 07:34:01 +0200 Subject: how to print the GREEK CAPITAL LETTER delta under utf-8 encoding In-Reply-To: <1180414659.066482.236370@i38g2000prf.googlegroups.com> References: <1180414659.066482.236370@i38g2000prf.googlegroups.com> Message-ID: <465BBB49.6000803@v.loewis.de> ??????????????? schrieb: > I lookup the utf-8 form of delta from the link. > http://www.fileformat.info/info/unicode/char/0394/index.htm > > and then I want to print it in the python ( I work under windows) > > #!/usr/bin/python > #coding=utf-8 > > print "\xce\x94" > > but the result is not the 'delta' but an unknown character. I assume you print to the terminal (cmd.exe). This cannot work; the terminal (usually) does not interpret the characters in UTF-8. Instead, you should print a Unicode string, e.g. print u"\N{GREEK CAPITAL LETTER DELTA}" or print u'\u0394' This should work as long as your terminal supports printing the letter at all. Regards, Martin From steve at holdenweb.com Fri May 25 13:06:53 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 25 May 2007 13:06:53 -0400 Subject: sockets, gethostname() changing In-Reply-To: <1180112249.598777.126950@m36g2000hse.googlegroups.com> References: <1180062244.266857.300830@m36g2000hse.googlegroups.com> <1180063489.535893.182970@x35g2000prf.googlegroups.com> <1180065033.520142.37050@q66g2000hsg.googlegroups.com> <1180076739.557165.196900@x35g2000prf.googlegroups.com> <1hynrtd.tvqdopconrxnN%aleax@mac.com> <1180112249.598777.126950@m36g2000hse.googlegroups.com> Message-ID: 7stud wrote: [...] > > The strange thing is: the hostname and port in the output are not what > I'm using in my server program: > --------- > import socket > > s = socket.socket() > > print "made changes 2" > > host = socket.gethostname() #I'm not connected to the internet when I > use this line > print host > > port = 1291 > s.bind((host, port)) > > s.listen(5) > while("Ctrl-C hasn't been entered"): > c, addr = s.accept() #blocks and waits for client connection > print "Got socket connection from", addr > c.send("Thank you for connecting. Now get lost.") > c.close() > ---------- > > The full output of that program is: > > made changes 2 > my-names-computer.local > Got socket connection from ('127.0.0.1', 49222) > > The hostname now appears to be permanently stuck as "127.0.0.1", and > the port is wrong. That output was so confusing to me, I wasn't even > sure whether the file I was editing was actually the file that was > executing, so I printed out "made changes #" at the top of the file to > make sure the file I was editing was the one that was actually > executing. > > I can't remember exactly what the output was for addr before I started > messing around with the HOSTNAME in /etc/config, but I'm pretty sure > addr contained the same hostname as the line above it in the output, > and the port matched the port in the program. > > Any ideas why the hostname and port in the last line of the output are > not the same as the ones used in the program anymore? > Because the client is using what's called an "ephemeral" port - it is getting an arbitrary port number from the TCP layer, guaranteed to be unused by any other socket, and using that to connect to your server socket. Remember a connection has two ends - the details you are printing out from your server are those of the client endpoint. If you run several clients simultaneously you will find that each uses a different port number. That's exactly what's needed to make sure that the protocol stack can deliver the right information to the right client. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From rahulnag22 at yahoo.com Fri May 25 13:54:59 2007 From: rahulnag22 at yahoo.com (rahulnag22 at yahoo.com) Date: 25 May 2007 10:54:59 -0700 Subject: Listbox - Active index Message-ID: <1180115699.413682.8310@r3g2000prh.googlegroups.com> Hi, I am using a listbox in selectmode = MULTIPLE, I can get the current selected item in the listbox from index = "ACTIVE" , but is there a way to convert this "ACTIVE" to get the current selection index as a number. For multiple selectmode listboxes it returns a tuple of selected indexes, so I would have to write some extra code to get the current active selection index from the tuple, instead I was hoping there would be a way to get the current selection index number from the "ACTIVE" index. Thanks Rahul From mail at microcorp.co.za Thu May 31 02:59:58 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 31 May 2007 08:59:58 +0200 Subject: Is PEP-8 a Code or More of a Guideline? References: <316098.9123.qm@web33510.mail.mud.yahoo.com><465C3861.8010508@aristote.info> <1180541819.177905.264630@u30g2000hsc.googlegroups.com> Message-ID: <016801c7a353$81ac1520$03000080@hendrik> "projecktzero" wrote: > On May 30, 12:36 am, "Hendrik van Rooyen" > wrote: > > "Maric Michaud" wrote: > > > > Typist is fine, although MCP that I am, I tend to think of > > typist as female... > > > - Hendrik > > What does being a Microsoft Certified Professional(MCP) have to do > with thinking of a typist as female? =) > Yikes! - Male Chauvinist Pig... ;-) - Hendrik From sjmachin at lexicon.net Sun May 27 19:08:43 2007 From: sjmachin at lexicon.net (John Machin) Date: 27 May 2007 16:08:43 -0700 Subject: Error in optparse documentation In-Reply-To: <1180302882.090651.235860@q75g2000hsh.googlegroups.com> References: <1180302882.090651.235860@q75g2000hsh.googlegroups.com> Message-ID: <1180307323.396786.157340@g37g2000prf.googlegroups.com> On May 28, 7:54 am, Shatadal wrote: > In the python documentation section 14.3.2.6 (http://docs.python.org/ > lib/optparse-generating-help.html) in the last line it is written > > "options that have a default value can include %default in the help > string--optparse will replace it with str() of the option's default > value. If an option has no default value (or the default value is > None), %default expands to none." > > However this is true only for python 2.4 and newer and not for older > versions. Though the documentation for optparse (section 14.3,http://docs.python.org/lib/module-optparse.html) says that the module > is new for python 2.3, in this version a help string (default value = > intermediate) e.g. > > help="interaction mode: novice, intermediate, or expert [default: > %default]" > > prints > > interaction mode: novice, intermediate, or expert [default: %default] > > and not: > > interaction mode: novice, intermediate, or expert [default: > intermediate] > > Only in python 2.4 and newer do you see the help string print as > > interaction mode: novice, intermediate, or expert [default: > intermediate] > > I think the documentation should be modified so that it is made clear > that %default in the help string behaves as is claimed only in version > 2.4 and higher. Don't think, act; submit a doc patch: """ Please add the text "New in version 2.4." to the end of the last bullet point in [the section that you quoted]. """ and move on. If you are maintaining software that must work on an older version of Python, you need to read the docs for that version, as well as the current docs -- you can't [reasonably] expect a birth certificate attached to each paragraph :-) From __peter__ at web.de Fri May 4 14:05:08 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 04 May 2007 20:05:08 +0200 Subject: adding methods at runtime and lambda References: <1178221975.149008.192410@y5g2000hsa.googlegroups.com> <1178300759.455134.60560@n59g2000hsh.googlegroups.com> Message-ID: Mike wrote: > staticmethod makes the function available to the whole class according > to the docs. What if I only want it to be available on a particular > instance? Say I'm adding abilities to a character in a game and I want > to give a particular character the ability to 'NukeEverybody'. I don't > want all characters of that type to be able to wipe out the entire > planet, just the particular character that got the powerup. Static methods are for specialists, you don't need them. But then, your initial post looked like you were just exploring the possibilities... You can - have the Character.nuke_everybody() method check a self._can_nuke_eb flag - subclass the Character class with a NukingChar subclass and make only one instance of that class - add an instancemethod to one Character instance The simpler the approach you take the smarter you are ;) Peter From dborne at gmail.com Thu May 31 11:03:05 2007 From: dborne at gmail.com (Dave Borne) Date: Thu, 31 May 2007 10:03:05 -0500 Subject: How do I Extract Attachment from Newsgroup Message In-Reply-To: <1180619689.128854.29180@q75g2000hsh.googlegroups.com> References: <1180619689.128854.29180@q75g2000hsh.googlegroups.com> Message-ID: <6e42ec490705310803p7b80323ep5988517f9bd1c53d@mail.gmail.com> > I looked for a solution > with mimetools (the way I'd approach it for email) but found nothing. ... > ', 'Content-Type: Multipart/Mixed;', ' > boundary="------------Boundary-00=_A5NJCP3FX6Y5BI3BH890"', 'Date: Thu, ... Playing with data = n.article('116431')[3] and email.message_from_string, there seems to be a problem with the content type being split up. I was able to get a multipart message by using msg = email.message_from_string('\n'.join(data).replace(';\n', ';')) (and adding an ending boundary to your sample data). This is a bit hackish and could cause problems if there are semicolons inside the message body (no warranties expressed or implied, etc.) Hope this helps, -Dave From wildemar at freakmail.de Fri May 18 13:58:13 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Fri, 18 May 2007 19:58:13 +0200 Subject: (Modular-)Application Framework / Rich-Client-Platform in Python In-Reply-To: <8ea03$464dc950$d443bb3a$5229@news.speedlinq.nl> References: <8ea03$464dc950$d443bb3a$5229@news.speedlinq.nl> Message-ID: <464DE935.1030400@freakmail.de> Stef Mientki wrote: > I took a look at Eclipse page you mentioned but after reading the first page I still don't > understand what you mean (and I never read beyond the first page ;-). > Well, what can I say ... ;) > With a plugin system, I can think of a complete operating system, > or I can think of something like a DTP, or simply Word, > or I can think of something like Signal WorkBench > etc. > Yes exactly. As I said: Nothing in particular. Just an environment that loads and unloads little bits if functionality, whatever those may be. I think what most people think of when they hear "plugin" is: An Application that can be extended. An RCP provides no more than the next step: No monolithic app, just plugins (which can have plugins themselves (which can have plugins themselves (which ...))). Write a text editor component and use it in your music-sequencer that also monitors your internet-activity, if you must. > I think if you don't express what all of the tasks of that framework will be, > it's not well possible to create one. > > Oh, but it is! Eclipse is such a framework. Pitty is, it's written in Java. ;) > Do you want just launching of applications, or do they have to communicate, > exchange data, launch each other, create together one document or more general control one process, > and lots of more questions ;-) > Who knows? Thats the beauty of it. Eclipse has been conceived as an IDE/Text-Editor. But now it is just a platform for others to build plugins for. Such as an IDE. There are plans to make an eclipse-based general PIM (called Haystack, I think). The concept is very simple, but for some reason, highly unusual at present. I'm pretty sure that this will change sooner or later. From bscrivener42 at gmail.com Sun May 13 20:57:22 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: 13 May 2007 17:57:22 -0700 Subject: GUI tutorial In-Reply-To: References: Message-ID: <1179104242.701176.160180@e65g2000hsc.googlegroups.com> On May 13, 12:51 pm, John K Masters wrote: > Can someone point me in the direction of a good tutorial on programming > python with a GUI? Alan Gauld added a gui programming tutorial to his main course. http://www.freenetpages.co.uk/hp/alan.gauld/ It's a frame page so I can't link directly, but select "GUI Programming" under Advanced Topics on the left. rd From steven at REMOVE.THIS.cybersource.com.au Mon May 7 20:56:59 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 08 May 2007 00:56:59 -0000 Subject: randomly write to a file References: <1178567497.042096.82940@w5g2000hsg.googlegroups.com> Message-ID: On Mon, 07 May 2007 12:51:37 -0700, rohit wrote: > i can read a specified line by using the module linecache but i am > struck as to how to implement writing to the n(th) line in a file > EFFICIENTLY > which means i don't want to traverse the file sequentially to reach the > n(th) line Unless you are lucky enough to be using an OS that supports random-access line access to text files natively, if such a thing even exists, you can't because you don't know how long each line will be. If you can guarantee fixed-length lines, then you can use file.seek() to jump to the appropriate byte position. If the lines are random lengths, but you can control access to the files so other applications can't write to them, you can keep an index table, which you update as needed. Otherwise, if the files are small enough, say up to 20 or 40MB each, just read them entirely into memory. Otherwise, you're out of luck. -- Steven. From tinaweb at bestemselv.com Thu May 17 01:24:39 2007 From: tinaweb at bestemselv.com (Tina I) Date: Thu, 17 May 2007 07:24:39 +0200 Subject: Distributing programs depending on third party modules. In-Reply-To: <464B0CC0.5030505@codebykevin.com> References: <53357$4649c4a6$4275d90a$20775@FUSE.NET> <-J6dnUQxANzMB9fbRVnzvAA@telenor.com> <464B0CC0.5030505@codebykevin.com> Message-ID: Kevin Walzer wrote: > Tina I wrote: >> Kevin Walzer wrote: > > >> And maybe the smartest thing to do would be to dump PyQt and just go >> for tkinter, however ugly it is :/ > > Tkinter doesn't have to be ugly. > > I sell a proprietary Tkinter app commercially on OS X: > > http://www.codebykevin.com/phynchronicity-running.png > Thanks, looks very nice :) I'll play around with Tkinter a little and maybe try it out for my next project just for fun. Tina From flavio.preto at gmail.com Sun May 6 16:26:41 2007 From: flavio.preto at gmail.com (Flavio Preto) Date: Sun, 6 May 2007 17:26:41 -0300 Subject: Newbie prob: How to write a file with 3 threads? In-Reply-To: References: <1178440537.257526.40980@y5g2000hsa.googlegroups.com> Message-ID: <5fb10ac20705061326q2d32aa39redad689348a6285f@mail.gmail.com> Is it not possible to acomplish this with a token-based algorithm? With 3 Threads: A, B and C Thread A start with Token. Thread with the token writes the byte and send the token to the next Or python has any issues to a file object shared among a few threads? []'s Flavio On 5/6/07, Marc 'BlackJack' Rintsch wrote: > > In <1178440537.257526.40980 at y5g2000hsa.googlegroups.com>, est wrote: > > > I need to write a file using 3 threads simutaniously, e.g. Thread 1 > > write the first byte of test.bin with an "a", second thread write the > > second byte "b", third thread write the third byte "c". Anyone could > > give a little example on how to do that? > > Simplest solution is: don't do that. Write from one thread and send the > date from the other threads via a `Queue.Queue` to the writing thread. > Send the number of the thread with the data so the writer thread knows in > which order the data has to be written. > > > I have my code, but it makes python intepreter crash everytime on my > > Vista. > > Show minimal (non-)working code, tell us the exception plus traceback and > explain "crash". > > Ciao, > Marc 'BlackJack' Rintsch > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nagle at animats.com Tue May 8 23:25:38 2007 From: nagle at animats.com (John Nagle) Date: Tue, 08 May 2007 20:25:38 -0700 Subject: Towards faster Python implementations - theory In-Reply-To: References: <1210i.7468$2v1.2505@newssvr14.news.prodigy.net> <1178641778.266569.13290@p77g2000hsh.googlegroups.com> Message-ID: Marc 'BlackJack' Rintsch wrote: > I don't see how this type inference for static types will work unless some > of the dynamism of the language will get restricted. But is this really > necessary? Isn't a JIT compiler and maybe type hinting good enough? Not necessarily. One of the more powerful optimizations is to optimize reference count updates. Often, you can hoist reference count updates out of loops, which is a big win. But to do that, you need to be sure that the code executed by the loop won't change unexpectedly. My point is that while all the dynamism in Python is occasionally useful, most of the time for most of the variables most of it isn't being used. If we can discard the excess baggage, unnecessary dictionary lookups, and unnecessary reference count updates a large fraction of the time, it's a big win. This requires "surprise-free" language semantics, so that when something unusual is going on, it's visibly reflected in the code. Surprise-free semantics also make code easier to debug. John Nagle From steve at holdenweb.com Fri May 18 16:34:33 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 18 May 2007 16:34:33 -0400 Subject: How to convert a number to binary? In-Reply-To: <1179474720.810650.10510@l77g2000hsb.googlegroups.com> References: <1179444832.775573.55830@y80g2000hsf.googlegroups.com> <1179445546.307017.275850@p77g2000hsh.googlegroups.com> <87lkfm64ry.fsf@benfinney.id.au> <1179474720.810650.10510@l77g2000hsb.googlegroups.com> Message-ID: Lyosha wrote: > On May 17, 11:10 pm, Ben Finney > wrote: > [...] >>> That's way too complicated... Is there any way to convert it to a >>> one- liner so that I can remember it? >> You put in a module so you don't *have* to remember it. >> >> Then, you use it in this one-liner: >> >> foo = to_base(15, 2) >> >> Carrying a whole lot of one-liners around in your head is a waste of >> neurons. Neurons are far more valuable than disk space, screen lines, >> or CPU cycles. > > While I agree with this general statement, I think remembering a > particular one-liner to convert a number to a binary is more valuable > to my brain than remembering where I placed the module that contains > this function. > > I needed the one-liner not to save disk space or screen lines. It's > to save time, should I need to convert to binary when doing silly > little experiments. I would spend more time getting the module > wherever it is I stored it (and rewriting it if it got lost). > > It's fun, too. > Id use the "silly little module" even for experiments. Most Python programmers keep a directory full of such "stock" modules. regards Steve From bogle at ihug.too.much.spam.co.nz Thu May 3 17:37:37 2007 From: bogle at ihug.too.much.spam.co.nz (Gib Bogle) Date: Fri, 04 May 2007 09:37:37 +1200 Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? In-Reply-To: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> Message-ID: Ah, so the firefighters were in on the conspiracy! From showell30 at yahoo.com Sun May 27 14:20:34 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 27 May 2007 11:20:34 -0700 (PDT) Subject: itertools.groupby In-Reply-To: <1180288146.066905.237550@q69g2000hsb.googlegroups.com> Message-ID: <905553.47920.qm@web33512.mail.mud.yahoo.com> --- 7stud wrote: > > I'd settle for a simple explanation of what it does > in python. > The groupby function prevents you have from having to write awkward (and possibly broken) code like this: group = [] lastKey = None for item in items: newKey = item.key() if newKey == lastKey: group.append(word) elif group: doSomething(group) group = [] lastKey = newKey if group: doSomething(group) See my other reply for what it actually does in a simple example. ____________________________________________________________________________________Choose the right car based on your needs. Check out Yahoo! Autos new Car Finder tool. http://autos.yahoo.com/carfinder/ From silverburgh.meryl at gmail.com Thu May 24 14:23:49 2007 From: silverburgh.meryl at gmail.com (silverburgh.meryl at gmail.com) Date: 24 May 2007 11:23:49 -0700 Subject: How can I time a method of a class in python using Timeit In-Reply-To: <1180028476.396282.316330@q69g2000hsb.googlegroups.com> References: <1180020970.039576.319230@m36g2000hse.googlegroups.com> <1180027843.322955.57280@q75g2000hsh.googlegroups.com> <1180028334.650900.283930@m36g2000hse.googlegroups.com> <1180028476.396282.316330@q69g2000hsb.googlegroups.com> Message-ID: <1180031029.147000.55680@m36g2000hse.googlegroups.com> On May 24, 12:41 pm, 7stud wrote: > Actually, you can do this: > > class Dog(object): > def aFunction(self): > result = 20 + 2 > def run(self): > #do stuff > aFunction() > #do other stuff > import timeit > > t = timeit.Timer("d.aFunction()", "from __main__ import Dog; d = > Dog()") > print t.timeit() > > Since you only want to time aFunction(), you can call it directly. Can 't = timeit.Timer()' run inside a thread? And I have multiple threads running this 't = timeit.Time()' function? From gagsl-py2 at yahoo.com.ar Tue May 15 23:34:36 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 16 May 2007 00:34:36 -0300 Subject: Recursion limit problems References: <1178921877.442519.165740@u30g2000hsc.googlegroups.com> <1179156916.706892.144770@y80g2000hsf.googlegroups.com> <5atnc4F2pkv2eU1@mid.uni-berlin.de> Message-ID: En Tue, 15 May 2007 09:28:52 -0300, Diez B. Roggisch escribi?: >> with the same hash value. >> That is, you should define __hash__ and one of (__cmp__ or __eq__). >> __neq__ (inequality) isn't required nor used by dict/set implementation. >> (Anyway, Python will transform a!=b into not(a==b), if __neq__ isn't >> defined). Neither <, <=, >, >= are used. > > No, it won't: > > http://docs.python.org/ref/customization.html#l2h-190 Ouch, sorry, my bad! -- Gabriel Genellina From steve at REMOVE.THIS.cybersource.com.au Sat May 12 23:45:17 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 13 May 2007 13:45:17 +1000 Subject: How to cleanly pause/stop a long running function? References: <1179003065.771223.25600@e65g2000hsc.googlegroups.com> Message-ID: On Sat, 12 May 2007 13:51:05 -0700, Basilisk96 wrote: > Suppose I have a function that may run for a long time - perhaps from > several minutes to several hours. An example would be this file > processing function: > > import os > def processFiles(startDir): > for root, dirs, files in os.walk(startDir): > for fname in files: > if fname.lower().endswith(".zip"): > # ... do interesting stuff with the file here ... > > Imagine that there are thousands of files to process. This could take > a while. How can I implement this so that the caller can pause or > interrupt this function, and resume its program flow? I don't think there really is what I would call a _clean_ way, although people may disagree about what's clean and what isn't. Here's a way that uses global variables, with all the disadvantages that entails: last_dir_completed = None restart = object() # a unique object def processFiles(startDir): global last_dir_completed if startDir is restart: startDir = last_dir_completed for root, dirs, files in os.walk(startDir): for fname in files: if fname.lower().endswith(".zip"): # ... do interesting stuff with the file here ... last_Dir_completed = root Here's another way, using a class. Probably not the best way, but a way. class DirLooper(object): def __init__(self, startdir): self.status = "new" self.startdir = startdir self.root = startdir def run(self): if self.status == 'new': self.loop(self.startdir) elif self.status == 'finished': print "nothing to do" else: self.loop(self.root) def loop(self, where): self.status = "started" for self.root, dirs, files in os.walk(where): # blah blah blah... Here's another way, catching the interrupt: def processFiles(startDir): try: for root, dirs, files in os.walk(startDir): # blah blah blah ... except KeyboardInterrupt: do_something_with_status() You can fill in the details :) As for which is "better", I think the solution using a global variable is the worst, although it has the advantage of being easy to implement. I think you may need to try a few different implementations and judge for yourself. -- Steven. From rahulnag22 at yahoo.com Mon May 14 13:30:31 2007 From: rahulnag22 at yahoo.com (rahulnag22 at yahoo.com) Date: 14 May 2007 10:30:31 -0700 Subject: tkinter button state = DISABLED Message-ID: <1179163831.016938.79840@w5g2000hsg.googlegroups.com> I have created a button widget with a button click binding. The button initially has a state=disabled. I can see the greyed out version of the button in the GUI. But If I click on the button it still invokes the callback/binding function. Any suggestions as to why the callback is being invoked even though the button has a disabled state. It looks like- b=Button(frame, text = "Button", state = 'disabled') b.bind("", lambda event : function() ) Thanks Rahul From mailmaverick666 at gmail.com Thu May 10 10:14:33 2007 From: mailmaverick666 at gmail.com (rishi pathak) Date: Thu, 10 May 2007 19:44:33 +0530 Subject: newb: Python Module and Class Scope In-Reply-To: <1178805769.658287.178240@q75g2000hsh.googlegroups.com> References: <1178805769.658287.178240@q75g2000hsh.googlegroups.com> Message-ID: <180b672e0705100714n461a5f84gf9e0ef90ed51e44e@mail.gmail.com> This works for me.Also tried importing this module into another program. The class is inside the module so like the different function's of a module can access each other,the same thing applies to a class and functions/classes #Test Module class foo: def __init__(self): self.data=1 def outData(self): print self.data main() def main(): print "I am the main" #Module test if __name__=="__main__": fooObj=foo() fooObj.outData() On 10 May 2007 07:02:49 -0700, johnny wrote: > > Can a class inside a module, access a method, outside of class, but > inside of the module? > > Eg. Can instance of class a access main, if so how? What is the > scope of "def main()" interms of class A? > > myModule: > > class A: > main() > > def main(): > > > thnx. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Regards-- Rishi Pathak National PARAM Supercomputing Facility Center for Development of Advanced Computing(C-DAC) Pune University Campus,Ganesh Khind Road Pune-Maharastra -------------- next part -------------- An HTML attachment was scrubbed... URL: From timr at probo.com Wed May 30 02:18:36 2007 From: timr at probo.com (Tim Roberts) Date: Wed, 30 May 2007 06:18:36 GMT Subject: Is PEP-8 a Code or More of a Guideline? References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <5c1jpkF2tl0ilU1@mid.individual.net> Message-ID: Frank Swarbrick wrote: > >Then you'd really love COBOL! > >:-) > >Frank >COBOL programmer for 10+ years Hey, did you hear about the object-oriented version of COBOL? They call it "ADD ONE TO COBOL". -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From gh at gregor-horvath.com Mon May 28 05:01:26 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Mon, 28 May 2007 11:01:26 +0200 Subject: What's the best way to iniatilize a function In-Reply-To: References: <7NmdncRrFaG3WMTbnZ2dnUVZ_gWdnZ2d@comcast.com> Message-ID: Jack schrieb: > I didn't call del explicitly. I'm expecting Python to call it when > the program exits. I put a logging line in __del__() but I never > see that line printed. It seems that __del__() is not being called > even when the program exits. Any idea why? > > http://effbot.org/pyfaq/my-class-defines-del-but-it-is-not-called-when-i-delete-the-object.htm better solutions: http://docs.python.org/ref/try.html http://docs.python.org/whatsnew/pep-343.html Gregor From ddimuc at sbcglobal.net Fri May 4 12:46:22 2007 From: ddimuc at sbcglobal.net (ddimuc at sbcglobal.net) Date: Fri, 04 May 2007 12:46:22 -0400 Subject: New York City Python Users Group Meeting - Tuesday May 8th In-Reply-To: <00b101c78d95$53be1c40$fefea8c0@haengma> References: <00b101c78d95$53be1c40$fefea8c0@haengma> Message-ID: <463B635E.9010508@sbcglobal.net> An HTML attachment was scrubbed... URL: From carsten at uniqsys.com Wed May 16 08:11:59 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 16 May 2007 08:11:59 -0400 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464aaee8$0$10188$9b4e6d93@newsspool4.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <46478694$0$1412$426a34cc@news.free.fr> <1hy252p.1anf7sr1p4yp12N%aleax@mac.com> <464988a4$0$20289$9b4e6d93@newsspool3.arcor-online.net> <464aaee8$0$10188$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <20070516120209.M33134@uniqsys.com> On Wed, 16 May 2007 09:12:40 +0200, Ren? Fleschenberg wrote > The X people who speak "no English" and program in Python. I > think X actually is very low (close to zero), because programming in > Python virtually does require you to know some English, wether you > can use non-ASCII characters in identifiers or not. It is naive to > believe that you can program in Python without understanding any > English once you can use your native characters in identifiers. That > will not happen. Please understand that: You basically *must* know > some English to program in Python, and the reason for that is not > that you cannot use non-ASCII identifiers. There is evidence against your assertions that knowing some English is a prerequisite for programming in Python and that people won't use non-ASCII identifiers if they could. Go read the posts by "HYRY" on this thread, a teacher from China, who teaches his students programming in Python, and they don't know any English. They *do* use non-ASCII identifiers, and then they use a cleanup script the teacher wrote to replace the identifiers with ASCII identifiers so that they can actually run their programs. This disproves your assertion on both counts. -Carsten From sjmachin at lexicon.net Tue May 1 18:55:08 2007 From: sjmachin at lexicon.net (John Machin) Date: 1 May 2007 15:55:08 -0700 Subject: How can I get the ascii code of a charter in python? In-Reply-To: <1178053581.390873.65850@n76g2000hsh.googlegroups.com> References: <1178053581.390873.65850@n76g2000hsh.googlegroups.com> Message-ID: <1178060108.853490.318050@h2g2000hsg.googlegroups.com> On May 2, 7:06 am, "tedpot... at gmail.com" wrote: > How can I get the ascii code of a charter in python? E.g. download from here: http://www.gutenberg.org/ebooks/10000 then in Python, use: text = open("the_file.txt").read() HTH, John From mail at microcorp.co.za Thu May 3 02:24:16 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 3 May 2007 08:24:16 +0200 Subject: Python un-plugging the Interpreter References: <1hwu415.1yyvbo61efn1uqN%aleax@mac.com> Message-ID: <00eb01c78d4b$af22b720$03000080@hendrik> "Jorgen Grahn" wrote: > On Wed, 25 Apr 2007 08:05:01 +0200, Hendrik van Rooyen wrote: > > "Jorgen Grahn" wrote: > ... > >> I doubt it. (But I admit that I am a bit negative towards thread > >> programming in general, and I have whined about this before.) > >> > > > > I find this last statement interesting, because it differs so much > > from my own attitude - getting a thread running was one of the > > first things I did when I started getting to grips with python. > > > > Do you mind "whining" some more - maybe I can learn > > something - threads seem to me to make a lot of things so > > much easier and more natural, as I see them as sequences > > that run "at the same time", and I find this immensely useful > > for all sorts of things, as it enables me to think in a simple > > linear fashion about parts of complicated things. > > It's the other way around for me -- using a threaded design looks > superficially more linear, but all the complexity is still there, and > then some. I mean, threads are well known for causing surprising and > hard-to-track-down (and hard to trigger!) bugs and performance > problems. > > (I'm comparing with the Unix select() call, and I assume the APIs I > want to use are designed to work with select(). i.e. use select()able > file descriptors.) This is a valuable insight - it is to a large extent true that threading is used to "front end" i/o - but that is not its only use... I tend to use it to build, via Queue glue, structures that resemble systolic arrays - where each thread does a small part of a whole job. > > > And if you > > add queues, you have something in your hand that you can > > do quite fancy stuff with in a robust, simple manner... > > > > *grin* before I discovered the queue module, I was using > > named pipes to communicate between threads... > > > > So you could say I am a threading freak if you want to, and > > I won't argue. > > > > But I would like to hear the opposite viewpoint.. > > Good. My viewpoint is due to my Unix background (but I'm not > insinuating that all Unix users dislike threads). > > Eric Raymond's "The Art of Unix Programming" sums up the threading > criticism, I think: > > http://catb.org/~esr/writings/taoup/html/multiprogramchapter.html > > /Jorgen Thanks - interesting link. This guy really is not turned on by threading... - Hendrik From warren at muse.com Thu May 31 10:49:22 2007 From: warren at muse.com (Warren Stringer) Date: Thu, 31 May 2007 07:49:22 -0700 Subject: c[:]() In-Reply-To: References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com><1180554872.3356.30.camel@dot.uniqsys.com><465DF3DE.40404@cc.umanitoba.ca><1180566831.239580.199300@m36g2000hse.googlegroups.com><005401c7a31a$136f7fe0$240110ac@Muse> Message-ID: <001c01c7a392$e07c6570$240110ac@Muse> Hey Douglas, Perhaps I was being too abstract? Here goes: ,------------------------------- | def selector(): | ... | return funcKey #get down get down | | def func(): | ... | funcSwitch = {} | funcSwitch[funcKey] = func | ... | funcSwitch[selector()]() even more interesting is a ,---------------------------------------- | def judge(contestants): | for contestant in contestants: | ... | if answersQuestionToSatisfaction: | yield semiFinalist | | beauty[judge(beauty)]() hmmmm, I suppost you could just call judge(beauty) and have the judge call the contestant personally. But that may be *too* personal. Moreover, what about the other judges? Wouldn't it be best to simply state: beauty[judges[:](beauty)].thankyouForThisOpportunity() This allows each judge to choose differently while all the contestants behave consistently. It kind of like an off the cuff decorator for generators, where beauty[...].decoration() Maybe there's a better way of doing this? I don't know. > >> > >>def a(): return 'b' > >>def b(): print 'polly! wakey wakey' > >>c = {} > >>c['a'] = b > >>c[a()]() #works! > > > > > >(typo correction for other easily-confused newbies like myself) > > > >I think you mean > >,---- > >| c['a']() #works! > >`---- > > > > Oh no, I get it, you meant... > ,---- > | c['b'] = b > | c[a()]() #works! > `---- > > ...or was it?:- > ,---- > | def a(): return 'a' > `---- > > -- > Doug Woodrow > > -- > http://mail.python.org/mailman/listinfo/python-list From thorsten at thorstenkampe.de Tue May 15 08:32:31 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 15 May 2007 13:32:31 +0100 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <1hy2qg3.iqfvwnrvr9kjN%aleax@mac.com> <46482624.6050507@web.de> <7xd512onsx.fsf@ruckus.brouhaha.com> <464951EF.7030900@web.de> <464997a5$0$10193$9b4e6d93@newsspool4.arcor-online.net> <4649a561$0$10187$9b4e6d93@newsspool4.arcor-online.net> Message-ID: * Ren? Fleschenberg (Tue, 15 May 2007 14:19:46 +0200) > Thorsten Kampe schrieb: > >> Identifiers which my terminal cannot even display surely > >> are not very readable. > > > > This PEP is not about you. It's about people who write in their native > > language and who are forced to use a dodgy transcription from > > characters of their own language to ASCII. > > It is impossible to write Python in a native language other than English > even with the implementation of this PEP. All you get is a weird mixture > of English identifiers from various libraries and identifiers in your > native language. You have a few English keywords that are not meant to be understood but can be learned. > And even if you consider that more clear and readable > than English-only Python code, the fact that it discourages code sharing > remains. It neither encourages or discourages anything. And I don't think encouraring or discouraging code sharing is a good thing. There is simply no general reason to do so. From antroy at gmail.com Tue May 15 04:17:18 2007 From: antroy at gmail.com (Ant) Date: 15 May 2007 01:17:18 -0700 Subject: Trying to choose between python and java In-Reply-To: References: Message-ID: <1179217038.226176.146250@n59g2000hsh.googlegroups.com> On May 15, 6:30 am, Anthony Irwin wrote: > #1 Does python have something like javas .jar packages. A jar file > contains all the program files and you can execute the program with > java -jar program.jar As someone else has said, Python has eggs: http://peak.telecommunity.com/DevCenter/PythonEggs > #3 Is there any equivalent to jfreechart and jfreereport > (http://www.jfree.orgfor details) in python. I can't remember what it is I use - I haven't got access to my server at the moment... But look in the cheese shop - I'm fairly sure it was from there. I'll post details if I remember. Alternatively this looks good (though I haven't tried it and it's only free for non-commercial use): http://www.dislin.de > #5 someone said that they used to use python but stopped because the > language changed or made stuff depreciated (I can fully remember > which) and old code stopped working. Is code written today likely to > still work in 5+ years or do they depreciate stuff and you have to update? Any language will have some compatibility problems when upgrading to a different version, and so you have the option of updating your program or using an old version of the language. I'm a professional Java developer, and though Java 6 has been out for some time now, every company I've worked for in the last couple of years still uses Java 1.4 due to problems with the upgrade. Python does strive however to stay backward compatible (3k not withstanding), and I've upgraded from 2.3 to 2.4 and now 2.5 with no problems. > Also does anyone else have any useful comments about python vs java > without starting a flame war. As I said, I'm a professional Java developer, and much prefer programming in Python when I can (and am even getting quite a lot of Python work at the moment via Jython :-) ) -- Ant... http://antroy.blogspot.com/ From mail at microcorp.co.za Wed May 16 03:36:28 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 16 May 2007 09:36:28 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de><46477f19$0$19845$426a74cc@news.free.fr> <4648294F.2000704@web.de><46487a6c$0$2400$426a74cc@news.free.fr> <464977D3.6010703@web.de><464993e7$0$23148$9b4e6d93@newsspool1.arcor-online.net> <464997E5.4050105@web.de> Message-ID: <03f901c7979e$85904500$03000080@hendrik> "Stefan Behnel" wrote: .:) This is not about "technical" English, this is about domain specific >English. How big is your knowledge about, say, biological terms or banking >terms in English? Would you say you're capable of modelling an application >from the domain of biology, well specified in a large German document, in >perfect English terms? > >And: why would you want to do that? Possibly because it looks better and reads easier than a dog ugly mix of perfectly good German words all mixed up with English keywords in an English style of sentence construction? - Hendrik -- "Hier sind wir unter uns" ;-) From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed May 16 04:24:38 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 16 May 2007 10:24:38 +0200 Subject: setting an attribute In-Reply-To: <1179300898.223314.76430@y80g2000hsf.googlegroups.com> References: <1179300898.223314.76430@y80g2000hsf.googlegroups.com> Message-ID: <464abfaf$0$15544$426a74cc@news.free.fr> 7stud a ?crit : > "When you bind (on either a class or an instance) an attribute whose > name is not special...you affect only the __dict__ entry for the > attribute(in the class or instance, respectively)." > > In light of that statement, how would one explain the output of this > code: > > class Test(object): > x = [1, 2] > > def __init__(self): > self.x[0] = 10 > > print Test.__dict__ #{.....'x':[1,2]....} > t = Test() > print t.x #[10, 2] > print t.__dict__ #{} > print Test.__dict__ #{.....'x':[10,2]...} > > It looks to me like self.x[0] is binding on an instance whose > attribute name is not special, self.x[0] = 10 doesn't bind self.x - it's just syntactic sugar for self.x.__setitem__(0, 10) (which itself is syntactic sugar for list.__setitem__(self.x, 0, 10)) > yet it doesn't affect any __dict__ > entry for the attribute in the instance Of course. The name 'x' is looked up in the instance, then in the class. Since there's no binding (only a method call on a class attribute), instance's dict is not affected. From mikeminer53 at hotmail.com Wed May 23 12:44:04 2007 From: mikeminer53 at hotmail.com (mkPyVS) Date: 23 May 2007 09:44:04 -0700 Subject: Resizing listbook's listview pane In-Reply-To: <1179932659.180278.72990@w5g2000hsg.googlegroups.com> Message-ID: <1179938643.976024.15720@h2g2000hsg.googlegroups.com> Sorry, copied from wxpython submit as well.. I'm using wxpython 2.8... Primariy I want the resize to happen programatically during object creation/post creation... I can worry about app size changes later. Thanks, From warren at muse.com Thu May 31 12:18:51 2007 From: warren at muse.com (Warren Stringer) Date: Thu, 31 May 2007 09:18:51 -0700 Subject: Is PEP-8 a Code or More of a Guideline? In-Reply-To: <465ecb3c$0$29072$426a74cc@news.free.fr> References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <5c1jpkF2tl0ilU1@mid.individual.net> <1180539790.654176.26900@q75g2000hsh.googlegroups.com> <646aw86i.fsf@mail.com> <465ecb3c$0$29072$426a74cc@news.free.fr> Message-ID: <002d01c7a39f$607de760$240110ac@Muse> Perhaps a foot pedal? Hmmm.... My two cellphones don't like underbars very much. And the shift key -- while much easier -- still is cumbersome. If outlook didn't autocaps on me, this message would be in all lowercase. In fact, when communicating with friends from outlook, to their sms, I take the trouble to correct my outlook's autocorrect. underbars are more of a reach and harder to read when you use a really nice font. camelBack -- damn, I just had to correct outlook's autocorrect on camelback -- so, what was I saying, oh yes -- camelBackNames are just freaking weird. Sooooo.... i.prefer.dots -- no, seriously sure it's slow, but forces you the think about names in a new way. or, perhaps going deep is sacrilege? > -----Original Message----- > From: python-list-bounces+warren=muse.com at python.org [mailto:python-list- > bounces+warren=muse.com at python.org] On Behalf Of Christophe > Sent: Thursday, May 31, 2007 6:18 AM > To: python-list at python.org > Subject: Re: Is PEP-8 a Code or More of a Guideline? > > Joe Riopel a ?crit :>> Each requires exactly the same number of key > strokes when I do the>> math. (Too lazy to explain further...)> > foo_bar> > f, o, o, shift + underscore, b, a, r = 8> fooBar> f, o, o, shift + b, a, r > = 7 > f, o, o, _, b, a, r = 7f, o, o, shift + b, a, r = 8 > Also the shift+b is much more work than 2 keypresses IMHO. On the other > hand, the underscore is done by pressing the 8 key without any other > modifier which is very easy and accessible. Yeap, french layout rules for > that naming convention :)-- > http://mail.python.org/mailman/listinfo/python-list From bbxx789_05ss at yahoo.com Wed May 2 10:26:07 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 2 May 2007 07:26:07 -0700 Subject: Writing a nice formatted csv file In-Reply-To: <1178115244.446071.317250@n76g2000hsh.googlegroups.com> References: <1178115244.446071.317250@n76g2000hsh.googlegroups.com> Message-ID: <1178115967.124030.266090@o5g2000hsb.googlegroups.com> On May 2, 8:14 am, redcic wrote: > Hi all, > > I use the csv module of Python to write a file. My code is of the > form : > > cw = csv.writer(open("out.txt", "wb")) > cw.writerow([1,2,3]) > cw.writerow([10,20,30]) > > And i get an out.txt file looking like: > 1,2,3 > 10,20,30 > > Whereas what I'd like to get is: > 1, 2, 3, > 10, 20, 30 > > which is more readable. > > Can anybody help me to do so ? > > Thanks, > > C?dric cvs files are constructed for efficient processing not formatting so that you can read them easier. If you want a formatted file, then construct one. From lisa.engblom at gmail.com Wed May 16 12:03:00 2007 From: lisa.engblom at gmail.com (Lisa) Date: 16 May 2007 09:03:00 -0700 Subject: remove all elements in a list with a particular value In-Reply-To: <1179330068.785878.181980@n59g2000hsh.googlegroups.com> References: <1179328873.105705.95580@l77g2000hsb.googlegroups.com> <1179330068.785878.181980@n59g2000hsh.googlegroups.com> Message-ID: <1179331379.872451.254760@n59g2000hsh.googlegroups.com> Great. Thanks for your help. From vasudevram at gmail.com Mon May 21 13:02:46 2007 From: vasudevram at gmail.com (vasudevram) Date: 21 May 2007 10:02:46 -0700 Subject: Help required with Python App In-Reply-To: References: Message-ID: <1179766965.602586.65690@x35g2000prf.googlegroups.com> On May 21, 8:11 pm, Trevor Hennion wrote: > Hi, > > I am producing a Web based database application for a customer and could > do with some help producing pdf documents from the data. > > The project uses Apache. Postgresql and Python CGI scripts on a Linux > server for a company with 20-25 users. > > I have been looking at thehttp://www.reportlab.org- ReportLab Toolkit, > but am rather busy with the other parts of the project, so if any one > located in the UK - Reading/Basingstoke area has the right > skills and time available now, please contact me. > > I have a small budget available for this work. > > Regards > > Trevor > > PS UK/Reading/Basingstoke area is essential. I don't have the time right now, though I'd be free for some work after a week or two; but I'm not in your area. ReportLab is quite good and has many features. I used it to build my xtopdf toolkit, a toolkit for conversion of other file formats to PDF. You could try using it (ReportLab) directly from the Python scripts in your app. If your needs are only for text to PDF conversion (of the textual data - numbers, strings and dates from the database), then you might want to take a look at xtopdf - see http://www.dancingbison.com/products.html. It may be a bit easier to use than ReportLab itself (it has a small and simple to use API), but only for text to PDF conversion - it doesn't support images as of now. It's released under the same license as ReportLab, the BSD license. xtopdf has sample programs that show you how to use it. It supports setting the font (anywhere in the output, but only one font at a time, headers and footers for each page, and automatic pagination). You can also read this article about it: http://www.packtpub.com/article/Using_xtopdf The article above shows how to use xtopdf to create PDF from various input formats - CSV, text, TDV, XLS, etc. All done very simply with just a few lines of code. You could try using either Reportlab or xtopdf or getting someone to help with using one of them. HTH Vasudev Ram Dancing Bison Enterprises http://www.dancingbison.com From mcPas.De.Spam at mclaveauPas.De.Spam.com Wed May 2 15:49:27 2007 From: mcPas.De.Spam at mclaveauPas.De.Spam.com (Michel Claveau) Date: Wed, 02 May 2007 21:49:27 +0200 Subject: Microsoft's Dynamic Languages Runtime (DLR) References: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> Message-ID: Re! During we post messages, then blog of Jim Hugunin is updated: http://blogs.msdn.com/hugunin/ -- @-salutations Michel Claveau From paul at boddie.org.uk Fri May 18 17:53:48 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 18 May 2007 14:53:48 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <80c33$464de327$547078de$4708@news.chello.at> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <464C5382.6080403@v.loewis.de> <1179423799.254286.294930@w5g2000hsg.googlegroups.com> <1179503525.018943.95740@u30g2000hsc.googlegroups.com> <1179508599.868680.177960@e65g2000hsc.googlegroups.com> <80c33$464de327$547078de$4708@news.chello.at> Message-ID: <1179525228.465303.75460@o5g2000hsb.googlegroups.com> Gregor Horvath wrote: > Paul Boddie schrieb: > > > Perhaps, but the treatment by your mail/news software plus the > > delightful Google Groups of the original text (which seemed intact in > > the original, although I don't have the fonts for the content) would > > suggest that not just social or cultural issues would be involved. > > I do not see the point. > If my editor or newsreader does display the text correctly or not is no > difference for me, since I do not understand a word of it anyway. It's a > meaningless stream of bits for me. But if your editor doesn't even bother to preserve those bits correctly, it makes a big difference. When ???????? becomes 6??????? because someone's tool did the equivalent of unicode_obj.encode("iso-8859-1", "replace"), then the stream of bits really does become meaningless. (We'll see if the former identifier even resembles what I've just pasted later on, or whether it resembles the latter.) > It's save to assume that for people who are finding this meaningful > their setup will display it correctly. Otherwise they could not work > with their computer anyway. Sure, it's all about "editor discipline" or "tool discipline" just as I wrote. I'm in favour of the PEP, generally, but I worry about the long explanations required when people find that their programs are now ill-formed because someone made a quick edit in a bad editor. Paul From kelvin.you at gmail.com Fri May 11 01:56:11 2007 From: kelvin.you at gmail.com (=?gb2312?B?yMvR1MLkyNXKx8zs0cSjrM37vKvM7NHEsru8+7zS?=) Date: 10 May 2007 22:56:11 -0700 Subject: how to refer to partial list, slice is too slow? In-Reply-To: <1178862631.470437.134180@h2g2000hsg.googlegroups.com> References: <1178862631.470437.134180@h2g2000hsg.googlegroups.com> Message-ID: <1178862971.447773.21760@o5g2000hsb.googlegroups.com> I make a sample here for the more clearly explanation s = " ..... - this is a large string data - ......." def parser1(data) # do some parser ... # pass the remainder to next parser parser2(data[100:]) def parser2(data) # do some parser ... # pass the remainder to next parser parser3(data[100:]) def parser3(data) # do some parser ... # pass the remainder to next parser parser4(data[100:]) ... From ed at leafe.com Thu May 24 11:15:10 2007 From: ed at leafe.com (Ed Leafe) Date: Thu, 24 May 2007 11:15:10 -0400 Subject: Python and GUI In-Reply-To: <46559F9F.4010807@bryant.edu> References: <1179761984.704369.116310@b40g2000prd.googlegroups.com> <4651CDBC.1070508@ulmcnett.com> <46559F9F.4010807@bryant.edu> Message-ID: On May 24, 2007, at 10:22 AM, Brian Blais wrote: > Then there is Dabo, which I personally have had problems with. I > am looking for a > pythonic, professional looking GUI framework. I first tried dabo > with python 2.4, > and had to install sqlite, which seemed a bit odd for trying to > just get a GUI > framework...I understand why, but when you're looking for one > thing, having it tied > to a completely different thing feels a little strange. FWIW, we made that decision only after Python itself committed to including SQLite as part of the standard distribution. While there may have been some problems during the transition, such as you apparently had, it made for a much better product in the long run. > I never got it working in > Python2.5, either on Linux or OS X, and the problem is most > definitely mine and I > didn't have the patience to debug it. I am really not trying to > diss dabo here, > because there enough people who swear by it, that it must be doing > many things right. I checked the archives, and didn't find any messages from you asking for help. We know that the documentation is far from complete, and the installation process can be problematic, but one thing we pride ourselves on is quick response to help requests, and then fixing whatever it was that caused the initial problem. > My problem with Dabo is not what it is, it is what I am looking > for...a pythonic GUI > framework. Coming from Unix, I generally feel that a program > should try to do one > thing, and one thing well. To mix really different functionality > seems to me to be a > bad idea. If you can use the GUI parts separately, why not package > it separately? > One might find a lot of users who only what that. We've thought about doing exactly that, but to be honest, it would take a large investment of time without a corresponding increase in value. Right now all you have to do is install Dabo, and then just use the dabo.ui classes. You never need to touch the database or business object layers if you don't want to. Also, I don't feel that we are "mixing different functionality". Rather, we are creating an integrated environment for those wishing to create rich desktop apps. Nearly all such apps require displaying and persisting information, and that's what Dabo is designed to do. If you don't need persistent information, the display stuff works just fine. I'd encourage anyone who is curious about what dabo.ui offers to view the part of my recent PyCon presentation that discusses exactly this topic. Take a look at http://dabodev.com/pycon2007?3 to see an example of simpler and more Pythonic Dabo code is compared to what you would have to write in either raw wxPython or even Wax. -- Ed Leafe -- http://leafe.com -- http://dabodev.com From showell30 at yahoo.com Sun May 27 10:21:18 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 27 May 2007 07:21:18 -0700 (PDT) Subject: totally lost newbie In-Reply-To: <1180261154.969654.147850@n15g2000prd.googlegroups.com> Message-ID: <838650.13938.qm@web33504.mail.mud.yahoo.com> --- mark wrote: > Hi all > > I posted earlier on this but have changed my > approach so here is my > latest attempt at solving a problem. I have been > working on this for > around 12 hours straight and am still struggling > with it. > > Write a program that reads the values for a random > list of cards from > a file, where each line in the file specifies a > single card with the > rank and then the suit separated by a space. The > rank should be an > integer in the range of 1 to 13 (Ace:1, King:13), > while the suit > should be a lower case character in the set { 'h', > 'd', 'c', 's' }. > Sort the card entries into suits ordered by rank, > and print out the > ordered list. Hint: sort the list first by rank, and > then by suit. > Given that the hint is to sort twice, you can first break down the problem by just trying to sort your list according to the number on the card, and don't worry about the suit. Also, try using a data file that doesn't have any face cards in it, to keep things simple at first. Then, to get the face cards working, think about this--a Jack is really just an 11, a Queen is just a 12, a King is just a 13, and an Ace is just a 1. When you read in your data, maybe you want to just work with the numbers internally? Do you know how to use a dictionary to map K to 13? Then, when it comes time to produce the final output, you'll need to map 13 back to 'K', which again involves using a dictionary. There are other approaches, too, just hope this sparks some thought. ____________________________________________________________________________________Be a better Heartthrob. Get better relationship answers from someone who knows. Yahoo! Answers - Check it out. http://answers.yahoo.com/dir/?link=list&sid=396545433 From R.Brodie at rl.ac.uk Tue May 29 11:57:14 2007 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Tue, 29 May 2007 16:57:14 +0100 Subject: Unicode to HTML entities References: <1180453921.357081.89500@n15g2000prd.googlegroups.com> Message-ID: "Clodoaldo" wrote in message news:1180453921.357081.89500 at n15g2000prd.googlegroups.com... >I was looking for a function to transform a unicode string into >htmlentities. >>> u'S?o Paulo'.encode('ascii', 'xmlcharrefreplace') 'São Paulo' From martin at v.loewis.de Thu May 17 07:59:09 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 17 May 2007 13:59:09 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179330761.676441.302650@p77g2000hsh.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de><464762B6.701@web.de> <46478694$0$1412$426a34cc@news.free.fr> <1hy252p.1anf7sr1p4yp12N%aleax@mac.com> <464988a4$0$20289$9b4e6d93@newsspool3.arcor-online.net> <464aaee8$0$10188$9b4e6d93@newsspool4.arcor-online.net> <464afa8d$0$10200$9b4e6d93@newsspool4.arcor-online.net> <1179330761.676441.302650@p77g2000hsh.googlegroups.com> Message-ID: <464c438e$0$14102$9b622d9e@news.freenet.de> > Consequently, Python's keywords and even the standard library can > exist with names being "just symbols" for many people. I already told that on the py3k list: Until a week ago, I didn't know why "pass" was chosen for the "no action" statement - with all my English knowledge, I still could not understand why the opposite of "fail" should mean "no action". Still, I have been using "pass" for more than 10 years now, without ever questioning what it means in English, and I've successfully used it as a token. Except for the first draft of Das Python-Buch, where I, from memory, thought the statement should be "skip"; I remembered it had four letters, and meant "go to the next line". Now I understand it is meaning 12 in Merriam-Webster's dictionary, a) "to decline to bid, double, or redouble in a card game", or b) "to let something go by without accepting or taking advantage of it". Regards, Martin From ptmcg at austin.rr.com Mon May 14 09:32:34 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 14 May 2007 06:32:34 -0700 Subject: Yet Another Software Challenge In-Reply-To: <1179148471.466017.156290@q75g2000hsh.googlegroups.com> References: <1179148471.466017.156290@q75g2000hsh.googlegroups.com> Message-ID: <1179149554.165345.222490@u30g2000hsc.googlegroups.com> On May 14, 8:14 am, Thierry wrote: > For those interested in programming riddles, I would like to > announce a new programming challenge I'm just launching athttp://software.challenge.googlepages.com > > This challenge is in its early stage and thus set to be continuously > improved. > > I would be especially interested in your comments and feedbacks about > this initiative and its relevance. > > Enjoy! > > Thierry A small typo in your instructions: ".hml" should be ".html". -- Paul From saif.shakeel at gmail.com Fri May 18 05:02:40 2007 From: saif.shakeel at gmail.com (saif.shakeel at gmail.com) Date: 18 May 2007 02:02:40 -0700 Subject: Unusual i/o problems In-Reply-To: References: <1179325595.708882.289510@e65g2000hsc.googlegroups.com> <1179471578.531264.51220@u30g2000hsc.googlegroups.com> Message-ID: <1179478960.749659.258480@q75g2000hsh.googlegroups.com> On May 18, 1:01 pm, Peter Otten <__pete... at web.de> wrote: > saif.shak... at gmail.com wrote: > > I am running the exe from command prompt,but i am not able to see > > the error as it goes off very quickly. > > http://effbot.org/pyfaq/how-do-i-run-a-python-program-under-windows.htm > > > How do i capture the error (traceback).I tried putting an input prompt > > after the expected line of error but wont work.Is there a command to > > capture the error. > > You can redirect stderr to a file: > > http://www.microsoft.com/resources/documentation/windows/xp/all/prodd... > > Peter ok i traced the error for above code.It says something like this: Traceback (most recent call last): File "C:\Projects\ODX Import\code_ini\odxparse_mod.py", line 294, in input_xml_sec = open(output_file,'r') TypeError: coercing to Unicode: need string or buffer, file found Can someone help me in this. Thanks From michael at jedimindworks.com Fri May 11 04:50:14 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Fri, 11 May 2007 03:50:14 -0500 Subject: searching algorithm In-Reply-To: References: Message-ID: <31AA93DB-0432-4BDF-B913-A6AA1A40F8C3@jedimindworks.com> On May 10, 2007, at 12:26 PM, Gigs_ wrote: > Hi all! > > I have text file (english-croatian dictionary) with words in it in > alphabetical > order. > This file contains 179999 words in this format: > english word: croatian word > > I want to make instant search for my gui > Instant search, i mean that my program search words and show words > to user as > user type letters. > yes, it needs to be fast > > Can someone give me some points (approaches) how to make this > Should i make indexes and go with file.seek > > or should breake dictionary in peaces and put words that start with > a in one and > with b in another... > ????? > > So if i have this words > ... > > if user type: "abs" program should list all words above in english > and in croatian > if user type: "absorb" than program should list last 3 words in > english and in > croatian > > > > > > any help would be appreciate! > my apologies for bad english Here's an idea: use a rats' nest of dictionaries and do all the lookup work up front when you build the rats' nest. Maybe something like this: #! /usr/bin/env python import pprint dictionary = """absinth:pelin absinthe:pelin absolute:apsolutan absolute:apsolutni kod absolute:apsolutno absolute:čist absolute:nesumnjiv absolute:potpun absolute:savrsen absolute coordinates:apsolutne koordinate absolute frequency:apsolutna učestalost absolute gap:apsolutni jaz absolute line spacing:apsolutni međurazmak linija absolute majority:apsolutna većina absolute pointing device:apsolutni pokazivački uređaj absolute quantity:apsolutni udio absolute value:apsolutna vrijednost absolute zero:apsolutna nula absolutely:apsolutno absolutely:bezuvjetno absolutely:nezavisno absolutely:potpuno absolutely:samostalno absolutely:sasvim absolution:odrjesenje absolution:oprostaj absolutism:apsolutizam absolve:odrijesiti absolve:osloboditi absorb:absorbirati absorb:apsorbirati absorb:crpsti""" lookup = {'words':{}, 'letters':{}} for translation in dictionary.split('\n'): english, croatian = translation.split(':') if english in lookup['words']: lookup['words'][english].append(croatian) else: lookup['words'][english] = [croatian] for position, letter in enumerate(english): if position == 0: youAreHere = lookup['letters'] if letter not in youAreHere: youAreHere[letter] = {'words':[]} youAreHere[letter]['words'].append(lookup['words'][english]) youAreHere = youAreHere[letter] def tryit(partial): youAreHere = lookup['letters'] for letter in partial: youAreHere = youAreHere[letter] return youAreHere['words'] if __name__ == '__main__': pprint.pprint(tryit('abso')) Hope this helps, Michael --- The Rules of Optimization are simple. Rule 1: Don't do it. Rule 2 (for experts only): Don't do it yet. -- Michael A. Jackson , "Principles of Program Design", 1975. From vivainio at gmail.com Mon May 28 15:17:48 2007 From: vivainio at gmail.com (Ville Vainio) Date: 28 May 2007 12:17:48 -0700 Subject: ANN: IPyKit, the standalone IPython prompt Message-ID: <1180379867.961913.46660@q69g2000hsb.googlegroups.com> Some of you might want to play with IPyKit, especially you need a swiss-army-knife Python prompt on a (win32) machine where you don't really want to install anything (python, pyreadline, ipython, PATH settings...). It's basically a py2exe'd "preconfigured" IPython. http://ipython.scipy.org/moin/IpyKit From kelvin.you at gmail.com Wed May 30 01:04:29 2007 From: kelvin.you at gmail.com (=?gb2312?B?yMvR1MLkyNXKx8zs0cSjrM37vKvM7NHEsru8+7zS?=) Date: 29 May 2007 22:04:29 -0700 Subject: How to print this character u'\u20ac' to DOS terminal Message-ID: <1180501468.957322.106650@z28g2000prd.googlegroups.com> Who could explain the follow issue ? >>> print u'??' ?? >>> print u'?' Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'gbk' codec can't encode character u'\x80' in position 0: il legal multibyte sequence >>> or I just put the unicode number >>> print u'\u0394' ?? >>> print u'\u20ac' Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'gbk' codec can't encode character u'\u20ac' in position 0: illegal multibyte sequence >>> My terminal is cmd.exe under windows XP. what's the different between the two character ? what can I do if I want to print the u'\u20ac'? From antroy at gmail.com Thu May 10 11:11:53 2007 From: antroy at gmail.com (Ant) Date: 10 May 2007 08:11:53 -0700 Subject: preferred windows text editor? In-Reply-To: <4642df05$0$83110$c30e37c6@lon-reader.news.telstra.net> References: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> <1178749301.768963.278070@w5g2000hsg.googlegroups.com> <1178783872.463067.297280@o5g2000hsb.googlegroups.com> <4642df05$0$83110$c30e37c6@lon-reader.news.telstra.net> Message-ID: <1178809913.227206.8040@e51g2000hsg.googlegroups.com> On May 10, 9:59 am, Charles Sanders wrote: > Ant wrote: > > > What method of executing code snippets in a Python shell do other Vim > > users use? Other than just copy/paste? > > Not vim, but good old vi so should work in vim > > 1. Mark the start of the fragment, for exampls ms (to mark > with label s). Labels a through z are available. > 2. Move to the end of the fragment. > 3. :'s,.w !python to send the fragment to the python > interpreter Yes - that works nicely for code snippets in isolation. My quest for tighter integration of the Python console/IPython and vim will have to continue... -- Ant... http://antroy.blogspot.com/ From dustin at v.igoro.us Wed May 2 13:45:21 2007 From: dustin at v.igoro.us (dustin at v.igoro.us) Date: Wed, 2 May 2007 12:45:21 -0500 Subject: gpp (conditional compilation) In-Reply-To: <1178127460.046945.254100@y80g2000hsf.googlegroups.com> References: <1178127460.046945.254100@y80g2000hsf.googlegroups.com> Message-ID: <20070502174521.GN14710@v.igoro.us> On Wed, May 02, 2007 at 10:37:40AM -0700, maxwell at ldc.upenn.edu wrote: > I'm trying to use the gpp utility (Gnu points to http://en.nothingisreal.com/wiki/GPP) > to do conditional compilation in Python, and I'm running into a > problem: the same '#' character introduces Python comments and is used > by default to introduce #ifdef etc. lines. The hacks you'll need to wrap gpp in to get it to work will make your head spin. I'm not sure what brought you to gpp, but if you're looking for a basic macro-processing language suitable for the kinds of tasks the C preprocessor performs, I would recommend M4. GNU has an implementation of the language, and it's actually quite widely used as the basis for the GNU autotools suite. It is incredibly flexible (enough so that its learning curve is a bit steep, but not too bad), but that flexibility enables it to work with just about any underlying language. Dustin From turbana at gmail.com Tue May 8 19:19:22 2007 From: turbana at gmail.com (Ian Clark) Date: Tue, 8 May 2007 16:19:22 -0700 Subject: e-mailing multiple values In-Reply-To: <050820072307.24482.464102B3000B7E4300005FA222135753330D010C0E06A10407020E@comcast.net> References: <050820072307.24482.464102B3000B7E4300005FA222135753330D010C0E06A10407020E@comcast.net> Message-ID: On 5/8/07, anil_jacob at comcast.net wrote: > > I have a script which has a method which returns multiple strings at once using the yield. I would like to send an e-mail of these values in a single e-mail instead of a mail for each string. How would I be able to do that? > > Thanks > AJ Are you looking for something like the following? If not, try posting a small sampling of your code. >>> def get_data(): ... data = ['ham', 'eggs', 'spam'] ... for item in data: ... yield item ... >>> all_data = [item for item in get_data()] >>> all_data ['ham', 'eggs', 'spam'] Ian From joshua at eeinternet.com Thu May 3 20:23:42 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Thu, 03 May 2007 16:23:42 -0800 Subject: Replacement for HTMLGen? Message-ID: <463a70b1$0$16345$88260bb3@free.teranews.com> I realize that in today's MVC-everything world, the mere mention of generating HTML in the script is near heresy, but for now, it's what I ened to do. :) That said, can someone recommend a good replacement for HTMLGen? I've found good words about it (http://www.linuxjournal.com/article/2986), but every reference to it I find points to a non-existant page (http://starship.python.net/lib.html is 404, http://www.python2.net/lib.html is not responding, http://starship.python.net/crew/friedrich/HTMLgen/html/main.html is 404) Found http://www.python.org/ftp/python/contrib-09-Dec-1999/Network/, but that seems a bit old. I found http://dustman.net/andy/python/HyperText, but it's not listed in Cheeseshop, and its latest release is over seven years ago. Granted, I know HTML doesn't change (much) but it's at least nice to know something you're going to be using is maintained. Any suggestions or pointers? j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE -- Posted via a free Usenet account from http://www.teranews.com From steven at REMOVE.THIS.cybersource.com.au Tue May 15 22:33:28 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 16 May 2007 02:33:28 GMT Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: I've made various comments to other people's responses, so I guess it is time to actually respond to the PEP itself. On Sun, 13 May 2007 17:44:39 +0200, Martin v. L?wis wrote: > PEP 1 specifies that PEP authors need to collect feedback from the > community. As the author of PEP 3131, I'd like to encourage comments to > the PEP included below, either here (comp.lang.python), or to > python-3000 at python.org > > In summary, this PEP proposes to allow non-ASCII letters as identifiers > in Python. If the PEP is accepted, the following identifiers would also > become valid as class, function, or variable names: L?ffelstiel, chang?, > ??????, or ??? (hoping that the latter one means "counter"). > > I believe this PEP differs from other Py3k PEPs in that it really > requires feedback from people with different cultural background to > evaluate it fully - most other PEPs are culture-neutral. > > So, please provide feedback, e.g. perhaps by answering these questions: > - should non-ASCII identifiers be supported? why? - would you use them > if it was possible to do so? in what cases? It seems to me that none of the objections to non-ASCII identifiers are particularly strong. I've heard many accusations that they will introduce "vulnerabilities", by analogy to unicode attacks in URLs, but I haven't seen any credible explanations of how these vulnerabilities would work, or how they are any different to existing threats. That's not to say that there isn't a credible threat, but if there is, nobody has come close to explaining it. I would find it useful to be able to use non-ASCII characters for heavily mathematical programs. There would be a closer correspondence between the code and the mathematical equations if one could write ?(?*?) instead of delta(mu*pi). (Aside: I wonder what the Numeric crowd would say about this?) -- Steven. From ptmcg at austin.rr.com Fri May 11 23:16:13 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 11 May 2007 20:16:13 -0700 Subject: need help with python In-Reply-To: <1178937707.004412.22360@q75g2000hsh.googlegroups.com> References: <1178934447.719778.197150@h2g2000hsg.googlegroups.com> <1178937249.263856.191460@p77g2000hsh.googlegroups.com> <1178937707.004412.22360@q75g2000hsh.googlegroups.com> Message-ID: <1178939773.253366.79710@h2g2000hsg.googlegroups.com> On May 11, 9:41 pm, adamur... at hotmail.com wrote: > On May 11, 9:34 pm, Paul McGuire wrote: > > > > > > > On May 11, 8:47 pm, adamur... at hotmail.com wrote: > > > > ya so im pretty much a newb to this whole python thing... its pretty > > > cool but i just started today and im already having trouble. i > > > started to use a tutorial that i found somewhere and i followed the > > > instructions and couldnt get the correct results. heres the code > > > stuff... > > > > temperature=input("what is the temperature of the spam?") > > > if temperature>50: > > > print "the salad is properly cooked." > > > else: > > > print "cook the salad some more." > > > > ya i was trying to do that but when i told it what the spams > > > temperature was, it just turned off... well it wasnt working at all at > > > first until i realized that i hadnt been following the instructions > > > completely correctly and that i was supposed to type that code up in a > > > notepad then save and open with python... so ya thats when it asked me > > > what temperature the spam was and i typed a number then it just closed > > > itself... im not really sure what went wrong... itd be real nice if > > > someone would be like a mentor or something... > > > Well, this list has a varying level of mentoring and newbie-tolerance, > > with more latitude for people who have made some effort to start with > > before posting things like "here's my homework problem, please send me > > the working code so I can hand it in." > > > I just ran your code interactively at the Python prompt, and it runs > > just fine. See? > > > >>> temperature=input("what is the temperature of the spam?") > > > what is the temperature of the spam?55>>> if temperature>50: > > > ... print "the salad is properly cooked." > > ... else: > > ... print "the salad is properly cooked." > > ... > > the salad is properly cooked. > > > I think the problem you are having is that, when you run your program > > by double-clicking on the xyz.py file in a file browser, the OS > > (Windows, I assume?) opens a separate console window, and runs the > > program, and then at the end of the program, CLOSES the window. I > > think your code is running just fine, I think your "the salad is > > whatever" messages get printed out, but afterward, your program ends, > > so the window closes before you can see how your salad turned out. > > > A simple workaround you can do is to add to the end of your program > > this statement: > > > input("") > > > This will cause the process to stop and wait for you to press the > > RETURN key, giving you time to stop and admire your salad results > > before closing the window. > > > One final note: many people post in a "write like I talk" style. This > > is okay while telling your story ("well it wasn't working at all at > > first..."), and the ee cummings all-lower-case is passable, but please > > drop the "ya"s. They are a verbal tic that may be okay in person, but > > do not translate at all to written posts. At least you don't say > > "like" every other word, and I thank you for that! :) > > > You can get a sense of other writing styles by reading through the > > comp.lang.python archives. I would also recommend that you might find > > more folks in the "just getting started" phase posting to the python- > > tutor mailing list (go tohttp://mail.python.org/mailman/listinfo/tutor), > > and you can skim through posts there for many introductory topics. > > > Good luck to you, and welcome to Python! > > > -- Paul > > well... i just discovered another of my mistakes. i was writing it in > notepad and not saving it as .py silly me... hoho ya that input thing > to get it to make u press enter worked tho... but only with that > one... ive got another one that i cant get to work even with the input > message to press enter. Sorry about the bad grammar. I'm used to > Myspace where no one gives a particular hoot about how you type. I > hope this is better. I will follow that link though. Thanks for the > help.- Hide quoted text - > > - Show quoted text - It's possible that your next program has a runtime error, which will raise an exception that, if not handled using try-except, will cause the program to exit with a message (a message that will flash by and then disappear, as the window closes immediately). One thing you should try is to run your python programs using a terminal window (sometimes called a "console window", or "the command line"). There are several ways to open one of these, the simplest on Windows is to click the "Start" button in the lower left corner, select "Run...", and enter the command "cmd". This will open up one of these white-letters-on-black-background windows for typing system commands. From this command line, you can run your Python programs by typing "python blah.py" where blah.py is the name of your Python script (which you created in Notepad and saved as blah.py. By running scripts this way, you will get to see *all* of your program output, without having the window close on you. (and please don't name all your scripts "blah.py", you should pick different names...) Another thing you might try is downloading and installing SciTE for Windows - a free super-Notepad, with built-in support for editing *and running* Python scripts. Enter your Python code, save it as "whatever.py", then press F5 - the editor will split down the middle, keeping your program in the left half, and show the output messages and exceptions on the right. I find this much easier than going back and forth between Notepad and a terminal window. Other developer editors (often called "IDE"s for Interactive Development Environment) work similarly, such as pythonwin or IDLE - there are many others to choose from, but coming from Notepad, SciTE will not be a big step, but will move you forward. -- Paul From mail at microcorp.co.za Thu May 10 03:44:29 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 10 May 2007 09:44:29 +0200 Subject: Towards faster Python implementations - theory References: <1210i.7468$2v1.2505@newssvr14.news.prodigy.net><013d01c79210$5e441280$03000080@hendrik> Message-ID: <016401c792da$e6210d00$03000080@hendrik> "Terry Reedy" wrote: > "Hendrik van Rooyen" wrote in message > news:013d01c79210$5e441280$03000080 at hendrik... > | I am relatively new on this turf, and from what I have seen so far, it > | would not bother me at all to tie a name's type to its first use, so that > | the name can only be bound to objects of the same type as the type > | of the object that it was originally bound to. > | > | But maybe I am missing the point of dynamism. > | > | Would an implementation of the above break lots of stuff in practice? > > For function local variables, if you mean 'originally bound to' in the > current call invocation, that would sometimes be ok (and that is sort of > what Psycho does). But if you mean in the original binding in the first > call invocation, then that would cripple many functions. > Errr - I was thinking a bit simplistic - I know I can write: def f(x): for y in x: print y # using print here as short for doing something complicated And that would currently "work" with any iterable, as x could currently be anything. It seems that such functions are the problem, as something like this: x = [1,2,3,4,5] for y in x: print y does not have the same hassle for x, but can shift the problem to y: x = [1,2,3,4,(1,2)] for y in x: print y I can't see an easy way to put the patient back into his straight jacket. Makes you want to use pre defined globals... - Hendrik From w.m.gardella.sambeth at gmail.com Mon May 28 22:55:58 2007 From: w.m.gardella.sambeth at gmail.com (w.m.gardella.sambeth at gmail.com) Date: 28 May 2007 19:55:58 -0700 Subject: Patch to pydoc (partial) to handle encodings other than ascii Message-ID: <1180407358.144609.259430@p77g2000hsh.googlegroups.com> Hello Pythonists: I am using SPE as python IDE on Windows, with Python 2.5.1 installed (official distro). As my mother tongue is Spanish, I had documented some modules in it (I now, I should have documented all in English, except if I were 110% sure than nobody else would read my docs, but they are only for in-house use). When I tried to use the pydoc tab that SPE attaches to every source file, I only found a message saying that my accented text coud not be decoded. Browsing the SPE's sources, I found that pydoc's HTMLDoc class could not handle the non-ascii characters. Then patched the Doc's class (the parent of HTMLDoc) code to look for the encoding declared in the source of the module to document, and (in HTMLDoc) decode the source with it. As the HTML file writer function used the same class and choked when writing the file, reencoded the text with the same encoding on writing. As I could not find the mail of pydoc's maintainer (the source code states that the autor is Ka-Ping Yee, but the original date is from 2001, and I could not find if he is still maintaining it), I want to make this patch available so can be possible to use pydoc on non-ascii sources (at least to generate programmatically HTML documentation). If the solution is useful (please don't hesitate in criticize it), may be can be incorporated on a future pydoc version. I don't know how to make a patch file (I usually don't do co-op programming, but use to code as a hobby), but of course I don't even think of sending 90 k of code to the newsgroup, so I am sending the modified code here, with the indication of where do the modifications: After line 323, replace if inspect.ismodule(object): return self.docmodule(*args) with: if inspect.ismodule(object): remarks = inspect.getcomments(object) start = remarks.find(' -*- coding: ') + 13 if start == 12: start = remarks.find('# vim:fileencoding=') + 19 if start == 18: if inspect.getsource(object)[:3] == '\xef\xbb\xbf': self.encoding = 'utf_8' else: self.encoding = sys.getdefaultencoding() else: end = remarks.find(' ', start) self.encoding = remarks[start:end] else: end = remarks.find('-*-', start) self.encoding = remarks[start:end].strip() return self.docmodule(*args) After the line 421 (moved to 437 with the previous insert), insert title = title.decode(self.encoding) contents = contents.decode(self.encoding) And finally replace line 1491 (now 1509): file.write(page) with: file.write(page.encode(html.encoding)) The code don't solves the encoding issue on consoles (just try to document utf-8 sources and see what funny things appears!), but if the approach can help, may be something can be worked to use it in a general way (I just don't know hoy to get the console encoding, and I don't use consoles most of the time). Hope that this can help to some other non-ascii user like me. Cheers (and sorry for the english). Walter Gardella From akiany at gmail.com Wed May 23 07:34:21 2007 From: akiany at gmail.com (Mike) Date: 23 May 2007 04:34:21 -0700 Subject: Basic Class/Instance Question In-Reply-To: <1vodj8x0pt1ow$.wi599psulrjv.dlg@40tude.net> Message-ID: <1179920061.597861.294280@k79g2000hse.googlegroups.com> Thanks Alan, I am still perplexed why the default value of this object is shared. hemm...d Back to programming, :) Sia On May 23, 7:19 am, Alan Franzoni wrote: > Il 23 May 2007 04:07:19 -0700, Siah ha scritto: > > > Ready to go insane here. Class A, taking on a default value for a > > __init__ is a function, taking a default value of [], which is a list, > which is a mutable object. That said, you should remember that this means > that such default value is 'shared' between all instances. If you don't > want that, do something like: > > def __init__(self, defaultvalue=None): > if defaultvalue is None: > defaultvalue=[] > > http://docs.python.org/tut/node6.html#SECTION006710000000000000000 > > -- > Alan Franzoni > - > Togli .xyz dalla mia email per contattarmi. > Remove .xyz from my address in order to contact me. > - > GPG Key Fingerprint (Key ID = FE068F3E): > 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From john at datavoiceint.com Tue May 8 10:48:00 2007 From: john at datavoiceint.com (HMS Surprise) Date: 8 May 2007 07:48:00 -0700 Subject: No module named urllib In-Reply-To: <1178633606.618416.155600@e51g2000hsg.googlegroups.com> References: <1178575589.059564.226060@q75g2000hsh.googlegroups.com> <87tzuop8s2.fsf@gmail.com> <1178577562.498615.222340@e51g2000hsg.googlegroups.com> <87ps5cp816.fsf@gmail.com> <1178578923.067315.14440@q75g2000hsh.googlegroups.com> <1178580280.902179.248000@w5g2000hsg.googlegroups.com> <1178630341.147781.39380@y5g2000hsa.googlegroups.com> <1178633606.618416.155600@e51g2000hsg.googlegroups.com> Message-ID: <1178635680.395877.56370@l77g2000hsb.googlegroups.com> On May 8, 9:13 am, HMS Surprise wrote: > > To summarize the summary, are you sure you need to use Jython instead of > > standard CPython? > > Thanks for all your help Carsten, you have been more than patient with > me. > > To answer your question I must admit I do not know. I am trying to use > a tool called maxq (maxq.tigris.org) that has limited documentation, > or limited in the depth needed by a python/jython neophyte such as me. > Maxq acts an http proxy and generates jython scripts for playback > testing of web apps. So far I have gained a lot of ground referring to > python documentation and even testing code snippets in python shells. > So lacking the knowledge of what is jython/maxq/python and being of at > best moderate intellect I find myself easily overwhelmed and > generally not sure what must be used where. Maxq does not have a tool > for parsing the web pages, therefore I wanted to add some library > calls to pick off some timestamps I must have. Perhaps I should start > looking for another tool, such as twill maybe. > > I will fetch an older python and see if that helps. > > Thanks again, > > jh Thanks again, Carsten. Using v2.2.3 got me past the urllib error. jh From sdoty044 at gmail.com Mon May 21 11:39:44 2007 From: sdoty044 at gmail.com (sdoty044 at gmail.com) Date: 21 May 2007 08:39:44 -0700 Subject: Python and GUI Message-ID: <1179761984.704369.116310@b40g2000prd.googlegroups.com> Just wondering on what peoples opinions are of the GUIs avaiable for Python? All I am doing is prompting users for some data (listbox, radio buttons, text box, ect...). Then I will have some text output, maybe a scrolling text message as things are happening. I have some minor things I need to do, for example, if Checkbutton X is clicked, I need to disable TextBox Y, and I would like to display the scrolling text (output) Ultimately, is it worth downloading and learning some of the packages avaiable for Python, or should I just stick to the Tkinter stuff that is included. More specifically, has anyone used the Qt stuff for python, easy to use? From kyosohma at gmail.com Tue May 29 09:46:16 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 29 May 2007 06:46:16 -0700 Subject: Storing tracebacks In-Reply-To: <1180410412.643608.30050@q66g2000hsg.googlegroups.com> References: <1180410412.643608.30050@q66g2000hsg.googlegroups.com> Message-ID: <1180446376.879439.55840@m36g2000hse.googlegroups.com> On May 28, 10:46 pm, George Sakkis wrote: > I'm reading the docs on sys.exc_info() but I can't tell for sure > whether I'm using it safely to get a snapshot of an exception and > reraise it later. The use case is a class which acts like a deferred > callable, a callable that will be called at some point in the future > (possibly in a different thread) and whose result or raised exception > is to be stored as an attribute. This will be available by calling the > result() method, which returns the original result or reraises the > exception: > > class JobRequest(object): > > def __init__(self, *args, **kwds): > self.args = args > self.kwds = kwds > self._exc_info = None > > def __call__(self): > raise NotImplementedError('Abstract method') > > def process(self): > try: > self._result = self(*self.args, **self.kwds) > except: > self._exc_info = sys.exc_info() > else: > self._exc_info = None > > def result(self): > if self._exc_info is not None: > type,exception,traceback = self._exc_info > raise type,exception,traceback > try: return self._result > except AttributeError: > raise UnprocessedRequestError() > > class UnprocessedRequestError(RuntimeError): > pass > > So far it seems it works as expected but I'd like to know if this is > error-prone and why. > > George I don't know enough about this method of getting tracebacks, but why wouldn't the traceback module work for you? It sounds like it uses the sys.exc_info() method you refer to. http://python.active-venture.com/lib/module-traceback.html Mike From claird at lairds.us Mon May 21 08:24:15 2007 From: claird at lairds.us (Cameron Laird) Date: Mon, 21 May 2007 12:24:15 +0000 Subject: Sysad tasks (was: Python compared to other language) References: <1hybvdz.1qnlesglcv0vcN%aleax@mac.com> <1179556574.341550.229190@q23g2000hsg.googlegroups.com> <4650acf1$0$4867$426a74cc@news.free.fr> Message-ID: In article <4650acf1$0$4867$426a74cc at news.free.fr>, Bruno Desthuilliers wrote: . . . >Ruby is probably far better than Python at sys-admin tasks. And, while . . . You've got me curious, Bruno; what do you see about Ruby that makes it so? From aleax at mac.com Mon May 7 22:53:34 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 7 May 2007 19:53:34 -0700 Subject: how do you implement a reactor without a select? References: <1178543812.260333.39280@w5g2000hsg.googlegroups.com> <1hxqfgq.4sjxga1dz7vv3N%aleax@mac.com> <1178552069.229745.124040@l77g2000hsb.googlegroups.com> Message-ID: <1hxrdhf.179bobg6tzv9cN%aleax@mac.com> Michele Simionato wrote: ... > I know about sched (it was the first thing I looked at): the problem > is that sched > adopt a blocking approach and it basically requires threads, whereas I As the "sleep for time N" callable, you can pass any callable you wish; I suggested one based on Queue.wait with timeout, which would indeed require some other thread to wake it, but any kind of system call which allows timeouts, such as select or poll, would work just as well. > wanted to > avoid them. Diez B. Roggisch's reply is closer to my expectations: > > >> Most probably the OS will have specialized APIs (or some wrapper lib > >> has) that allow for reactor registration for events of different kinds > >> including timers. > > But what kind of specialized API do I have at my disposition for > timers on Linux? > It looks like this is the question I should have asked the first > time ;) What do you expect from "timers on Linux" that you could not get with a simple "sleep for the next N milliseconds"? A timer (on Linux or elsewhere) can jog your process N milliseconds from now, e.g. with a SIGALRM or SIGPROF, and you can set one with the setitimer syscall (presumably accessible via ctypes, worst case -- I've never used it from Python, yet), but how would that help you (compared to plain sleep, select, poll, or whatever else best fits your need)? Alex From tijs_news at bluescraper.com Thu May 31 09:14:11 2007 From: tijs_news at bluescraper.com (Tijs) Date: Thu, 31 May 2007 15:14:11 +0200 Subject: file reading by record separator (not line by line) References: <1180614374.027569.235540@g4g2000hsf.googlegroups.com> <1180615143.228557.258760@g4g2000hsf.googlegroups.com> Message-ID: <465eca24$0$327$e4fe514c@news.xs4all.nl> Lee Sander wrote: > I wanted to also say that this file is really huge, so I cannot > just do a read() and then split on ">" to get a record > thanks > lee Below is the easy solution. To get even better performance, or if '<' is not always at the start of the line, you would have to implement the buffering that is done by readline() yourself (see _fileobject in socket.py in the standard lib for example). def chunkreader(f): name = None lines = [] while True: line = f.readline() if not line: break if line[0] == '>': if name is not None: yield name, lines name = line[1:].rstrip() lines = [] else: lines.append(line) if name is not None: yield name, lines if __name__ == '__main__': from StringIO import StringIO s = \ """> name1 line1 line2 line3 > name2 line 4 line 5 line 6""" f = StringIO(s) for name, lines in chunkreader(f): print '***', name print ''.join(lines) $ python test.py *** name1 line1 line2 line3 *** name2 line 4 line 5 line 6 -- Regards, Tijs From b.r.willems at gmail.com Mon May 7 21:09:56 2007 From: b.r.willems at gmail.com (Bart Willems) Date: Mon, 07 May 2007 21:09:56 -0400 Subject: Why stay with lisp when there are python and perl? In-Reply-To: <1178219732.127815.3260@y80g2000hsf.googlegroups.com> References: <1178155239.007219.205020@y5g2000hsa.googlegroups.com> <1178219732.127815.3260@y80g2000hsf.googlegroups.com> Message-ID: Xah Lee wrote: > blah blah blah blah blah lisp blah blah blah > blah blah lisp blah blah. Blah blah? Blah blah! > blah blah blah blah blah; > 1) Blah lisp. > 2) Blah blah. > 3) Blah lisp blah. > blah blah blah blah blah. Blah blah lisp! Blah lisp! > Blah lisp! Blah! Blah blah blah! Lisp blah blah! Ok. I give up. WTF is this being cross-posted in the Python forum? From bytter at gmail.com Sat May 12 13:22:17 2007 From: bytter at gmail.com (Hugo Ferreira) Date: Sat, 12 May 2007 18:22:17 +0100 Subject: Drawing Text on a Path Message-ID: <4e8efcf50705121022j634d337q7bb4ced863a6e8c2@mail.gmail.com> Hi everyone, I need to draw some curved text on an image. I've digged both PIL and aggdraw documentation for this kind of feature, but found nothing. However, AGG itself does support rendering text along a path, but I can't seem to figure out how to deal with the API/Wrapper differences... Could someone give me an hand here? Thanks in advance! Hugo Ferreira From sjmachin at lexicon.net Tue May 8 00:36:26 2007 From: sjmachin at lexicon.net (John Machin) Date: 7 May 2007 21:36:26 -0700 Subject: getmtime differs between Py2.5 and Py2.4 In-Reply-To: <1hxrebv.5tn2pnql23q7N%aleax@mac.com> References: <463FA51D.1060600@v.loewis.de> <463fb305$0$326$e4fe514c@news.xs4all.nl> <1178585991.924458.154570@l77g2000hsb.googlegroups.com> <1hxrebv.5tn2pnql23q7N%aleax@mac.com> Message-ID: <1178598986.181606.116830@n59g2000hsh.googlegroups.com> On May 8, 1:04 pm, a... at mac.com (Alex Martelli) wrote: > John Machin wrote: > > > [E:\Projects]c:\Python24\python.exe -c "import os; print > > os.path.getmtime('p64.py')"> > 1164470381 > > > > [E:\Projects]c:\Python25\python.exe -c "import os; print > > os.path.getmtime('p64.py')" > > > > 1164466781.28 > > > > This is python 2.4.4 and Python 2.5.1 on windows XP. > > > The reported time clearly differs. > > > > --Irmen > > > Well nitpicked, but irrelevant to the OP's perceptual problem. > > > The reported time clearly differs due to the result being (as > > documented) now a float instead of an int. The OP is complaining about > > an alleged difference of time-zone magnitude (i.e. at least 30 > > minutes, not 0.28 seconds). Somehow he has got the idea that Python > > 2.4 & earlier returned local time, not UTC. > > Please look at those number again, beyond the float/int distinction. > > >>> 1164466781.28 - 1164470381 > > -3599.7200000286102 > > the difference (rounding to an int number of seconds) is just about one > hour; in certain parts of the world (Europe and Africa), that could > indeed be a timezone issue. > Whoops! I looked at the start & the end but not the middle [sorry, Irmen]. OK, I suspect a daylight-saving issue. I'm at UTC-1000, with no DST in effect. I get only the int/float difference, not a 1 hour difference and not a 10 hour difference. What we need now is for someone in northern America or Asia (2 or more hours offset from UTC), with and without DST if effect, to try it out. From sturlamolden at yahoo.no Fri May 11 10:59:23 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 11 May 2007 07:59:23 -0700 Subject: Towards faster Python implementations - theory In-Reply-To: References: <1210i.7468$2v1.2505@newssvr14.news.prodigy.net> <1178804728.527486.196400@y80g2000hsf.googlegroups.com> Message-ID: <1178895563.144837.176310@e65g2000hsc.googlegroups.com> On May 10, 4:02 pm, Tim Golden wrote: > But the relevant bit of your last paragraph is at the start: > "We should...". Sorry, bad choice of words. > see it faster. That's great. But unless people > puts their money where their mouths are, I don't I know, I know. But that doesn't stop me from envying what the Lisp community has achieved. Python still sucks if we are using it for scientific simulations, testing CPU-bound algorithms, etc. Sure it is only 150-200 times slower than C for these tasks, but that can amount to the difference between one day and half a year of CPU time. But as strange as it may seem, it can still be advantageous to use Python. E.g. it may be less expensive to run the simulation in parallel on 200 CPUs than writing the code in C instead of Python. From levander404 at gmail.com Sun May 6 00:46:28 2007 From: levander404 at gmail.com (levander) Date: 5 May 2007 21:46:28 -0700 Subject: Emacs and pdb after upgrading to Ubuntu Feisty Message-ID: <1178426788.614637.209400@w5g2000hsg.googlegroups.com> I've been using pdb under emacs on an Ubuntu box to debug python programs. I just upgraded from Ubuntu Edgy to Feisty and this combo has stopped working. Python is at 2.5.1 now, and emacs is at 21.41.1. It used to be I could just "M-x pdb RET pdb RET" and be presented with a prompt where I could debug my script, as well as an arrow in another source code buffer indicating where I am in the source code. Now however, when I do "M-x pdb RET pdb ~/grabbers/npr-grabber.py -s WESUN", I get this is in a buffer called *gud*: Current directory is /home/levander/grabbers/ No prompt or anything follows it, just that one line. It doesn't pop up an arrow in the other buffer either. None of the regular commands like 'n', 's', or 'l' do anything here. So, I did a 'Ctrl-C' and got: > /home/levander/grabbers/npr-grabber.py(24)() -> """ (Pdb) > /home/levander/grabbers/npr-grabber.py(30)() -> import getopt (Pdb) Traceback (most recent call last): File "/usr/bin/pdb", line 1213, in main pdb._runscript(mainpyfile) File "/usr/bin/pdb", line 1138, in _runscript self.run(statement, globals=globals_, locals=locals_) File "bdb.py", line 366, in run exec cmd in globals, locals File "", line 1, in File "/home/levander/grabbers/npr-grabber.py", line 30, in import getopt File "/home/levander/grabbers/npr-grabber.py", line 30, in import getopt File "bdb.py", line 48, in trace_dispatch return self.dispatch_line(frame) File "bdb.py", line 66, in dispatch_line self.user_line(frame) File "/usr/bin/pdb", line 144, in user_line self.interaction(frame, None) File "/usr/bin/pdb", line 187, in interaction self.cmdloop() File "cmd.py", line 130, in cmdloop line = raw_input(self.prompt) KeyboardInterrupt Uncaught exception. Entering post mortem debugging Running 'cont' or 'step' will restart the program > /home/levander/grabbers/cmd.py(151)cmdloop() -> pass (Pdb) It's wierd because at the bottom of that call stack, it does look like it's wating for input, but no input works... And, after I hit Ctrl-C I do get a prompt as you see at the bottom of that listing just above. Now I type "quit" and get: Post mortem debugger finished. The /home/cponder/grabbers/npr- grabber.py will be restarted Anybody can tell me who to get pdb working under emacs on Ubuntu Feisty? From orl at gmx.de Tue May 29 11:31:23 2007 From: orl at gmx.de (=?iso-8859-1?Q?=22Orlando_D=F6hring=22?=) Date: Tue, 29 May 2007 17:31:23 +0200 Subject: [B,IX] = sort(A,...) - Order for sort()-function Message-ID: <20070529153123.94720@gmx.net> Dear community, I want to use the sort function to sort a (nested) list. General information can be found below. http://www.python.org/doc/2.4.2/lib/typesseq-mutable.html http://wiki.python.org/moin/HowTo/Sorting http://www.python.org/doc/2.4.4/whatsnew/node12.html I want to solve the following problem. Given a list I do not only want to retrieve the sorted list but also the position of the original elements (IX below). The example is taken from Matlab syntax: http://www.mathworks.com/access/helpdesk/help/techdoc/ref/sort.html '[B,IX] = sort(A,...) also returns an array of indices IX, where size(IX) == size(A). If A is a vector, B = A(IX). If A is an m-by-n matrix, then each column of IX is a permutation vector of the corresponding column of A, such that for j = 1:n B(:,j) = A(IX(:,j),j); end' -- A = [ 3 7 5 0 4 2 ]; # in Python: A = [[3,7,5],[0,4,2]] [B,IX] = sort(A,2) # sort by rows B = 3 5 7 0 2 4 IX = 1 3 2 1 3 2 # first line: 3 was formerly in the first position, 5 formerly in position 3, 7 formerly in position 2 # second line: similiarly Yours, Orlando -- Psssst! Schon vom neuen GMX MultiMessenger geh?rt? Der kanns mit allen: http://www.gmx.net/de/go/multimessenger From "ruili_gc(Ray)" at earthlink.net Tue May 1 23:05:04 2007 From: "ruili_gc(Ray)" at earthlink.net (Ray) Date: Wed, 02 May 2007 03:05:04 GMT Subject: test Message-ID: test only From nyamatongwe+thunder at gmail.com Wed May 16 06:22:01 2007 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Wed, 16 May 2007 10:22:01 GMT Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <7x4pmg716p.fsf@ruckus.brouhaha.com> <4648EC26.8020907@v.loewis.de> Message-ID: Eric Brunel: > ... there is no > keyboard *on Earth* allowing to type *all* characters in the whole > Unicode set. My keyboard in conjunction with the operating system (US English keyboard on a Windows XP system) allows me to type characters from any language. I haven't learned how to type these all quickly but I can get through a session of testing Japanese input by myself. Its a matter of turning on different keyboard layouts through the "Text Services and Input Languages" control panel. Then there are small windows called Input Method Editors that provide a mapping from your input to the target language. Other platforms provide similar services. Neil From xreload at gmail.com Thu May 17 03:51:15 2007 From: xreload at gmail.com (xreload) Date: 17 May 2007 00:51:15 -0700 Subject: Problem with socket.recv() Message-ID: <1179388275.768789.49320@p77g2000hsh.googlegroups.com> Hello ! I have some class for getting html documents : """ Wrapper for Python sockets lib """ import socket import urlparse import random import io import re import sys # socket wrapper class class sock: def __init__(self,url): parse = urlparse.urlparse(url) self.req = [] # request tuple self.response = "" # response data self.port = socket.getservbyname("www","tcp") # remote host port if parse[2] is not '': if parse[4] is not '': self.path = parse[2] + "?" + parse[4] else: self.path = parse[2] else: self.path = "/" # request path if parse[1] is not '': self.host = parse[1] # remote host name else: self.host = "" self.req.append("GET " + self.path + " HTTP/1.1") self.req.append("Host: " + self.host) # set user-agent def useragent(self, useragent): self.req.append("User-Agent: " + useragent) # set document max size in bytes def range(self, size=0): self.range = size # get response document body def get_body(self): body = self.response.split("\r\n\r\n", 2) try: return body[1] except: return self.response # do http request def request(self, timeout=60,chunk=1024): self.req.append("Accept: */*") self.req.append("Pragma: no-cache") self.req.append("Connection: close") s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(timeout) try: s.connect((self.host,self.port)) except: print "Cant connect to remote host: "+self.host try: s.sendall("\r\n".join(self.req)+"\r\n\r\n") except: print "Cant write data to socket" while 1: try: buffer = s.recv(chunk) except: print "Cant read data from socket." break if not buffer : break self.response = self.response+buffer if len(self.response) > self.range and self.range != 0: print "Document is too big" break try: s.close() except: print "Cant close socket" if __name__ == '__main__': if len(sys.argv) < 2: print '\nNo URL specified for module test.\nUsage: sock.py ' sys.exit() test = sock(sys.argv[1]) test.useragent("Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 4.0)") test.range() test.request() print test.get_body() ----------- So, lets do : sock.py "http://forums.childrenwithdiabetes.com/showthread.php?t=5030" - it not ok , only some part of document. wget "http://forums.childrenwithdiabetes.com/showthread.php?t=5030" - it ok ! sock.py "http://www.google.com/" - it ok ! Why i got only some part of document ? This is some bug in sockets module or i do something wrong in my code? Help me please , iam "googled" several hours , but not found any related information. All my bests.Igor. From steve at holdenweb.com Wed May 16 22:31:00 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 16 May 2007 22:31:00 -0400 Subject: In a text file: how do I tell the EOF, from a blank line? In-Reply-To: <1179368197.929029.134400@p77g2000hsh.googlegroups.com> References: <1179368197.929029.134400@p77g2000hsh.googlegroups.com> Message-ID: walterbyrd wrote: > How do I test for the end of a file, in such a why that python can > tell the EOF from a blank line? > Only when the EOF is reached will you read an entirely empty line. Real empty lines read as a newline terminator. However, there are any better ways to process the lines of a file than reading it line by line. For example you can iterate over the lines with something like f = open("myfile.txt", 'r') for line in f: ... do something with 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From rene at korteklippe.de Tue May 15 08:35:33 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 15 May 2007 14:35:33 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <1hy2qg3.iqfvwnrvr9kjN%aleax@mac.com> <46482624.6050507@web.de> <7xd512onsx.fsf@ruckus.brouhaha.com> <464951EF.7030900@web.de> <464997a5$0$10193$9b4e6d93@newsspool4.arcor-online.net> <4649a561$0$10187$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <4649a914$0$10186$9b4e6d93@newsspool4.arcor-online.net> Thorsten Kampe schrieb: >> It is impossible to write Python in a native language other than English >> even with the implementation of this PEP. All you get is a weird mixture >> of English identifiers from various libraries and identifiers in your >> native language. > > You have a few English keywords that are not meant to be understood > but can be learned. I am talking about the stdlib, not about the very few keywords Python has. Are you going to re-write the standard library in your native language so you can have a consistent use of natural language among your code? > It neither encourages or discourages anything. And I don't think > encouraring or discouraging code sharing is a good thing. There is > simply no general reason to do so. I disagree, but since that is a question of ideology, it makes little sense to argue about it. -- Ren? From bj_666 at gmx.net Wed May 16 18:36:01 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 17 May 2007 00:36:01 +0200 Subject: cPickle.dumps differs from Pickle.dumps; looks like a bug. References: <1179335622.006820.22460@q23g2000hsg.googlegroups.com> <1179352356.025319.43310@w5g2000hsg.googlegroups.com> Message-ID: In , Daniel Nogradi wrote: > The OP was not comparing identity but equality. So it looks like a > real bug, I think the following should be True for any function f: > > if a == b: f(a) == f(b) > > or not? In [74]: def f(x): ....: return x / 2 ....: In [75]: a = 5 In [76]: b = 5.0 In [77]: a == b Out[77]: True In [78]: f(a) == f(b) Out[78]: False And `f()` doesn't even use something like `random()` or `time()` here. ;-) Ciao, Marc 'BlackJack' Rintsch From showell30 at yahoo.com Mon May 28 11:27:32 2007 From: showell30 at yahoo.com (Steve Howell) Date: Mon, 28 May 2007 08:27:32 -0700 (PDT) Subject: Is PEP-8 a Code or More of a Guideline? In-Reply-To: Message-ID: <532985.65767.qm@web33506.mail.mud.yahoo.com> --- Roy Smith wrote: > It's certainly easier to parse ip_address as > compared to IPAddress. > Same with snmp_manager vs SNMPManager. > Somebody earlier was actually advocating something called proper_case, in which you can capitalize certain letters for clarity, like test_for_Heisenberg_uncertainty. Regarding acronyms, I'm curious about how people interpret PEP 8 for the following. Acronyms: get_HTTP_response get_http_response Abbreviations: get_file_id get_file_ID ____________________________________________________________________________________Be a better Globetrotter. Get better travel answers from someone who knows. Yahoo! Answers - Check it out. http://answers.yahoo.com/dir/?link=list&sid=396545469 From lawsfaq2 at yahoo.com Tue May 15 16:59:42 2007 From: lawsfaq2 at yahoo.com (lawsfaq2 at yahoo.com) Date: 15 May 2007 13:59:42 -0700 Subject: Need a PC Computer Info Portal? Message-ID: <1179262782.372578.57470@q75g2000hsh.googlegroups.com> Personal Computers (PC's) contains a lot of info that the average user doesn't usually know. At http://PCTermDefinitions.com there is extensive infomation related to this topic (all free). Along with a link portal to other PC computer related sites. From i3dmaster at gmail.com Thu May 17 16:12:10 2007 From: i3dmaster at gmail.com (i3dmaster) Date: 17 May 2007 13:12:10 -0700 Subject: Execute commands from file In-Reply-To: References: <1179320782.594398.67980@u30g2000hsc.googlegroups.com> <464b370c$0$3808$5402220f@news.sunrise.ch> <1179387023.005808.60670@o5g2000hsb.googlegroups.com> Message-ID: <1179432730.143022.66340@y80g2000hsf.googlegroups.com> On May 17, 3:02 am, Douglas Woodrow wrote: > On Thu, 17 May 2007 00:30:23, i3dmaster wrote > > >f = open(file,'rb') > >for i in f: > > exec i > > Why are you opening the file in binary mode? > > -- > Doug Woodrow 'b' is generally useful on systems that don't treat binary and text files differently. It will improve portability. From walterbyrd at iname.com Wed May 16 22:02:18 2007 From: walterbyrd at iname.com (walterbyrd) Date: 16 May 2007 19:02:18 -0700 Subject: how do I count spaces at the beginning of a string? Message-ID: <1179367338.906430.97420@k79g2000hse.googlegroups.com> The strings start with whitespace, and have a '*' or an alphanumeric character. I need to know how many whitespace characters exist at the beginning of the string. From steven.bethard at gmail.com Wed May 2 19:51:02 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 02 May 2007 17:51:02 -0600 Subject: __dict__s and types and maybe metaclasses... In-Reply-To: <1178140405.468223.146220@l77g2000hsb.googlegroups.com> References: <1178140405.468223.146220@l77g2000hsb.googlegroups.com> Message-ID: <463923E6.7060301@gmail.com> Adam Atlas wrote: > Suppose I want to create a type (i.e. a new-style class via the usual > `class blah(...)` mechanism) but, during the process of creating the > type, I want to replace its __dict__ If I understand you right, what you want is something like:: class MyDict(object): def __getitem__(self, key): ... def __setitem__(self, key, value): ... ... magic incantation to use a MyDict instance for class Foo ... class Foo(object): a = 1 # calls MyDict.__setitem__('a', 1) def bar(self): # calls MyDict.__setitem__('bar', ) ... b = a + 2 # calls MyDict.__getitem__('a') and then # calls MyDict.__setitem__('b', 3) If that's right, then the answer is "no, you can't do this". There was some discussion of allowing such a thing in Python 3.0, but it fizzled. (Check the python-3000 archives if you're interested.) So what's the real problem you're trying to solve? STeVe From esj at harvee.org Thu May 31 09:59:14 2007 From: esj at harvee.org (Eric S. Johansson) Date: Thu, 31 May 2007 09:59:14 -0400 Subject: Is PEP-8 a Code or More of a Guideline? In-Reply-To: <1180473481.265262.75690@o5g2000hsb.googlegroups.com> References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <007001c7a204$a5a45e10$240110ac@Muse> <1180473481.265262.75690@o5g2000hsb.googlegroups.com> Message-ID: sjdevnull at yahoo.com wrote: > FWIW, even though I think proper-case-with-seperators is greatly > preferrable to camelCase, I certainly don't think that speaking the > names is a really major point. unless you or someone with working hands helps fix up voicecoder, it is a major point for people like me. http://voicecode.iit.nrc.ca/ From stefan.behnel-n05pAM at web.de Mon May 14 08:51:49 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 14 May 2007 14:51:49 +0200 Subject: multi threaded SimpleXMLRPCServer In-Reply-To: References: Message-ID: <46485B65.2010605@web.de> Vyacheslav Maslov wrote: > I need multi threaded version of SimpleXMLRPCServer. Does python library > already have implementation of this one? Or i need to implement multi > threading by myself? > > Which way is the simpliest? Twisted has XML-RPC support: http://twistedmatrix.com/trac/ Stefan From michael at jedimindworks.com Fri May 11 05:42:12 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Fri, 11 May 2007 04:42:12 -0500 Subject: 4 byte integer In-Reply-To: <46443344$1_1@glkas0286.greenlnk.net> References: <46443344$1_1@glkas0286.greenlnk.net> Message-ID: <08C94642-CD20-4E5B-9238-D2C91F5950CC@jedimindworks.com> On May 11, 2007, at 4:25 AM, Paul D Ainsworth wrote: > Greetings everyone. I'm a relative newcomer to python and I have a > technical > problem. > > I want to split a 32 bit / 4 byte unsigned integer into 4 separate > byte > variables according to the following logic: - > > bit numbers 0..7 byte 1 > bit numbers 8..15 byte 2 > bit numbers 16..23 byte 3 > bit numbers 24..31 byte 4 > > Each of these byte variables to contain integer data from 0 to 255 > (or 0 to > FF in hex mode) > > I had thought that struct.unpack with an input message format of > 'I' would > be the way to do it, but its reporting an error that it doesn't > want to > accept an integer. > > Please can anyone advise? Have a look at http://aspn.activestate.com/ASPN/Cookbook/Python/ Recipe/113799 From nospam at noemailhere.nowhere Tue May 15 21:21:04 2007 From: nospam at noemailhere.nowhere (Anthony Irwin) Date: Wed, 16 May 2007 11:21:04 +1000 Subject: Trying to choose between python and java In-Reply-To: References: Message-ID: Hi All, Thanks to all that replied. I noticed that someone said that the way you used regular expressions changed at some point. That is probably what upset the person I was talking to about python they are a huge perl fan and use regular expressions heavily. The reason for asking about the .jar type functionality was to try and make it easier to distribute the application as some people said. I run linux systems and if I want to give the app to a windows user then I don't really want to muck about trying to create a windows install for them as I don't personally have a copy of windows to do it with so I thought that just giving them one file and telling them to install the run time environment would make it easier. I tend to use the shebang #!/usr/bin/env python in my scripts so far but I imagine that having that would not work on say windows. Or is there some kind of file extension association for people running windows instead of the shebang? I saw on the python site a slide from 1999 that said that python was slower then java but faster to develop with is python still slower then java? -- Kind Regards, Anthony Irwin http://www.irwinresources.com http://www.makehomebusiness.com email: anthony at above domains, - www. From carsten at uniqsys.com Fri May 25 11:07:34 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 25 May 2007 11:07:34 -0400 Subject: just a bug In-Reply-To: References: <1179841504.782279.86490@u36g2000prd.googlegroups.com> <1180082137.329142.45350@p77g2000hsh.googlegroups.com> Message-ID: <1180105655.3743.24.camel@dot> On Fri, 2007-05-25 at 17:30 +0300, Maksim Kasimov wrote: > I insist - my message is correct and not contradicts no any point of w3.org xml-specification. The fact that you believe this so strongly and we disagree just as strongly indicates a fundamental misunderstanding. Your fundamental misunderstanding is between bytes and unicode code points. The contents of an XML document is a sequence of unicode code points, encoded into a sequence of bytes using some character encoding. The header should identify that encoding. In the absence of an explicit encoding specification, the parser will guess what encoding the content uses. In your case, the encoding is absent, and the parser guesses utf-8, but your string is not a legible utf-8 string. If you want to convey an arbitrary sequence of bytes as if they were characters, you need to pick a character encoding that can handle an arbitrary sequence of bytes. utf-8 can not do that. ISO-8859-1 can, but you need to specify the encoding explicitly. Observe what happens if I take your example and insert an encoding specification: >>> iMessage = '\n\n \n\n\n' >>> minidom.parseString(iMessage) Of course, when you extract your CDATA, it will come out as a unicode string which you'll have to encode with ISO-8859-1 to turn it into a sequence of bytes. Then you add the sequence of bytes from the next message, and in the end that should yield a valid utf-8-encoded string once you've collected and assembled all fragments. Hope this helps, -- Carsten Haese http://informixdb.sourceforge.net From eiwot at hotmail.com Wed May 23 23:11:52 2007 From: eiwot at hotmail.com (Eiwot) Date: Thu, 24 May 2007 03:11:52 +0000 Subject: New update on Python Message-ID: Hi New update at http://pyarticles.blogspot.com . Check it out Cheers _________________________________________________________________ Create the ultimate e-mail address book. Import your contacts to Windows Live Hotmail. www.windowslive-hotmail.com/learnmore/managemail2.html?locale=en-us&ocid=TXT_TAGLM_HMWL_reten_impcont_0507 -------------- next part -------------- An HTML attachment was scrubbed... URL: From nick at craig-wood.com Tue May 15 05:30:03 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 15 May 2007 04:30:03 -0500 Subject: Trying to choose between python and java References: Message-ID: Anthony Irwin wrote: > #4 If I write a program a test it with python-wxgtk2.6 under linux are > the program windows likely to look right under windows and mac? wx adopts the native look and feel for the platform. I've used it under linux and windows where it looks fine! I've never used it under mac. > #5 someone said that they used to use python but stopped because the > language changed or made stuff depreciated (I can fully remember > which) and old code stopped working. Is code written today likely to > still work in 5+ years or do they depreciate stuff and you have to > update? The language does change gently. New language features are added. Backwards compatibility is deemed very important. Read PEP 5 "Guidelines for Language Evolution" for more info. http://www.python.org/dev/peps/pep-0005/ Libraries are deprecated but not removed. Read PEP 4 "Deprecation of Standard Modules" if you want to know more. http://www.python.org/dev/peps/pep-0004/ There is more churn in the libraries which aren't distributed with python. There is also the Python 3000 project. The point of this project is to remove the deprecated stuff and the accumulated cruft and make python shiny and new again. A lot of python programs will run unmodified under Python 3000 anyway. However there is a translator to translate to the new Python 3000 format. Python 3000 is probably a year from its first stable release. I suspect it won't be in wide use for several years after that. http://www.python.org/dev/peps/pep-3000/ Don't be scared of Python 3000 though it is just a gentle revision of the language, nothing like, lets say, going from perl 5 to perl 6. > Also does anyone else have any useful comments about python vs java > without starting a flame war. You'll be a lot more productive writing python code in my experience so if development time is important to you, then go with python. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From sturlamolden at yahoo.no Sun May 20 09:45:36 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 20 May 2007 06:45:36 -0700 Subject: Can't embed python in C++(Mingw[3.*] compiler) In-Reply-To: <1179591280.469302.289010@p77g2000hsh.googlegroups.com> References: <1179591280.469302.289010@p77g2000hsh.googlegroups.com> Message-ID: <1179668736.158370.128460@p47g2000hsd.googlegroups.com> On May 19, 6:14 pm, Arjun Narayanan wrote: > For thr program, > #include "E:\Python25\include\Python.h" Consider using #include "E:/Python25/include/Python.h" or #include "E:\\Python25\\include\\Python.h" instead. Or use #include and compile with -IE:/Python25/include From rrs at researchut.com Wed May 23 14:20:01 2007 From: rrs at researchut.com (Ritesh Raj Sarraf) Date: Wed, 23 May 2007 23:50:01 +0530 Subject: Namespace issue Message-ID: Hi, I need a little help in understanding how Namespaces and scoping works with Classes/Functions in Python. Here's my code: class FetchData: def __init__(self, dataTypes=["foo", "bar", "spam"], archive=False): self.List = [] self.Types = dataTypes if archive: self.Archiver = Archiver(True) def FetchData(self, PackageName, Filename=None): try: import my_module except ImportError: return False if Filename != None: try: file_handle = open(Filename, 'a') except IOError: sys.exit(1) (amnt, header, self.List) = my_module.get_data(PackageName) This is the only way this code will work. As per my understanding, the bad part is that on every call of the method FetchData(), an import would be done. To not let that happen, I can put the import into __init__(). But when I put in there, I get a NameError saying that my_module is not available even though it got imported. All I noticed is that the import has to be part of the method else I end up getting a NameError. But always importing my_module is also not good. What is the correct way of doing this ? IMO, ideally it should be part of __init__() and be imported only when the class is instantiated. Thanks, Ritesh -- If possible, Please CC me when replying. I'm not subscribed to the list. From slewin at rogers.com Sat May 19 17:28:43 2007 From: slewin at rogers.com (scott) Date: Sat, 19 May 2007 17:28:43 -0400 Subject: [Bulk] Re: Python compared to other language In-Reply-To: <1179597080.29334.10.camel@enterprise> References: <1179540061.598417.13870@y80g2000hsf.googlegroups.com> <1179597080.29334.10.camel@enterprise> Message-ID: <464F6C0B.3020902@rogers.com> Michael Torrie wrote: > I think the original poster will find Python, and may wxPython, > satisfies the bulk of his development needs. True, I like how Python is a general language that can be used for many different purposes and hope to learn wxPython as well. I have read through the archives and found some good suggestions for books/tutorials. -- Your friend, Scott Sent to you from a 100% Linux computer using Kubuntu Version 7.04 (Feisty Fawn) From jim at reallykillersystems.com Wed May 9 12:09:32 2007 From: jim at reallykillersystems.com (James Beck) Date: Wed, 9 May 2007 12:09:32 -0400 Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> <08qk33t594ih0ulmjmev90d22lkfnotgoe@4ax.com> <463C2A3A.8332D211@hotmail.com> <0k8p33h90bp5tfajedb4bmd2eik8gfi2ho@4ax.com> <4640CB37.907C9988@earthlink.net> <464132D5.8F6C0936@earthlink.net> Message-ID: In article <464132D5.8F6C0936 at earthlink.net>, mike.terrell at earthlink.net says... > James Beck wrote: > > > > In article <4640CB37.907C9988 at earthlink.net>, mike.terrell at earthlink.net > > says... > > > James Beck wrote: > > > > > > > > Yep, you must have access to better drugs than I do. > > > > You get to hallucinate your stuff up. > > > > Don't forget to adjust your tin beanie! > > > > > > > > > Its not a beanie. He had his head tin plated. :( > > > > > I just the "How it's Made" that showed how they make bronzed baby shoes. > > Maybe they can adapt that process to tin plate heads. > > Would save these guys thousands of $$$ on foil. > > > > Jim > > > > Yeah, they wouldn't need it done very often. Only when the dead skin > builds up so much it pushes the old one off their bald heads. > > Now that made me laugh. The visual of a tin skull cap popping off from sluffing skin. POP! Jim From ivoras at __fer.hr__ Sun May 13 18:43:39 2007 From: ivoras at __fer.hr__ (Ivan Voras) Date: Mon, 14 May 2007 00:43:39 +0200 Subject: GUI tutorial In-Reply-To: References: Message-ID: John K Masters wrote: > Can someone point me in the direction of a good tutorial on programming > python with a GUI? I'm just starting out with python and have written a > few scripts successfully but would like to add a graphical front end to > them to make it easier for my work colleagues, most of whom have never > used a command line, to use. If you're using Linux or some other unix-like platform, try PyGTK: http://www.pygtk.org/pygtk2tutorial/index.html (Yes, it can run on Windows, but it tends to be more complicated there). -- (\__/) (O.o) (> < ) This is Bunny. Copy Bunny into your signature to help him on his way to world domination! -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 258 bytes Desc: OpenPGP digital signature URL: From steve at holdenweb.com Sat May 19 09:24:33 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 19 May 2007 09:24:33 -0400 Subject: List Moderator In-Reply-To: <880dece00705190012g4f3d3ef6v4e6c87a156708bb0@mail.gmail.com> References: <880dece00705172218n71123b55q531ec0c5e500f208@mail.gmail.com> <880dece00705190012g4f3d3ef6v4e6c87a156708bb0@mail.gmail.com> Message-ID: Dotan Cohen wrote: > On 18/05/07, Steve Holden wrote: >> Dotan Cohen wrote: >>> Is this list not moderated? I'm really not interested in Britney >>> Spears boobs. All the spam on this list is from the same place, it >>> should be very easy to filter. >>> >> Is it a list, is it a newsgroup? No, it's c.l.py! >> >> In fact you could be reading this in a number of different forms, and >> there are equally many ways to inject content into the stream. It's >> surprisingly difficult to filter everything out, though the list >> managers at python.org seem to do a remarkably effective job. > > I don't believe that a python list manager would have a hard time > coming up with a regex that /dev/nulled any post with the words > "britney", "spears", "boobs", "tits", or the like. > >> I'm not particularly interested in that subject matter either, but >> believe me there could be a lot more of that kind of thing than actually >> makes it through! > > And if it doesn''t start getting filtered now, the spammers will see > this list as an easy target and will attack it. Believe me. > I'm sorry, but you have no idea what you are talking about. Most of what can be done *is* being done, which is why you see the relatively low spam volumes you do. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From tijs_news at bluescraper.com Thu May 31 08:41:14 2007 From: tijs_news at bluescraper.com (Tijs) Date: Thu, 31 May 2007 14:41:14 +0200 Subject: non standard path characters References: Message-ID: <465ec26a$0$336$e4fe514c@news.xs4all.nl> Robin Becker wrote: > A kind user reports having problems running the reportlab tests because > his path has non-ascii characters in it eg > > .....\Mes documents\Mes T?l?chargements\Firefox\... > > somewhere in the tests we look at the path and then try and convert to > utf8 for display in pdf. > > Is there a standard way to do these path string conversions? > > Paths appear to come from all sorts of places and given the increasing use > of zip file packaging it doesn't seem appropriate to rely on the current > platform as a single choice for the default encoding. Zip files contain a bit flag for the character encoding (cp430 or utf-8), see the ZipInfo object in module zipfile and the link (on that page) to the file format description. But I think some zip programs just put the path in the zipfile, encoded in the local code page, in which case you have no way of knowing. -- Regards, Tijs From JiaFangTao at gmail.com Wed May 23 21:58:28 2007 From: JiaFangTao at gmail.com (Bruce) Date: 23 May 2007 18:58:28 -0700 Subject: how to use imaageop.scale In-Reply-To: References: <1179903754.084688.312200@w5g2000hsg.googlegroups.com> Message-ID: <1179971908.653346.95200@d30g2000prg.googlegroups.com> On May 23, 5:31 pm, "Amit Khemka" wrote: > On 23 May 2007 00:02:34 -0700, Bruce wrote: > > > Hi, I want to compress a jpg file. e.g. a jpg file which has RGB band > > (24bit per pixel), 100 * 100 size to 50 * 50 size. I > > tried to use scale function in imageop module but failed. Any > > suggestions about this? Thanks! > > Were there any exceptions/error-messasges ? > Do you jpeg libraries installed for hadling jpeg format ? > > Cheers, > > -- > ---- > Amit Khemka -- onyomo.com > Home Page:www.cse.iitd.ernet.in/~csd00377 > Endless the world's turn, endless the sun's Spinning, Endless the quest; > I turn again, back to my own beginning, And here, find rest. Amit & Marc, thank you very much. Now I used PIL instead and it works fine. But I still don't know how to complete this simple task with imageop module. THANKS ANYWAY! Bruce From sickcodemonkey at gmail.com Sat May 19 22:27:35 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Sat, 19 May 2007 22:27:35 -0400 Subject: interesting dict bug Message-ID: <2adc542f0705191927u799da2ak9e884cef53f15979@mail.gmail.com> Here is a segment of some code that I have. CODE: -------------- print filename params2 = {'filename':filename,'id3title':title,'id3artist':artist,'id3album':album,'id3year':year,'id3track':track,'id3genre':genre,'uname':username,'password':password,'filesToUpload':open(file, 'rb')} print params2 ---------------- OUTPUT: 01.mp3 {'password': u'XXX', 'id3year': '2002', 'id3album': 'album, 'id3title': 'Lose Yourself', 'filename': u'01.mp3', 'uname': u'', 'id3genre': 'Soundtrack', 'id3artist': 'Eminem', 'filesToUpload': , 'id3track': 'Unknown'} -------------- Does anyone know how the random " u' " is getting into the params2 or know how to around this? I am using Python 2.5 on MacOSX. -------------- next part -------------- An HTML attachment was scrubbed... URL: From stargaming at gmail.com Mon May 21 18:21:14 2007 From: stargaming at gmail.com (Stargaming) Date: Tue, 22 May 2007 00:21:14 +0200 Subject: [Fwd: Re: managed lists?] In-Reply-To: References: <4651fe96$0$24671$426a34cc@news.free.fr> Message-ID: Jorgen Bodde schrieb: > Hi Bruno, > > Thanks for your answer. > > Well what I am after is a list of relations to some class type. And in > that list I do not wish to have accidentally put ints, strings, only > one type of object, or interface. Now I can make the list interface > safe, but it is only meant for relational purposes only. So to > illustrate: > > Song <>---->> Tab > Song <>--->> Tuning > > I want a "tabs" collection only consisting of Tab objects. They are > very specific so "mimicing" a tab interface is not something that will > be done anytime soon. > > I'm a traditional C++ programmer, and maybe I go through some > transitional phase I don't know but exposing my list as read / > (over)write property to the "outside world" being the rest of my > object model, is just asking for problems. So this "strong" typed list > will ensure me at "add" time the exception occurs, rather then > somewhere in my applciation who knows much later that something blows > up because the "object" from that list is retrieved and something > unpredictable goes wrong. Is that so weird to do? As I said earlier I > am a python newbie, I love the language, but the fact it can blow up > at unpredictable times, gives me shivers. > >> Everything in Python is an object. Including integers. And there's no >> 'char' type in Python. > > > The array type by the way says in the API that it can be constructed > with a simple type like a char as in a "c" type, an int as in a "i" > type etc.. > > See here: > > http://www.python.org/doc/1.5.2p2/lib/module-array.html > > So what I understand it's purpose is creating a buffer of some kind of > a fixed type to maybe communicate with other DLL's or objects that > require such a thing. > > As I said, I might be going through a transitional phase, but exposing > my relation list as simply a list class where all kinds of objects can > be dumped in, seems too much for me at this point ;-) > > Thanks, > - Jorgen Consider this: Who should add wrong-typed objects (see Bruno's post for reasons why you shouldn't care about types, anyways) to your list, when not you yourself? And if the programmer makes something wrong, he should fix it immediately. What happens if your application throws some error like "invalid type added to ObjectList"? Users won't unterstand it, so the intended audience is you again. Good night, Stargaming From s.mientki at id.umcn.nl Thu May 31 03:40:39 2007 From: s.mientki at id.umcn.nl (stef) Date: Thu, 31 May 2007 09:40:39 +0200 Subject: is there a standard way to "install" egg-files under windows ? In-Reply-To: <6at7i.6773$5j1.4204@newssvr21.news.prodigy.net> References: <4c205$465dbe2b$d443bb3a$17537@news.speedlinq.nl> <5c5u7lF2v1pm3U1@mid.uni-berlin.de> <6at7i.6773$5j1.4204@newssvr21.news.prodigy.net> Message-ID: <58b61$465e7bf7$83aef404$12927@news1.tudelft.nl> John Nagle wrote: > Diez B. Roggisch wrote: >> Stef Mientki schrieb: >> >>> hello, >>> >>> after 4 months playing around with Python, >>> and I still have troubles with egg files. >>> Sometimes it works, sometimes it doesn't. >>> >>> If I google on "python egg", I get lost of links, >>> which contains huge pages of information, >>> and I'm totally scared off. > > ".egg" files are actually ".zip" files. So you can > rename them to ".zip" and unpack them where they need to go. > This is usually easier than debugging "easy_install". > > John Nagle thanks guys, I'm slowly getting the picture. Now knowing it's a zip file, and trying several egg-files through easy_install, I noticed different things, - sometimes the egg is unzipped and placed in the "site-package" directory - sometimes it's just copied (unzipped) to the site-package directory. My first conclusion that egg-installation didn't work sometimes, has probably to do with version conflicts between the already installed libs and the new to install libs, but I guess that's the benefit of open source ;-) So if that's all, the renaming to .zip might be a less obscure way of working. cheers, Stef Mientki From stefan.behnel-n05pAM at web.de Wed May 23 07:44:27 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 23 May 2007 13:44:27 +0200 Subject: xml.parsers.expat loading xml into a dict and whitespace In-Reply-To: References: <163f0ce20705222316x7d6247a7hea019e7fd2aa2ee2@mail.gmail.com> Message-ID: <4654291B.8060504@web.de> kaens wrote: > Now the code looks like this: > > import xml.etree.ElementTree as etree > > optionsXML = etree.parse("options.xml") > options = {} > > for child in optionsXML.getiterator(): > if child.tag != optionsXML.getroot().tag: > options[child.tag] = child.text > > for key, value in options.items(): > print key, ":", value Three things to add: Importing cElementTree instead of ElementTree should speed this up pretty heavily, but: Consider using iterparse(): http://effbot.org/zone/element-iterparse.htm *untested*: from xml.etree import cElementTree as etree iterevents = etree.iterparse("options.xml") options = {} for event, child in iterevents: if child.tag != "parent": options[child.tag] = child.text for key, value in options.items(): print key, ":", value Note that this also works with lxml.etree. But using lxml.objectify is maybe actually what you want: http://codespeak.net/lxml/dev/objectify.html *untested*: from lxml import etree, objectify # setup parser = etree.XMLParser(remove_blank_text=True) lookup = objectify.ObjectifyElementClassLookup() parser.setElementClassLookup(lookup) # parse parent = etree.parse("options.xml", parser) # get to work option1 = parent.option1 ... # or, if you prefer dictionaries: options = vars(parent) for key, value in options.items(): print key, ":", value Have fun, Stefan From janzon at gmail.com Thu May 10 10:41:44 2007 From: janzon at gmail.com (John) Date: 10 May 2007 07:41:44 -0700 Subject: High resolution sleep (Linux) In-Reply-To: <8l90i.911$UU.403@newssvr19.news.prodigy.net> References: <1178274122.142071.91740@y5g2000hsa.googlegroups.com> <8l90i.911$UU.403@newssvr19.news.prodigy.net> Message-ID: <1178808104.915724.176100@n59g2000hsh.googlegroups.com> On 9 Maj, 03:23, John Nagle wrote: > Hendrik van Rooyen wrote: > > "Tim Roberts" wrote" > > It is also possible to keep the timer list sorted by "expiry date", > > and to reprogram the timer to interrupt at the next expiry time > > to give arbitrary resolution, instead of implementing a regular 'tick'. > > Yes, and that's a common feature in real-time operating systems. > If you're running QNX, you can expect that if your high priority > task delays to a given time, you WILL get control back within a > millisecond of the scheduled time. Even tighter timing control > is available on some non-x86 processors. > > Some CPUs even have hardware support for a sorted event list. > The Intel 8061, which ran the engines of most Ford cars in the 1980s, > had that. > > But no way are you going to get consistent timing resolution like that > from Python. It's an interpreter with a garbage collector, after all. > > John Nagle The application the original poster (i.e. me) was interested in was a program that sends ethernet packets at a loosely specified rate. A loop that sends all packets with no sleep in between will send them at a too high rate. Using the default sleep in my Python interpreter sleeps to long, since even a few microseconds add up when you send hundreds of thousands of packets. If the process scheduler deals with another process now and then, it doesn't matter. If it switches to another application between each packet is beeing sent, that's a problem. Anyways, what I need is high resolution sleep, not high resolution timing. Installing a real time OS seems like overkill. (Yes I know, one can also send, say, 50 packets at a time, and then sleep, send 50 more packets, and so on.) From claird at lairds.us Sat May 26 11:44:15 2007 From: claird at lairds.us (Cameron Laird) Date: Sat, 26 May 2007 15:44:15 +0000 Subject: Muzzle Velocity (was: High resolution sleep (Linux) References: <1178274122.142071.91740@y5g2000hsa.googlegroups.com> Message-ID: In article , Dennis Lee Bieber wrote: >On Sun, 6 May 2007 10:15:26 +0200, "Hendrik van Rooyen" > declaimed the following in comp.lang.python: > > >> A rifle bullet can travel at around 5000 feet per second. > > You've got some fast rifles over there... > > The .17Remington just passes 4000fps and is one of the two or three >fastest ( http://www.gunsandammomag.com/ammunition/the_17_remington/ ). >The .17HMR is around 2600fps ( >http://www.shootingtimes.com/ammunition/17_hmr_0508/ ). More common >rounds -- .308Winchester [7.62 NATO] run ~2700-3000fps ( >http://www.chuckhawks.com/08_family_cartridges.htm ). Even the .50BMG >(Browning Machine Gun) is only a 2900fps round ( >http://www.chuckhawks.com/50BMG.htm ). In comparison, some of the GAMO >and RWS-Diana air guns can push a .177 pellet around 1000fps. . . . I know Dennis knows this, but it's probably appropriate to add for other readers that there are even more common rounds, and far slower shots, than the .308, in many contexts. Typical civilian fare in the US, with typical muzzle velocities in feet per second, include .22 LR 1138 .223 3140 .30-30 2200 .30-06 2700 .38 815 .45 ACP 910 Variations in cartridge loading, barrel length, and so on, can easily lead to differences up to 30% in muzzle velocity. From phawkins at connact.com Tue May 8 16:36:12 2007 From: phawkins at connact.com (Patricia J. Hawkins) Date: Tue, 08 May 2007 16:36:12 -0400 Subject: Emacs and pdb after upgrading to Ubuntu Feisty References: <1178426788.614637.209400@w5g2000hsg.googlegroups.com> <1178638304.190312.177150@u30g2000hsc.googlegroups.com> Message-ID: <878xbznjcz.fsf@metta.hawkinsia.com> >>>>> "l" == levander writes: l> Okay, thanks Alexander and Bernstein. I'll lookinto Emacs 23, but l> I'm worried about compatibility with modes. Does all the stuff l> that works in Emacs 21 work in 23? Like even that ipython.el file, l> does it work in Emacs 23? Well... Python 2.5.1c1 (release25-maint, Apr 12 2007, 21:00:25) Type "copyright", "credits" or "license" for more information. IPython 0.7.2 -- An enhanced Interactive Python. ? -> Introduction to IPython's features. %magic -> Information about IPython's 'magic' % functions. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. In [1]: 3 + 4 Out[1]: 7 In [2]: And pdb: Current directory is /media/extend/skeezix/pjh/CODING/python/ > /media/extend/skeezix/pjh/CODING/python/fibclass.py(3)() -> class Fib: (Pdb) n > /media/extend/skeezix/pjh/CODING/python/fibclass.py(14)() -> f = Fib() (Pdb) n > /media/extend/skeezix/pjh/CODING/python/fibclass.py(15)() -> print f[10] (Pdb) n 89 --Return-- > /media/extend/skeezix/pjh/CODING/python/fibclass.py(15)()->None -> print f[10] (Pdb) n --Return-- > (1)()->None (Pdb) n The program finished and will be restarted > /media/extend/skeezix/pjh/CODING/python/fibclass.py(3)() -> class Fib: (Pdb) This is emacs 23.0.0.1, from a weekly Feisty build of emacs-snapshot-gtk maintained by Alexandre Vassalotti, which also includes the xft font backend. Which means anti-aliased fonts on emacs... :) See: http://peadrop.com/blog/2007/01/06/pretty-emacs/ -- Patricia J. Hawkins Hawkins Internet Applications www.hawkinsia.com From http Sun May 13 23:10:11 2007 From: http (Paul Rubin) Date: 13 May 2007 20:10:11 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <7x4pmg716p.fsf@ruckus.brouhaha.com> Message-ID: <7xiraw3xt8.fsf@ruckus.brouhaha.com> Neil Hodgson writes: > >> Plenty of programming languages already support unicode identifiers, > > Could you name a few? Thanks. > C#, Java, Ecmascript, Visual Basic. Java (and C#?) have mandatory declarations so homoglyphic identifiers aren't nearly as bad a problem. Ecmascript is a horrible bug-prone language and we want Python to move away from resembling it, not towards it. VB: well, same as Ecmascript, I guess. From gagsl-py2 at yahoo.com.ar Thu May 17 19:24:07 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 17 May 2007 20:24:07 -0300 Subject: omissions in python docs? References: <1179419983.750044.65030@n59g2000hsh.googlegroups.com> Message-ID: En Thu, 17 May 2007 13:39:43 -0300, 7stud escribi?: > 2) The fnmatch module does not even mention translate(). > > I have a hard time believing I am the first one to notice those > omissions. At least for 2) you're late. It's already documented on 2.5.1: http://sourceforge.net/tracker/index.php?func=detail&aid=1630844&group_id=5470&atid=105470 -- Gabriel Genellina From arkanes at gmail.com Tue May 1 11:26:04 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 1 May 2007 10:26:04 -0500 Subject: Why are functions atomic? In-Reply-To: References: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> <1178030115.591931.137040@h2g2000hsg.googlegroups.com> Message-ID: <4866bea60705010826j62f16b4v82230bf3c5621c4d@mail.gmail.com> On 1 May 2007 15:17:48 GMT, Duncan Booth wrote: > 7stud wrote: > > > Does deepcopy work? > > It doesn't copy a function. > > The easiest way to make a modified copy of a function is to use the 'new' > module. > > >>> def f(x=2): print "x=", x > > >>> g = new.function(f.func_code, f.func_globals, 'g', (3,), > f.func_closure) > >>> g() > x= 3 > >>> f() > x= 2 > -- > http://mail.python.org/mailman/listinfo/python-list > The copy module considers functions to be immutable and just returns the object. This seems pretty clearly wrong to me - functions are clearly not immutable and it's easy to copy a function using new, as shown above. >From copy.py: def _copy_immutable(x): return x for t in (type(None), int, long, float, bool, str, tuple, frozenset, type, xrange, types.ClassType, types.BuiltinFunctionType, types.FunctionType): d[t] = _copy_immutable From aleax at mac.com Mon May 21 01:20:17 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 20 May 2007 22:20:17 -0700 Subject: A few questions References: Message-ID: <1hyfmze.2m4hspymmbswN%aleax@mac.com> jay wrote: > Hi, > > I'm totally new to Python and was hoping someone might be able to > answer a few questions for me: > > 1. What are your views about Python vs Perl? Do you see one as > better than the other? Yep: if I didn't find Python more readable, maintainable and understandable, I obviously wouldn't have switched. > 2. Is there a good book to start with while learning Python? I'm > currently reading 'Python Essential Reference' by David M. Beazley. > So far it looks like a pretty good book, but would like more > tutorials to work with (I've also been reading through the tutorials > at 'python.org' which has some excellent stuff!). Beazley's excellent book, like my direct competitor "Python in a Nutshell", is mostly meant as a _reference_, not as a tutorial. There are many "starters' books": try "Dive into Python" (has the advantage that you can try it for free online, just web search for it), or "Python for Dummies", "Learning Python", "Core Python", and many more. > 3. Currently, I write most of my code with Xcode (on the Mac > platform) using Applescript. This gives me GUI capabilities. Is > there anything you'd recommend that I could use for Python that would > give me a GUI interface? I'd like this to be able to work for both > the Mac and Windows platforms. I've been reading a little about > 'Claro Graphics Toolkit' and 'PyGUI'... would you recommend either of > those? I'll be writing code on a Mac so I need something that will > run on that system. If you wanted to work with exactly the same wonderful GUI Applescript gives you, you should try PyObjC and use it with your Mac's Cocoa... however, that doesn't work well on Windows. QT4 with PyQt 4 (with Eric4 as the IDE) is probably the best approach today for such cross-platform work (haven't tried it yet, but I can vouch for the previous releases -- Qt3, PyQt 3, Eric3). Most popular, however, is no doubt wxWindows -- mostly because you can freely use it to develop SW which you plan to distribute under closed-source licenses, while Qt &c force you to choose -- either pay, or, if you even distribute your code, it will have to be under the GPL. I'm not sure how well wxWindows works on Mac nowadays, though -- I'm sure somebody else will be able to tell you. For me personally, nowadays, it's Cocoa for Mac-only apps, while any non-Mac-only apps I write as web-apps instead. Alex From thardy99 at gmail.com Sun May 6 22:36:36 2007 From: thardy99 at gmail.com (Teresa Hardy) Date: Sun, 6 May 2007 19:36:36 -0700 Subject: Beginner question on threads - solved Message-ID: >If there is the possibility that the same thread had acquired the lock >earlier, you should use an RLock instead. Gabriel, Thanks for the great hint. I didn't find RLock in my initial reading. So as I read up on RLock, I did a quick search on vlock. It turns out that I was using vlock as a variable and it is also a lock that wasn't in my initial reading. So I changed the variable name and the threads started working properly. Thanks! Teresa -------------- next part -------------- An HTML attachment was scrubbed... URL: From david at boddie.org.uk Sat May 19 13:01:11 2007 From: david at boddie.org.uk (David Boddie) Date: Sat, 19 May 2007 19:01:11 +0200 Subject: No Python for Blackberry? References: <1179537588.505753.275200@q75g2000hsh.googlegroups.com> Message-ID: <58f4d$464f2d58$54d1d767$11871@news.chello.no> On Saturday 19 May 2007 03:19, walterbyrd wrote: > I could not find a version of Python that runs on a Blackberrry. > > I'm just amazed. A fairly popular platform, and no Python > implementation? If you can get the hardware into the hands of capable developers, they'll put Python on it. ;-) David From mcl.office at googlemail.com Wed May 16 06:42:49 2007 From: mcl.office at googlemail.com (mosscliffe) Date: 16 May 2007 03:42:49 -0700 Subject: Splitting a quoted string. Message-ID: <1179312169.045429.80960@e65g2000hsc.googlegroups.com> I am looking for a simple split function to create a list of entries from a string which contains quoted elements. Like in 'google' search. eg string = 'bob john "johnny cash" 234 june' and I want to have a list of ['bob', 'john, 'johnny cash', '234', 'june'] I wondered about using the csv routines, but I thought I would ask the experts first. There maybe a simple function, but as yet I have not found it. Thanks Richard From apardon at forel.vub.ac.be Tue May 8 05:23:24 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 8 May 2007 09:23:24 GMT Subject: how do you implement a reactor without a select? References: <1178543812.260333.39280@w5g2000hsg.googlegroups.com> <1hxqfgq.4sjxga1dz7vv3N%aleax@mac.com> <1178552069.229745.124040@l77g2000hsb.googlegroups.com> <1hxrdhf.179bobg6tzv9cN%aleax@mac.com> <1178596109.282088.175300@u30g2000hsc.googlegroups.com> Message-ID: On 2007-05-08, Michele Simionato wrote: > On May 8, 4:53 am, a... at mac.com (Alex Martelli) wrote: >> What do you expect from "timers on Linux" that you could not get with a >> simple "sleep for the next N milliseconds"? A timer (on Linux or >> elsewhere) can jog your process N milliseconds from now, e.g. with a >> SIGALRM or SIGPROF, and you can set one with the setitimer syscall >> (presumably accessible via ctypes, worst case -- I've never used it from >> Python, yet), but how would that help you (compared to plain sleep, >> select, poll, or whatever else best fits your need)? > > I hoped there was a library such thay I could register a Python > callable (say > a thunk) and having it called by the linux timer at time t without > blocking I once played with the following module to do something similar. Maybe it is usefull to you as is, or can give you an idea on how to proceed. I only tested it on linux. ---------------------------- alarm.py -------------------- m signal import signal, SIG_IGN, SIGALRM from time import time from thread import allocate_lock from heapq import heappush, heappop from os import kill, getpid import errno from select import select, error as SelectException from ctypes import * libc = cdll.LoadLibrary("/lib/libc.so.6") class _timeval(Structure): _fields_ = [("tv_sec" , c_long), ("tv_usec", c_long)] def timeval(tm): sec = int(tm) usec = int(1000000 * (tm - sec)) return _timeval(sec, usec) class itimerval(Structure): _fields_ = [("it_interval", _timeval), ("it_value", _timeval)] def alarm(tm): tv = timeval(tm) ti = timeval(0.0) ntv = itimerval(ti, tv) otv = itimerval(timeval(0.0), timeval(0.0)) rt = libc.setitimer(0, byref(ntv), byref(otv)) #print otv.it_value.tv_sec , otv.it_value.tv_usec if rt: raise ValueError else: return otv.it_value.tv_sec + otv.it_value.tv_usec / 1000000.0 def sleep(tm): wakeup = time() + tm while tm >= 0: try: select([],[],[],tm) except SelectException , Err_Info: #print dir(Err_Info) if Err_Info[0] != errno.EINTR: raise tm = wakeup - time() alarms = [] alarm_lock = allocate_lock() def AlarmHandler(sgnr, frame): alarm_lock.acquire() now = time() while alarms and alarms[0].moment <= now: current = heappop(alarms) if not current.canceled: current.func(*current.args, **current.kwds) current.executed = True now = time() alarm_lock.release() if alarms: #print alarms[0].moment - now, alarms alarm(alarms[0].moment - now) signal(SIGALRM, AlarmHandler) class Alarm(object): def __init__(self, tp, func, *args, **kwds): alarm(0) try: alarm_lock.acquire() self.canceled = False self.executed = False self.func = func self.args = args self.kwds = kwds self.moment = tp heappush(alarms, self) now = time() delta = alarms[0].moment - now #print alarms finally: alarm_lock.release() if delta <= 0: pass kill(getpid(), SIGALRM) else: alarm(delta) def __cmp__(self, other): return cmp(self.moment, other.moment) def __str__(self): return "" % self.moment __repr__ = __str__ def Cancel(self): try: alarm_lock.acquire() if self.executed: raise ValueError, "Cancelation was too late" else: self.canceled = True except: alarm_lock.release() ----------------------------------------------------------------------------------------------- You use it as follows: from alarm import Alarm alert = Alarm(exucutemoment, function, positionalarguments, keywordarguments) # unless alert.Cancel is called before the alert went off, the function # with its arguments will be called at the specified time. # If you are using threads, you are advised to do most of the work in a # different thread and leave the main thread to only treat the alarms. From debajit at debajit.com Tue May 22 03:30:27 2007 From: debajit at debajit.com (Debajit Adhikary) Date: Tue, 22 May 2007 03:30:27 -0400 Subject: How do I parse simple entity references in XML like ><? Message-ID: <110a172d0705220030g17f5f488h9b7897f81403a2f8@mail.gmail.com> I've written a SAX XML parser and cannot seem to be able to parse simple entity references e.g.
    <
    abc
    >
It looks the XML parser that i'm using hasn't implemented the startEntity() and endEntity() methods. How do I parse such simple entity references using Python? --------------------------------------------- The code I'm using is: parser = make_parser() saxRssParser = SaxRssParser() # Implementation parser.setContentHandler(saxRssParser) parser.setProperty(handler.property_lexical_handler, saxRssParser) # For cdata, comments etc. parser.parse(filename) - Debajit -------------- next part -------------- An HTML attachment was scrubbed... URL: From bradallen137 at gmail.com Wed May 2 00:25:38 2007 From: bradallen137 at gmail.com (bradallen) Date: 1 May 2007 21:25:38 -0700 Subject: Python user group in Portland, OR? In-Reply-To: <1178057364.942127.203200@n76g2000hsh.googlegroups.com> References: <1178054753.732189.137230@h2g2000hsg.googlegroups.com> <1178057364.942127.203200@n76g2000hsh.googlegroups.com> Message-ID: <1178079938.469358.318960@p77g2000hsh.googlegroups.com> On May 1, 5:09 pm, Matimus wrote: > Python.org lists PORPIG (PORtland Python Intrest Group) but the site > that it points to no longer seems to represent that. Also, when I > looked into going to a meeting a while back, the last one listed was > some time in 2004. I will put this out there though, if someone wants > to start a PIG back up for Portland I would certainly be interested. I > am at least one Python developer living in the Portland area. The web > contains evidence of others as well. In general there is a fairly > large software development presence in Portland, especially around > Open Source. Thanks for the response. If there is not an active local user group, maybe it would be a good idea to start one. It can be a lot of fun and professionally rewarding, and a city like Portland is a great environment due to all the free public spaces for congregating. I would be happy to meet with you and any other Portland Python programmers to talk about ideas for organizing a user group. There is also some good discussion about it on the Python Advocacy the mailing list, because PSF has begun an effort to foster and promote user groups. Sometime next week might be a good time for a meeting during a weekday evening at a dinner place in the main city center area of Portland. Maybe by then there would be enough time to find others and invite them to join us. I can be contacted via e-mail using "brad" + ampersand + "allendev." + "com" From stefan.behnel-n05pAM at web.de Tue May 15 08:54:18 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 15 May 2007 14:54:18 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179226183.215907.140450@q75g2000hsh.googlegroups.com> Message-ID: <4649AD7A.20202@web.de> Anton Vredegoor wrote: > The older they get the harder it is for them to learn language. By > withholding them English language experience at an early age you are > doing them a disservice because later on they will have more trouble. What does "withholding" mean here? Remember: we're talking about foreign language identifiers here, not about foreign literature. I don't think all identifiers in the stdlib are a) well chosen b) correct English words So: what can you learn from ASCII identifiers that will honestly help you with the english language in your later life? This kind of argument is just plain off-topic. Stefan From hn_sd_ywx_xiaq at 163.com Sat May 26 03:34:55 2007 From: hn_sd_ywx_xiaq at 163.com (XiaQ) Date: Sat, 26 May 2007 15:34:55 +0800 Subject: Xml parser References: Message-ID: You can use DOM http://diveintopython.org/, Chapter 9 "ashish" wrote > Hi All, > > I want to know weather is there any api available in python for parsing > xml(XML parser) > > Regards > Ashish > From zdenekmaxa at yahoo.co.uk Tue May 29 07:32:30 2007 From: zdenekmaxa at yahoo.co.uk (Zdenek Maxa) Date: Tue, 29 May 2007 13:32:30 +0200 Subject: multiline regular expression (replace) In-Reply-To: <1180432000.953227.144690@i13g2000prf.googlegroups.com> References: <1180432000.953227.144690@i13g2000prf.googlegroups.com> Message-ID: <465C0F4E.8080805@yahoo.co.uk> half.italian at gmail.com wrote: > On May 29, 2:03 am, Zdenek Maxa wrote: > >> Hi all, >> >> I would like to perform regular expression replace (e.g. removing >> everything from within tags in a XML file) with multiple-line pattern. >> How can I do this? >> >> where = open("filename").read() >> multilinePattern = "^ .... <\/tag>$" >> re.search(multilinePattern, where, re.MULTILINE) >> >> Thanks greatly, >> Zdenek >> > > Why not use an xml package for working with xml files? I'm sure > they'll handle your multiline tags. > > http://effbot.org/zone/element-index.htm > http://codespeak.net/lxml/ > > ~Sean > > Hi, that was merely an example of what I would like to achieve. However, in general, is there a way for handling multiline regular expressions in Python, using presumably only modules from distribution like re? Thanks, Zdenek From bdesth.quelquechose at free.quelquepart.fr Sun May 13 09:55:22 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 13 May 2007 15:55:22 +0200 Subject: Dynamic subclassing ? In-Reply-To: <1178981677.003637.292860@y80g2000hsf.googlegroups.com> References: <1178976888.443891.116090@y80g2000hsf.googlegroups.com> <4645cc78$0$20196$426a74cc@news.free.fr> <1178981677.003637.292860@y80g2000hsf.googlegroups.com> Message-ID: <46470ea6$0$19237$426a74cc@news.free.fr> manatlan a ?crit : > On 12 mai, 17:00, Bruno Desthuilliers > wrote: > >>manatlan a ?crit : >> >> >>>I've got an instance of a class, ex : >> >>>b=gtk.Button() >> >>>I'd like to add methods and attributes to my instance "b". >>>I know it's possible by hacking "b" with setattr() methods. >> >>You don't even need setattr() here, you can set the attributes directly. >> >> >> >> >>>But i'd >>>like to do it with inheritance, a kind of "dynamic subclassing", >>>without subclassing the class, only this instance "b" ! >> >>>In fact, i've got my instance "b", and another class "MoreMethods" >> >>>class MoreMethods: >>> def sayHello(self): >>> print "hello" >> >>You don't necessarily need subclassing here. What you want is a typical >>use case of the Decorator pattern: >> >>class MoreMethods(object): >> def __init__(self, button): >> self._button = button >> >> def sayHello(self): >> print "hello" >> >> def __getattr__(self, name): >> return getattr(self._button, name) >> >> def __setattr__(self, name, value): >> if name in dir(self._button): >> setattr(self._button, name, value) >> else: >> object.__setattr__(self, name, value) >> >>b = MoreMethods(gtk.Button()) >>b.set_label("k") >>b.say_hello() > > > except that "b" is not anymore a "gtk.Button", but a "MoreMethods" > instance ... > i'd like that "b" stay a "gtk.Button" ... > I don't understand why, but... Then write a function that "inject" all the additionnal methods to your gtk.Button. Or do the composition/delegation the other way round, and monkeypatch gtk.Button's __getattr__. From simon at brunningonline.net Wed May 23 23:23:36 2007 From: simon at brunningonline.net (Simon Brunning) Date: Thu, 24 May 2007 08:53:36 +0530 Subject: Parallel/distributed generator In-Reply-To: <1179943256.575473.62610@q66g2000hsg.googlegroups.com> References: <1179943256.575473.62610@q66g2000hsg.googlegroups.com> Message-ID: <8c7f10c60705232023g29f0cafbt1a5168dd0e60556a@mail.gmail.com> On 23 May 2007 11:00:56 -0700, George Sakkis wrote: > I'm looking for any existing packages or ideas on how to implement the > equivalent of a generator (in the Python sense, i.e. > http://www.python.org/dev/peps/pep-0255/) in a parallel/distributed > way. Kamaelia? http://tinyurl.com/35fjbr -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues From cbmeeks at gmail.com Tue May 29 07:44:58 2007 From: cbmeeks at gmail.com (cbmeeks) Date: 29 May 2007 04:44:58 -0700 Subject: Resize image NO PIL!! In-Reply-To: References: <1180406398.615904.22230@g4g2000hsf.googlegroups.com> Message-ID: <1180439098.295241.169160@o5g2000hsb.googlegroups.com> Nope. They don't support that either. I emailed them (again) asking for these features or at least see if they are in the works sometime in the future and I keep getting their standard response which is basically "you can do it yourself if you upgrade to our $249/mo dedicated plan". I'd go with EC2 for $70/mo first! Thanks cbmeeks On May 28, 11:12 pm, Dave Benjamin wrote: > cbmeeks wrote: > > I have created an image hosting site and when a user uploads an image, > > I want a service to run on the server to create a few thumbnails while > > the user does other things. > > > My stupid host (pair.com) doesn't have PIL installed and I'm too much > > of a stupid newbie to figure out how to get it to work with them > > (access denied while installing it, of course). > > > Also, they don't have any python interface setup for GD. > > > Anyway, I don't know what my options are. I'm thinking: > > > 1) Find another host with mod_python, PIL, and other Python goodies > > 2) use PHP to create the thumbnails > > 3) Open the images into a buffer and try to do the calculations > > myself > > Have you checked to see if Imagemagick is available? You could use the > "convert" command via os.system or something along those lines... > > Dave From mtobis at gmail.com Thu May 24 13:22:15 2007 From: mtobis at gmail.com (Michael Tobis) Date: 24 May 2007 10:22:15 -0700 Subject: CP4E revival In-Reply-To: <465562f1$0$14719$afc38c87@news.optusnet.com.au> References: <1179941107.366354.101860@h2g2000hsg.googlegroups.com> <465562f1$0$14719$afc38c87@news.optusnet.com.au> Message-ID: <1180027335.166890.276770@q69g2000hsb.googlegroups.com> On May 24, 5:03 am, Richard Jones wrote: > Michael Tobis wrote: > >http://tinyurl.com/yr62r3 > > > seems to short-circuit some pointless hoop-jumping to get you to the > > article. > > Hoop-jumping implemented to prevent just this kind of direct linking (and > thus not saving of the PDF to local disk to view, and thus increasing the > load on the server). > > Thanks for abusing the free service being provided to the Python Papers > journal. > > Richard OK, oops, I'll take the tinyurl link down anywhere I can; I really didn't (and still don't) quite get the server side issue but so be it. (I thought it was a measure to ensure a license to view, which is not in fact required in this case.) On the other hand, given the modest reaction to the article (pro or con) I am not getting the sense that it has generated a lot of traffic. I'd prefer flames about the content, though. mt From gagsl-py2 at yahoo.com.ar Mon May 21 09:58:31 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 21 May 2007 10:58:31 -0300 Subject: howto get function from module, known by string names? References: <1179228596.349933.168610@l77g2000hsb.googlegroups.com> <1179753182.107111.94060@y2g2000prf.googlegroups.com> Message-ID: En Mon, 21 May 2007 10:13:02 -0300, dmitrey escribi?: > And howto check does module 'asdf' exist (is available for import) or > no? (without try/cache of course) What's wrong with this: try: import asdf except ImportError: asdf = None ...later... if asdf: asdf.zxcv(1) ... -- Gabriel Genellina From Maksim.Kasimov at gmail.com Tue May 22 09:45:05 2007 From: Maksim.Kasimov at gmail.com (sim.sim) Date: 22 May 2007 06:45:05 -0700 Subject: xml.dom.minidom: how to preserve CRLF's inside CDATA? Message-ID: <1179841504.782279.86490@u36g2000prd.googlegroups.com> Hi all. i'm faced to trouble using minidom: #i have a string (xml) within CDATA section, and the section includes "\r\n": iInStr = '\n\n' #After i create DOM-object, i get the value of "Data" without "\r\n" from xml.dom import minidom iDoc = minidom.parseString(iInStr) iDoc.childNodes[0].childNodes[0].data # it gives u'BEGIN:VCALENDAR \nEND:VCALENDAR\n' according to http://www.w3.org/TR/REC-xml/#sec-line-ends it looks normal, but another part of the documentation says that "only the CDEnd string is recognized as markup": http://www.w3.org/TR/REC-xml/#sec-cdata-sect so parser must (IMHO) give the value of CDATA-section "as is" (neither both of parts of the document do not contradicts to each other). How to get the value of CDATA-section with preserved all symbols within? (perhaps use another parser - which one?) Many thanks for any help. From mailmaverick666 at gmail.com Tue May 8 06:50:18 2007 From: mailmaverick666 at gmail.com (rishi pathak) Date: Tue, 8 May 2007 16:20:18 +0530 Subject: File Name Format In-Reply-To: <5ab28oF2n4947U1@mid.uni-berlin.de> References: <5ab28oF2n4947U1@mid.uni-berlin.de> Message-ID: <180b672e0705080350k7dfb69e8wc6a7b821995c953b@mail.gmail.com> One thing you could do is to create assign dir for c drive d drive etc as /c , /d etc then this would work unix_name = win_name.replace("\\","/").replace("c:","/c").replace("d:","/d") On 5/8/07, Diez B. Roggisch wrote: > > Anand wrote: > > > Greetings, > > > > How do I convert programmatically the file names from WIN32 to UNIX > > format? > > > > A code snippet would be of great help. > > We are new to python! :) > > unix_name = win_name.replace("\\", "/") > > But this of course won't work for anything that starts with a drive letter > for example. > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > -- Regards-- Rishi Pathak National PARAM Supercomputing Facility Center for Development of Advanced Computing(C-DAC) Pune University Campus,Ganesh Khind Road Pune-Maharastra -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven.bethard at gmail.com Wed May 23 16:37:39 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 23 May 2007 14:37:39 -0600 Subject: converting text and spans to an ElementTree In-Reply-To: References: Message-ID: Neil Cerutti wrote: > On 2007-05-22, Steven Bethard wrote: >> Thanks a lot! This put me on the right track (though the >> devil's definitely in the details). It's working now:: >> >> >>>>> tree = xmltools.text_and_spans_to_etree('aaa aaa aaaccc cccaaa', [ >> ... (etree.Element('a'), 0, 21), >> ... (etree.Element('b'), 11, 11), >> ... (etree.Element('c'), 11, 18), >> ... ]) >>>>> etree.tostring(tree) >> 'aaa aaa aaaccc cccaaa' >>>>> tree = xmltools.text_and_spans_to_etree('bbb\naaaccc\ncccaaa', [ >> ... (etree.Element('a'), 0, 17), >> ... (etree.Element('b'), 0, 4), >> ... (etree.Element('c'), 7, 14), >> ... (etree.Element('b'), 14, 14), >> ... ]) >>>>> etree.tostring(tree) >> 'bbb\naaaccc\ncccaaa' >>>>> tree = xmltools.text_and_spans_to_etree('abc', [ >> ... (etree.Element('a'), 0, 3), >> ... (etree.Element('b'), 0, 3), >> ... (etree.Element('c'), 0, 3), >> ... ]) >>>>> etree.tostring(tree) >> 'abc' >> >> >> And for the sake of any poor soul who runs into a similar >> problem, here's the code I wrote using Gabriel's hints above:: > > When I saw you manually keeping a stack, I called Captain > Recursion on my Red-Alert Recursion Phone. > > (I'm sorry he left out the Element stuff, which he doesn't know > or use yet. The Captain's get_tree just returns the string) Heh heh. I actually thought about writing it recursively, but note that you need both recursive and non-recursive parts of this algorithm to do the ElementTree part right: * the recursive (or stack) part assigns children to parents * the non-recursive part assigns text or tail to the previous element (note that's previous in a sequential sense, not a recursive sense) I'm sure I could implement this recursively, passing around annother appropriate argument, but it wasn't obvious to me that the code would be any cleaner. STeVe From kerny404 at gmail.com Sun May 20 11:02:22 2007 From: kerny404 at gmail.com (andrea) Date: 20 May 2007 08:02:22 -0700 Subject: Path python versions and Macosx In-Reply-To: <1179176403.535076.185320@u30g2000hsc.googlegroups.com> References: <1178915809.065874.133030@o5g2000hsb.googlegroups.com> <1178924996.452067.308320@h2g2000hsg.googlegroups.com> <1179143193.232099.285980@u30g2000hsc.googlegroups.com> <1179176403.535076.185320@u30g2000hsc.googlegroups.com> Message-ID: <1179673342.685448.215040@l77g2000hsb.googlegroups.com> On 14 Mag, 23:00, half.ital... at gmail.com wrote: > On May 14, 4:46 am, andrea wrote: > > > > > On 12 Mag, 01:09, half.ital... at gmail.com wrote: > > > > On May 11, 1:36 pm, andrea wrote: > > > > > Hi everyone, > > > > I use python on macosx with textmate as editor (great program). > > > > > I also use macport to install unix programs from the command line and > > > > I find it great too. > > > > Well I would like to have all my modules in the path when I'm using > > > > textmate AND when I use the commandline (ipython), but because > > > > textmate and the command line use different python versions they also > > > > search in different places.. > > > > > I found somewhere to write .pythonrc.py like this > > > > > #!/usr/bin/env python > > > > import sys > > > > PATH='/opt/local/lib/python2.4/site-packages/' > > > > sys.path.append(PATH) > > > > del sys > > > > > But it doesn't work either, I also tried to append this > > > > PATH="/Library/Frameworks/Python.framework/Versions/Current/bin:/opt/ > > > > local/lib/python2.4/site-packages:${PATH} > > > > to .bash_profile but nothing. > > > > > Where should I set this variables?? > > > > > Thanks a lot > > > > You can set environment variables for gui apps with this freeware:http://www.versiontracker.com/dyn/moreinfo/macosx/15073 > > > > You can edit some text files as well, but this thing just makes it > > > much easier. > > > > ~Sean > > > Ok thanks, but why it doesn't work setting the .bash_profile?? What > > should I set manually theorically?? The problem is also that I have > > many modules for python 2.4 and trying to import them from the 2.5 of > > course gives errors.. > > I installed them with macports (compiling), how can I make them switch > > to 2.5??? > > thanks > > Gui applications are not launched through the bash shell. > The .bash_profile never gets read. > > You can accomplish the same thing as the freewware app I mentioned by > editing the xml file at ~/.MacOSX/environment.plist. Its a simple xml > file with keys and their corresponding values. > > Not sure about the modules. You can force a script to look for libs > in a given directory like you mentioned, but that needs to go at the > top of each python file instead of a .pythonrc file. Maybe the > modules will work with 2.5, maybe not. > > ~Sean If I put it on the top of every file it works, it just need to be of the same version... The problem is that I would like it to run everywhere, putting a specific path is not good idea imho (I could use try except but it's annoying). From vatamane at gmail.com Wed May 16 17:52:36 2007 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 16 May 2007 14:52:36 -0700 Subject: cPickle.dumps differs from Pickle.dumps; looks like a bug. In-Reply-To: <1179335622.006820.22460@q23g2000hsg.googlegroups.com> References: <1179335622.006820.22460@q23g2000hsg.googlegroups.com> Message-ID: <1179352356.025319.43310@w5g2000hsg.googlegroups.com> On May 16, 1:13 pm, Victor Kryukov wrote: > Hello list, > > I've found the following strange behavior of cPickle. Do you think > it's a bug, or is it by design? > > Best regards, > Victor. > > from pickle import dumps > from cPickle import dumps as cdumps > > print dumps('1001799')==dumps(str(1001799)) > print cdumps('1001799')==cdumps(str(1001799)) > > outputs > > True > False > > vicbook:~ victor$ 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.>>> quit() > > vicbook:~ victor$ uname -a > Darwin vicbook 8.9.1 Darwin Kernel Version 8.9.1: Thu Feb 22 20:55:00 > PST 2007; root:xnu-792.18.15~1/RELEASE_I386 i386 i386 If you unpickle though will the results be the same? I suspect they will be. That should matter most of all (unless you plan to compare objects' identity based on their pickled version.) Remember, that by default pickle and cPickle will create a longer ASCII representation, for a binary representation use a higher pickle protocol -- 2 instead of 1. Hope that helps, -Nick Vatamaniuc From sjmachin at lexicon.net Sat May 12 20:45:13 2007 From: sjmachin at lexicon.net (John Machin) Date: 12 May 2007 17:45:13 -0700 Subject: ctree data In-Reply-To: References: Message-ID: <1179017113.436962.69100@o5g2000hsb.googlegroups.com> On May 13, 7:05 am, Carl K wrote: > A friend needs to convert c-tree plus data to MySql. I can to the "to MySql > part, but need some help with the "from c-tree." If I just wanted to get this > done, I would hunt down the ODBC driver and use some MSy thing. But I am trying > to hone my Python skills, but right now I am in over my head, thus this post. I > think with a little boost I will be able to make it all come together. (well, > little boost may be an understatement - I have no clue how close/far I am from > what I need.) > > My searching around has come up with a few ways to use Python to read the data: > > 1. pull what I need from some other py code that uses c-tree: > > http://oltp-platform.cvs.sourceforge.net/oltp-platform/OLTPP/services...http://oltp-platform.cvs.sourceforge.net/oltp-platform/OLTPP/scripts/... > > 12 a,b,c = ZipCode.Get() > 13 print "Zip code is ", a > 14 print "State is ", b > 15 print "City is ", c > > I am sure this is what I want. I just haven't figured out where to start. > > 2. "Pyrex" to create Python bindings to C API with minimal C knowledge. I took > C and did a few little utilities on my own in the 90's. plus I can make a > tarball. today I am not sure I even qualify for "minimal." > > 3. the C API is present as a shared object (.so), use it from Python with > ctypes. I have no idea what that means. > > 4. odbc - I am actually not thrilled about using the ctree odbc driver in any > environment, because someone else who tried to use it on some other data a few > years ago said it was flaky, and support was next to useless. > > 5, get someone who knows perl to do it usinghttp://cpan.uwinnipeg.ca/htdocs/Db-Ctree/Db/Ctree.html- This just shows what > lengths I am willing to go to. but I really don't want to start learning perl. > Possible option 6: Find out if there is (a) a ctree utility program that dumps a ctree table to a flat file in documented easily-parsed format plus (b) a method of getting the metadata for each column (type, decimal places, etc) if that info is not already available from (a). It's entirely possible that SQL "select * from the_table" will do (a) for you, if the output is given with full precision, and there's a method of getting the columns delimited properly. HTH, John From maric at aristote.info Wed May 23 19:21:48 2007 From: maric at aristote.info (Maric Michaud) Date: Thu, 24 May 2007 01:21:48 +0200 Subject: using google search api for python In-Reply-To: References: Message-ID: <4654CC8C.3020201@aristote.info> Larry Bates a ?crit : > Gerardo Herzig wrote: >> Hi all. Im looking for the pyGoogle for making google searchs y a python >> script. The thing is, all im founding is an AJAX api, but the >> application ill use is NOT a web app. So, someone know if there is a >> pure python api that i can download and use? >> >> Thanks! >> Gerardo > > The server (Google) on the other end doesn't know what type of app you > are. It just responds to XMLRPC requests. I haven't used the interface > but I'm guessing that I would use Twisted to make XMLRPC request to Google > and process the response XML payload using Elementree. > Yes, you could if you have time... or you can just use the straightforward xmlrpclib which is in stdlib. I used it with Zope and it just works fine. just try : import xmlrpclib help(xmlrpclib) Larry, excuse for the private mail. From Mattia.Gentilini_REMOVE_ at _REMOVE_CNAF.INFN.IT Fri May 25 10:01:28 2007 From: Mattia.Gentilini_REMOVE_ at _REMOVE_CNAF.INFN.IT (Mattia Gentilini) Date: Fri, 25 May 2007 16:01:28 +0200 Subject: just a bug In-Reply-To: References: <1179841504.782279.86490@u36g2000prd.googlegroups.com> <1180082137.329142.45350@p77g2000hsh.googlegroups.com> Message-ID: Richard Brodie ha scritto: > For HTML, yes. it accepts all sorts of garbage, like most > browsers; I've never, before now, seen it accept an invalid > XML document though. It *could* depend on Content-Type. I've seen that Firefox treats XHTML as HTML (i.e. not trying to validate it) if you set Content-Type to text/html. However, the same document with Content-Type application/xhtml+xml is checked for well-formedness (if the DOM inspector is installed). So probably Firefox treats that bad-encoded document ad text/html (maybe as a failsafe setting), this could explain why it accepts that. -- |\/|55: Mattia Gentilini e 55 = log2(che_palle_sta_storia) (by mezzo) |/_| ETICS project at CNAF, INFN, Bologna, Italy |\/| www.getfirefox.com www.getthunderbird.com * Using Mac OS X 10.4.9 powered by Cerebros (Core 2 Duo) * From aisaac at american.edu Fri May 11 09:32:41 2007 From: aisaac at american.edu (Alan Isaac) Date: Fri, 11 May 2007 13:32:41 GMT Subject: change of random state when pyc created?? References: <588D53831C701746A2DF46E365C018CE01D2CA93@LITEXETSP001.etrsouth.corp.entergy.com> Message-ID: This is an attempt to synthesize Bill and Carsten's proposals. http://docs.python.org/lib/typesmapping.html: for footnote (3) Keys and values are listed in an arbitrary order. This order is indeterminate and generally depends on factors outside the scope of the containing program. However, if items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond. http://docs.python.org/lib/types-set.html: append a new sentence to 2nd par. Iteration over a set returns elements in an indeterminate order, which generally depends on factors outside the scope of the containing program. Alan Isaac From mike.klaas at gmail.com Thu May 31 14:18:13 2007 From: mike.klaas at gmail.com (Klaas) Date: 31 May 2007 11:18:13 -0700 Subject: Python memory handling In-Reply-To: References: <1180611604.247696.149060@h2g2000hsg.googlegroups.com> <1180627331.756615.132650@k79g2000hse.googlegroups.com> Message-ID: <1180635493.493153.119710@r19g2000prf.googlegroups.com> On May 31, 11:00 am, Thorsten Kampe wrote: > If it's swapped to disk than this is a big concern. If your Python app > allocates 600 MB of RAM and does not use 550 MB after one minute and > this unused memory gets into the page file then the Operating System > has to allocate and write 550 MB onto your hard disk. Big deal. You have a long-running python process that allocates 550Mb of _small_ objects and then never again uses more than a tenth of that space? This is an abstract corner case, and points more to a multi-process design rather than a flaw in python. The unbounded size of python's int/float freelists are slightly more annoying problems, but nearly as trivial. -Mike From noagbodjivictor at gmail.com Tue May 1 16:38:36 2007 From: noagbodjivictor at gmail.com (noagbodjivictor at gmail.com) Date: 1 May 2007 13:38:36 -0700 Subject: Python for Windows other way to getting it? Message-ID: <1178051916.033367.205320@h2g2000hsg.googlegroups.com> Hello I don't have permission to install new application on the PC I'm using, I need a zipped version of python that I can copy on my external drive. Where can I get a zip version? Thanks From steve at holdenweb.com Thu May 24 16:30:19 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 24 May 2007 16:30:19 -0400 Subject: trouble converting c++ bitshift to python equivalent In-Reply-To: <1180037677.633613.30160@u30g2000hsc.googlegroups.com> References: <1180037677.633613.30160@u30g2000hsc.googlegroups.com> Message-ID: nanodust at gmail.com wrote: > hello all > > i am relatively new to python, catching on, but getting stuck on > simple thing: > > i have two string bytes i need to push into a single (short) int, like > so in c: > > temp = strBuf[2]; > > temp = (temp<<7)+(strBuf[1]); > > c code works, but having trouble getting python to perform same > function! > > keep getting type & operator errors (i apparently can't bitshift on > str or int?) > > curious what the best way is to do this, in python... > > i'll stick w/ it & post when i sort it > > > meanwhile, any help greatly appreciated > You should really use the struct module for that type of conversion, but you also need to know that indexing of lists and tuples starts at 0, not 1. For the specific case that you're discussing, you could convert each character to its corresponding integer value and use shifting and adding with those: temp = (ord(strBuf[1]) << 8) + ord(strBuf[0]) Obviously if the byte order is wrong you would need to reverse the 0 and 1 elements. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From andre.roberge at gmail.com Wed May 16 07:32:17 2007 From: andre.roberge at gmail.com (=?utf-8?B?QW5kcsOp?=) Date: 16 May 2007 04:32:17 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464aaee8$0$10188$9b4e6d93@newsspool4.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de><464762B6.701@web.de> <46478694$0$1412$426a34cc@news.free.fr> <1hy252p.1anf7sr1p4yp12N%aleax@mac.com> <464988a4$0$20289$9b4e6d93@newsspool3.arcor-online.net> <464aaee8$0$10188$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <1179315137.548395.148410@u30g2000hsc.googlegroups.com> "Years ago", i wrote RUR-PLE (a python learning environment based on Karel the Robot). Someone mentioned using RUR-PLE to teach programming in Chinese to kids. Here's a little text extracted from the English lessons (and an even smaller one from the Turkish one). I believe that this is relevant to this discussion. ========== While the creators of Reeborg designed him so that he obeys instructions in English, they realised that not everyone understands English. So, they gave him the ability to easily learn a second language. For example, if we want to tell someone to "move forward" in French, we would say "avance". We can tell Reeborg that "avance" is a synonym of "move" simply by writing avance = move. The order here is important; the known command has to be on the right, and the new one has to be on the left. Note that we don't have any parentheses "()" appearing since the parentheses would tell Reeborg that we want him to obey an instruction; here, we are simply teaching him a new word. When we want Reeborg to follow the new instruction, we will use avance(). [snip] If you want, you can also teach Reeborg a synonym for turn_off. Or, you may give synonyms in a language other than French if you prefer, even creating your own language. Then, watch Reeborg as he obeys instructions written in your language. [snip] Note that, if English is not your favourite language, you can always create a synonym in your language, as long as you define it first, before using it. However, the synonym you introduce must use the English alphabet (letters without any accents). For example, in French, one might define vire_a_gauche = turn_left and use vire_a_gauche() to instruct the robot to turn left. ----------(this last paragraph, now translated in Turkish) E?er ?ngilizce sizin favori diliniz de?ilse komutlar? her zaman kendi dilinizde de tan?mlayabilirsiniz, ancak kendi dilinizde tan?mlad???n?z komutlar? olu?tururken yaln?zca ?ngiliz alfabesindeki 26 harfi kullanabilirsiniz. ?rne?in T?rk?ede sola d?n?? i?in sola_don = turn_left kullan?lmal?d?r (? yerine o kullan?lm?? dikkat ediniz). Bu tan?mlamay? yapt?ktan sonra Reeborg'u sola d?nd?rmek i?in sola_don() komutunu kullanabilirsiniz. ================= I don't read Turkish, but I notice the number 26 there (plus a many accented letters in the text), suspecting it refers to a small English alphabet. It always bugged me that I could not have proper robot commands in French. While I would not use any non-ascii characters in my coding project (because I like to be able to get bug reports [and patch!] from others), I would love to be able to rewrite the lessons for RUR-PLE using commands in proper French, rather than the bastardized purely ascii based version. And I suspect it would be even more important in Chinese... Andr? From stugots at qwest.net Thu May 31 11:12:20 2007 From: stugots at qwest.net (John DeRosa) Date: Thu, 31 May 2007 08:12:20 -0700 Subject: Is PEP-8 a Code or More of a Guideline? References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <5c1jpkF2tl0ilU1@mid.individual.net> <5c6qutF2tlf3oU1@mid.individual.net> Message-ID: On Wed, 30 May 2007 20:41:32 -0600, Frank Swarbrick wrote: >Tim Roberts wrote: >> Frank Swarbrick wrote: >>> Then you'd really love COBOL! >>> >>> :-) >>> >>> Frank >>> COBOL programmer for 10+ years >> >> Hey, did you hear about the object-oriented version of COBOL? They call it >> "ADD ONE TO COBOL". > >I know you were joking, but the COBOL 2002 standard implements OO. >It's OK, but quite obviously "bolted on". Exactly the same situation as the OO in C++... From szhorvat at gmail.com Mon May 21 08:31:44 2007 From: szhorvat at gmail.com (Szabolcs) Date: Mon, 21 May 2007 14:31:44 +0200 Subject: Lists vs tuples (newbie) In-Reply-To: <1179749339.954399.322320@a26g2000pre.googlegroups.com> References: <1179749339.954399.322320@a26g2000pre.googlegroups.com> Message-ID: Thanks for all the replies! Phoe6 wrote: > 1) Return values from a function. When you return multiple values > from a function. You store them as a tuple and access them > individually rather then in the list, which bear the danger of being > modified. > Look up the standard library itself and you will find many instances. > > (cin, cout, cerr) = os.popen3('man man') > > If you had the above as list, then you might end up spoiling things > knowingly/unknowingly. Could you please elaborate on this (or give an explicit example how might one do something bad unknowingly when returning multiple values in a list)? Should I think of tuples simply as a safeguard and reminder (because I consciously use them for different thing than lists, as the faq suggests)? Something similar to C++'s "const" (i.e. not strictly necessary but useful for avoiding bugs)? Szabolcs From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue May 15 04:43:36 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 15 May 2007 10:43:36 +0200 Subject: Trying to choose between python and java In-Reply-To: References: Message-ID: <464972ad$0$23728$426a74cc@news.free.fr> Anthony Irwin a ?crit : > Hi All, > > I am currently trying to decide between using python or java and have a > few quick questions about python that you may be able to help with. > > #1 Does python have something like javas .jar packages. A jar file > contains all the program files and you can execute the program with java > -jar program.jar Python eggs > I am sort of hoping python has something like this because I feel it > makes it easier to distribute between platforms e.g. linux, mac windows > etc. Note that while highly portable (and ported), Python is not as autistic as Java and doesn't try to pretend the underlying platform doesn't exists... > #2 What database do people recommend for using with python that is easy > to distribute across linux, mac, windows. If you're thinking of embedded databases, the answer is SQLite. Else, PostgreSQL and MySQL both run on Windows and mowt unices. > #3 Is there any equivalent to jfreechart and jfreereport > (http://www.jfree.org for details) in python. > > #4 If I write a program a test it with python-wxgtk2.6 under linux are > the program windows likely to look right under windows and mac? > > #5 someone said that they used to use python but stopped because the > language changed or made stuff depreciated s/depreciated/deprecated/ > (I can fully remember which) > and old code stopped working. This is very strange, and even looks like FUD. Python has gone very far into maintaining compatibility, and there's a lot of pretty old code still running on latest Python versions. > Is code written today likely to still work > in 5+ years or do they depreciate stuff and you have to update? I still use code written more than five years ago. > Anyway hopefully someone can help me out with these last few questions I > have. > > Also does anyone else have any useful comments about python vs java > without starting a flame war. Err... reading the last words, I think I'd better shut my mouth now. From nyamatongwe+thunder at gmail.com Wed May 16 09:46:10 2007 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Wed, 16 May 2007 13:46:10 GMT Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <7x4pmg716p.fsf@ruckus.brouhaha.com> <4648EC26.8020907@v.loewis.de> Message-ID: Eric Brunel: > Funny you talk about Japanese, a language I'm a bit familiar with and > for which I actually know some input methods. The thing is, these only > work if you know the transcription to the latin alphabet of the word you > want to type, which closely match its pronunciation. So if you don't > know that ??? is pronounced "uriba" for example, you have absolutely > no way of entering the word. Even if you could choose among a list of > characters, are you aware that there are almost 2000 "basic" Chinese > characters used in the Japanese language? And if I'm not mistaken, there > are several tens of thousands characters in the Chinese language itself. > This makes typing them virtually impossible if you don't know the > language and/or have the correct keyboard. It is nowhere near that difficult. There are several ways to approach this, including breaking up each character into pieces and looking through the subset of characters that use that piece (the Radical part of the IME). For ?, you can start with the cross with a short bottom stroke (at the top of the character) ?, for ? look for the crossy thing on the left ?. The middle character is simple looking so probably not Chinese so found it in Hiragana. Another approach is to count strokes (Strokes section of the IME) and look through the characters with that number of strokes. Within lists, the characters are ordered from simplest to more complex so you can get a feel for where to look. Neil From michael at jedimindworks.com Thu May 17 13:47:41 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Thu, 17 May 2007 12:47:41 -0500 Subject: FreeType In-Reply-To: <1179422948.600593.117310@p77g2000hsh.googlegroups.com> References: <1179422948.600593.117310@p77g2000hsh.googlegroups.com> Message-ID: On May 17, 2007, at 12:29 PM, Glich wrote: > Hi, where can I download freetype (>= 2.1.7)? I need it to use > matplotlib. I have search a lot but still can not find it. Thanks! Type 'freetype' in the google search form, and click the "I'm Feeling Lucky" button. If that doesn't work for some reason, go to freetype.org. From fruels at gmail.com Wed May 2 05:26:13 2007 From: fruels at gmail.com (whitewave) Date: 2 May 2007 02:26:13 -0700 Subject: DiffLib Question In-Reply-To: <1178097127.286181.216520@y80g2000hsf.googlegroups.com> References: <1178095577.190066.158960@y80g2000hsf.googlegroups.com> <1178097127.286181.216520@y80g2000hsf.googlegroups.com> Message-ID: <1178097973.516943.248720@y80g2000hsf.googlegroups.com> Hi, Thank you for your reply. But I don't fully understand what the charjunk and linejunk is all about. I'm a bit newbie in python using the DiffLib. I'm I using the right code here? I will I implement the linejunk and charjunk using the following code? >>> a = difflib.Differ().compare(d1,d2) >>> dif =[] >>> for i in a: ... dif.append(i) ... s = ''.join(dif) Thanks Jen From aboudouvas at panafonet.gr Tue May 8 08:30:50 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 8 May 2007 05:30:50 -0700 Subject: Gui thread and async jobs. Message-ID: <1178627450.408287.139070@p77g2000hsh.googlegroups.com> Hi, i am reading the book "Python Cookbook, 2nd edition" and i encountered a very handy recipe, the one that is called "Combining GUIs and Asynchronous I/O with Threads" It is talking about retain a main GUI thread, doing async work with worker threads and have both talk through a Queue object to dispatch their messages, so the main (GUI) thread remain responsive. It has a very good example by using Tkinter and Qt that is indeed working. The only point that make me wonder is that the QUI thread has to use some polling to check for messages in the Queue. Author said that another alternatives exists (by not doing polling) but the complexity makes them non-practical for the 90% of ocassions. I remember in C# we deal with that sort of things with events/ delegates. Hos the same thing is possible in Python, has anyone any link(s) to have a look ? From nagle at animats.com Sun May 13 02:46:53 2007 From: nagle at animats.com (John Nagle) Date: Sat, 12 May 2007 23:46:53 -0700 Subject: Setting thread priorities Message-ID: <2sy1i.2542$LR5.1451@newssvr17.news.prodigy.net> There's no way to set thread priorities within Python, is there? We have some threads that go compute-bound, and would like to reduce their priority slightly so the other operations, like accessing the database and servicing queries, aren't slowed as much. John Nagle From 2007 at jmunch.dk Sun May 13 18:32:06 2007 From: 2007 at jmunch.dk (Anders J. Munch) Date: Mon, 14 May 2007 00:32:06 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476081.7080609@web.de> Message-ID: <46479282$0$4156$ba624c82@nntp02.dk.telia.net> Josiah Carlson wrote: > On the other hand, the introduction of some 60k+ valid unicode glyphs > into the set of characters that can be seen as a name in Python would > make any such attempts by anyone who is not a native speaker (and even > native speakers in the case of the more obscure Kanji glyphs) an > exercise in futility. > So you gather up a list of identifiers and and send out for translation. Having actual Kanji glyphs instead a mix of transliterations and bad English will only make that easier. That won't even cost you anything, since you were already having docstrings translated, along with comments and documentation, right? > But this issue isn't limited to different characters sharing glyphs! > It's also about being able to type names to use them in your own code > (generally very difficult if not impossible for many non-Latin > characters), or even be able to display them. For display, tell your editor the utf-8 source file is really latin-1. For entry, copy-paste. - Anders From scanepa at gmail.com Tue May 29 04:35:28 2007 From: scanepa at gmail.com (Stefano Canepa) Date: 29 May 2007 01:35:28 -0700 Subject: Python tutorials In-Reply-To: Message-ID: <1180427728.475784.295680@q75g2000hsh.googlegroups.com> On 29 Mag, 09:08, Laurentiu wrote: > Hello! > > i was searching the net for some python video > tutorials (free and payed). > > i found some interesting stuff atwww.showmedo.combut > i want something more complex. > > can someone give me some address for python video > tutorials or companies how made this tutorials, free > or payed. > > i search at Lynda.com and vtc but i didn't find any > python references. > > thanks for all answers. > > Laurentiu Have you tried: http://www.cs.luc.edu/~anh/python/hands-on/handsonHtml/handson.html http://diveintopython.org/ Bye sc From dibanders at yahoo.com Fri May 4 01:36:23 2007 From: dibanders at yahoo.com (Dave Lim) Date: Thu, 3 May 2007 22:36:23 -0700 (PDT) Subject: problem with py2exe and microsoft speech SDK 5.1 Message-ID: <282438.64479.qm@web33515.mail.mud.yahoo.com> >On May 3, 1:29 pm, Dave Lim wrote: >> Hello, this is my first time in the mailing list so >> bear with me. >> >> Basically what I did was I followed this site:http://surguy.net/articles/speechrecognition.xml >> >> So I installed microsoft speech SDK 5.1 and then used >> pythonwin COM MakePy utility for it and it worked out >> fine. However, I need to compile my program into a >> .exe and I have no idea how to make this work. I tried >> using py2exe but I get the error: >> >> Traceback (most recent call last): >> File "simple-speech-recognition.py", line 57, in ? >> TypeError: Error when calling the metaclass bases >> cannot create 'NoneType' instances >> >> If anybody knows a good solution to this problem I >> would very much appreciate it if you can guide me to >> the right path / solution. >> >> Thank you very much! >> -Dave Lim >> >> __________________________________________________ >> Do You Yahoo!? >> Tired of spam? Yahoo! Mail has the best spam protection aroundhttp://mail.yahoo.com > >I've never done this, but I want to at some point, so I went and >grabbed some good links on packaging up Python apps: > >http://davidf.sjsoft.com/mirrors/mcmillan-inc/install1.html >http://www.pharscape.org/content/view/33/51/ >http://wiki.python.org/moin/Py2Exe >http://www.py2exe.org/index.cgi/Tutorial > >There's also growth in using Python Eggs: http://peak.telecommunity.com/DevCenter/PythonEggs > >Mike Thanks for the links. But I already have compiled it successfully into an executable my only problem is i still have that error. I still have the same error: Traceback (most recent call last): File "simple-speech-recognition.py", line 57, in ? TypeError: Error when calling the metaclass bases cannot create 'NoneType' instances I used py2exe and I also added typelibs in the options however that didn't seem to fix my problem. Below is my setup.py, can anyone tell me what I'm lacking or doing wrong here? setup.py from distutils.core import setup import py2exe setup(options = {"py2exe": {"typelibs": [('{C866CA3A-32F7-11D2-9602-00C04F8EE628}',0,5,0)]}}, console = ["simple.py"]) Dave __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From sbassi at clubdelarazon.org Fri May 4 08:56:42 2007 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Fri, 4 May 2007 09:56:42 -0300 Subject: default config has no md5 module? In-Reply-To: <4e307e0f0705040001t69300dabw5df37c2799201787@mail.gmail.com> References: <4e307e0f0705040001t69300dabw5df37c2799201787@mail.gmail.com> Message-ID: <9e2f512b0705040556h22bed3bam6466f425df88e2ac@mail.gmail.com> On 5/4/07, Leo Jay wrote: > i want to compile a python by myself, but after configure and make, it > seems that md5 is not built by default. > > what should i do to compile md5 as an module? md5 module was deprecated, now it functions are in hashlib. (see http://docs.python.org/lib/module-hashlib.html). So you may not need to compile md5 module at all. -- Sebasti?n Bassi (???????) Diplomado en Ciencia y Tecnolog?a. GPG Fingerprint: 9470 0980 620D ABFC BE63 A4A4 A3DE C97D 8422 D43D Club de la raz?n (www.clubdelarazon.org) From kyosohma at gmail.com Tue May 22 10:15:54 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 22 May 2007 07:15:54 -0700 Subject: NOOOOB In-Reply-To: <1179836189.980255.38810@a26g2000pre.googlegroups.com> References: <1179829763.464614.123920@a26g2000pre.googlegroups.com> <1179836189.980255.38810@a26g2000pre.googlegroups.com> Message-ID: <1179839457.449774.96870@x18g2000prd.googlegroups.com> On May 22, 7:16 am, marc wyburn wrote: > On May 22, 11:29 am, jolly wrote: > > > Hey guys, > > > I want to begin python. Does anyone know where a good starting point > > is? > > > Thanks, > > Jem > > i went through the tutorials on the main site and then followed up > with mark Hammonds book for windows stuff. I got a few other books as > well to reference but I've found it easy enough to find info for > almost everything on the net. If you need reference books that delve deep into the language while being somewhat understandable, I would recommend "Programming Python" by Lutz or "Core Python Programming" by Chun. "Beginning Python" by Hetland covers just about everything you'd need to know and it includes some fairly complex examples in the back...plus it's about half the size of the other two books. Other than that, I'd with the other guys on this. The web has lots of good examples, puzzles and for most of the standard library, decent docs, although not always with good or thorough examples. Enjoy! Mike From steve at holdenweb.com Sun May 6 17:27:08 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 06 May 2007 17:27:08 -0400 Subject: Error in python.org homepage. In-Reply-To: References: <1178013832.880214.134660@l77g2000hsb.googlegroups.com> Message-ID: Terry Reedy wrote: > wrote in message > news:1178013832.880214.134660 at l77g2000hsb.googlegroups.com... > | Hi to all!!! > | > | I sended an email to webmaster at python dot org, but was blocked... > | why?.... > > No idea > I doubt very much that the poster was blocked. It's likely that he received an email auto-response as a first-time poster, and may not have understood it. Allessio, if that's the case please let me know if you think we could improve the message to make it easier to understand. > | In the homepage of python.org there is an error: the link that point > | to source distribution is not > | updated to Python 2.5.1. > > Just checked and both links now point to > http://www.python.org/download/releases/2.5.1/ > That's because I independently spotted the error some while ago and raised a ticket against it: http://pydotorg.python.org/pydotorg/ticket/427 Note that if you find a bug anywhere in www.python.org the left-hand navigation feature contains a "report website bug" link which is the appropriate way to raise these issues. You may need to create an account on the Trac instance used to track web site issues (which means emailing someone due to spam comments in the past, sorry) but you can then raise these issues directly with the site maintenance team. It may also be worth mentioning that we are always on the look out for dedicated and conscientious new additions to the web team, so if you would like to lend a hand please email webmaster at python.org. It helps if you are already "known" in some way, such as being a regular contributor to c.l.py, but that's not an absolute requirement as far as I know. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From aspineux at gmail.com Thu May 31 07:45:21 2007 From: aspineux at gmail.com (aspineux) Date: 31 May 2007 04:45:21 -0700 Subject: non standard path characters In-Reply-To: References: Message-ID: <1180611921.653938.159500@h2g2000hsg.googlegroups.com> I thing you should change the code page before to run the test, doing something like : c:\> chcp 850 c:\> ....\python.exe ......\test.py look for the good code page for you, maybe 850, 437 or 1230 or 1250 should work Regards On 31 mai, 12:17, Robin Becker wrote: > A kind user reports having problems running the reportlab tests because his path > has non-ascii characters in it eg > > .....\Mes documents\Mes T?l?chargements\Firefox\... > > somewhere in the tests we look at the path and then try and convert to utf8 for > display in pdf. > > Is there a standard way to do these path string conversions? > > Paths appear to come from all sorts of places and given the increasing use of > zip file packaging it doesn't seem appropriate to rely on the current platform > as a single choice for the default encoding. > -- > Robin Becker From rene at korteklippe.de Wed May 16 03:51:46 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Wed, 16 May 2007 09:51:46 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <46478694$0$1412$426a34cc@news.free.fr> <1hy252p.1anf7sr1p4yp12N%aleax@mac.com> <464988a4$0$20289$9b4e6d93@newsspool3.arcor-online.net> <464aaee8$0$10188$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <464ab811$0$10185$9b4e6d93@newsspool4.arcor-online.net> Gregor Horvath schrieb: > Ren? Fleschenberg schrieb: > >> today, to the best of my knowledge. And "in some form or another" >> basically means that the PEP would create more possibilities for things >> to go wrong. That things can already go wrong today does not mean that >> it does not matter if we create more occasions were things can go wrong >> even worse. > > Following this logic we should not add any new features at all, because > all of them can go wrong and can be used the wrong way. No, that does not follow from my logic. What I say is: When thinking about wether to add a new feature, the potential benefits should be weighed against the potential problems. I see some potential problems with this PEP and very little potential benefits. > I love Python because it does not dictate how to do things. > I do not need a ASCII-Dictator, I can judge myself when to use this > feature and when to avoid it, like any other feature. *That* logic can be used to justify the introduction of *any* feature. -- Ren? From http Sun May 13 20:59:23 2007 From: http (Paul Rubin) Date: 13 May 2007 17:59:23 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <20070513160046.GC29172@v.igoro.us> <7x646wa9wz.fsf@ruckus.brouhaha.com> Message-ID: <7xfy608bkk.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > > It certainly does apply, if you're maintaining a program and someone > > submits a patch. In that case you neither click nor type the > > character. You'd normally just make sure the patched program passes > > the existing test suite, and examine the patch on the screen to make > > sure it looks reasonable. The phishing possibilities are obvious. > > Not to me, I'm afraid. Can you explain how it works? A phisher might be > able to fool a casual reader, but how does he fool the compiler into > executing the wrong code? The compiler wouldn't execute the wrong code; it would execute the code that the phisher intended it to execute. That might be different from what it looked like to the reviewer. From fumanchu at amor.org Tue May 22 23:38:27 2007 From: fumanchu at amor.org (fumanchu) Date: 22 May 2007 20:38:27 -0700 Subject: Cherrypy setup questions In-Reply-To: References: Message-ID: <1179891507.498030.157230@m36g2000hse.googlegroups.com> On May 22, 6:38 pm, Brian Blais wrote: > I'd like to start trying out some cherrypy apps, but I've > been having some setup problems. I think I need some > bone-head simple example to clear my understanding. :) > > I'm on a system running Apache, that I don't have root > access to. I will be publishing the html/image/python > files in a directory off of my current web page, and > running the app as a user on the system. I'd like to be > able to specify the base url for the app, especially if > I have more than one app. I've read the docs, but am > getting confused with the config file information, and > exactly how to set it up. I'm using CherryPy 3.0.1, > the latest I know. > > Some questions I have: > 1) can I configure cherrypy to look at requests only > off a base url, like: > > http://www.provider.com:8080/~myusername/apps Yes, you can. Assuming you're using the "cherrypy.quickstart" function, supply the "base url" in the "script_name" argument; for example: sn = 'http://www.provider.com:8080/~myusername/apps' cherrypy.quickstart(Root(), sn, config) If you're using cherrypy.tree.mount instead of quickstart, it takes a similar argument. > 2) If you run (as in Unix): > > cd app1 > python mycherrypyapp1.py & > > cd ../app2 > python mycherrypyapp2.py & > > Does this start 2 cherrypy servers, trying to both fight > for port 8080, or is there only one, and the two apps share it? This will almost certainly start two cherrypy servers. You can run one on a different port via a "server.socket_port" config entry if you like. If you want them both to run on the same port but different "base urls", you should write a small "mysite.py" which mounts them as desired; for example: # mysite.py import cherrypy import app1, app2 cherrypy.tree.mount(app1.root, "/app1") cherrypy.tree.mount(app2.root, "/app2") cherrypy.server.quickstart() cherrypy.engine.start() cherrypy.engine.block() > I didn't see a CherryPy mailing list, so I'm posting here, > but if there is somewhere else better I'd be glad to know! There is a cherrypy-users mailing list, and I'm CC'ing it so you can reply there if you like. :) Hope that helps! Robert Brewer System Architect Amor Ministries fumanchu at amor.org From jon at ffconsultancy.com Tue May 15 05:43:23 2007 From: jon at ffconsultancy.com (Jon Harrop) Date: Tue, 15 May 2007 10:43:23 +0100 Subject: Iron Python Message-ID: <464981fa$0$8759$ed2619ec@ptn-nntp-reader02.plus.net> Anybody tried it? -- Dr Jon D Harrop, Flying Frog Consultancy The F#.NET Journal http://www.ffconsultancy.com/products/fsharp_journal/?usenet From aboudouvas at panafonet.gr Thu May 3 17:29:13 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 3 May 2007 14:29:13 -0700 Subject: 32 OS on 64-bit machine In-Reply-To: <1178204299.233068.59730@p77g2000hsh.googlegroups.com> References: <1178183424.548438.303170@y80g2000hsf.googlegroups.com> <1178204299.233068.59730@p77g2000hsh.googlegroups.com> Message-ID: <1178227753.228105.37350@h2g2000hsg.googlegroups.com> At Amd Turion 64, it gives: ('32bit', 'ELF') From cedric.louyot at gmail.com Thu May 10 04:31:14 2007 From: cedric.louyot at gmail.com (redcic) Date: 10 May 2007 01:31:14 -0700 Subject: matplotlib problem Message-ID: <1178785874.916502.84960@y80g2000hsf.googlegroups.com> I've got a question regarding matplotlib. I use the command: pylab.plot(...) to create a graph. Then, the execution of the code stops after the line: pylab.show() which is off course the last line of my code. My problem is that I have to close the figure window before in order to finish the execution of my code. I'd like to be able to launch my program other times with different parameters without having to close the figure windows before each launch. Just so you know, I'm using TkAgg backend and the SciTE editor. Following the answer I was given in the thread: http://groups.google.com/group/comp.lang.python/browse_thread/thread/939fc6c7a9645bd8/f939f2db9da55430?lnk=gst&q=redcic&rnum=1#f939f2db9da55430 I set "interactive : True" in matplotlibrc. I also tried the other things I had been advised to do but I still have the same problem. Any other idea ? Thanks, C?dric From p.f.moore at gmail.com Thu May 24 12:09:50 2007 From: p.f.moore at gmail.com (Paul Moore) Date: 24 May 2007 09:09:50 -0700 Subject: of destructors, open files and garbage collection In-Reply-To: <1180021256.619953.80500@q66g2000hsg.googlegroups.com> References: <1180021256.619953.80500@q66g2000hsg.googlegroups.com> Message-ID: <1180022990.573608.81300@m36g2000hse.googlegroups.com> On 24 May, 16:40, "massimo s." wrote: > Now, what I thought is that if I call > > del(item) > > it will delete item and also all objects created inside item. Sort of, but it's a bit more subtle. You'll stop the name "item" from referring to your item - if nothing else refers to your item, it will be garbage collected (and __del__ will get called). But you can have other references, and in this case, __del__ is not called until *they* are released as well. Here's an example: >>> class C: ... def __del__(self): ... print "del called" ... >>> c = C() >>> # Now we have one reference to the object, in c. So delete it: ... >>> del c del called >>> # Just as we want. ... # Let's create a new C, but store a second reference to it in "a". ... >>> c = C() >>> a = c >>> # Now we can delete c, but a still refers to the object, so it isn't collected ... >>> del c >>> # But if we delete a, it is! ... >>> del a del called >>> OK. Now in your case, it's a bit more complex. You delete item. Suppose that causes the item to be garbage collected (there are no other references). Then, the item will be collected. This removes the attribute item.blah, which refers to the blah object. So the blah object is collected - *as long as no other references exist to that item*. Here's another example: >>> class B: ... def __init__(self): ... self.c = C() ... def __del__(self): ... print "B's delete called" ... >>> b = B() >>> del b B's delete called del called >>> # But if we have a second reference to b.c, that causes the object to stay alive: ... >>> b = B() >>> a = b.c >>> del b B's delete called >>> del a del called >>> See? Even though b was collected, its c attribute is still accessible under the name 'a', so it's kept alive. > Question 1: > This is not the case. I have to call del(item.blah), otherwise files > are kept open and the for loops end with a "Too many open files" > error. Why isn't __del__() called on objects belonging to a parent > object? Is it OK? Did the above help to clarify? > So I thought: > oh, ok, let's put del(self.blah) in item.__del__() > Question 2: > This doesn't work either. Why? It's not needed - it's not the item.blah reference that's keeping the blah object alive, it's another one. You *can* fix this by tracking down all the references and explicitly deleting them one by one, but that's not really the best answer. You're micromanaging stuff the garbage collector is supposed to handle for you. Ultimately, you've got a design problem, as you're holding onto stuff you no longer need. Whether you use del, or add an explicit blah.close() method to close the filehandle, you've got to understand when you're finished with a filehandle - if you know that, you can close it at that point. Here's a final example that may help: >>> a = [] >>> for i in range(10): ... a.append(C()) ... >>> # Lots of work, none of which uses a ... >>> a = [] # or del a del called del called del called del called del called del called del called del called del called del called See how you finished with all of the C objects right after the for loop, but they didn't get deleted until later? I suspect that's what's happening to you. If you cleared out the list (my a = [] statement) as soon as you're done with it, you get the resources back that much sooner. Hope this helps, Paul. From wagner at mail.webway.com.br Wed May 23 15:42:26 2007 From: wagner at mail.webway.com.br (wagner) Date: Wed, 23 May 2007 19:42:26 GMT Subject: Web archtecture using two layers in Phyton Message-ID: <20070523194226.3168.qmail@mailhost.wcf.org.br> Hello, I need to develop an web applications that meet the following requirements: - 2 layers: the first one is the user interface (browser) and the second one is the interaction with the operacional system of the server. - the second layer must be developed using Python. I'd like to know if it is possible to implement this system... making the second layer using python and the first layer using another web technologies like AJAX for example. Does anybody have any experience in developing python web applications? Maybe send me some links or documentation about it... The final goal is to make diferent user interfaces (layer 1) that can integrate with the second layer... for example, one web interface and one local interface using python+qt (example)... i don't know if this is possible and how can this be implemented... any help is aprreciated... Thanks in advance, Wagner. From sturlamolden at yahoo.no Wed May 2 14:22:41 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 2 May 2007 11:22:41 -0700 Subject: Microsoft's Dynamic Languages Runtime (DLR) Message-ID: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> On Monday Microsoft announced a new runtime for dynamic languages, which they call "DLR". It sits on top of the conventional .NET runtime (CLR) and provides services for dynamically typed languages like Python or Lisp (thus the cross-posting). Apparently is is distributed under a BSD-like open-source license. I am curious to know how it performs in comparison to CPython and an efficient compiled Lisp like CMUCL. Speed is a major problem with CPython but not with .NET or CMUCL, so it will be interesting to see how the DLR performs in comparison. It would be great to finally see a Python that runs on steroids, but knowing M$ bloatware my expectations are not too high. Has anyone looked at the DLR yet? What are your impression? Jim Hugunin har written about the DLR in his blog: http://blogs.msdn.com/hugunin/ To cite one of the comments: "Fuck this microsoft bollocks! You just stole the Lisp runtime ideas and fucked them up by stupid it salesman lingo." (Khrishna) Sturla Molden From 2007 at jmunch.dk Sun May 13 19:25:04 2007 From: 2007 at jmunch.dk (Anders J. Munch) Date: Mon, 14 May 2007 01:25:04 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1hy252p.1anf7sr1p4yp12N%aleax@mac.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <46478694$0$1412$426a34cc@news.free.fr> <1hy252p.1anf7sr1p4yp12N%aleax@mac.com> Message-ID: <46479eec$0$4166$ba624c82@nntp02.dk.telia.net> Alex Martelli wrote: > > Homoglyphic characters _introduced by accident_ should not be discounted > as a risk, as, it seems to me, was done early in this thread after the > issue had been mentioned. In the past, it has happened to me to > erroneously introduce such homoglyphs in a document I was preparing with > a word processor, by a slight error in the use of the system- provided > way for inserting characters not present on the keyboard; I found out > when later I went looking for the name I _thought_ I had input (but I > was looking for it spelled with the "right" glyph, not the one I had > actually used which looked just the same) and just could not find it. There's any number of things to be done about that. 1. # -*- encoding: ascii -*- (I'd like to see you sneak those homoglyphic characters past *that*.) 2. pychecker and pylint - I'm sure you realise what they could do for you. 3. Use a font that doesn't have those characters or deliberately makes them distinct (that could help web browsing safety too). I'm not discounting the problem, I just dont believe it's a big one. Can we chose a codepoint subset that doesn't have these dupes? - Anders From bbxx789_05ss at yahoo.com Thu May 31 15:34:12 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 31 May 2007 12:34:12 -0700 Subject: interesting take on python OO Message-ID: <1180640052.617845.172400@m36g2000hse.googlegroups.com> http://www.evolt.org/article/OO_programming_the_Python_way/18/449/ ----- The last article gives you the absolute basics of using Python. This time, we'll do the OO side of Python. Yes, Python: a true object- oriented language with classes, inheritance and all. Ok, my OO background comes from the usual suspects of OO language, C+ +, Java and Object Pascal (Delphi). So I have this preconceived idea about what Python OO should be. When I discover how OO is implemented in Python, my first reaction was: "What the is this s#~! ?" My idealism about OO is offended by what Python does with object and classes. It offers a new perspective on what can be done with classes and object. Over time Python has grown on me, and now I can really appreciate what it can do. So if you have the same reaction as mine, keep reading. It will grow on you as well. ---- lol From kw at codebykevin.com Mon May 21 23:41:58 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Mon, 21 May 2007 23:41:58 -0400 Subject: A few questions In-Reply-To: References: Message-ID: <46526686.9030301@codebykevin.com> jay wrote: > > Anyway, I had one more quick question... in order to run wxPython apps, > do I have to have MacPython, etc. loaded on each Mac (or PC) in order > for it to run any apps I write? Or is there a way to compile the code > to where I can distribute an app I write and the other users don't need > to load anything in order to run the app? Google for "py2app." It's the standard tool for distributing standalone Python apps on OS X. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From gagsl-py2 at yahoo.com.ar Thu May 3 09:09:34 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 03 May 2007 10:09:34 -0300 Subject: file Error References: <1178195977.521889.167910@p77g2000hsh.googlegroups.com> Message-ID: En Thu, 03 May 2007 09:39:37 -0300, escribi?: > Hi, > I am parsing an xml file,and using raw_input command to ask the > user to enter the file name.Ex > >>>> > Enter The ODX File Path: > > Suppose my code does not work properly,then in the python idle window > it shows something like this: > [...traceback...] > I want the inputfile prompt to appear regardless of > the error condition.I dont know where the problem lies.Can someone > help me out. - IDLE is a development environment - don't use it to actually run your program in production. - Instead of asking the user to type the file name, accept it as a parameter, that's what almost everyone else does in the world... It has many advantages: you can associate your program with the filename extension, you can use the "Send to..." menu, you can run it inside a batch file, you can drop a file over your program to be processed, etc. -- Gabriel Genellina From jm.suresh at gmail.com Tue May 15 11:40:55 2007 From: jm.suresh at gmail.com (jm.suresh@no.spam.gmail.com) Date: 15 May 2007 08:40:55 -0700 Subject: Storing and searching nodes of a tree In-Reply-To: References: <1179233407.473173.259110@h2g2000hsg.googlegroups.com> Message-ID: <1179243655.596897.6450@e51g2000hsg.googlegroups.com> On May 15, 6:33 pm, Marc 'BlackJack' Rintsch wrote: > In <1179233407.473173.259... at h2g2000hsg.googlegroups.com>, > > > > jm.sur... at no.spam.gmail.com wrote: > > I use these names as keys in a dictionary, and store node's data. > > Now given a name like "abc", I want to find the key with the following > > rule: > > If the key exists return the value > > If the key does not exist, return the value of the leaf node whose > > name is in the given name. For, "abc", it is "ab" . For, "ad", it is > > "a". > > > I suppose there must be a simpler solution to this problem. I > > implemented it like this: > > d = {'a':0, 'aa':12, 'ab':43, 'aaa':22, 'aab':343, 'ac':33} > > name = 'abc' > > key = max( [ x for x in d.iterkeys() if x in name] ) > > value = d[key] > > > I can change the data structure from dictinory to tuple of key,value > > pairs or any thing, and afford to keep them in a particular order. Is > > there any way I can speed up this as I have to do this for around 4000 > > times with tree size being ~5000. > > What about this: > > def search(tree, path): > while path: > result = tree.get(path) > if result is not None: > return result > path = path[:-1] > raise KeyError('path not on tree') > > Ciao, > Marc 'BlackJack' Rintsch If I have the tree in the dictionary, the code would like this, def search(tree, path): while path and not(tree.haskey(path)): path = path[:-1] if path: return tree[path] else: raise KeyError('path not on tree') Another qn -- dict.haskey() takes logn time, am I right? - Suresh From jstroud at mbi.ucla.edu Mon May 7 19:29:09 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 07 May 2007 16:29:09 -0700 Subject: SkimpyGimpy PNG canvas w/ Javascript mouse tracking In-Reply-To: <1178552561.117926.143230@l77g2000hsb.googlegroups.com> References: <1178552561.117926.143230@l77g2000hsb.googlegroups.com> Message-ID: aaronwmail-usenet at yahoo.com wrote: > SkimpyGimpy is a collection of tools for generating > HTML visual, PNG image, and WAVE audio components > for use in web based applications including CAPTCHA Can you advertise "CAPTCHA" as it is trademarked by Carnegie Mellon? James From steve at holdenweb.com Mon May 7 07:28:00 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 07 May 2007 07:28:00 -0400 Subject: Basic question about sockets and security In-Reply-To: References: Message-ID: Dave Dean wrote: > Hi all, > I'm just starting out in sockets/network programming, and I have a very > basic question...what are the 'security' implications of opening up a > socket? For example, suppose I've written a simple chat server and chat > client. The server opens a socket, listens on a port, and accepts incoming > connections. The clients open a socket and connect to the server. If the > server receives a message from a client, it sends that message out to every > client. When a client receives a message, it places it in a text widget. > So...are there inherent dangers in doing this? I have no real security > concern in the actual application, but can an open socket somehow allow > someone access to the rest of the computer? Is the 'security' of the socket > handled at the OS level (or within the socket module)? > I realize this isn't necessarily a Python question, but I wrote my > application in Python and I'm not sure where to start. I'll repost this > elsewhere if someone points me towards a more relevant group. It's something that all Python network newbies would like to know about (and OUGHT to know about), so it's a valid question. Essentially all opening a server socket does is to allow anyone who can connect to send data to your process. The difficulties usually begin when your process doesn't handle it in a secure way. Typically in a language like C this will involve failing to check its length, thereby allowing a malicious user to send an over-length input and (since local variables in CC are held on the stack) overwriting crucial data like function return addresses. Such exploits can be used to inject code into your process and have it run. Since server processes often run at a high level of privilege, so does the exploit code. Another way you can introduce vulnerabilities into your code is to craft inputs that, when incorporated into system calls, maliciously change the intent of your code. So suppose you had a command to allow a user to ping another computer, you might do (something like) os.system("ping "+address) where the address is what the user types in. However, if the user types in something like 192.168.12.13 ; rm /etc/passwd then your call becomes os.system("ping 192.168.12.13; rm /etc/passwd") and executes two shell statements, the second of which is rather destructive. So, as long as you aren't passing any user data to the operating system in any way shape or form you are probably in reasonably good shape. But this is easier to do than you might imagine, and you always need to ask yourself what the downside potential of malicious inputs might be. Python's libraries are well written by and large, and the language itself checks the bounds of all data structure accesses, making buffer overflow exploits of the type I described much less of a risk, but the OS vulnerabilities still remain for you to avoid by careful coding. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From castironpi at gmail.com Mon May 7 20:59:18 2007 From: castironpi at gmail.com (castironpi at gmail.com) Date: 7 May 2007 17:59:18 -0700 Subject: inspected console In-Reply-To: <1178581950.683620.251980@y80g2000hsf.googlegroups.com> References: <1178581950.683620.251980@y80g2000hsf.googlegroups.com> Message-ID: <1178585958.578959.149680@e65g2000hsc.googlegroups.com> On May 7, 6:52 pm, castiro... at gmail.com wrote: > Presents a console permitting inspection. Input as well as output > saved in Python-readable form. > Python 2.5.1 memoryconsole4.py logging to My Documents\console.log>>> class A: > > ... def f( self ): > ... print 2 > ...>>> a=A() > >>> import inspect > >>> inspect.getsource( a.f ) > > '\tdef f( self ):\n\t\tprint 2\n' > > This enabled by a log file, optionally set to console.log. Contents > are: > > #Mon May 07 2007 06:33:42 PM Python win32 2.5.1 in memoryconsole4.py > class A: > def f( self ): > print 2 > > a=A() > import inspect > inspect.getsource( a.f ) > #fb: '\tdef f( self ):\n\t\tprint 2\n' > > Line 10 Microsoft Win32 convenience binding; line 49 a little > confusing. Give it a shot. > > from code import InteractiveConsole > import sys > from os import environ > from datetime import datetime > from StringIO import StringIO > from re import sub > from os.path import join,split,abspath > > class LoggedStdOut(StringIO): > deflog= environ['USERPROFILE']+\ > '\\My Documents\\console.log' > def __init__( self, log=None ): > StringIO.__init__( self ) > self.stdout= None > self.trip,self.head= True,'' > self.logname= log or LoggedStdOut.deflog > self.prettyname=join(split(split(abspath( > self.logname))[0])[1],split(abspath(self.logname))[1]) > for x,_ in enumerate( open( self.logname,'r' ) ): continue > self._lineno= x #can use linecache > self._log= open( self.logname,'a' ) > def catch( self,head='#fb: ' ): > self.stdout= sys.stdout > sys.stdout= self > self.head= head > self.trip= True > def throw( self ): > sys.stdout= self.stdout > self.stdout= None > def getlineno( self ): > return self._lineno > def logwrite( self, data ): > self._log.write( data ) > self._lineno+= data.count('\n') > def logflush( self ): > self._log.flush() > def write( self, data ): > datal= sub( '\n([^$])','\n%s\\1'%self.head,data ) > if self.trip: self.logwrite( self.head ) > self.logwrite( datal ) > self.trip= data.endswith('\n') > return self.stdout.write( data ) > def writelines( self, data ): > raise 'Branch uncoded' > > class LoggedInteractiveConsole(InteractiveConsole): > def __init__( self,log=None,locals=None,filename=None ): > self.out= LoggedStdOut( log ) > if filename is None: filename= split(self.out.logname)[1] > InteractiveConsole.__init__( self,locals,filename ) > self.locals.update( __logname__= abspath( > self.out.logname ) ) > def push( self,line ): > self.out.logwrite( '%s\n'%line ) > self.out.logflush() > self.out.catch() > more= InteractiveConsole.push( self,line ) > self.out.throw() > return more > def write( self,data ): > return sys.stdout.write( data ) > def interact( self,banner=None,*args ): > self.out.logwrite( '\n#%s Python %s %s in %s\n'%\ > ( datetime.now().strftime( > '%a %b %d %Y %I:%M:%S %p' ), > sys.platform,sys.version.split()[0], > split(sys.argv[0])[1] ) ) > if banner is None: banner=\ > "Python %s %s logging to %s"%\ > ( sys.version.split()[0],split(sys.argv[0])[1], > self.out.prettyname ) > return InteractiveConsole.interact( self,banner,*args ) > > import compiler > import linecache > class NotatedConsole(LoggedInteractiveConsole): > """-Code object- intercepted in runsource, and rerun with > stored source before runsource. Built-in runsource > does not modify source between call and runcode.""" > def runsource( self,sc,filename='',*args ): > self._runsourceargs= sc,filename > return LoggedInteractiveConsole.runsource( self,sc, > filename,*args ) > def runcode( self,*args ): > sc,filename= self._runsourceargs > linecache.checkcache( filename ) > #custom second compile (fourth actually) > t= compiler.parse( sc ) > compiler.misc.set_filename( filename,t ) > def set_lineno( tree, initlineno ): > worklist= [ tree ] > while worklist: > node= worklist.pop( 0 ) > if node.lineno is not None: > node.lineno+= initlineno > worklist.extend( node.getChildNodes() ) > set_lineno( t,self.out.getlineno()-len( self.buffer )+1 ) > code= compiler.pycodegen.\ > InteractiveCodeGenerator( t ).getCode() > LoggedInteractiveConsole.runcode( self,code ) > linecache.checkcache( filename ) > > if __name__=='__main__': > console= NotatedConsole() > console.interact() Console-defined objects can be pickled as well. ">>>edit()" opens console.log. Editor objects are pickled between statements. Python 2.5.1 furtherconsoles-display.py logging to My Documents \console.log >>> class A: ... b=0 ... >>> from pickle import loads,dumps >>> loads(dumps(A)) >>> loads(dumps(A)).b 0 >>> edit() Loaded ok and the few lines from console.log: #Mon May 07 2007 07:55:30 PM Python win32 2.5.1 in furtherconsoles- display.py class A: b=0 from pickle import loads,dumps loads(dumps(A)) #fb: loads(dumps(A)).b #fb: 0 edit() Hard coded paths on lines 24 and 67. Hope that's copy-and-pasteable import memoryconsole4 as memoryconsole from os.path import join,exists,split,abspath from os import environ from sys import argv import sys import cPickle as pickle from subprocess import Popen from datetime import datetime,timedelta class Editors: """Pickled after every statement.""" def edit( self,filename=None ): assert hasattr( self,'_cmdlinestr' ) and hasattr( self,'console' ) if filename is None: filename= abspath( self.console.out.logname ) parms= { 'filename': filename, 'loglen': self.console.out.getlineno() +len(self.console.buffer)+1 } Popen( self._cmdlinestr % parms ) print >>sys.stderr, "Loaded ok" def __repr__( self ): return '<%s at %i: %s>'%(self.__class__,id(self),repr( [ x for x in dir(self) if not x.startswith('__') ] )) def __call__( self,*args ): self.edit( *args )#what find default? class EditorsConsole(memoryconsole.NotatedConsole): defdat= join( environ['USERPROFILE'],'My Documents\ \consoleeditor.pickle' ) def __init__( self,cmdlinestr,datname=None,*args,**kwargs ): memoryconsole.NotatedConsole.__init__( self,*args,**kwargs ) self._datname= datname or self.defdat if exists( self._datname ): self.edit= pickle.load( open( self._datname,'rb' ) ) else: self.edit= Editors() self.edit._cmdlinestr= cmdlinestr self.locals.update( edit=self.edit ) self.edit.console= self self.lasttimestamp= datetime.now() def push( self,*args ): more= memoryconsole.NotatedConsole.push( self,*args ) if not more and datetime.now()- self.lasttimestamp > timedelta( minutes= 25 ): self.lasttimestamp= datetime.now() self.out.logwrite( '#%s in %s\n'%\ ( self.lasttimestamp.strftime( '%a %b %d %Y %I:%M:%S %p' ),split(argv[0])[1] ) ) del self.edit.console pickle.dump( self.edit,open( self._datname,'wb' ) ) #don't pickle me self.edit.console= self return more def __repr__( self ): return '<%s at %i: %s>'%(self.__class__,id(self),repr( [ x for x in dir(self) if not x.startswith('__') ] )) import compiler as c from memory import Memory import imp from sys import modules class ModuleConsole(EditorsConsole): def __init__( self,log=None,locals=None,filename=None ): EditorsConsole.__init__( self,log,locals,filename ) self.workmodule= imp.new_module( 'workmodule' ) self.workmodule.__file__= self.out.logname modules[self.workmodule.__name__]= self.workmodule self.locals.update( workmodule=self.workmodule, __name__=self.workmodule.__name__ ) self.locals.update( __file__=self.workmodule.__file__ )#may omit __logname__ del self.locals['__logname__'] def runcode( self,*args ): EditorsConsole.runcode( self,*args ) for k,v in self.locals.iteritems(): setattr( self.workmodule,k,v ) if __name__=='__main__': editorscmdlinestr= '"%s" "%%(filename)s" -cursor %%(loglen)i: 1'%join(environ['PROGRAMFILES'],'editplus 2\\editplus.exe') console= ModuleConsole(editorscmdlinestr) console.interact() From gh at gregor-horvath.com Wed May 16 03:30:23 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Wed, 16 May 2007 09:30:23 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464aaee8$0$10188$9b4e6d93@newsspool4.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <46478694$0$1412$426a34cc@news.free.fr> <1hy252p.1anf7sr1p4yp12N%aleax@mac.com> <464988a4$0$20289$9b4e6d93@newsspool3.arcor-online.net> <464aaee8$0$10188$9b4e6d93@newsspool4.arcor-online.net> Message-ID: Ren? Fleschenberg schrieb: > today, to the best of my knowledge. And "in some form or another" > basically means that the PEP would create more possibilities for things > to go wrong. That things can already go wrong today does not mean that > it does not matter if we create more occasions were things can go wrong > even worse. Following this logic we should not add any new features at all, because all of them can go wrong and can be used the wrong way. I love Python because it does not dictate how to do things. I do not need a ASCII-Dictator, I can judge myself when to use this feature and when to avoid it, like any other feature. Gregor From tjreedy at udel.edu Mon May 14 14:20:40 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 14 May 2007 14:20:40 -0400 Subject: Recursion limit problems References: <1178921877.442519.165740@u30g2000hsc.googlegroups.com> <1179156916.706892.144770@y80g2000hsf.googlegroups.com> Message-ID: "elventear" wrote in message news:1179156916.706892.144770 at y80g2000hsf.googlegroups.com... On May 12, 12:25 am, "Gabriel Genellina" wrote: > En Fri, 11 May 2007 19:17:57 -0300, elventear > escribi?: > "The only required property is that objects which compare equal have the > same hash value; it is advised to somehow mix together (e.g., using > exclusive or) the hash values for the components of the object that also > play a part in comparison of objects. If a class does not define a > __cmp__() method it should not define a __hash__() operation either; if > it I suspect/believe that the above should be __cmp__() or __eq__() both for uniformity with the usage below and also because objects do not need to be ordered (__cmp__) to be used as dict keys. > defines __cmp__() or __eq__() but not __hash__(), its instances will not > be usable as dictionary keys. If a class defines mutable objects and > implements a __cmp__() or __eq__() method, it should not implement > __hash__(), since the dictionary implementation requires that a key's > hash > value is immutable (if the object's hash value changes, it will be in the > wrong hash bucket)." Thanks for the information. I have a doubt regarding the wording in the paragraph on top. Since I am defining a hash for my object, it makes sense that I should be able to define equality. But I am not sure about inequality, in my specific case. The paragraph above mentions that __cmp__ should be defined if I define a __hash__, but in the default behaviour of __cmp__ inequality is included. So what should I do? Also why is equality necessary to be defined? Do dicts only use __hash__ or do they use equality as well? =============== Dicts first compare hashes and if they are equal, then check equality. If two unequal strings have the same hash value, as is possible of course (given only 2**32 possible hashes and many more possible strings), both can still be used as different keys. Ditto for unequal numbers. Or for a number and string with equal hashes. And so on. The first quoted sentence, about mixing, is directed at minimizing such hash collisions. Terry Jan Reedy From aisaac at american.edu Thu May 3 13:08:56 2007 From: aisaac at american.edu (Alan Isaac) Date: Thu, 03 May 2007 17:08:56 GMT Subject: relative import broken? References: <1hxa9x3.c0unyd1jw7vu9N%aleax@mac.com> <1hxcdkq.47p2r6beuctcN%aleax@mac.com> Message-ID: "Alex Martelli" wrote in message news:1hxcdkq.47p2r6beuctcN%aleax at mac.com... > Very simply, PEP 328 explains: > """ > Relative Imports and __name__ > > Relative imports use a module's __name__ attribute to determine that > module's position in the package hierarchy. If the module's name does > not contain any package information (e.g. it is set to '__main__') then > relative imports are resolved as if the module were a top level module, > regardless of where the module is actually located on the file system. > """ To change my question somewhat, can you give me an example where this behavior (when __name__ is '__main__') would be useful for a script? (I.e., more useful than importing relative to the directory holding the script, as indicated by __file__.) Thanks, Alan Isaac From nufuhsus at gmail.com Fri May 11 17:22:06 2007 From: nufuhsus at gmail.com (nufuhsus at gmail.com) Date: 11 May 2007 14:22:06 -0700 Subject: Interesting list Validity (True/False) In-Reply-To: References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> <1178917940.363627.216580@y5g2000hsa.googlegroups.com> Message-ID: <1178918526.243360.235280@y5g2000hsa.googlegroups.com> On May 11, 5:19 pm, Carsten Haese wrote: > On Fri, 2007-05-11 at 14:12 -0700, nufuh... at gmail.com wrote: > > However, how would you test for the falsness of the object arg? > > if not arg: > # stuff > > -- > Carsten Haesehttp://informixdb.sourceforge.net I think that is the ticket Carsten! Thanks for all the good information all y'all. From m.yanowitz at kearfott.com Mon May 14 15:03:43 2007 From: m.yanowitz at kearfott.com (Michael Yanowitz) Date: Mon, 14 May 2007 15:03:43 -0400 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <4648B002.3050508@web.de> Message-ID: <005701c7965a$97244c70$0d7d12ac@kearfott.com> Let me guess - the next step will be to restrict the identifiers to be at most 6 characters long. -----Original Message----- From: python-list-bounces+m.yanowitz=kearfott.com at python.org [mailto:python-list-bounces+m.yanowitz=kearfott.com at python.org]On Behalf Of Stefan Behnel Sent: Monday, May 14, 2007 2:53 PM To: python-list at python.org Subject: Re: PEP 3131: Supporting Non-ASCII Identifiers Marc 'BlackJack' Rintsch schrieb: > In , Michel Claveau > wrote: > >> And Il1 O0 ? > > Hm, we should ban digits from identifier names. :-) Ah, good idea - and capital letters also. After all, they are rare enough in English to just plain ignore their existance. Stefan :) -- http://mail.python.org/mailman/listinfo/python-list From eino.makitalo at gmail.com Tue May 8 17:00:13 2007 From: eino.makitalo at gmail.com (eino) Date: 8 May 2007 14:00:13 -0700 Subject: Question about file handles and windows handles @ Windows Operating Systems Message-ID: <1178658013.349284.94980@n59g2000hsh.googlegroups.com> Very hard to find right function... If I open file fname="c:\\temp\\foobar.txt" file_foobar = file(fname) file_foobar.fileno() returns 3 becausee of unix like library used in windows python.... If I'd like to get to known what windows handle it has hfile=win32file.CreateFile( ff,win32con.GENERIC_READ| win32con.GENERIC_WRITE,win32con.FILE_SHARE_READ| win32con.FILE_SHARE_WRITE,None, win32con.OPEN_ALWAYS,win32con.FILE_ATTRIBUTE_NORMAL , 0 ) hfile.handle returns 88 Are there any function to get windows handle of file which is already opened with built-in file-function. -Eino From vatamane at gmail.com Wed May 9 20:11:01 2007 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 9 May 2007 17:11:01 -0700 Subject: Sorting attributes by catagory In-Reply-To: References: Message-ID: <1178755860.993987.312700@e51g2000hsg.googlegroups.com> On May 9, 11:32 am, Ron Adam wrote: > This is for a new version of pydoc if I can get the class attributes sorted > out. The module level attributes aren't too difficult to categorize. > > (I might be just too tired to see the obvious.) > > The original pydoc did this a somewhat round about way, so I would like to > find a more direct method if possible. > > Where dir(obj) is used to get all attributes of a module or class. And > they are then sorted into categories depending on what they are. > > (In order of precedence.) > > For modules: > > - imported_items (defined in another module, > or is another module) > - classes > - functions > - other_objects (everything else) > > For classes: > > - from_else_where (object created someplace else) > - inherited_attributes (from parents classes or type) > - static_methods_here > - class_methods_here > - other_methods > - properties > - getset_descriptors > - other_descriptors > - other_attributes (everything else) > > A single function that accepts an object and can return one of the above > (or equivalent) strings would be ideal. Finer grained categorizing is ok > as long as they don't overlap more than one group. > > It seems I can get some of these fairly easy with the inspect module, but > others I need to test in multiple ways. > > Any ideas? > > Cheers, > Ron Ron, Consider using epydoc if you can. Epydoc will sort the methods and it will also let you use custom CSS style sheets for the final HTML output. Check out the documentation of my PyDBTable module. http://www.psipy.com/PyDBTable -Nick Vatamaniuc From creamy.loads at gmail.com Wed May 23 14:45:24 2007 From: creamy.loads at gmail.com (creamy.loads at gmail.com) Date: 23 May 2007 11:45:24 -0700 Subject: * Unlimited BARTAB! Message-ID: <1179945924.797585.221590@x18g2000prd.googlegroups.com> http://hootys.blogspot.com/ - Free Downloads! Amazing Deals. From jstroud at mbi.ucla.edu Wed May 23 20:26:59 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 23 May 2007 17:26:59 -0700 Subject: Creating Graphs for the Web In-Reply-To: References: <1179955032.556481.170260@g4g2000hsf.googlegroups.com> Message-ID: Michael Bentley wrote: > > On May 23, 2007, at 4:17 PM, erikcw wrote: > >> I'm working on a django powered website, and need to dynamically >> generate some graphs (bar, pie, and line) from users' data stored in >> MySQL. >> >> Can anyone recommend a good library I can use for this? > > > Matplotlib! > > In the perennial spirit of one-upsmanship (or one-sidewaysmanship at the very least): Pychart! James From aaronwmail-usenet at yahoo.com Mon May 7 19:47:34 2007 From: aaronwmail-usenet at yahoo.com (aaronwmail-usenet at yahoo.com) Date: 7 May 2007 16:47:34 -0700 Subject: SkimpyGimpy PNG canvas w/ Javascript mouse tracking In-Reply-To: References: <1178552561.117926.143230@l77g2000hsb.googlegroups.com> Message-ID: <1178581654.759964.114680@n59g2000hsh.googlegroups.com> re: http://skimpygimpy.sourceforge.net On May 7, 7:29 pm, James Stroud asks: > Can you advertise "CAPTCHA" as it is trademarked by Carnegie Mellon? > > James I can easily forward them a generous portion of my earnings from this project if needed :). Actually I think the term is in common use like "Kleenex". A quick glance at http://www.lanapsoft.com/products.html shows no mention of CMU. -- Aaron Watters === sometimes if something doesn't seem to make sense it's because it makes no sense From apardon at forel.vub.ac.be Wed May 23 07:42:12 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 23 May 2007 11:42:12 GMT Subject: Basic Class/Instance Question References: <1179918439.085344.171330@u30g2000hsc.googlegroups.com> <46542543$0$6795$426a74cc@news.free.fr> Message-ID: On 2007-05-23, Bruno Desthuilliers wrote: > Siah a ?crit : >> Ready to go insane here. Class A, taking on a default value for a >> variable. Instantiating two separate objects of A() gives me a shared >> val list object. Just see the example bellow: >> >> >> class A(object): >> def __init__(self, val=[]): >> self.val=val >> >> obj1 = A() >> obj2 = A() >> >> print obj1 is obj2 # False - as expected >> print obj1.val is obj2.val # True! - Why... oh god WHY > > >> >> ----------- >> Using python 2.4. Is this a bug with this version of python? How can I >> trust the rest of the universe is still in place? Could she still like >> me? Many questions I have. Lets start with the python problem for now. > > This is a FAQ. Default arguments are only evaled once - when the def > statement is evaled (which is usually at import time). The solution is > simple: don't use mutable objects as default arguments: An immutable object would have given the same behaviour in this case class A(object): def __init__(self, val = ()): self.val=val obj1 = A() obj2 = A() print obj1 is obj2 # False print obj1.val is obj2.val # True From bblais at bryant.edu Thu May 24 10:22:23 2007 From: bblais at bryant.edu (Brian Blais) Date: Thu, 24 May 2007 10:22:23 -0400 Subject: Python and GUI In-Reply-To: References: <1179761984.704369.116310@b40g2000prd.googlegroups.com> <4651CDBC.1070508@ulmcnett.com> Message-ID: <46559F9F.4010807@bryant.edu> Peter Decker wrote: > On 5/21/07, Paul McNett

wrote: > >> Shameless plug: consider using Dabo on top of wxPython - we feel it >> makes wxPython even easier and more pythonic, but admittedly there's a >> bit of a learning curve there too. Even though Dabo is a full >> application framework originally meant for desktop database >> applications, it is modular and you can choose to only use the UI >> bits... http://dabodev.com > > I second this. I used (and struggled!) with wxPython for over a year. > The results were great, but I hated coding it. I switched to the Dabo > UI wrapper, and stuff that used to take me a day to create is now done > in an hour or two. > Hello, I'd like to ask the Python community about this, because it seems to me that there is a real need that is not being met very effectively. Almost everyone agrees that wxPython looks great and is very powerful, and for full-fledged cross-platform applications is nearly the best, if not *the* best, choice as far as *function* and *look* are concerned. The next sentence out of Python programmers seems to be "...but wx is written in C++ and definitely shows, even in the Python port". It's just not very pythonic. Then there is Dabo, which I personally have had problems with. I am looking for a pythonic, professional looking GUI framework. I first tried dabo with python 2.4, and had to install sqlite, which seemed a bit odd for trying to just get a GUI framework...I understand why, but when you're looking for one thing, having it tied to a completely different thing feels a little strange. I never got it working in Python2.5, either on Linux or OS X, and the problem is most definitely mine and I didn't have the patience to debug it. I am really not trying to diss dabo here, because there enough people who swear by it, that it must be doing many things right. My problem with Dabo is not what it is, it is what I am looking for...a pythonic GUI framework. Coming from Unix, I generally feel that a program should try to do one thing, and one thing well. To mix really different functionality seems to me to be a bad idea. If you can use the GUI parts separately, why not package it separately? One might find a lot of users who only what that. Finally, consider wax (http://zephyrfalcon.org/labs/wax.html). In my view, this is *exactly* what python needs, and its not being maintained anymore as far as I can tell. What I like about it is: 1) it is small...I can include the entire wax distribution in my app with only a 780k footprint. 2) it is a very thin layer on wx, so when something doesn't quite work, I can immediately fall back onto wx, mixing and matching wax and wx objects. it's just that the wax objects have more pythonic calling and use properties Is there a reason that the port of wxPython doesn't include wax, or something similar? It would seem pretty straightforward, when porting the wx to Python, to simply include such a wrapper. I wish I were more clever, and had more time, to take over the maintenance of wax because I think it is the most straightforward, practical, and pythonic solution out there. Do others think like me here? thanks, Brian Blais -- ----------------- bblais at bryant.edu http://web.bryant.edu/~bblais From gagsl-py2 at yahoo.com.ar Tue May 15 23:18:49 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 16 May 2007 00:18:49 -0300 Subject: Quote aware split References: <41749080705151750m3367c65dy4d1ae6ca66c2a16b@mail.gmail.com> Message-ID: En Tue, 15 May 2007 21:50:15 -0300, Ondrej Baudys escribi?: > After trawling through the archives for a simple quote aware split > implementation (ie string.split-alike that only splits outside of > matching quote) and coming up short, I implemented a quick and dirty > function that suits my purposes. Just a small comment: > def qsplit(chars, sep, quote="'"): > """ Quote aware split """ > qcount = 0 > splitpoints = [-1] # ie. seperator char found before first letter ;) > for index, c in enumerate(chars): > if c is quote: > qcount += 1 > if c is sep and qcount % 2 == 0: > splitpoints.append(index) The "is" operator checks object *identity*, that is, if both operands are actually the same object. It may or may not work here, depending on many implementation details. You really should check if they are *equal* instead: if c == quote: qcount += 1 if c == sep and qcount % 2 == 0: splitpoints.append(index) See: py> x='a' py> y='A'.lower() py> y 'a' py> x==y True py> x is y False -- Gabriel Genellina From mccredie at gmail.com Wed May 30 18:25:34 2007 From: mccredie at gmail.com (Matimus) Date: 30 May 2007 15:25:34 -0700 Subject: replace the base class In-Reply-To: <1180557641.633245.189900@p77g2000hsh.googlegroups.com> References: <1180557641.633245.189900@p77g2000hsh.googlegroups.com> Message-ID: <1180563934.099612.244460@q19g2000prn.googlegroups.com> This is a rather simplistic example, but you may be able to use a mixin class to achieve what you need. The idea is that you write a class that overrides only what is needed to add the new functionality. For you it would be Color. [code] class Graph(object): def _foo(self): print "Graph._foo" class Color(object): def _foo(self): print "Color._foo" class Circle(Graph): def bar(self): self._foo() class ColorCircle(Color,Circle): # the order of parent classes is important pass if __name__ == "__main__": c1 = Circle() c2 = ColorCircle() c1.bar() #prints: Graph._foo c2.bar() #pritns: Color._foo [/code] You might not have to do anything already. Try this and see if it works: [code] ColorCircle(ColorGraph,Circle): pass [/code] Note that you will probably have to create an __init__ method, and explicitly call the __init__ methods for the base classes. If the __init__ for Circle ends up calling the __init__ method from Graph, you may have issues. That is why the Color mixin that I created inherited from object not Graph. It helps to avoid clashing __init__ methods. Matt From gagsl-py2 at yahoo.com.ar Thu May 17 01:29:35 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 17 May 2007 02:29:35 -0300 Subject: cPickle.dumps differs from Pickle.dumps; looks like a bug. References: <1179335622.006820.22460@q23g2000hsg.googlegroups.com> <1179352356.025319.43310@w5g2000hsg.googlegroups.com> <5f56302b0705161524u5902320cy11e0f67a798e8089@mail.gmail.com> <4866bea60705161539q19378836j108750b3e287132e@mail.gmail.com> Message-ID: En Thu, 17 May 2007 02:09:02 -0300, Josiah Carlson escribi?: > All strings of length 0 (there is 1) and 1 (there are 256) are interned. I thought it was the case too, but not always: py> a = "a" py> b = "A".lower() py> a==b True py> a is b False py> a is intern(a) True py> b is intern(b) False -- Gabriel Genellina From kirk at jobspam/mapssluder.net Tue May 15 12:43:16 2007 From: kirk at jobspam/mapssluder.net (Kirk Job Sluder) Date: Tue, 15 May 2007 16:43:16 GMT Subject: Trying to choose between python and java References: Message-ID: Anthony Irwin writes: > #1 Does python have something like javas .jar packages. A jar file > contains all the program files and you can execute the program with > java -jar program.jar Python does this with eggs and distutils that copy your files into the proper location. For os x you also have py2applet which creates an application bundle that can be put onto a disk image and dragged into the Applications folder. A similar utility exists for MSWin, but I've not used it. > #2 What database do people recommend for using with python that is > easy to distribute across linux, mac, windows. pysqlite3 for python is included in python 2.5 and can be added to python 2.4. For java you would probably use HyperSonic or Derby. At least one winner in the java camp for me is db4o, which is a bit like shelve on steroids with an object-oriented query language. > #4 If I write a program a test it with python-wxgtk2.6 under linux are > the program windows likely to look right under windows and mac? There are enough idiom differences between OS X, MSWin, Gnome and Qt that native look and feel is very, very difficult to achieve. Java comes close with SWT. WxPython applications seem to port badly to OS X, and are tricky to build into an application bundle. As a example of how these differences in idioms can become problems, Mozilla Thunderbird on OS X regularly has issue with unmodified keybindings. With Thunderbird 2.0 shift-J marks a message as junk, even when you are entering text into a dialog box. The tkinter application Leo uses the control key as a modifier on OS X rather than the command key. The basic point is that you need to test on all platforms you want to develop for. My very biased view of the domain is as follows: OS X/Cocoa: PyObjC KDE + Win + OS X/X11: PyQt Win + Gnome + OS X/Carbon: wxPython or Jython+SWT Simple, easy, and universal: tkinter Rich, complex, and universal: Jython+Swing > Also does anyone else have any useful comments about python vs java > without starting a flame war. I've found it useful to use a mix of pure java and jython, although I'm still working through some gotchas in regards to compiling jython code that's acessible from java. > -- > Kind Regards, > Anthony Irwin > > http://www.irwinresources.com > http://www.makehomebusiness.com > email: anthony at above domains, - www. -- Kirk Job Sluder From kakeez at hotmail.com Wed May 30 14:03:31 2007 From: kakeez at hotmail.com (Karim Ali) Date: Wed, 30 May 2007 18:03:31 +0000 Subject: Appending a log file and see progress as program executes Message-ID: Hi, I am writing a program that will take several days to execute :) and would like to append to a log file but be able to open that file at any time and see the errors that have occured. So this is what I am doing: ---------------------------------------------- flog = open('out.log', 'a') .... when needed: sys.stdout=flog print "error message" ------------------------------------------------ This will print directly to log. I use sys.stdout so i can quickly (in code) change back and forth between errors displayed on screen and errors logged.. This works great. The only problem is that I cant see anything in the log file when I try to open it say with notepad while the program is running...and this is not good at all! Any suggestions are appreciated. Karim _________________________________________________________________ See Fireworks On Live Image Search http://search.live.com/images/results.aspx?q=Fireworks&mkt=en-ca&FORM=SERNEP From john at datavoiceint.com Wed May 2 13:21:41 2007 From: john at datavoiceint.com (HMS Surprise) Date: 2 May 2007 10:21:41 -0700 Subject: Time functions In-Reply-To: References: <1178125256.640115.26480@o5g2000hsb.googlegroups.com> Message-ID: <1178126501.245493.210150@y80g2000hsf.googlegroups.com> On May 2, 12:03 pm, Marc 'BlackJack' Rintsch wrote: > In <1178125256.640115.26... at o5g2000hsb.googlegroups.com>, HMS Surprise > wrote: > > > I wish to generate a datetime string that has the following format. > > '05/02/2007 12:46'. The leading zeros are required. > > > I found '14.2 time' in the library reference and have pulled in > > localtime. Are there any formatting functions available or do I need > > to make my own? Perhaps there is something similar to C's printf > > formatting. > > You mean like `time.strftime()`!? :-) > > Ciao, > Marc 'BlackJack' Rintsch Thanks for posting. I think I have an import misconception. I use import from time localtime, strftime t = strftime('%m/%d/%Y %H:%M', localtime()) This works. How would one use it with the module name pre-pended? thanx, jvh From ivoras at __fer.hr__ Sun May 13 18:49:13 2007 From: ivoras at __fer.hr__ (Ivan Voras) Date: Mon, 14 May 2007 00:49:13 +0200 Subject: __dict__ for instances? In-Reply-To: <46477c9d$0$1408$426a74cc@news.free.fr> References: <46472764$0$23138$9b4e6d93@newsspool1.arcor-online.net> <46477c9d$0$1408$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: >> "WARNING: "on_button_clicked" not callable or a tuple" > > Please post the relevant code and the full traceback. The code: Class W: def __init__(self): self.xml = gtk.glade.XML("glade/mainwin.glade") self.window = self.xml.get_widget("mainwin") self.xml.signal_autoconnect(self) w = W() gtk.main() The error (not an exception, only the message appears and the handler doesn't work): ** (finstall.py:7551): WARNING **: handler for 'on_button_next_clicked' not callable or a tuple (the file has some 20 lines, not 7551) -- (\__/) (O.o) (> < ) This is Bunny. Copy Bunny into your signature to help him on his way to world domination! -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 258 bytes Desc: OpenPGP digital signature URL: From mensanator at aol.com Wed May 16 18:59:12 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 16 May 2007 15:59:12 -0700 Subject: python shell In-Reply-To: <1179337107.842668.112690@k79g2000hse.googlegroups.com> References: <1179337107.842668.112690@k79g2000hse.googlegroups.com> Message-ID: <1179356351.981354.175100@q23g2000hsg.googlegroups.com> On May 16, 12:38 pm, Krypto wrote: > I have been using python shell to test small parts of the big program. > What other ways can I use the shell effectively. My mentor told me > that you can virtually do anything from testing your program to > anything in the shell. Any incite would be useful. Yeah? Well tell your mentor he can take his programs and his literal interpretaions to the other side of the river!! Oh...wait. Did you mean "insight"? One thing that covers a LOT of ground is you can run other programs from the shell and capture their output (assuming the output is text to stdout). For example, I can run the program factor!.exe from the command line: C:\python25\user>factor!.exe 27 PRIME_FACTOR 3 PRIME_FACTOR 3 PRIME_FACTOR 3 But I can also run it from the Python shell: >>> import os >>> f = os.popen("factor! 27").readlines() >>> f ['PRIME_FACTOR 3\n', 'PRIME_FACTOR 3\n', 'PRIME_FACTOR 3\n'] >>> q = [int(i.split()[1]) for i in f] >>> q [3, 3, 3] Now, you've got the factors without having to write your own factoring program and you never had to leave the shell. What more could you ask for? From rene at korteklippe.de Tue May 15 09:27:29 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 15 May 2007 15:27:29 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> <4648294F.2000704@web.de> <46487a6c$0$2400$426a74cc@news.free.fr> <4649a1b6$0$23131$9b4e6d93@newsspool1.arcor-online.net> <4649af35$0$10195$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <4649b53f$0$20299$9b4e6d93@newsspool3.arcor-online.net> Thorsten Kampe schrieb: > It has nothing to do with that. It simply allows people to write their > own identifier names with their native character set without using > dodgy transcriptions (that might not even exist). There is no sense in > making people write "ueber" instead of "?ber". That's 20th century > thinking and archaic. "ueber" at least displays correctly on virtually any computer system in use today, which for example makes it possible to read and process tracebacks, something that might actually not only concern developers, but also end-users. -- Ren? From silverfrequent at gmail.com Sun May 20 22:33:24 2007 From: silverfrequent at gmail.com (Silver Rock) Date: Sun, 20 May 2007 23:33:24 -0300 Subject: Python assignment loop Message-ID: i need to do something like this: ### import wx x=number for i in range(500): "var"+str(i)=ClassXYZ(...,x+i,...) #.... code y=number for i in range(y): ClassAAAA(object_called_by_the_string("var"+str(i)),...) ### i can't figure out how to do this, and could not find it on the web. c. From carsten at uniqsys.com Sat May 12 13:56:28 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 12 May 2007 13:56:28 -0400 Subject: Interesting list Validity (True/False) In-Reply-To: <1178918808.091358.233740@o5g2000hsb.googlegroups.com> References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> <1178914190.166662.285410@p77g2000hsh.googlegroups.com> <1178915791.584216.293130@l77g2000hsb.googlegroups.com> <1178918808.091358.233740@o5g2000hsb.googlegroups.com> Message-ID: <1178992588.3243.12.camel@localhost.localdomain> On Fri, 2007-05-11 at 14:26 -0700, mensanator at aol.com wrote: > if arg==True: > > tests the type property (whether a list is a boolean). That sounds nonsensical and incorrect. Please explain what you mean. "if arg==True" tests whether the object known as arg is equal to the object known as True. Regards, -- Carsten Haese http://informixdb.sourceforge.net From dotancohen at gmail.com Fri May 18 01:18:45 2007 From: dotancohen at gmail.com (Dotan Cohen) Date: Fri, 18 May 2007 08:18:45 +0300 Subject: List Moderator Message-ID: <880dece00705172218n71123b55q531ec0c5e500f208@mail.gmail.com> Is this list not moderated? I'm really not interested in Britney Spears boobs. All the spam on this list is from the same place, it should be very easy to filter. Dotan Cohen http://lyricslist.com/ http://what-is-what.com/ From grflanagan at yahoo.co.uk Wed May 16 10:07:20 2007 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 16 May 2007 07:07:20 -0700 Subject: Newbie Question: Getting a list of files In-Reply-To: References: Message-ID: <1179324440.729561.27920@w5g2000hsg.googlegroups.com> On May 16, 2:12 am, Brian wrote: > How do I, in Python, obtain a recursive list of files in a specified > directory, including the subdirectories, etc? import os def iter_dirs(root, dirs=False): stack = [root] while stack: dir = stack.pop(0) for f in (os.path.join(dir, basename) for basename in os.listdir(dir)): if os.path.isdir(f) and not os.path.islink(f): stack.append(f) if dirs: yield f else: yield f From steve at holdenweb.com Thu May 24 12:27:31 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 24 May 2007 12:27:31 -0400 Subject: installing cx_Oracle. In-Reply-To: References: Message-ID: Dennis Lee Bieber wrote: > On Thu, 24 May 2007 09:07:07 -0500, Carl K > declaimed the following in comp.lang.python: > >> Getting closer, thanks Bill and Diez. >> >> $ export ORACLE_HOME >> $ ORACLE_HOME=/usr/lib/oracle/xe/app/oracle/product/10.2.0/client > > Don't those lines need to be reversed? Set the variable in the > current shell, and /then/ export it? Modern shells actually allow the single statement export ORACLE_HOME=/usr/lib/oracle/xe/app/oracle/product/10.2.0/client 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From jn2007zq9mmbt77av7lijp at newsguy.com Thu May 17 13:41:03 2007 From: jn2007zq9mmbt77av7lijp at newsguy.com (Richard Hanson) Date: Thu, 17 May 2007 10:41:03 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: On Sun, 13 May 2007 17:44:39 +0200, Martin v. L?wis wrote: > The syntax of identifiers in Python will be based on the Unicode > standard annex UAX-31 [1]_, with elaboration and changes as defined > below. > > Within the ASCII range (U+0001..U+007F), the valid characters for > identifiers are the same as in Python 2.5. This specification only > introduces additional characters from outside the ASCII range. For > other characters, the classification uses the version of the Unicode > Character Database as included in the ``unicodedata`` module. > > The identifier syntax is `` *``. > > ``ID_Start`` is defined as all characters having one of the general > categories uppercase letters (Lu), lowercase letters (Ll), titlecase > letters (Lt), modifier letters (Lm), other letters (Lo), letter numbers > (Nl), plus the underscore (XXX what are "stability extensions" listed in > UAX 31). > > ``ID_Continue`` is defined as all characters in ``ID_Start``, plus > nonspacing marks (Mn), spacing combining marks (Mc), decimal number > (Nd), and connector punctuations (Pc). > > > [...] > >.. [1] http://www.unicode.org/reports/tr31/ First, to Martin: Thanks for writing this PEP. While I have been reading both sides of this debate and finding both sides reasonable and understandable in the main, I have several questions which seem to not have been raised in this thread so far. Currently, in Python 2.5, identifiers are specified as starting with an upper- or lowercase letter or underscore ('_') with the following "characters" of the identifier also optionally being a numerical digit ("0"..."9"). This current state seems easy to remember even if felt restrictive by many. Contrawise, the referenced document "UAX-31" is a bit obscure to me (which is not eased by the fact that various browsers render non-ASCII characters differently or not at all depending on the setup and font sets available). Further, a cursory perusing of the unicodedata module seems to refer me back to the Unicode docs. I note that UAX-31 seems to allow "ideographs" as ``ID_Start``, for example. From my relative state of ignorance, several questions come to mind: 1) Will this allow me to use, say, a "right-arrow" glyph (if I can find one) to start my identifier? 2) Could an ``ID_Continue`` be used as an ``ID_Start`` if using a RTL (reversed or "mirrored") identifier? (Probably not, but I don't know.) 3) Is or will there be a definitive and exhaustive listing (with bitmap representations of the glyphs to avoid the font issues) of the glyphs that the PEP 3131 would allow in identifiers? (Does this question even make sense?) I have long programmed in RPL and have appreciated being able to use, say, a "right arrow" symbol to start a name of a function (e.g., "->R" or "->HMS" where the '->' is a single, right-arrow glyph).[1] While it is not clear that identifiers I may wish to use would still be prohibited under PEP 3131, I vote: +0 __________________________________________ [1] RPL (HP's Dr. William Wickes' language and environment circa the 1980s) allows for a few specific "non-ASCII" glyphs as the start of a name. I have solved my problem with my Python "appliance computer" project by having up to three representations for my names: Python 2.x acceptable names as the actual Python identifier, a Unicode text display exposed to the end user, and also if needed, a bitmap display exposed to the end user. So -- IAGNI. :-) -- Richard Hanson From michele.simionato at gmail.com Mon May 7 09:16:52 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 7 May 2007 06:16:52 -0700 Subject: how do you implement a reactor without a select? Message-ID: <1178543812.260333.39280@w5g2000hsg.googlegroups.com> I have always been curious about how people implement mainloops (or, in Twisted terminology, reactors). So I sit down and I wrote the following simple implementation: import itertools class SimpleReactor(object): DELAY = 0.001 # seconds def __init__(self): self._event = {} # action id -> (scheduled time, action, args) self._counter = itertools.count(1) # action id generator self.running = False def callLater(self, deltat, action, *args): """Schedule an action with arguments args in deltat seconds. Return the action id""" now = time.time() i = self._counter.next() self._event[i] = now + deltat, action, args return i def cancelCallLater(self, action_id): "Cancel the action identified by action_id" del self._event[action_id] def default_action(self): # to be overridden "Invoked at each lap in the mainloop" time.sleep(self.DELAY) # don't run too fast, rest a bit def cleanup_action(self): # to be overridden "Invoked at the end of the mainloop" def manage_exc(self, e): "Invoked at each call" raise e def dooneevent(self): "Perfom scheduled actions" now = time.time() for i, (start_time, action, args) in self._event.items(): if now >= start_time: # it's time to start the action self.cancelCallLater(i) # don't run it again try: action(*args) except Exception, e: self.manage_exc(e) def run(self): "Run the main loop" self.running = True try: while self.running: self.default_action() self.dooneevent() except KeyboardInterrupt: print 'Stopped via CTRL-C' finally: self.cleanup_action() def stop(self): self.running = False Notice that I copied the Twisted terminology, but I did not look at Twisted implementation because I did not want to use a select (I assume that the GUI mainloops do not use it either). The trick I use is to store the actions to perform (which are callables identified by an integer) in an event dictionary and to run them in the mainlooop if the current time is greater than the scheduled time. I had to add a time.sleep(.001) call in the default_action to avoid consuming 100% of the CPU in the loop. I wonder if real mainloops are done in this way and how bad/good is this implementation compared to a serious one. Any suggestion/hint/ advice is well appreciated. Thanks, Michele Simionato From DELETETHISyang.news at MAILNULLdeletethis.com Sun May 20 04:22:43 2007 From: DELETETHISyang.news at MAILNULLdeletethis.com (Yang) Date: 20 May 2007 08:22:43 GMT Subject: Closing socket file descriptors References: Message-ID: Hi, thanks for your answer. Should I just use that object's close() method? Is it safe to assume that objects that have fileno() also have close()? (Statically typed interfaces would come in handy now.) I'm writing a simple asynchronous I/O framework (for learning purposes - I'm aware of the myriad such frameworks for Python), and I'm writing a wrapper around objects that can be passed into select.select(). Since select() requires objects that have fileno's, that's the only requirement I place on the wrapped object's interface, and thus why I've been using FD-based operations: class handle( object ): '''handle( underlying_file ) -> handle object A wrapper for a nonblocking file descriptor/handle. Wraps any object with a fileno() method.''' __slots__ = [ '_real' ] # _real is the underlying file handle. Must support fileno(). def __init__( self, real_handle ): self._real = real_handle def fileno( self ): return self._real.fileno() def close( self ): close( self._real.fileno() ) # seems that this must now become: self._real.close() def wait_readable( self ): ... "js " wrote in news:mailman.7927.1179646552.32031.python-list at python.org: > Hello, Yang. > > You're not supposed to use os.open there. > See the doc at http://docs.python.org/lib/os-fd-ops.html > > Is there any reason you want to use os.close? > > On 20 May 2007 04:26:12 GMT, Yang > wrote: >> Hi, I'm experiencing a problem when trying to close the file descriptor >> for a socket, creating another socket, and then closing the file >> descriptor for that second socket. I can't tell if my issue is about >> Python or POSIX. >> >> In the following, the first time through, everything works. On the >> second connection, though, the same file descriptor as the first >> connection may be re-used, but for some reason, trying to do >> os.read/close on that file descriptor will cause an error. >> >> Thanks in advance for any help on why this problem is occurring and/or >> how to resolve it (preferrably, I can continue to use file descriptors >> instead of resorting to socket.recv/socket.close). >> >> def handle( s ): >> print id(s), s >> print os.read( s.fileno(), 4096 ) # s.recv(4096) >> os.close( s.fileno() ) # s.close() >> svr = socket.socket() >> svr.bind( ( 'localhost', 8003 ) ) >> svr.listen( 1 ) >> while True: >> print 'accepting' >> s,_ = svr.accept() >> handle( s ) >> >> # Traceback (most recent call last): >> # File "./normal_server_close_error.py", line 25, in >> # handle( s ) >> # File "./normal_server_close_error.py", line 13, in handle >> # print os.read( s.fileno(), 4096 ) # s.recv(4096) >> # OSError: [Errno 9] Bad file descriptor >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > From bdesth.quelquechose at free.quelquepart.fr Mon May 21 18:07:23 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 22 May 2007 00:07:23 +0200 Subject: Python Web Programming - looking for examples of solid high-traffic sites In-Reply-To: References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> <1hy9yf9.1nnsttj139za6bN%aleax@mac.com> <1hyarxo.iqtdo1v9qpivN%aleax@mac.com> Message-ID: <46520db5$0$6394$426a34cc@news.free.fr> John Nagle a ?crit : (snip) > YouTube's home page is PHP. Try "www.youtube.com/index.php". > That works, while the obvious alternatives don't. > If you look at the page HTML, you'll see things like > > onclick="_hbLink('LogIn','UtilityLinks');">Log In > > So there's definitely PHP inside YouTube. What about learning more on web servers configuration ? http://zope.alostnet.eu/index.php "definitively php", hu ? From fsckedagain at gmail.com Tue May 1 16:35:21 2007 From: fsckedagain at gmail.com (fscked) Date: 1 May 2007 13:35:21 -0700 Subject: read list of dirnames and search for filenames Message-ID: <1178051721.935868.194700@o5g2000hsb.googlegroups.com> I cannot seem to get this to work. I am hyst trying to read in a list of paths and see if the directory or any sub has a filename pattern. Here is the code: import os, sys from path import path myfile = open("boxids.txt", "r") for line in myfile.readlines(): d = path(line) for f in d.walkfiles('*Config*.xml'): print f And here is my error: Traceback (most recent call last): File "Untitled.py", line 21, in ? for f in d.walkfiles('*Config*.xml'): File "C:\Python24\Lib\site-packages\path.py", line 460, in walkfiles childList = self.listdir() File "C:\Python24\Lib\site-packages\path.py", line 328, in listdir names = os.listdir(self) WindowsError: [Errno 3] The system cannot find the path specified: u'X: \\Instructions\\97544546294\n/*.*' What I don't get is if I just print the path it prints correctly, but it keeps adding double "\"s to it. I tried changing the backslashies to forward slashies and I get : WindowsError: [Errno 3] The system cannot find the path specified: u'X:/Instructions/97544546294\n/*.*' help? From jjreavis at gmail.com Mon May 28 13:47:58 2007 From: jjreavis at gmail.com (Jeff Reavis) Date: 28 May 2007 10:47:58 -0700 Subject: Tix and OS X In-Reply-To: References: <1180218876.623283.174680@p77g2000hsh.googlegroups.com> Message-ID: <1180374478.312151.285860@q75g2000hsh.googlegroups.com> On May 26, 8:51 pm, Kevin Walzer wrote: > Jeff Reavis wrote: > > Does python not ship with Tix for OS X? I know there was an issue with > > 2.5.0 and Tix on Windows, and upgrading to 2.5.1 fixed it. > > Unfortunately, I seem to have the same issue with OS X and 2.5.1. The > > error I get is: > > > self.tk.eval('package require Tix') > > _tkinter.TclError: can't find package Tix > > > I did find tkinter.so (Tkinter seems to work), but nothing matching > > tix.so. > > Is this a known issue? I haven't found any information about it on the > > web or in this group. > > > Thanks in advance. > > > This is an Intel Mac, btw. > > > -jjr > > You have to have the Tcl Tix package installed--the Python module just > wraps it. > > -- > Kevin Walzer > Code by Kevinhttp://www.codebykevin.com Thanks, but I still find it strange that the tix so is not included for the Mac. When dll was missing in Python 2.5 it was considered a bug (www.python.org/sf/1568240). -jjr From steve at REMOVE.THIS.cybersource.com.au Sun May 6 02:00:18 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 06 May 2007 16:00:18 +1000 Subject: change of random state when pyc created?? References: <1178408359.113807.181570@l77g2000hsb.googlegroups.com> Message-ID: On Sun, 06 May 2007 00:20:04 +0000, Alan Isaac wrote: >> Should you not expect to get the same result each time? Is that not >> the point of setting a constant seed each time you run the script? > > Yes. That is the problem. > If I delete module2.pyc, > I do not get the same result. I think you have missed what John Machin is pointing out. According to your original description, you get different results even if you DON'T delete module2.pyc. According to your original post, you get the _same_ behaviour the first time you run the script, regardless of the pyc file being deleted or not. You wrote: [quote] module1 sets a seed like this:: if __name__ == "__main__": random.seed(314) main() I execute module1.py from the (Windows) shell. I get a result, let's call it result1. I execute it again. I get another result, say result2. Running it again and again, I get result2. [end quote] So, with module2.pyc file existing, you get result1 the first time you execute module1.py, and then you get result2 every time from then onwards. How is that different from what you wrote next? [quote] Now I delete module2.pyc. I execute module1.py from the shell. I get result1. I execute it again; I get result2. >From then on I get result2, unless I delete module.pyc again, in which case I once again get result1. [end quote] You get the same behaviour with or without module2.pyc: the first run of the script gives different results from subsequent runs. You can reset that first run by deleting module2.pyc. I'm still perplexed how this is possible, but now I'm more perplexed. If you want to send me the modules, I will have a look at them as well. Many eyes make for shallow bugs... -- Steven. From steve at holdenweb.com Sat May 19 14:36:26 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 19 May 2007 14:36:26 -0400 Subject: docs patch: dicts and sets In-Reply-To: <1179596822.923443.67500@k79g2000hse.googlegroups.com> References: <_5-dnU7aIN73j9LbnZ2dnUVZ_uCinZ2d@comcast.com> <1179593927.503393.127350@u30g2000hsc.googlegroups.com> <1179596822.923443.67500@k79g2000hse.googlegroups.com> Message-ID: 7stud wrote: > On May 19, 11:38 am, Steve Holden wrote: >> Except in those instances where users added information that was >> explicitly wrong. > > It's a self correcting mechanism. Other reader's will spot the error > and post corrections. > The last thing I want to read in a language's documentation is an ill-informed and sometimes interminable argument about a particular feature. For documentation I'm all in favor of user contributions, but I believe an editorial process is required to ensure readability. I am aware that the documentation isn't perfect but it's pretty good, and I don't think throwing it open to anyone (including, by the way, web spammers) to add to it is necessarily the best way to improve 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From __peter__ at web.de Sun May 20 07:19:30 2007 From: __peter__ at web.de (Peter Otten) Date: Sun, 20 May 2007 13:19:30 +0200 Subject: Unable to strip \n characters References: <1179658203.040541.220800@p77g2000hsh.googlegroups.com> Message-ID: aiwarrior wrote: > Im writing a personal wrapper to the perl script offered by > rapidshare, so that im able to use multiple files and glob pathnames, > but im using a file so i can track and resume any uploading data. The > problem is the lines come with a \n character that im not bein able to > take out, > > files = f.readlines() > for upload in files: The readlines() is call is superfluous; just iterate over the file instead: for upload in f: > upload.strip("\n") Python strings are immutable (cannot be altered). Instead of changing them you create a new one that you assign to the same name: upload = upload.strip("\n") Peter From tjreedy at udel.edu Wed May 2 12:38:17 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 2 May 2007 12:38:17 -0400 Subject: I need help speeding up an app that reads football scores andgenerates rankings References: <1178118022.865173.266300@h2g2000hsg.googlegroups.com> Message-ID: "jocknerd" wrote in message news:1178118022.865173.266300 at h2g2000hsg.googlegroups.com... | About 10 years ago, I wrote a C app that would read scores from | football games and calculate rankings based on the outcome of the | games. In fact, I still use this app. You can view my rankings at | http://members.cox.net/jocknerd/football. | | A couple of years ago, I got interested in Python and decided to | rewrite my app in Python. I got it to work but its painfully slow | compared to the C app. I have a file containing scores of over 1500 | high school football games for last season. With my Python app, it | takes about 3 minutes to process the rankings. With my C app, it | processes the rankings in less than 15 seconds. A ratio of 12 to 1 is not bad. However.... | The biggest difference in my two apps is the C app uses linked lists. | I feel my Python app is doing too many lookups which is causing the | bottleneck. You have to do as many lookups as you have to do, but looking up teams by name in a linear scan of a list is about the slowest way possible. Replace 'teamlist' with a dict 'teams' keyed by team name. Replace 'lookupTeam(team)' by 'if team not in teams: addTeam(team)' and delete the lookupTeam function. Similarly 'lookupTeamRate(team)' becomes 'teams[team]['grate'] (and delete function). And 'updateTeamRate(team,rate)' becomes teams[team]['rate'] = rate' (and delete function. And similarly for updateTeamRating and anything else using teamlist. In many places, multiple lookups in teams could be eliminated. For instance, 'team1 = teams[g['team1']]. Then use 'team1' to manipulate its rating and other attributes. | You can download the source code from http://members.cox.net/jocknerd/downloads/fbratings.py | and the data file from http://members.cox.net/jocknerd/downloads/vhsf2006.txt Minor point. Multiple functions do 'localvar = ; return localvar'. The simpler 'return ' will be slightly faster. Your comments and function name eliminate any documentary need for the otherwise useless local var. Function calls are relatively slow in Python. So calling def totalPtsGame (score1, score2): return score1 + score2 is slower than simply adding the scores 'in place'. Terry Jan Reedy You can also, people say, use the profiler to find where time is going. From Steffen.Oschatz at googlemail.com Thu May 10 06:07:36 2007 From: Steffen.Oschatz at googlemail.com (Steffen Oschatz) Date: 10 May 2007 03:07:36 -0700 Subject: Multiple regex match idiom In-Reply-To: <87r6pqxtgh.fsf@busola.homelinux.net> References: <87r6pqxtgh.fsf@busola.homelinux.net> Message-ID: <1178791656.249645.295810@e65g2000hsc.googlegroups.com> On 9 Mai, 11:00, Hrvoje Niksic wrote: > I often have the need to match multiple regexes against a single > string, typically a line of input, like this: > > if (matchobj = re1.match(line)): > ... re1 matched; do something with matchobj ... > elif (matchobj = re2.match(line)): > ... re2 matched; do something with matchobj ... > elif (matchobj = re3.match(line)): > .... > > Of course, that doesn't work as written because Python's assignments > are statements rather than expressions. The obvious rewrite results > in deeply nested if's: > > matchobj = re1.match(line) > if matchobj: > ... re1 matched; do something with matchobj ... > else: > matchobj = re2.match(line) > if matchobj: > ... re2 matched; do something with matchobj ... > else: > matchobj = re3.match(line) > if matchobj: > ... > > Normally I have nothing against nested ifs, but in this case the deep > nesting unnecessarily complicates the code without providing > additional value -- the logic is still exactly equivalent to the > if/elif/elif/... shown above. > > There are ways to work around the problem, for example by writing a > utility predicate that passes the match object as a side effect, but > that feels somewhat non-standard. I'd like to know if there is a > Python idiom that I'm missing. What would be the Pythonic way to > write the above code? Instead of scanning the same input over and over again with different, maybe complex, regexes and ugly looking, nested ifs, i would suggest defining a grammar and do parsing the input once with registered hooks for your matching expressions. SimpleParse (http://simpleparse.sourceforge.net) with a DispatchProcessor or pyparsing (http://pyparsing.wikispaces.com/) in combination with setParseAction or something similar are your friends for such a task. Steffen From josiah.carlson at sbcglobal.net Thu May 17 01:09:02 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Wed, 16 May 2007 22:09:02 -0700 Subject: cPickle.dumps differs from Pickle.dumps; looks like a bug. In-Reply-To: References: <1179335622.006820.22460@q23g2000hsg.googlegroups.com> <1179352356.025319.43310@w5g2000hsg.googlegroups.com> <5f56302b0705161524u5902320cy11e0f67a798e8089@mail.gmail.com> <4866bea60705161539q19378836j108750b3e287132e@mail.gmail.com> Message-ID: Daniel Nogradi wrote: > Caching? > >>>> from cPickle import dumps >>>> dumps('0') == dumps(str(0)) > True >>>> dumps('1') == dumps(str(1)) > True >>>> dumps('2') == dumps(str(2)) > True > ........ > ........ >>>> dumps('9') == dumps(str(9)) > True >>>> dumps('10') == dumps(str(10)) > False >>>> dumps('11') == dumps(str(11)) > False All strings of length 0 (there is 1) and 1 (there are 256) are interned. - Josiah From konrad.hinsen at laposte.net Tue May 22 03:40:12 2007 From: konrad.hinsen at laposte.net (Konrad Hinsen) Date: Tue, 22 May 2007 09:40:12 +0200 Subject: Installing Python in a path that contains a blank In-Reply-To: References: Message-ID: On 21.05.2007, at 21:11, Stargaming wrote: > You could give /foo/bar\ baz/ham or "/foo/bar baz/ham" (either > escaping > the blanks or wrapping the path in quotation marks) a try. I can't > verify it either, just guess from other terminals' behaviour. I tried both already, but neither one works. If I use a backslash, it doesn't end up in the Makefile, and if I use quotes, I get lots of error messages that I don't really want to analyze. Thanks for your reply anyway! Konrad. From mensanator at aol.com Sat May 12 21:43:54 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 12 May 2007 18:43:54 -0700 Subject: Interesting list Validity (True/False) In-Reply-To: References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> <1178914190.166662.285410@p77g2000hsh.googlegroups.com> <1178915791.584216.293130@l77g2000hsb.googlegroups.com> <1178918808.091358.233740@o5g2000hsb.googlegroups.com> <1179017740.656323.209590@e51g2000hsg.googlegroups.com> Message-ID: <1179020634.130689.171960@o5g2000hsb.googlegroups.com> On May 12, 8:10?pm, Carsten Haese wrote: > On Sat, 2007-05-12 at 17:55 -0700, mensana... at aol.com wrote: > > On May 12, 12:56?pm, Carsten Haese wrote: > > > On Fri, 2007-05-11 at 14:26 -0700, mensana... at aol.com wrote: > > > > if arg==True: > > > > > tests the type property (whether a list is a boolean). > > > > That sounds nonsensical and incorrect. Please explain what you mean. > > > > > Sec 2.2.3: > > Objects of different types, except different numeric types and > > different string types, never compare equal; > > > > That doesn't explain what you mean. How does "if arg==True" test whether > "a list is a boolean"? >>> type(sys.argv) >>> type(True) Actually, it's this statement that's non-sensical. "if arg==True" tests whether the object known as arg is equal to the object known as True. None of these four examples are "equal" to any other. >>> a = 1 >>> b = (1,) >>> c = [1] >>> d = gmpy.mpz(1) >>> >>> type(a) >>> type(b) >>> type(c) >>> type(d) >>> a==b False >>> b==c False >>> a==d True And yet a==d returns True. So why doesn't b==c also return True, they both have a 1 at index position 0? >>> x = [1] >>> y = [1] >>> x==y True > > -- > Carsten Haesehttp://informixdb.sourceforge.net From conor.robinson at gmail.com Wed May 30 20:44:06 2007 From: conor.robinson at gmail.com (py_genetic) Date: 30 May 2007 17:44:06 -0700 Subject: Create a new class on the fly Message-ID: <1180568447.449581.250500@g37g2000prf.googlegroups.com> Is this possible or is there a better way. I need to create a new class during runtime to be used inside a function. The class definition and body are dependant on unknows vars at time of exec, thus my reasoning here. class PosRecords(tables.IsDescription): class A(object): self.__init__(self, args): ........ def mkClass(self, args): eval( "class B(object): ...") #definition on B is dependant on dynamic values in string ......do stuff with class thanks. From jadestar at idiom.com Mon May 14 18:09:08 2007 From: jadestar at idiom.com (James T. Dennis) Date: Mon, 14 May 2007 22:09:08 -0000 Subject: Hello gettext Message-ID: <1179180548.306413@smirk> You'd think that using things like gettext would be easy. Superficially it seems well documented in the Library Reference(*). However, it can be surprisingly difficult to get the external details right. * http://docs.python.org/lib/node738.html Here's what I finally came up with as the simplest instructions, suitable for an "overview of Python programming" class: Start with the venerable "Hello, World!" program ... slightly modified to make it ever-so-slightly more "functional:" #!/usr/bin/env python import sys def hello(s="World"): print "Hello,", s if __name__ == "__main__": args = sys.argv[1:] if len(args): for each in args: hello(each) else: hello() ... and add gettext support (and a little os.path handling on the assumption that our message object files will not be readily installable into the system /usr/share/locale tree): #!/usr/bin/env python import sys, os, gettext _ = gettext.lgettext mydir = os.path.realpath(os.path.dirname(sys.argv[0])) localedir = os.path.join(mydir, "locale") gettext.bindtextdomain('HelloPython', localedir) gettext.textdomain('HelloPython') def hello(s=_("World")): print _("Hello,"), s if __name__ == "__main__": args = sys.argv[1:] if len(args): for each in args: hello(each) else: hello() Note that I've only added five lines, the two modules to my import line, and wrapped two strings with the conventional _() function. This part is easy, and well-documented. Running pygettext or GNU xgettext (-L or --language=Python) is also easy and gives us a file like: # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR ORGANIZATION # FIRST AUTHOR , YEAR. # msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "POT-Creation-Date: 2007-05-14 12:19+PDT\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=CHARSET\n" "Content-Transfer-Encoding: ENCODING\n" "Generated-By: pygettext.py 1.5\n" #: HelloWorld.py:10 msgid "World" msgstr "" #: HelloWorld.py:11 msgid "Hello," msgstr "" ... I suppose I should add the appropriate magic package name, version, author and other values to my source. Anyone remember where those are documented? Does pygettext extract them from the sources and insert them into the .pot? Anyway, I minimally have to change one line thus: "Content-Type: text/plain; charset=utf-8\n" ... and I suppose there are other ways to do this more properly. (Documented where?) I did find that I could either change that in the .pot file or in the individual .po files. However, if I failed to change it then my translations would NOT work and would throw an exception. (Where is the setting to force the _() function to fail gracefully --- falling back to no-translation and NEVER raise exceptions? I seem to recall there is one somewhere --- but I just spent all evening reading the docs and various Google hits to get this far; so please excuse me if it's a blur right now). Now we just copy these templates to individual .po files and make our LC_MESSAGES directories: mkdir locale && mv HelloPython.pot locale cd locale for i in es_ES fr_FR # ... do cp HelloPython.pot HelloPython_$i.po mkdir -p $i/LC_MESSAGES done ... and finally we can work on the translations. We edit each of the _*.po files inserting "Hola" and "Bonjour" and "Mundo" and "Monde" in the appropriate places. And then process these into .mo files and move them into place as follows: for i in *_*.po; do i=${i#*_} msgfmt -o ./${i%.po}/LC_MESSAGES/HelloPython.mo done ... in other words HelloPython_es_ES.po is written to ./es_ES/LC_MESSAGES/HelloPython.mo, etc. This last part was the hardest to get right. To test this we simply run: $HELLO_PATH/HelloPython.py Hello, World export LANG=es_ES $HELLO_PATH/HelloPython.py Hola, Mundo export LANG=fr_FR $HELLO_PATH/HelloPython.py Bonjour, Monde export LANG=zh_ZH $HELLO_PATH/HelloPython.py Hello, World ... and we find that our Spanish and French translations work. (With apologies if my translations are technically wrong). Of course I realize this only barely scratches the surface of I18n and L10n issues. Also I don't know, offhand, how much effort would be required to make even this trivial example work on an MS Windows box. It would be nice to find a document that would cover the topic in more detail while still giving a sufficiently clear and concise set of examples that one could follow them without getting hung up on something stupid like: "Gee! You have to create $LANG/LC_MESSAGES/ directories and put the .mo files thereunder; the Python won't find them under directly under $LANG nor under LC_MESSAGES/$LANG" ... and "Gee! For reasons I don't yet understand you need call both the .bindtextdomain() AND the .textdomain() functions." ... and even "Hmmm ... seems that we don't need to import locale and call local.setlocale() despite what some examples in Google seem to suggest"(*) * http://www.pixelbeat.org/programming/i18n.html (So, when to you need that and when is gettext.install() really useful?) (I gather that the setlocale() stuff is not for simple string translations but for things like numeric string formatting with "%d" % ... for example). -- Jim Dennis, Starshine: Signed, Sealed, Delivered From antroy at gmail.com Wed May 16 07:17:29 2007 From: antroy at gmail.com (Ant) Date: 16 May 2007 04:17:29 -0700 Subject: iteration doesn't seem to work ?? In-Reply-To: References: Message-ID: <1179314249.015385.153270@e65g2000hsc.googlegroups.com> On May 16, 9:41 am, stef wrote: > hello, > > can someone tell me why the following iteration doesn't work, > and > how I should replace empty strings in a list with a default value. See the other reponse for the why. Here's another how, using list comprehension.: 1 > v = ['123', '345', '', '0.3'] 2 > v = [x if x else '3' for x in v] 3 > v 3 = ['123', '345', '3', '0.3'] Note that this replaces the list, so won't be appropriate for modifying a list passed in from elsewhere. -- Ant... http://antroy.blogspot.com/ From herman_slagman at placid-dash-sky-dot-org Mon May 21 06:39:09 2007 From: herman_slagman at placid-dash-sky-dot-org (Herman Slagman) Date: Mon, 21 May 2007 12:39:09 +0200 Subject: Translating some Java to Python In-Reply-To: <1179738814.282655.192700@r3g2000prh.googlegroups.com> References: <1179692679.422164.27700@r3g2000prh.googlegroups.com> <1179738814.282655.192700@r3g2000prh.googlegroups.com> Message-ID: <465176ce$0$323$e4fe514c@news.xs4all.nl> "Ant" schreef in bericht news:1179738814.282655.192700 at r3g2000prh.googlegroups.com... > Herman has shown you *how* to do static methods in Python, but > typically they are not used. Since Python has first class functions, > and they can be defined at the module level, there is no need to use > static methods. Hmm, As an experienced developer I'm rather new to Python, so please forgive me any non-Pythonic babbling. >From a language point you're probably right, but from a design point I'd like to have methods that are clearly associated with a class as methods of that class, even if they don't use any class or instance related data. Herman From john at datavoiceint.com Mon May 7 19:02:03 2007 From: john at datavoiceint.com (HMS Surprise) Date: 7 May 2007 16:02:03 -0700 Subject: No module named urllib In-Reply-To: <87ps5cp816.fsf@gmail.com> References: <1178575589.059564.226060@q75g2000hsh.googlegroups.com> <87tzuop8s2.fsf@gmail.com> <1178577562.498615.222340@e51g2000hsg.googlegroups.com> <87ps5cp816.fsf@gmail.com> Message-ID: <1178578923.067315.14440@q75g2000hsh.googlegroups.com> On May 7, 5:45 pm, Jorge Godoy wrote: > HMS Surprise writes: > > Perhaps I should have put qoutes in my sentence. > > Or I should have read it slowly. ;-) > > > I get the "no module message named urllib". > > Can you please > > import sys > print sys.path > > and put the answer here on the newsgroup? > > -- > Jorge Godoy Thanks for posting. Ah, there is the problem. Now how to fix it? I am running my program from maxq which generates jython scripts. It is not looking at my PYTHONPATH as sys.path = ['.', 'C:\\maxq\\lib\\Lib', 'C:\\maxq\\jython'] However I copied the urllib file to the directory with the scripts so thought it should pick it up there. jh From rNOSPAMon at flownet.com Thu May 17 15:26:34 2007 From: rNOSPAMon at flownet.com (Ron Garret) Date: Thu, 17 May 2007 12:26:34 -0700 Subject: Is wsgi ready for prime time? References: Message-ID: In article , Stargaming wrote: > Ron Garret wrote: > > The wsgiref module in Python 2.5 seems to be empty: > > > > [ron at mickey:~/Sites/modpy]$ python > > Python 2.5 (r25:51908, Mar 1 2007, 10:09:05) > > [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin > > Type "help", "copyright", "credits" or "license" for more information. > > > >>>>import wsgiref > >>>>dir(wsgiref) > > > > ['__builtins__', '__doc__', '__file__', '__name__', '__path__'] > > > > > > So... is wsgi considered ready for production use, or is it still on the > > bleeding edge? And if the former, which implementation should one use? > > > > rg > > >>> help(wsgiref) > Help on package wsgiref: > > NAME > wsgiref - wsgiref -- a WSGI (PEP 333) Reference Library > > DESCRIPTION > Current Contents: > > * util -- Miscellaneous useful functions and wrappers > > * headers -- Manage response headers > > * handlers -- base classes for server/gateway implementations > > * simple_server -- a simple BaseHTTPServer that supports WSGI > > * validate -- validation wrapper that sits between an app and a server > to detect errors in either > > To-Do: > > * cgi_gateway -- Run WSGI apps under CGI (pending a deployment > standard) > > * cgi_wrapper -- Run CGI apps under WSGI > > * router -- a simple middleware component that handles URL traversal > > PACKAGE CONTENTS > handlers > headers > simple_server > util > validate > > Reading the documentation can be useful sometimes. Recommending > http://docs.python.org/lib/module-wsgiref.html, too. I did read the documentation, but the documentation does not seem to reflect reality, e.g.: >>> wsgiref.util Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'util' >>> wsgiref.headers Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'headers' >>> wsgiref.handlers Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'handlers' >>> Hence my question. rg From kyosohma at gmail.com Thu May 3 14:40:17 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 3 May 2007 11:40:17 -0700 Subject: NewB: Glob Question In-Reply-To: <1178213910.976263.207630@e65g2000hsc.googlegroups.com> References: <1178213910.976263.207630@e65g2000hsc.googlegroups.com> Message-ID: <1178217617.829564.312150@u30g2000hsc.googlegroups.com> On May 3, 12:38 pm, J wrote: > Greetings Group- > > I'm trying to put together a pattern matching script that scans a > directory tree for tif images contained in similar folder names, but > running into a NewB problem already. Is it the way I'm trying to join > multiple paths? Any help would be greatly appericated. Thanks, J! > > import glob, sys, os > > topdir = sys.argv[1] > tifFilter = '*.tif' > dirFilter = '**' > > tifList = glob.glob(os.path.join(topdir, tifFilter)) > tifList = tifList + glob.glob(os.path.join(topdir, dirFilter, > tifFilter)) > > for tif in tifList: > print os.basename(tif) + " is in " + os.dirname(tif) I messed around with this some and I believe you are correct. When you tell it to search using '**', glob will look only in directories that are two characters long. This is obviously not what is needed. Instead, try setting it like this: dirFilter = '*\\' That seemed to work for me. Good luck! Mike From larry.bates at websafe.com Tue May 22 10:11:45 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 22 May 2007 09:11:45 -0500 Subject: pipe tutorial In-Reply-To: References: Message-ID: <6LOdndzGvuaCZ8_bnZ2dnUVZ_oDinZ2d@comcast.com> Gigs_ wrote: > does anyone know some good tutorial on pipes in python? > > thx Pipes is specific only to Windows (you can use sockets on Windows/Linux/mac). The only specific treatment of pipes I've seen is in Python Programming for Win32 by Mark Hammond/Andy Robinson. -Larry From sjmachin at lexicon.net Sat May 26 20:21:30 2007 From: sjmachin at lexicon.net (John Machin) Date: 26 May 2007 17:21:30 -0700 Subject: Why isn't this query working in python? In-Reply-To: <1180207521.072958.322770@p47g2000hsd.googlegroups.com> References: <1180103946.552760.239200@p47g2000hsd.googlegroups.com> <6e42ec490705250751i89d3cf3v3a3062690d0284aa@mail.gmail.com> <1180207521.072958.322770@p47g2000hsd.googlegroups.com> Message-ID: <1180225290.235515.274000@q19g2000prn.googlegroups.com> On May 27, 5:25 am, erikcw wrote: > On May 25, 11:28 am, Carsten Haese wrote: > > > > > On Fri, 2007-05-25 at 09:51 -0500, Dave Borne wrote: > > > > I'm trying to run the following query: > > > ... > > > > member_id=%s AND expire_date > NOW() AND completed=1 AND (product_id > > > > Shouldn't you be using the bind variable '?' instead of '%s' ? > > > The parameter placeholder for MySQLdb is, indeed and unfortunately, %s. > > The OP is using parameter substitution correctly, though in an > > obfuscated fashion. 'sql' is a misnamed tuple containing both the query > > string *and* the parameters, which is being unpacked with '*' into two > > arguments to the execute call. > > > The only problem I see is that the parameters should be a sequence, i.e. > > (self.uid,) instead of just (self.uid). > > > HTH, > > > -- > > Carsten Haesehttp://informixdb.sourceforge.net > > I tried adding the comma to make it a sequence - but now change. > > ('SELECT payment_id FROM amember_payments WHERE member_id=%s AND > expire_date > NOW() AND completed=1 AND (product_id >11 AND product_id > <21)', (1608L,)) > () > > What else could it be? > Possibly a type mismatch. How is member_id declared in the CREATE TABLE? For diagnostic purposes, try passing in (1608,) and ('1608',). From msurel at comcast.net Fri May 4 13:45:59 2007 From: msurel at comcast.net (Mike) Date: 4 May 2007 10:45:59 -0700 Subject: adding methods at runtime and lambda In-Reply-To: References: <1178221975.149008.192410@y5g2000hsa.googlegroups.com> Message-ID: <1178300759.455134.60560@n59g2000hsh.googlegroups.com> On May 3, 11:25 pm, "Gabriel Genellina" wrote: > En Thu, 03 May 2007 16:52:55 -0300, Mike escribi?: > > > I was messing around with adding methods to a class instance at > > runtime and saw the usual code one finds online for this. All the > > examples I saw say, of course, to make sure that for your method that > > you have 'self' as the first parameter. I got to thinking and thought > > "I have a lot of arbitrary methods in several utility files that I > > might like to add to things. How would I do that?" And this is what I > > came up with: > > I don't see the reason to do that. If you have a function that does not > use its "self" argument, what do you get from making it an instance method? > If -for whatever strange reason- you want it to actually be a method, use > a static method: > > py> def foo(x): > ... print "I like %r" % x > ... > py> class A(object): pass > ... > py> a = A() > py> A.foo = staticmethod(foo) > py> a.foo() > Traceback (most recent call last): > File "", line 1, in > TypeError: foo() takes exactly 1 argument (0 given) > py> a.foo("coffee") > I like 'coffee' > py> A.foo("tea") > I like 'tea' > > -- > Gabriel Genellina staticmethod makes the function available to the whole class according to the docs. What if I only want it to be available on a particular instance? Say I'm adding abilities to a character in a game and I want to give a particular character the ability to 'NukeEverybody'. I don't want all characters of that type to be able to wipe out the entire planet, just the particular character that got the powerup. From researchbase at gmail.com Sun May 6 14:02:42 2007 From: researchbase at gmail.com (krishnakant Mane) Date: Sun, 6 May 2007 23:32:42 +0530 Subject: problem with quoted strings while inserting into varchar field of database. Message-ID: hello, I finally got some code to push a pickled list into a database table. but now the problem is technically complex although possible to solve. the problem is that I can nicely pickle and store lists in a blob field with the help of dumps() for picklling into a string and then passing the string to the blob. I am also able to get back the string safely and do a loads() to unpickle the object. but this only works when list contains numbers. if there is a list such als lst = ["a","b","c"] then after a dumpls I get a pickled object into a string but when I try to insert this into the blob field it refuses to get into the table. there is an sql syntax error. I further discovered that the string variable that contains the pickled object contains a lot of single quots "'" and this is what is probably preventing the sql insert from succedding. can some one suggest how to work around this problem? regards, Krishnakant. From kw at codebykevin.com Wed May 16 09:53:04 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Wed, 16 May 2007 09:53:04 -0400 Subject: Distributing programs depending on third party modules. In-Reply-To: <-J6dnUQxANzMB9fbRVnzvAA@telenor.com> References: <53357$4649c4a6$4275d90a$20775@FUSE.NET> <-J6dnUQxANzMB9fbRVnzvAA@telenor.com> Message-ID: <464B0CC0.5030505@codebykevin.com> Tina I wrote: > Kevin Walzer wrote: > And maybe the smartest thing to do would be to dump PyQt and just go for > tkinter, however ugly it is :/ Tkinter doesn't have to be ugly. I sell a proprietary Tkinter app commercially on OS X: http://www.codebykevin.com/phynchronicity-running.png It takes some work to get Tkinter looking polished. You have to use extension packages for things like table views, tree views, platform-specific theming, and so on. Fortunately, all that stuff is available in Tkinter: Tile for Tkinter: http://tkinter.unpythonic.net/wiki/TileWrapper Tabelist for Tkinter (with Tile support): http://tkinter.unpythonic.net/wiki/TableListTileWrapper pyBwidgets: http://tkinter.unpythonic.net/bwidget/ Tile, Tablelist and BWidgets are my extension packages of choice. There are others as well. Here's a sample application that uses some of the packages outlined above: http://tkinter.unpythonic.net/wiki/PyLocateTile (includes Mac and X11-based screen shots) It may not be worth your time to port from PyQt to Tkinter, but I did want to show a bit how you can create a polished GUI with Tkinter. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From kakeez at hotmail.com Wed May 23 20:09:36 2007 From: kakeez at hotmail.com (Karim Ali) Date: Thu, 24 May 2007 00:09:36 +0000 Subject: Call script which accepts com. line par. from another script and error control Message-ID: Hi, I would really appreciate help on this. I have a script (s1.py) which I would like to call from another script (s2.py). No problem there. The first issue is that s1.py has a command line parser which I would like to keep but instead of fetching the information from the command line, I would like to direct the parser to get the information from a variable so i can call sp1.py from sp2.py and give it an expression to parse that normally would go on the command line. To make things clearer: s1.py (currently) -------------------------------------------- def ... def ... cmdl_parser = optparse.OptionParser.. cmdl_parser.add_option.. (cmdl_opts, cmdl_args) = cmdl_parser.parse_args() ----------------------------------------------------------------- sp1.py (the one I would like) --------------------------------------------------------------------------------------------- def ... def ... def MAIN(expression2parse) <----- add a main so can call from other script cmdl_parser = optparse.OptionParser.. cmdl_parser.add_option.. (cmdl_opts, cmdl_args) = cmdl_parser.parse_args() <---------------------------do this but on "expression2parse" ----------------------------------------------------------------------------------------------------------------------------------- The second issue is error control. In case of an error in sp1.py I want the error handling to happen at the level of sp2.py so I can better manage things. Does anyone know how this could be done. Essentially return control to sp2.py? I am new to Python (5 hours) but have extensive programming in C++. I would really appreciate your input. Thanks! Kakeez _________________________________________________________________ Fight Allergies With Live Search http://search.live.com/results.aspx?q=Remedies+For+Spring+Allergies&mkt=en-ca&FORM=SERNEP From paul at boddie.org.uk Tue May 15 07:02:58 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 15 May 2007 04:02:58 -0700 Subject: Trying to choose between python and java In-Reply-To: References: Message-ID: <1179226978.624299.209780@e65g2000hsc.googlegroups.com> On 15 May, 07:30, Anthony Irwin wrote: > > I am currently trying to decide between using python or java and have > a few quick questions about python that you may be able to help with. > > #1 Does python have something like javas .jar packages. A jar file > contains all the program files and you can execute the program with > java -jar program.jar Some people will propose Python .egg files, but I believe plain .zip files containing packages may be enough for your purposes, provided that there are no native code libraries inside. > I am sort of hoping python has something like this because I feel it > makes it easier to distribute between platforms e.g. linux, mac > windows etc. See also... http://wiki.python.org/moin/DistributionUtilities > #2 What database do people recommend for using with python that is > easy to distribute across linux, mac, windows. See the following pages for guidance: http://wiki.python.org/moin/DatabaseProgramming http://wiki.python.org/moin/ChoosingDatabase You will probably be most interested in sqlite, particularly as support for that database system is now part of Python's standard library (from Python 2.5 onwards), although the libraries are also available separately. [...] > #5 someone said that they used to use python but stopped because the > language changed or made stuff depreciated (I can fully remember > which) and old code stopped working. Is code written today likely to > still work in 5+ years or do they depreciate stuff and you have to update? It's "deprecated", not "depreciated", by the way! I tend to complain about changes in the language a lot, mostly because I think that they can be confusing and off-putting for beginners, make documentation and literature outdated, and distract from more important areas of improvement, but I don't think that previous language changes have necessarily caused me many problems. My own active projects are at most around four years old, but as these projects have developed, I think that language changes have been the least of my problems. ;-) People could use such things as an excuse to bash Python, but the favourite languages of some of those people may well be undergoing fundamental changes with substantial potential breakage and no reasonable escape from the upgrade treadmill. Meanwhile, it's completely possible to stick with a particular version of Python and to write code against that without being forced to upgrade because of stability issues. Indeed, Python has reached a level of maturity (unlike certain competitors) where a conservative approach to version adoption is completely viable: I'm using Python 2.3.x in my work, and aside from a few conveniences that I miss from using Python 2.4.x elsewhere, it's still very much a going concern. Python 3.x will be somewhat different from Python 2.x, but people are working on tools to help developers target both branches of the language simultaneously, and it wouldn't surprise me if the 2.x series continued in such a way that the differences between the branches get smaller over time as developers gradually adopt the ways of the refined 3.x language and libraries - this has been happening with Zope 2.x and Zope 3.x, in fact. Personally, I plan to stick with Python 2.x for some time to come unless something really compelling shows up in Python 3.x, and I even intend to hang on to Python 2.4.x for as long as I reasonably can. There's no point in upgrading systems purely for the sake of upgrading. Paul From khemkaamit at gmail.com Fri May 25 08:04:28 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Fri, 25 May 2007 17:34:28 +0530 Subject: Xml parser In-Reply-To: <46557351.9050205@motorola.com> References: <46557351.9050205@motorola.com> Message-ID: <1360b7230705250504y1e1edf93gad9d8c9083dbc0e1@mail.gmail.com> On 5/24/07, ashish wrote: > Hi All, > > I want to know weather is there any api available in python for parsing > xml(XML parser) Checkout cElementTree . Cheers, -- ---- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. From nogradi at gmail.com Sat May 12 12:38:50 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Sat, 12 May 2007 18:38:50 +0200 Subject: Dynamic subclassing ? In-Reply-To: <1178976888.443891.116090@y80g2000hsf.googlegroups.com> References: <1178976888.443891.116090@y80g2000hsf.googlegroups.com> Message-ID: <5f56302b0705120938m2b00b0d5pee957a42349ac5a5@mail.gmail.com> > I've got an instance of a class, ex : > > b=gtk.Button() > > I'd like to add methods and attributes to my instance "b". > I know it's possible by hacking "b" with setattr() methods. But i'd > like to do it with inheritance, a kind of "dynamic subclassing", > without subclassing the class, only this instance "b" ! > > In fact, i've got my instance "b", and another class "MoreMethods" > > class MoreMethods: > def sayHello(self): > print "hello" > > How could i write ... > > "b = b + MoreMethods" > > so "b" will continue to be a gtk.Button, + methods/attributs of > MoreMethods (it's what i call "dynamic inheritance") ...so, things > like this should work : > > - b.set_label("k") > - b.sayHello() > > I can't find the trick, but i'm pretty sure it's possible in an easy > way. How about: class MoreMethods: def sayHello(self): print "hello" class myButton( gtk.Button, MoreMethods ): pass b = myButton( ) isinstance( b, gtk.Button ) # True b.sayHello( ) # "hello" Daniel From phd at phd.pp.ru Thu May 10 11:02:51 2007 From: phd at phd.pp.ru (Oleg Broytmann) Date: Thu, 10 May 2007 19:02:51 +0400 Subject: SQLObject 0.8.4 Message-ID: <20070510150251.GF18313@phd.pp.ru> Hello! I'm pleased to announce the 0.8.4 release of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.8.4 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.8.3 ---------------- Bug Fixes --------- * Fixed a bug in SQLRelatedJoin that ignored per-instance connection. * Fixed a bug in MySQL connection in case there is no charset in the DB URI. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From yavannadil at yahoo.com Thu May 3 15:33:26 2007 From: yavannadil at yahoo.com (yavannadil at yahoo.com) Date: 3 May 2007 12:33:26 -0700 Subject: How do I get type methods? Message-ID: <1178220806.664557.245780@c35g2000hsg.googlegroups.com> Hello! If I do import uno localContext=uno.getComponentContext() then localContext is of type I guess it's a new type provided by PyUNO extension. localContext.__class__ is None Is there any way to list all methods of that new type, via Python C API or through interpreter (other then dir(localContext) )? What I want is to call localContext's methods like in the tutorial example: x=MyClass() MyClass.f(x) Thank you, Dmitri From thorsten at thorstenkampe.de Thu May 31 15:38:15 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Thu, 31 May 2007 20:38:15 +0100 Subject: generating a tree-like structure References: <1180638948.157965.210260@q66g2000hsg.googlegroups.com> Message-ID: * (31 May 2007 12:15:48 -0700) > On May 31, 12:44 pm, Thorsten Kampe wrote: > > This is a fairly general question: is there some kind of module or > > framework that allows building a tree like structure from certain kind > > of data? > > > > To be specific: I have a program that dumps the content of a LDAP > > directory including all properties and values and groups the result > > from the LDAP search by objClass. > > > > Now I was thinking: would it be possible to generate from the totally > > unordered output that the LDAP server gives me, a tree like > > representation that displays the hierarchy (omitting the values or > > even properties if necessary)? > > > > It should be a textual representation of what you see in GUI programs > > like "LDAP Administrator" but the output should be represented like > > the "tree" program in Linux or Windows "tree.com". > > I think you might be able to use ElementTree. The website for the > module claims it can be used for hierarchical data structures: > http://effbot.org/zone/element-index.htm > > Did you look at any of the Python LDAP tools? They might be useful > too. See some of the links below: > http://linuxjournal.com/article/6988 > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303336 > > Hopefully they'll give some guidance. I've not used LDAP myself as of > yet. I already have the LDAP output part working - with python-ldap under Cygwin - and I generate HMTL output with markup.py. Pretty simple. But a tree structure output would be even prettier... From aspineux at gmail.com Thu May 24 15:24:58 2007 From: aspineux at gmail.com (aspineux) Date: 24 May 2007 12:24:58 -0700 Subject: need advice on building core code for python and PHP In-Reply-To: <1180028001.569139.317660@q66g2000hsg.googlegroups.com> References: <1180025115.704410.250890@a35g2000prd.googlegroups.com> <1180028001.569139.317660@q66g2000hsg.googlegroups.com> Message-ID: <1180034698.387087.251590@o5g2000hsb.googlegroups.com> On 24 mai, 19:33, Szabolcs Nagy wrote: > > Is there a way I could code the base (core) code in Python and have > > PHP call it? I've really liked using SQLAlchemy and there are other > > * quick and dirty solution: > in a shell: > $ python yourscript.py pipe_out > in the php script: > fwrite(pipe_in, input_data); > results = fread(pipe_out, sizeof_results); > > * simple and nice solution: > do not ever use php Write a CGI wrapper around your python script, and publish it using mod_python. And make the appropriate http requests from PHP. From dustin at v.igoro.us Thu May 3 13:12:27 2007 From: dustin at v.igoro.us (dustin at v.igoro.us) Date: Thu, 3 May 2007 12:12:27 -0500 Subject: _csv.Error: string with NUL bytes In-Reply-To: <1178211458.634214.306500@o5g2000hsb.googlegroups.com> References: <1178204593.280648.208040@c35g2000hsg.googlegroups.com> <1178209090.674787.202970@o5g2000hsb.googlegroups.com> <1178211458.634214.306500@o5g2000hsb.googlegroups.com> Message-ID: <20070503171227.GA3560@v.igoro.us> On Thu, May 03, 2007 at 09:57:38AM -0700, fscked wrote: > > As Larry said, this most likely means there are null bytes in the CSV file. > > > > Ciao, > > Marc 'BlackJack' Rintsch > > How would I go about identifying where it is? A hex editor might be easiest. You could also use Python: print open("filewithnuls").read().replace("\0", ">>>NUL<<<") Dustin From daniele.varrazzo at gmail.com Mon May 7 13:57:46 2007 From: daniele.varrazzo at gmail.com (Daniele Varrazzo) Date: 7 May 2007 10:57:46 -0700 Subject: Latest errors on pickled objects and blob datatypes in mysql In-Reply-To: References: Message-ID: <1178560666.419489.41400@o5g2000hsb.googlegroups.com> On 7 Mag, 19:08, "krishnakant Mane" wrote: > hello, > finally the errors for my sql query have changed so I have even > changed the thread subject because I feel now that this is not doable > in mysql and this seams to be a bug, ither in python or the MySQLdb > module or perhaps both. And why not also a bug in MySQL? Or a neutrino hitting your CPU changing a 0 into an 1? Doesn't the Occam razor suggest it may be your fault? :) > my table is called testobj and the blob field is called obj. > now following is my query with the cursor named CSRInsert. > CSRInsert.execute("insert into testobj (obj) values (?);",(pickled_object)) > the error is, > "type error, not all arguments formatted during string formatting ". > > can some one now figure out what could be the problem? Please, read the fine manual. if you had read the DBAPI documentation as previously suggested, you would know that you MUST use "%s" placeholder, not "?" (because MySQLdb.paramstyle == 'format'). Just replace the placeholder in your sql string and keep passing sql and values as two distinct arguments. The second argument of the execute() method MUST be a tuple (or a mapping for named parameters, but let's stick to the positional ones). "(pickled_object)" is not a tuple, it is just an object in parenthesis. To represent a tuple with a single argument you must write "(pickled_object,)", notice the trailing comma. Try: CSRInsert.execute("insert into testobj (obj) values (%s);", (pickled_object,)) -- Daniele From a.schmolck at gmail.com Mon May 14 07:43:07 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: Mon, 14 May 2007 12:43:07 +0100 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <7x4pmg716p.fsf@ruckus.brouhaha.com> Message-ID: Neil Hodgson writes: > Paul Rubin wrote: >>> Plenty of programming languages already support unicode identifiers, >> >> Could you name a few? Thanks. > > C#, Java, Ecmascript, Visual Basic. (i.e. everything that isn't a legacy or niche language) scheme (major implementations such as PLT and the upcoming standard), the most popular common lisp implementations, haskell[1], fortress[2], perl 6 and I should imagine (but haven't checked) all new java or .NET based languages (F#, IronPython, JavaFX, Groovy, etc.) as well -- the same goes for XML-based languages. (i.e. everything that's up and coming, too) So as Neil said, I don't think keeping python ASCII and interoperable is an option. I don't happen to think the anti-unicode arguments that have been advanced so far terribly convincing so far[3], but even if they were it wouldn't matter much -- the ability of functioning as a painless glue language has always been absolutely vital for python. cheers 'as Footnotes: [1] [2] [3] Although I do agree that mechanisms to avoid spoofing and similar problems (what normalization scheme and constraints unicode identifiers should be subjected to) merit careful discussion. From paul at floorball-flamingos.nl Thu May 31 15:09:15 2007 From: paul at floorball-flamingos.nl (Paul Melis) Date: Thu, 31 May 2007 21:09:15 +0200 Subject: Python memory handling In-Reply-To: <1180623978.372352.194860@q69g2000hsb.googlegroups.com> References: <1180611604.247696.149060@h2g2000hsg.googlegroups.com> <1180623978.372352.194860@q69g2000hsb.googlegroups.com> Message-ID: <465f1d5c$0$18138$9a622dc7@news.kpnplanet.nl> frederic.pica at gmail.com wrote: > I will try later with python 2.5 under linux, but as far as I can see, > it's the same problem under my windows python 2.5 > After reading this document : > http://evanjones.ca/memoryallocator/python-memory.pdf > > I think it's because list or dictionnaries are used by the parser, and > python use an internal memory pool (not pymalloc) for them... I tried the f.readlines() approach and with 2.5 on linux the list is freed. Paul From carsten at uniqsys.com Fri May 4 22:19:49 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 04 May 2007 22:19:49 -0400 Subject: What happened to webmaster@python.org? Message-ID: <1178331589.3212.24.camel@localhost.localdomain> Hiya, I just tried sending an email to webmaster at python.org to request a website change, and the email bounced back with this excerpt from the delivery failure report: """ Reporting-MTA: dns; bag.python.org [...] Final-Recipient: rfc822; webmaster at bag.python.org Original-Recipient: rfc822; webmaster at python.org Action: failed Status: 5.0.0 Diagnostic-Code: X-Postfix; unknown user: "webmaster" """ Who should I contact to request the website change? Thanks, Carsten. From eBankGame2010 at gmail.com Mon May 21 06:18:48 2007 From: eBankGame2010 at gmail.com (ebankgame.com) Date: 21 May 2007 03:18:48 -0700 Subject: www.eBankGame.com Buy WoW gold RS gold WG k gold Message-ID: <1179742728.092348.315800@u36g2000prd.googlegroups.com> www.eBankGame.com Buy WoW gold RS gold WG k gold www.eBankGame.com (w w w .e BankGame . c o m ) As you might or might not known that Taiwan earthquake has caused most of supplier are experiencing the serve problem to process the gold. However, eBankGame is always stay line with all the game players to help you guys to enjoy the game at any time. We provide Gold Farmer service for you to own the gold with little bit expense. Your expense will be more valuable by take one action and gain multiple purposes. The service is focus on gold farming for your character in the game by using professional human player to taking tasks and gain reputation in the game in order to gain the gold for you (We do not apply any plug- in or Bots on your character). Meanwhile your character will be improved 1-15 power leveling which depends on your original level (this aspect is not available for Level 60). www.eBankGame.com (w w w .e BankGame . c o m) 1.The Fastest Delivery Speed on all Servers in 1-8 hours since your payment arrives.If the deliver is delayed over 8 hours, you will get 5% extra gold for the late.Or you can request a refund. 2.Special Discount Servers.Sometimes, there will be some servers, with special discounts, with extremely NICE PRice on some certain servers. 3.Perfect Service.24 hours service with various contact methods: MSN, ICQ, Online Chat on Web homepage,Welcome to www.eBankGame.com If any problem, please contact us asap! Happy shopping! Sincerely, www.eBankGame.com E-mail:ebankgame2010 at gmail.com MSN:ebagame2010 at msn.com ICQ:468873592 Choose your game World of Warcraft EU World of Warcraft US Lord of The Rings EU Lord of The Rings US Lineage II EverQuest2 Guild Wars Final Fantacy XI Runescape 2 RFO Online Dungeons & Dragons Online Eve Online Star Wars Galaxies go to www.eBankGame.com From aspineux at gmail.com Thu May 24 13:08:16 2007 From: aspineux at gmail.com (aspineux) Date: 24 May 2007 10:08:16 -0700 Subject: No file from stdin In-Reply-To: <20070524184811.6e439221.tartifola@gmail.com> References: <20070524184811.6e439221.tartifola@gmail.com> Message-ID: <1180026496.005351.6600@q75g2000hsh.googlegroups.com> On 24 mai, 18:48, Tartifola wrote: > Hi, > suppose a script of python is waiting for a file from the stdin and none > is given. How can I make the script to stop and, for example, print an > error message? > > Sorry for the n00b question and thanks import sys import os.path if len(sys.argv)<2: print >>sys.stderr, 'Usage: %s filename' % (os.path.basename(sys.argv[0]),) sys.exit(1) print 'Your filename is %s' % (sys.argv[1],) From gagsl-py2 at yahoo.com.ar Mon May 14 03:21:03 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 14 May 2007 04:21:03 -0300 Subject: Interesting list Validity (True/False) References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> <1178914190.166662.285410@p77g2000hsh.googlegroups.com> <1178915791.584216.293130@l77g2000hsb.googlegroups.com> <1178918808.091358.233740@o5g2000hsb.googlegroups.com> <1179017740.656323.209590@e51g2000hsg.googlegroups.com> <1179020634.130689.171960@o5g2000hsb.googlegroups.com> <1179073565.933957.174250@o5g2000hsb.googlegroups.com> <1179110721.982567.89610@p77g2000hsh.googlegroups.com> Message-ID: En Sun, 13 May 2007 23:45:22 -0300, mensanator at aol.com escribi?: > On May 13, 2:09?pm, Carsten Haese wrote: >> There are no exceptions. > "...and when I say none, I mean there is a certain amount." One of the beautiful things about Python that I like, is how few exceptions it has; most things are rather regular. -- Gabriel Genellina From antroy at gmail.com Wed May 2 03:36:29 2007 From: antroy at gmail.com (Ant) Date: 2 May 2007 00:36:29 -0700 Subject: os.path.join In-Reply-To: <1178089436.202973.148650@h2g2000hsg.googlegroups.com> References: <1178072869.844914.59010@u30g2000hsc.googlegroups.com> <1178083903.677905.32710@c35g2000hsg.googlegroups.com> <1178089436.202973.148650@h2g2000hsg.googlegroups.com> Message-ID: <1178091389.258193.10200@u30g2000hsc.googlegroups.com> On May 2, 8:03 am, half.ital... at gmail.com wrote: > On May 1, 11:10 pm, "Gabriel Genellina" ... > > I think it's a bug, but because it should raise TypeError instead. > > The right usage is os.path.join(*pathparts) ... > Wow. What exactly is that * operator doing? Is it only used in > passing args to functions? Does it just expand the list into > individual string arguments for exactly this situation? Or does it > have other uses? It's used for unpacking a collection into arguments to a function. It's also used at the other end for receiving a variable length set of arguments. i.e. >>> x = (1,3) >>> def add(a, b): return a + b >>> add(*x) 4 >>> def add(*args): return reduce(int.__add__, args) >>> add(1,2,3,4,5,6) 21 >>> add(*x) 4 The same sort of thing holds for keyword arguments: >>> def print_kw(**kw): for k in kw: print kw[k] >>> print_kw(a=1, b=2) 1 2 >>> d = {'a': 1, 'b': 10, 'c': 100} >>> print_kw(**d) 1 100 10 From gagsl-py2 at yahoo.com.ar Sat May 19 13:57:26 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 19 May 2007 14:57:26 -0300 Subject: Writelines() a bit confusing References: <1179578195.565952.244110@u30g2000hsc.googlegroups.com> <464EFC46.8090902@pythonmeister.com> Message-ID: En Sat, 19 May 2007 10:31:50 -0300, Stefan Sonnenberg-Carstens escribi?: > so you'd want this: > > f.writelines([x+os.linesep for x in strings]) > > or something similar. You would use os.linesep *only* if the file was opened in binary mode - unusual if you want to write lines of text. For a file opened in text mode (the default) the line terminator is always '\n' - let Python handle the platform differences. On Windows you would end with malformed or duplicate line terminators if you use explicitely os.linesep when writing. See http://mail.python.org/pipermail/python-list/2000-May/037191.html -- Gabriel Genellina From daniel.gadenne at caramail.fr Tue May 22 13:58:13 2007 From: daniel.gadenne at caramail.fr (daniel gadenne) Date: Tue, 22 May 2007 19:58:13 +0200 Subject: dabo framework dependancies In-Reply-To: References: <1179761984.704369.116310@b40g2000prd.googlegroups.com> Message-ID: <46532f57$0$32303$426a34cc@news.free.fr> Paul McNett wrote: > Shameless plug: consider using Dabo on top of wxPython - we feel it > makes wxPython even easier and more pythonic, but admittedly there's a > bit of a learning curve there too. Even though Dabo is a full > application framework originally meant for desktop database > applications, it is modular and you can choose to only use the UI > bits... http://dabodev.com Hi Paul, I'm considering moving over to dabo for wxpython development. However I do not write traditional database applications ? la foxpro (I'm a 20 years user of fox...) anymore. Only xml-fed applications. I'm a bit hesitant to jump onboard since dabo seemns to carry over its own lot of database connectivity dependancy. Can you reasonably use dabo for plain datafree application? Fran?ois From siona at chiark.greenend.org.uk Thu May 17 08:47:08 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 17 May 2007 13:47:08 +0100 (BST) Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <+Yl*xeSKr@news.chiark.greenend.org.uk> Message-ID: Hendrik van Rooyen wrote: >"Sion Arrowsmith" wrote: >>Hendrik van Rooyen wrote: >>>I still don't like the thought of the horrible mix of "foreign" >>>identifiers and English keywords, coupled with the English >>>sentence construction. >>How do you think you'd feel if Python had less in the way of >>(conventionally used) English keywords/builtins. Like, say, Perl? >Would not like it at all, for the same reason I don't like re's - >It looks like random samples out of alphabet soup to me. What I meant was, would the use of "foreign" identifiers look so horrible to you if the core language had fewer English keywords? (Perhaps Perl, with its line-noise, was a poor choice of example. Maybe Lisp would be better, but I'm not so sure of my Lisp as to make such an assertion for it.) -- \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 enleverlesX.XmcX at XmclaveauX.com Sat May 12 13:33:16 2007 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Sat, 12 May 2007 19:33:16 +0200 Subject: Bug? import cp1252 Message-ID: <46462b1a$0$25919$ba4acef3@news.orange.fr> Hi! I've a problem with these 2 scripts: file aaa.py (write in ANSI/cp1252): # -*- coding: cp1252 -*- compo={} compo['pxrtf']= { 'fichier': "pxrtf.py", 'description': "G?n?ration de fichiers RTF" } file bbb.py (write in ANSI/cp1252): # -*- coding: cp1252 -*- import aaa With run bbb.py, I see: Traceback (most recent call last): File "D:\dev\python\bbb.py", line 3, in import aaa File "D:\dev\python\aaa.py", line 3 ^ SyntaxError: invalid syntax (run directly aaa.py give no problem) (Python 2.5.1 + win_XP-SP2_french) BUT, if I write the file aaa.py in UTF-8, with 1st line: # -*- coding: utf-8 -*- the problem is removed (file bbb.py stay in ANSI/cp1252) Bug? or am I wrong? @-salutations Michel Claveau From rogerb at rogerbinns.com Wed May 23 20:00:52 2007 From: rogerb at rogerbinns.com (Roger Binns) Date: Wed, 23 May 2007 17:00:52 -0700 Subject: How to release the GIL from C? In-Reply-To: References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Roger Binns wrote: > I am trying to release the GIL in a multi-threaded program (efforts > detailed below) without any success. The ultimate cause was that the program forked to go into daemon mode. I had called PyOS_AfterFork() as the documents directed. What I hadn't realised (and isn't documented) is that AfterFork() reinitialises the Python threading state by making a new GIL and acquires it. The acquiring bit meant none of my other threads could ever get it. It is still unclear from the docs exactly which combination of functions dealing with threadstate, threads and lock you need to call to just unilaterally give up the GIL (ie when you don't have following block that wants to reacquire the GIL) Roger -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (GNU/Linux) iD8DBQFGVNW0mOOfHg372QQRAuyOAJ4pCCIK779XgvaUdKBtSa+nHElrHQCgiueP n/0uMFCSH3SrQhMXdm2Jb/o= =uh4D -----END PGP SIGNATURE----- From a.schmolck at gmail.com Sun May 6 08:48:50 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: Sun, 06 May 2007 13:48:50 +0100 Subject: Emacs and pdb after upgrading to Ubuntu Feisty References: <1178426788.614637.209400@w5g2000hsg.googlegroups.com> Message-ID: levander writes: > Anybody can tell me who to get pdb working under emacs on Ubuntu > Feisty? This is not a direct answer to your question, but I'd recommend you try ipython (apt-get'able) and ipython.el; (manual install). Just enter ``pdb on`` in the interactive shell to end up in the debugger on errors and the corresponding file and line is opened in emacs. BTW, I'd also suggest to upgrade to emacs-snapshot (23 alpha -- but don't be overly worried -- seems more stable than 21. to me so far), for one thing you get decent (ttf) fonts: 'as From zubeido at yahoo.com.br Sat May 19 08:36:35 2007 From: zubeido at yahoo.com.br (aiwarrior) Date: 19 May 2007 05:36:35 -0700 Subject: Writelines() a bit confusing Message-ID: <1179578195.565952.244110@u30g2000hsc.googlegroups.com> If file.WriteLines( seq ) accepts a list and it says it writes lines, why does it write the whole list in a single line. Be cause of that the reverse of file.writelines(seq) is not file.readlines(). Are the assumptions i made correct? If yes why is this so? I find a function called writelines not actualy writing the list in lines wierd. [code] something = ['re','ri','ro'] f.writelines( something ) something_else = f.readlines() [/code] In this case the list something_else will be diffrent from something From vb at itechart.com Fri May 11 07:34:33 2007 From: vb at itechart.com (VB) Date: 11 May 2007 04:34:33 -0700 Subject: Custom Software Development Message-ID: <1178883272.993621.107170@e51g2000hsg.googlegroups.com> iTechArt Group - Custom Software Development and Offshore outsourcing Company http://www.itechart.com/ Offshore custom software development company iTechArt - Web site and Content Management Solutions development, CMS consulting: Ektron, Drupal and DotNetNuke iTechArt Group provides high quality custom software development services and offshore software development. On December 2006, iTechArt Group became an authorized Microsoft Certified Partner. This means that our company has been recognized by Microsoft for our vast expertise and authorized to custom software development; provide IT service consulting and custom business solutions. Custom Software Development and Offshore outsourcing Company iTechArt has worked together since 2003 to design build and deliver .NET Web Content Management software solutions that help clients meet their strategic objectives. We are agile oriented development partner able to consistently deliver solid results. iTechArt software development team assemblies specialists in the development of custom software applications and offshore software outsourcing services. Working concepts of our company are based on proven approaches and international standards used for custom software development such as Capability Maturity Model Integration for Software Engineering (CMMI- SW). In the same breath we have our own standpoint on software development process management which is fully effective and comprehensible for our clients. iTechArt offers software development in the next main directions: 1. Custom Software Development (Offshore outsourcing for worldwide based software development companies.) 2. Software Development for Digital Signage (Media content development and remote displays / information kiosks Web-based software application management.) 3. Web Site Development (E-commerce solutions, CMS/DotNetNuke/Ektron/ Drupal, Web 2.0/PHP/MySQL/AJAX, Flash/Action script/Flex and many more.) 4. Offshore Development Center (Dedicated development team of software developers. Our offshore development centers operate as an extension to clients' existing software engineering business.) Contact iTechArt ( http://www.itechart.com/ )about custom software development, end-to-end software solutions, outsourcing software development, custom DotNetNuke module development, DotNetNuke consulting, dotnetnuke hosting, first class Java and .Net developers, software application design, software testing, Quality Assurance, functionality testing and defect analysis, performance and stress testing, usability testing, Microsoft Media Services and Adobe Media Flash Server solutions, digital signage solutions and custom development, Ektron CMS400.NET developers, CMS, .NET Web Content Management software solutions Web: http://www.itechart.com/ http://www.itechart.com/Pages/ProductsServices/HowWeWork.aspx http://www.itechart.com/Pages/ProductsServices/BusinessModels.aspx http://www.itechart.com/Pages/ProductsServices/CustomSoftwareDevelopment.aspx http://www.itechart.com/Pages/ProductsServices/DotNetNukeModuleDevelopment.aspx From larry.bates at websafe.com Thu May 3 09:38:00 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 03 May 2007 08:38:00 -0500 Subject: passing an array of variant in vb to a python COM object = win32com bug ? In-Reply-To: <1178196117.469260.12770@e65g2000hsc.googlegroups.com> References: <1178178883.246149.279780@c35g2000hsg.googlegroups.com> <1178196117.469260.12770@e65g2000hsc.googlegroups.com> Message-ID: vml wrote: > On 3 mai, 14:20, "Gabriel Genellina" wrote: >> En Thu, 03 May 2007 04:54:43 -0300, vml escribi?: >> >> >> >>> I have a python com object which contains a method to inverse an array >>> in vb 6 the definition of the class is : >>> class Fop: >>> _public_methods_ = [ 'SqVal' ] >>> def SqVal(self,*val): >>> #vol=(val[0][0],val[0][1]) >>> #mat1=mat((vol)) >>> #up=linalg.inv(mat1) >>> return str(val)#up >>> _reg_verprogid_ = "Python.Fop.3" >>> _reg_progid_ = "Python.Fop" >>> _reg_desc_ = "Python Fop" >>> _reg_clsid_ = "{30BD3490-2632-11cf-AD5B-524153480001}" >>> I pass to this method an array of variant which is the matrix to >>> invert like that: >>> vb6 code : >>> Set obj = CreateObject("Python.Fop") >>> Dim ty(1, 1) As Variant >>> ty(0, 0) = 1 >>> ty(1, 0) = 2 >>> ty(0, 1) = 3 >>> ty(1, 1) = 4 >>> toto = obj.SqVal(ty) >>> when I dispaly toto as str(val) I obtain the following tuple "(((1, >>> 3), (2, 4)),)" which is not usable .... >>> Do you have an idea to explain this strange behaviour ? >> This is the expected behaviour. Writing it completely in Python: >> >> py> def SqVal(*val): >> ... return str(val) >> ... >> py> ty=((1,3),(2,4)) >> py> SqVal(ty) >> '(((1, 3), (2, 4)),)' >> >> The *val parameter receives a tuple, whose elements are the positional >> arguments used when calling the function. As you call the function with a >> single argument, val receives a tuple with a single element. >> Perhaps you want to write it as: >> >> py> def SqVal(val): >> ... print val[0][0] >> ... print val[0][1] >> ... print val[1][0] >> ... print val[1][1] >> ... >> py> SqVal(ty) >> 1 >> 3 >> 2 >> 4 >> >> (Of course, if used as a Fop method, dont forget the "self" parameter) >> >> -- >> Gabriel Genellina > > I just tried to replace the *val by SqVal(self,val) and call the > method in vb but it crashes down : > > "when refilling safe array the sequence must have the same number of > dimension as the existing array" > > my python code is now : > > def SqVal(self,val): > ## volr=[val[0][0][i] for i in range(size(val,2))] > ## voli=[val[0][1][i] for i in range(size(val,2))] > ## mat1=mat(volr)+1j*mat(voli) > ## up=linalg.pinv(mat1) > ## out=up.real.tolist() > ## out.extend(up.imag.tolist()) > return val > > By the way Do you have any idea to debug the com server script ? ( I > would like to know if a can access the value in the function while > calling it from vb 6) > > > > > tahnks a lot ! > > Debugging COM objects is best done using logging module or at least writing to a file during processing. You can review the log file to see what was going on. -Larry From whamil1 at entergy.com Tue May 1 09:14:53 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Tue, 1 May 2007 08:14:53 -0500 Subject: Dict Copy & Compare In-Reply-To: Message-ID: <588D53831C701746A2DF46E365C018CE01D2CA84@LITEXETSP001.etrsouth.corp.entergy.com> > -----Original Message----- > From: Steven D'Aprano > Sent: Monday, April 30, 2007 10:14 PM > To: python-list at python.org > Subject: RE: Dict Copy & Compare > > On Mon, 30 Apr 2007 12:50:58 -0500, Hamilton, William wrote: > > >> On quick question, how can I order a dict by the 'values' (not keys) > >> before > >> looping? Is that possible? > >> > > > > The easiest way I can think of is to create a new dict that's reversed. > > > > reverseDict = {} > > for key in dict1: > > if dict1[key] not in reverseDict: > > reverseDict[dict1[key]]=[key] > > else: > > reverseDict[dict1[key]].append(key) > > > > This gives you a dictionary that has the old dict's values as keys, and > > the old dict's keys as lists of values. You can then sort the keys of > > this dict and do what you want with it. Of course, the values in dict1 > > have to be valid dictionary keys for this to work. If they aren't, you > > may be able to get away with converting them to strings. > > > Oh man, maybe you need to re-think what you consider "easier". > > for value in dict1.itervalues() > do_something_with(value) This iterates through a list of values, with no information about the keys at all. Not particularly applicable to the OP's needs. > If you need the keys as well: > > for key, value in dict1.iteritems() > do_something_with(key, value) This iterates through values and keys, in no particular order. Still not useful. > > If you need to process the values (say, sort them) first: > > pairs = list(dict1.iteritems()) # or dict1.items() > pairs.sort() > for key, value in pairs: > do_something_with(key, value) > > I'll leave sorting by value instead of key as an exercise. Hrmm. Maybe you missed the part where the OP was asking how to sort a dict's contents by value? I'm pretty sure I quoted it. My bit of code would be better if I had used iteritems() (I hadn't come across that function yet). But, it's a solution, and more useful than vague statements about what someone else needs to rethink and various bits of code that don't solve the problem presented. --- -Bill Hamilton From bbxx789_05ss at yahoo.com Tue May 15 02:41:27 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 14 May 2007 23:41:27 -0700 Subject: removing spaces between 2 names In-Reply-To: References: <1179208842.114189.233060@e65g2000hsc.googlegroups.com> Message-ID: <1179211287.521561.309130@e65g2000hsc.googlegroups.com> On May 15, 12:14 am, Steven Howe wrote: > saif.shak... at gmail.com wrote: > > Hi, > > Suppose i have a string stored in variable,how do i remove the > > space between them,like if i have the name: > > "USDT request" in a variable.i need "USDTrequest",without any space . > > Thanks > > from string import replace > st = 'abcd acdfg xtit' > st.replace(' ','') > 'abcdacdfgxtit' > > sph > > -- > HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 The methods in the string module are deprecated. Skip the import and use a string's built in replace() method instead: s = "hello world" result = s.replace(" ", "") print result From kyosohma at gmail.com Tue May 8 17:19:41 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 8 May 2007 14:19:41 -0700 Subject: Another easy pair of questions In-Reply-To: <4640E7A1.7000902@v.loewis.de> References: <1178655556.202998.241870@e65g2000hsc.googlegroups.com> <4640E7A1.7000902@v.loewis.de> Message-ID: <1178659181.732068.106970@l77g2000hsb.googlegroups.com> On May 8, 4:12 pm, "Martin v. L?wis" wrote: > > In a python Tk shell in Windows, what is the equivalent of unix's pwd? > > os.getcwd() > > > In a python Tk shell in Windows, is there an easy way to reoeat an > > earlier command, similar to Tcl/Tk's hist? > > Press the cursor-up key. > > Martin Lots more information on getting path information can be found at this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/474083 Mike From duncan.booth at invalid.invalid Wed May 30 03:25:41 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 30 May 2007 07:25:41 GMT Subject: Unicode to HTML entities References: <1180453921.357081.89500@n15g2000prd.googlegroups.com> <1180455075.419150.166050@r19g2000prf.googlegroups.com> Message-ID: Clodoaldo wrote: > On May 29, 12:57 pm, "Richard Brodie" wrote: >> "Clodoaldo" wrote in message >> >> news:1180453921.357081.89500 at n15g2000prd.googlegroups.com... >> >> >I was looking for a function to transform a unicode string into >> >htmlentities. >> >>> u'S?o Paulo'.encode('ascii', 'xmlcharrefreplace') >> >> 'São Paulo' > > That was a fast answer. I would never find that myself. > You might actually want: >>> cgi.escape(u'S?o Paulo & Esp?rito Santo').encode('ascii', 'xmlcharrefreplace') 'São Paulo & Espírito Santo' as you have to be sure to escape any ampersands in your unicode string before doing the encode. From info at egenix.com Tue May 29 11:33:41 2007 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Tue, 29 May 2007 17:33:41 +0200 Subject: ANN: eGenix mxODBC 3.0 Developer Licenses (mxODBC Database Interface) Message-ID: <465C47D5.5070903@egenix.com> ________________________________________________________________________ eGenix.com mxODBC 3.0 Developer Licenses Available ________________________________________________________________________ eGenix is pleased to announce the immediate availability of developer licenses for our Python ODBC database interface, the eGenix mxODBC Distribution 3.0 for Python. This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/mxODBC-3.0-Developer-License-Announcement.html ________________________________________________________________________ INTRODUCTION The eGenix mxODBC Distribution is an add-on distribution for our eGenix mx Base Distribution. It comes with mxODBC, our universal ODBC database interface for Python. ________________________________________________________________________ DEVELOPER LICENSES FOR mxODBC 3.0 eGenix is now shipping developer licenses for mxODBC which allow the integration and redistribution of mxODBC into your products. * Make use of the power and flexibility of this cross-platform, robust and stable interface and connect to most available databases with less hassles, fewer configuration problems and great performance. * Enjoy the same database interface API on all supported platforms: Windows, Linux, Mac OS X, FreeBSD and Solaris. * This is true write-once, deploy anywhere ! ________________________________________________________________________ HOW DOES IT WORK ? The setup works just like for a regular stand-alone installation of mxODBC. eGenix will send you the required license files after purchase and all you have to do, is install them in the product folder. You can then work on your product and ship the license files together with the product, so that your customers can use the product integrated mxODBC just like you do on your development machines. Once licensed, you don't have to pay eGenix royalties or fees for distributing mxODBC together with your products. ________________________________________________________________________ WHICH RESTRICTIONS APPLY ? Restrictions are very modest: * you must get a proper license for all developer machines and developers working on the product * the mxODBC version included in the product must be tied to your product, ie. it should not be usable outside your product * you are not permitted to use mxODBC in a product that would introduce competition for eGenix products. The full legal details are available in the eGenix.com Commercial License Agreement 1.2.0. Please see the product page for details: http://www.egenix.com/products/python/mxODBC/#Licensing ________________________________________________________________________ TRY BEFORE YOU BUY You can request 30-day evaluation licenses by writing to sales at egenix.com, stating your name (or the name of the company) and the number of eval licenses that you need. We will then issue you licenses and send them to you by email. Please make sure that you can receive ZIP file attachments on the email you specify in the request, since the license files are send out as ZIP attachements. ________________________________________________________________________ PRICING mxODBC 3.0 Developer CPU Licenses can be purchased in our eGenix Online Shop at http://www.egenix.com/shop/. Please see the mxODBC distribution page for details on buying licenses or contact sales at egenix.com. ________________________________________________________________________ DOWNLOADS The download archives and instructions for installing the package can be found at: http://www.egenix.com/products/python/mxODBC/ IMPORTANT: In order to use the eGenix mx Commercial package you will first need to install the eGenix mx Base package which can be downloaded from here: http://www.egenix.com/products/python/mxBase/ _______________________________________________________________________ SUPPORT Commercial support for these packages is available from eGenix.com. Please see http://www.egenix.com/services/support/ for details about our support offerings. Enjoy, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, May 29 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 timr at probo.com Thu May 24 02:56:45 2007 From: timr at probo.com (Tim Roberts) Date: Thu, 24 May 2007 06:56:45 GMT Subject: too much memory use References: <1179860235.044137.295080@a26g2000pre.googlegroups.com> Message-ID: rohit wrote: > >i am making a program for desktop search. >in order to make it more effective im implementing the records in the >form of a tree(files starting with 'a','b','c'....have different >trees ..so 26 trees in all) in memory and writing it down in file. >the max size file has 16000 records...now to implement the tree in >list i'm using line no as index ..and empty child nodes are >represented as "\n" >all this work is going on in the memory.. >problem is the system eats up my 512 mb RAM +1gb virtual store n hangs >cant think of an effective way to implement tree in memory(i can >compact it on disk by writing just the index no..along with the record >from which tree in memory can be reconstructed, but i have to >implement tree as previous to implement random access) Why don't you just use a database? That's what they're designed for. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From nufuhsus at gmail.com Fri May 11 17:15:26 2007 From: nufuhsus at gmail.com (nufuhsus at gmail.com) Date: 11 May 2007 14:15:26 -0700 Subject: Interesting list Validity (True/False) In-Reply-To: <1178917940.363627.216580@y5g2000hsa.googlegroups.com> References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> <1178917940.363627.216580@y5g2000hsa.googlegroups.com> Message-ID: <1178918126.115130.88430@h2g2000hsg.googlegroups.com> On May 11, 5:12 pm, nufuh... at gmail.com wrote: > On May 11, 5:07 pm, Carsten Haese wrote: > > > > > > > On Fri, 2007-05-11 at 12:28 -0700, nufuh... at gmail.com wrote: > > > Hello all, > > > > First let me appologise if this has been answered but I could not find > > > an acurate answer to this interesting problem. > > > > If the following is true: > > > C:\Python25\rg.py>python > > > 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. > > > >>> [] == [] > > > True > > > >>> ['-o'] == [] > > > False > > > >>> ['-o'] == False > > > False > > > Your confusion stems from the fact that for a given object, the answer > > to the following three questions can be vastly different: > > a) Is the object identical to True? > > b) Is the object equal to True? > > c) Is the object considered to be True in an "if" statement? > > > Observe: > > > >>> def check_trueness(obj): > > > ... if obj is True: print repr(obj), "is identical to True." > > ... else: print repr(obj), "is not identical to True." > > ... if obj == True: print repr(obj), "is equal to True." > > ... else: print repr(obj), "is not equal to True." > > ... if obj: print repr(obj), "is considered to be True by if." > > ... else: print repr(obj), "is not considered to be True by if." > > ...>>> check_trueness(True) > > > True is identical to True. > > True is equal to True. > > True is considered to be True by if.>>> check_trueness(1) > > > 1 is not identical to True. > > 1 is equal to True. > > 1 is considered to be True by if.>>> check_trueness([1]) > > > [1] is not identical to True. > > [1] is not equal to True. > > [1] is considered to be True by if.>>> check_trueness([]) > > > [] is not identical to True. > > [] is not equal to True. > > [] is not considered to be True by if. > > > Testing whether an object is equal to True is a much stronger test than > > whether it is considered to be True in an 'if' statement, and the test > > for identity is stronger still. Testing whether an object is equal to > > True or identical to True is useless in most Python programs. > > > So, rather than doing this: > > > if thing==True: > > # blah > > > Just do this: > > > if thing: > > # blah > > > Hope this helps, > > > -- > > Carsten Haesehttp://informixdb.sourceforge.net-Hide quoted text - > > > - Show quoted text - > > Thanks Carsten (& all), I will give the if thing: # blah trick. I > guess I am starting to seem my own confusion. As Grant mentioned, I > was comparing ['-o'] to True which of course is False :o) > > However, how would you test for the falsness of the object arg?- Hide quoted text - > > - Show quoted text - Would that be arg is not True: # blah.? From showell30 at yahoo.com Sun May 27 12:14:47 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 27 May 2007 09:14:47 -0700 (PDT) Subject: PHP5 programmer learning Python In-Reply-To: <1180280496.946434.26760@q69g2000hsb.googlegroups.com> Message-ID: <650522.41140.qm@web33514.mail.mud.yahoo.com> --- romiro wrote: > I've recently tried > C#, a very short > lived re-attempt at C++ and Java, and Ruby. To the extend that you're familiar with C++/Java/Ruby, you may find this link as an interesting way to see how Python looks: http://www.dmh2000.com/cjpr/cmpframe.html ____________________________________________________________________________________Be a better Heartthrob. Get better relationship answers from someone who knows. Yahoo! Answers - Check it out. http://answers.yahoo.com/dir/?link=list&sid=396545433 From jstroud at mbi.ucla.edu Wed May 16 17:58:13 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 16 May 2007 14:58:13 -0700 Subject: How do I tell the difference between the end of a text file, and an empty line in a text file? In-Reply-To: <1179352021.803070.200780@k79g2000hse.googlegroups.com> References: <1179352021.803070.200780@k79g2000hse.googlegroups.com> Message-ID: walterbyrd wrote: > Python's lack of an EOF character is giving me a hard time. > > I've tried: > [ stuff ] for s in f: do_whatever_with_s(s) James From sickcodemonkey at gmail.com Tue May 22 11:52:53 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Tue, 22 May 2007 11:52:53 -0400 Subject: py2exe compiling In-Reply-To: <562a25f0705211232g79c7a7acva40065addf3673ab@mail.gmail.com> References: <562a25f0705211232g79c7a7acva40065addf3673ab@mail.gmail.com> Message-ID: <2adc542f0705220852k62e53b0awf92d1ab4388677ba@mail.gmail.com> Have you looked at the "Tips and Tricks" on Py2exe's website? http://www.py2exe.org/index.cgi/GeneralTipsAndTricks I believe this next link will help you add custom data to your app. http://www.py2exe.org/index.cgi/CustomDataInExe .dave On 5/21/07, Pyro wrote: > > Hello, > > I have just finished my script and am ready to distrabute it. I am having > a little trouble using py2exe though. > > here is what i have at the top of my file for imports: > > import string, array, sgmllib, re, sys, cookielib, urllib2, random, > ConfigParser, time > from urllib2 import urlopen > from ClientForm import ParseResponse > from configobj import ConfigObj > > > Now, there are some other file attributes i need a bit of help with. > > icon = nigel.ico > file name = name > file author = cody woolaver > file version = 0.1.3 > file comments = uhhh, a comment ^^ > > Thanks for your help > ~Cody Woolaver > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From elventear at gmail.com Wed May 2 01:53:55 2007 From: elventear at gmail.com (elventear) Date: 1 May 2007 22:53:55 -0700 Subject: Problem with inspect.getfile In-Reply-To: <1178041715.206440.134530@y80g2000hsf.googlegroups.com> References: <1178041715.206440.134530@y80g2000hsf.googlegroups.com> Message-ID: <1178085235.386994.258310@e65g2000hsc.googlegroups.com> Found the offending code. I was importing between files that were at the same level of the hierarchy without using absolute references. Coded worked fine, but inspect didn't. Was this gaffe on my part? Or was inspect supposed to handle it? Thanks! On May 1, 12:48 pm, elventear wrote: > Hello, > > I am trying to use someone else's module that makes use of > inspect.getsourcelines. The code was not working for me, so I have > been debugging to see why it is not working. I have reduced my problem > to getting the wrong file path in the getfile->return > object.co_filename call. > > Basically the path I get is: > > "/Users/elventear/Documents/UTMEM/Projects/geotools/parsers/parser.py" > > When the correct path should be: > > "/Users/elventear/Documents/UTMEM/Projects/packages/geotools/parsers/ > parser.py" > > Finally my PYTHONPATH contains: > > "/Users/elventear/Documents/UTMEM/Projects/packages" > > So basically, I am able to resolve correctly the package from withing > Python, I don't know why there is this confusion about the filename > that contains my objects and methods. > > Any ideas on how to correct this would be appreciated. > > This is under MacOSX 10.4.9, Python 2.5 (Build from Fink). > > Thanks! From martin at v.loewis.de Sat May 19 03:33:50 2007 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sat, 19 May 2007 09:33:50 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <_pq3i.1390$wH4.1177@news-server.bigpond.net.au> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <464C5382.6080403@v.loewis.de> <1179423799.254286.294930@w5g2000hsg.googlegroups.com> <1179503525.018943.95740@u30g2000hsc.googlegroups.com> <_pq3i.1390$wH4.1177@news-server.bigpond.net.au> Message-ID: <464EA85E.1040508@v.loewis.de> >> But you're making a strawman argument by using extended ASCII >> characters that would work anyhow. How about debugging this (I wonder >> will it even make it through?) : >> >> class ???????? >> ??? = 0 >> ?????? ?? ?=10 > > That would be invalid syntax since the third line is an assignment > with target identifiers separated only by spaces. Plus, the identifier starts with a number (even though ? is not DIGIT SIX, but FULLWIDTH DIGIT SIX, it's still of category Nd, and can't start an identifier). Regards, Martin From szhorvat at gmail.com Mon May 21 07:48:44 2007 From: szhorvat at gmail.com (Szabolcs) Date: Mon, 21 May 2007 13:48:44 +0200 Subject: Lists vs tuples (newbie) Message-ID: I was wondering about why are there both tuples and lists? Is there anything I can do with a tuple that I cannot do with a list? In what circumstances is it advantageous to use tuples instead of lists? Is there a difference in performance? I am still learning Python, so please be gentle ... Szabolcs From skip at pobox.com Fri May 4 12:06:44 2007 From: skip at pobox.com (Skip Montanaro) Date: Fri, 4 May 2007 16:06:44 +0000 (UTC) Subject: curses mystical error output References: <17977.2867.158091.217653@montanaro.dyndns.org> Message-ID: > You might be trying to write to a section that is currently off > screen. Bingo. I *thought* I was okay, but I wasn't refreshing until the end of the display loop, so I never saw all the addstr() calls that had succeeded but which had yet to be painted. Adding a refresh() call in the loop exposed my ignorance. Thx Ian, Skip From steven at REMOVE.THIS.cybersource.com.au Mon May 7 23:35:49 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 08 May 2007 03:35:49 -0000 Subject: randomly write to a file References: <1178567497.042096.82940@w5g2000hsg.googlegroups.com> <1178574062.496137.11640@y5g2000hsa.googlegroups.com> <1hxre1l.15ydbuikdt4dsN%aleax@mac.com> Message-ID: On Mon, 07 May 2007 20:00:57 -0700, Alex Martelli wrote: > Steven D'Aprano wrote: > >> On Mon, 07 May 2007 14:41:02 -0700, Nick Vatamaniuc wrote: >> >> > Rohit, >> > >> > Consider using an SQLite database. It comes with Python 2.5 and >> > higher. SQLite will do a nice job keeping track of the index. You can >> > easily find the line you need with a SQL query and your can write to >> > it as well. When you have a file and you write to one line of the >> > file, all of the rest of the lines will have to be shifted to >> > accommodate, the potentially larger new line. >> >> >> Using an database for tracking line number and byte position -- isn't >> that a bit overkill? >> >> I would have thought something as simple as a list of line lengths >> would do: >> >> offsets = [35, # first line is 35 bytes long >> 19, # second line is 19 bytes long... 45, 12, 108, 67] >> >> >> To get to the nth line, you have to seek to byte position: >> >> sum(offsets[:n]) > > ...and then you STILL can't write there (without reading and rewriting > all the succeeding part of the file) unless the line you're writing is > always the same length as the one you're overwriting, which doesn't seem > to be part of the constraints in the OP's original application. I'm > with Nick in recommending SQlite for the purpose -- it _IS_ quite > "lite", as its name suggests. Hang on, as I understand it, Nick just suggesting using SQlite for holding indexes into the file! That's why I said it was overkill. So whether the indexes are in a list or a database, you've _still_ got to deal with writing to the file. If I've misunderstood Nick's suggestion, if he actually meant to read the entire text file into the database, well, that's just a heavier version of reading the file into a list of strings, isn't it? If the database gives you more and/or better functionality than file.readlines(), then I have no problem with using the right tool for the job. -- Steven. From ai.nature at gmail.com Thu May 31 22:29:09 2007 From: ai.nature at gmail.com (ai) Date: Thu, 31 May 2007 19:29:09 -0700 Subject: How to clean a module? In-Reply-To: References: <1180622824.836459.222090@q19g2000prn.googlegroups.com> Message-ID: <1180664949.469850.63440@j4g2000prf.googlegroups.com> Perhaps you misundstand me. I means if you reedit a module file and reload it, the interpreter doesn't follow the change you have made exactly. For example, you import a module, edit the module file (you may remove a global variable or change its name), save the change, reload the module (or del the module and import it again). At last, you will find the origin variable still exists in the interpreter. If you don't notice this, you may meet some strange problems when you do refacting. On Jun 1, 12:17 am, Maric Michaud wrote: > ai a ?crit : > > > It assumes that there is a module A which have two global variables X > > and Y. If I run "import A" in the IDLE shell, then I can use A.X and > > A.Y correctly. But if I want to change the module A and then delete > > the variable Y, I find I can use A.Y just the same as before! > > It's unlikely to be true, see below. > > > In fact, I have tried all the following methods but can't remove the > > A.Y: > > execute "import A" again > > "reload(A)" > > "del A; import A" > > Yes, if you use "del A.Y", it works. But it is stupid since there are > > probably many names. In my thought, if no one references objects in A, > > "del A" will release all memory about A. But it seems that the fact is > > not. So I can not refresh the namespace to follow changes of a module > > easily and I will worry about the memory if I del a module. > > I want to know if there is a way to clear a module entirely. > > Actually I do not see your problem and your exact need, when I type the > following in python prompt I just see expected behavior, what is a > problem to you ? Maybe you could post a code explaining it. > > In [64]: import a > > In [65]: a.X > > Out[65]: 0 > > In [66]: a.X = 2 > > In [67]: del a > > In [68]: import a as b > > In [69]: b.X > > Out[69]: 2 > > In [71]: for name in [ n for n in b.__dict__ if not n.startswith('__') ] > : > ....: b.__dict__.__delitem__(name) > > ....: > > ....: > > In [72]: b.X > > --------------------------------------------------------------------------- > > Traceback (most recent call > last) > > C:\Documents and Settings\maric\Bureau\ in () > > : 'module' object has no attribute 'X' > > In [73]: reload(b) > > Out[73]: > > In [74]: b.X > > Out[74]: 0 > > In [75]: del b.X > > In [76]: del b > > In [77]: import a > > In [78]: a.b > > --------------------------------------------------------------------------- > > Traceback (most recent call > last) > > C:\Documents and Settings\maric\Bureau\ in () > > : 'module' object has no attribute 'b' From mad.vijay at gmail.com Thu May 3 06:19:28 2007 From: mad.vijay at gmail.com (SamG) Date: 3 May 2007 03:19:28 -0700 Subject: 32 OS on 64-bit machine In-Reply-To: <1178186326.789203@nntpcache01.si.eunet.at> References: <1178183424.548438.303170@y80g2000hsf.googlegroups.com> <1178186326.789203@nntpcache01.si.eunet.at> Message-ID: <1178187568.032961.172620@c35g2000hsg.googlegroups.com> On May 3, 2:58 pm, Harald Karner wrote: > SamG wrote: > > If anyone has a x86_64 machine and is running a 32bit OS on top of > > that.... could you tell me what output would you get for the following > > program > > > #====================== > > import platform > > print platform.processor() > > print platform.architecture() > > #====================== > > > Thanks in advance > > : )~ > > Microsoft Windows XP [Version 5.1.2600] > (C) Copyright 1985-2001 Microsoft Corp. > > C:\>python > Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import platform > >>> print platform.processor () > > >>> print platform.architecture () > ('32bit', 'WindowsPE') > >>> Thanks, I would be more interested in the output on Linux's or Unix Thanks again : )~ From bbxx789_05ss at yahoo.com Thu May 31 04:03:48 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 31 May 2007 01:03:48 -0700 Subject: trouble with wxPython intro In-Reply-To: <1180598161.088508.15920@q69g2000hsb.googlegroups.com> References: <1180581067.908739.252960@a26g2000pre.googlegroups.com> <1180598161.088508.15920@q69g2000hsb.googlegroups.com> Message-ID: <1180598628.211499.212240@m36g2000hse.googlegroups.com> On May 31, 1:56 am, 7stud wrote: > By setting redirect=False in wx.App.__init__(), the errors will be > sent to the console. Hmmm...I just read a note I scribbled in the margin of my book that says setting redirect=False sends the error messages to the console on Mac and Windows. Are you using one of those operating systems? If not, what os are you using, and do you get errors messages in the console when using wx.PySimpleApp()? Thanks From saif.shakeel at gmail.com Mon May 14 05:51:56 2007 From: saif.shakeel at gmail.com (saif.shakeel at gmail.com) Date: 14 May 2007 02:51:56 -0700 Subject: Removing part of string In-Reply-To: <1179129881.435117.146890@e51g2000hsg.googlegroups.com> References: <1179122203.691267.64200@o5g2000hsb.googlegroups.com> <1179129881.435117.146890@e51g2000hsg.googlegroups.com> Message-ID: <1179136316.529622.316700@h2g2000hsg.googlegroups.com> On May 14, 1:04 pm, half.ital... at gmail.com wrote: > On May 13, 10:56 pm, saif.shak... at gmail.com wrote: > > > > > > > Hi, > > I am parsing an xml file ,and one part of structure looks > > something like this: > > > - > PhysicalLink="Infotainment_Control_Bus_CAN"> > > Infotainment_Control_Bus_CAN_TIMEOUT_AX > > Timeout N_As/N_Ar > > Time from transmit request until a CAN frame transmit > > confirmation is received. > > > > > In my code i am extracting the data within > > ,which is Timeout N_As/N_Ar.These tags repeat and will have > > different timer names..like > > > - > PhysicalLink="Infotainment_Control_Bus_CAN"> > > Infotainment_Control_Bus_CAN_TIMEOUT_BS > > Timeout N_Bs > > Time that the transmitter of a multi-frame message > > shall wait to receive a flow control (FC) frame before timing out with > > a network layer error. > > > > > I need to remove the words Timeout from the data,and > > take only the abbrevation..i.e.N_As/N_bs like that .In short i have to > > remove the words which come with name Time,and also the space which > > comes next to it. > > and take only the abbreviation.Can someone help me in this. > > Thanks > > Did you get elementtree working?- Hide quoted text - > > - Show quoted text - Thanks for thr replies.It helped a lot. Regarding the element tree problem,the module error is gone but a new problem has appeared,which i have posted in new thread, From mail at microcorp.co.za Wed May 9 03:03:40 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 9 May 2007 09:03:40 +0200 Subject: SEO - Search Engine Optimization - Seo Consulting References: <1177808356.681710.42980@n76g2000hsh.googlegroups.com> <#O8fXGAjHHA.3700@TK2MSFTNGP06.phx.gbl> <1178160448.699851.227600@p77g2000hsh.googlegroups.com> Message-ID: <013e01c79210$5ef38c60$03000080@hendrik> "Steve Holden" wrote: > Steven D'Aprano wrote: > > On Wed, 02 May 2007 19:47:28 -0700, Huck Phin wrote: > [a request for peace, love and understanding, concluding with] > >> We all should be a little more considerate of each other. > > > > And if the hippy hug fest fails to stop spamming, perhaps we'll be allowed > > to hunt them down like rabid dogs and stick their heads up on pikes as a > > warning to others. > > > > Hey, a man can dream can't he??? *wink* > > > > > Yeah, just ONE day a year when we could roast them on spits over open > fires ... just to discourage the survivors, you understand. > This is a surprisingly violent group of people, judging by the responses elicited in this thread, and in the muzzle velocity one. Better watch my step... - Hendrik From fuzzyman at gmail.com Fri May 4 17:43:53 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 4 May 2007 14:43:53 -0700 Subject: Microsoft's Dynamic Languages Runtime (DLR) In-Reply-To: References: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> <1178151313.421106.43130@o5g2000hsb.googlegroups.com> <1178151574.302703.205560@l77g2000hsb.googlegroups.com> <1178296035.993859.183720@n59g2000hsh.googlegroups.com> <1178313159.059210.97560@y80g2000hsf.googlegroups.com> Message-ID: <1178315033.313457.168550@y80g2000hsf.googlegroups.com> On May 4, 10:39 pm, Steven Howe wrote: > Fuzzyman wrote: [snip ...] > > >> You are childishly beckoning Usenet etiquette to be gone so that you > >> may do whatever you wish. But I trust that you will not, out of spite > >> for being rebuked, turn a few small mistakes into a persistent style. > > Thank goodness! I was getting ready to filter the DLR crap out. If it's > from microsoft, > it got to be crap. Yeah - I mean what does Jim hugunin know about Python anyway... Bound to be crap... Fuzzyman http://www.voidspace.org.uk/ironpython/index.shtml > sph > > -- > HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 From steve at REMOVE.THIS.cybersource.com.au Sun May 6 09:20:37 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 06 May 2007 23:20:37 +1000 Subject: Did you read about that? References: <1178446711.502374.286790@l77g2000hsb.googlegroups.com> <1178452403.114975.249050@u30g2000hsc.googlegroups.com> Message-ID: On Sun, 06 May 2007 04:53:23 -0700, Dustan wrote: > SPAM! > SPAM! > SPAM! > SPAM! > SPAM! > SPAM! > SPAM! > SPAM! Gosh, you think so? I'm glad we had you around to tell us, otherwise we might have thought it was about Python programming. Actually, many of us wouldn't even have seen it in the first place, because our ISPs do a good job of filtering out obvious spam before we even see it. And then people like you come along, and reply to it, and we see the reply -- complete with the original spam. -- Steven. From kyosohma at gmail.com Mon May 21 09:55:19 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 21 May 2007 06:55:19 -0700 Subject: model browser In-Reply-To: References: <5f56302b0705201155j706cc8e0ydc62a436e4c86299@mail.gmail.com> Message-ID: <1179755718.974998.256260@a26g2000pre.googlegroups.com> On May 20, 3:02 pm, "Daniel Nogradi" wrote: > And before you ask, yes, I did readhttp://mail.python.org/pipermail/python-list/2007-May/440337.htmlbut > there was nothing beyond django/tg :) SqlAlchemy is being or has been integrated with quite a few web frameworks. You might check that out: http://www.sqlalchemy.org/ Mike From collver at peak.org Fri May 4 09:40:50 2007 From: collver at peak.org (Ben Collver) Date: Fri, 04 May 2007 06:40:50 -0700 Subject: My Python annoyances In-Reply-To: References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> <1178202431.147195.249790@u30g2000hsc.googlegroups.com> Message-ID: <7oqdnVScpod-qqbbnZ2dnUVZ_qmpnZ2d@scnresearch.com> Thorsten Kampe wrote: > He was using /Windows/ Python in Cygwin *chuckle*... Windows Python > says Ctrl-Z because it doesn't know that it's been run from bash where > Ctrl-Z is for job control. > > And the lesson we learn from that: if you're using Windows Python use > a Windows shell. If you're using a Cygwin shell use Cygwin Python - > unless you know what you're doing (which he wasn't). The reason I tried to do this: Cygwin python lacks _winreg, but I wanted to SSH into Cygwin to run this script. I suppose the folks who know what they are doing probably stick to wscript and WMI for this sort of stuff. Ben From antroy at gmail.com Tue May 15 15:18:09 2007 From: antroy at gmail.com (Ant) Date: 15 May 2007 12:18:09 -0700 Subject: Trying to choose between python and java In-Reply-To: <1179217038.226176.146250@n59g2000hsh.googlegroups.com> References: <1179217038.226176.146250@n59g2000hsh.googlegroups.com> Message-ID: <1179256689.152170.316320@p77g2000hsh.googlegroups.com> On May 15, 9:17 am, Ant wrote: ... > I can't remember what it is I use - I haven't got access to my server > at the moment... But look in the cheese shop - I'm fairly sure it was > from there. I'll post details if I remember. Alternatively this looks > good (though I haven't tried it and it's only free for non-commercial > use):http://www.dislin.de It's pychart that I use fr charting. Nice and simple to use - though I only use it for simple charts, so I'm not sure how powerful it is. -- Ant... http://antroy.blogspot.com/ From mcl.office at googlemail.com Thu May 10 04:27:18 2007 From: mcl.office at googlemail.com (mosscliffe) Date: 10 May 2007 01:27:18 -0700 Subject: Newbie (but improving) - Passing a function name with parameters as a parameter Message-ID: <1178785638.736644.312970@e51g2000hsg.googlegroups.com> I am trying to time a function's execution, but I get 'TypeError: 'bool' object is not callable' when I try to run it. I suspect it is my calling of 'timeloop' with the function name 'lookup' and its associated variables or it could just be some stupid error on my part. function 'lookups' was working OK Any help will be appreciated. Thanks - Richard ===The offending Code ===== #!/usr/bin/python def timeloop(dofunction,iters=10): import datetime print "->-> Start of test", "LOOPS=", iters, datetime.datetime.now().ctime() for x in xrange(iters): print x dofunction() print "<-<- End of test", "LOOPS=", iters, datetime.datetime.now().ctime() def lookup(recs,patterns): matchcount = 0 pattcount = 0 for patt in patterns: if matchcount < pattcount: break pattcount += 1 for rec in recs: # print "PATT:", patt, " REC:", rec, " PATTCOUNT=", pattcount if patt in rec: matchcount +=1 break # print"MATCHCOUNT=",matchcount, "PATTCOUNT=", pattcount if matchcount == pattcount: return True else: return False myrecs = ['This is a title for Brian', 'this is detail one for brian', 'this is detail two for brian', 'this is another detail one for brian'] test1 = ['one', 'nomatch'] test2 = ['one', 'two'] test3 = ['title', 'two', 'nomatcheither'] mypatts = test1 timeloop(lookup(myrecs,mypatts), 10) From anton.vredegoor at gmail.com Fri May 4 05:52:17 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Fri, 04 May 2007 11:52:17 +0200 Subject: OT somewhat: Do you telecommute? What do you wish the boss understood about it? In-Reply-To: <1177951550.535520.144460@h2g2000hsg.googlegroups.com> References: <1177951550.535520.144460@h2g2000hsg.googlegroups.com> Message-ID: estherschindler wrote: > * If you telecommute, full- or part-time, what *one* thing do you wish > the CIO or IT Management would understand that they don't currently > "get"? I'm not currently telecommuting but last year I had a telecommuting job for half a year. What I would want to say to all future employers considering to hire telecommuting personnel is : Don't let the telecommuter pay the extra costs that are caused by telecommuting. And I don't mean only the financial aspects, I also mean the immaterial costs. For example if one is working at home it can be hard for an employer to check whether the work is still progressing and if there are no immediate results there can be some suspicion that the employee is just sitting at home watching television or is out shopping, because hey, there's no way to check that anyway and people tend to become lazy if no one is watching them? So the employer can become tempted to find ways to check upon his employee by other means. Why not let him write a daily report of his activities even if you never read it? Why not ask for an open MSN chat window at all times so that one can check how fast the employee is responding? Is he at his desk *right now*? These are all things that are not usually asked of the people sitting in the main office and create an extra burden for the employee. In fact the employee gets burdened with the costs of the employers insecurities. If one doesn't trust the employee then don't hire him or don't let him telecommute in the first place! Then there are other aspects. For example sometimes I had to use an expensive mobile Internet connection when I was on the road or when the Internet connection at home didn't work. It was some account that lets one use some amount of megabytes for free but after that was used up there were high costs for each further megabyte. It was certainly the wrong kind of subscription but sometimes it's hard to determine whether one buys an expensive flat rate subscription with the risk of all this money never being used because one is using the home Internet connection all the time. On the other hand things can really get expensive if one has the cheap fixed megabytes type of account and the home Internet connection fails for an extended period or if one has to be on location often. So sometimes the wrong business decision was made. But if someone at the workplace has a HD crash or some other costly error happens this is normally not something the employee has to pay for. If one is informed about the costs and one doesn't read the emails but just says "fix that server malfunction *now*, don't mind the connection costs" one should not be scolding the employee for the large bills that appear one month later. Then there are things like travel costs and hotel costs, say we want the employee to be present at the office for a few days each month, the employee can pay for it in advance and the employer will reimburse him later on. Normally employees get a fixed paycheck each month and there are few extra costs involved and things can get arranged quickly. However the extra costs for the telecommuter are highly variable and so there can be a situation where one has payed in advance out of ones own pocket and one has to ask more than once to receive the money back. If one has to ask too often this can be highly demoralizing, because this is time and money spent on the company without earning anything. The employer maybe starts to think: "Hey this guy is living in an expensive hotel and eating in restaurants while other people go there to have a vacation, so why should I have to pay for that?" Well for the employee it's a completely different story, hotel rooms aren't fun if one arrives late at night and leaves early in the morning and cities remain tantalizing mysteries if one never has the time to do some sightseeing. There is also the idea that working at home is some luxurious privilege that the employee should be thankful for. I can tell you that even the nicest home can become a prison if one has to be there all the time. In fact any escape can be a relief so one is thankful to spend some time in a hotel room ... But that doesn't mean it's vacation! No way. It's just that other people get out of their homes normally at the beginning of the day, a telecommuter *has* to go out for a walk or go bicycling for half an hour or so during lunch break just to keep fit. A normal employee can integrate that into his routine of coming to work and having lunch at a nearby restaurant. So all in all my conclusion is, if one wants the employee to be happy and loyal, don't destroy his good intentions by letting him pay for all kinds of luxuries that he didn't ask for and that aren't even much fun anyway. Even though such things might seem the most desirable working environments for those having to work in a crowded office where they have to go to each day, sitting alone at home or being in anonymous hotels in big cities and eating at restaurants is *not* as good as it seems when one has to do it in someone else's time. Then there is the disadvantage of not being informed adequately of what is going on at the main office. If there is a blame game going on for something that went wrong, those in the distance are always last in line that can distance themselves from the problem, and anyway, electronic communications don't work as well as face to face contacts. Be aware of that too and don't let your telecommuters always be the ones who get blamed by the nearby workforce. You'll end up hiring and firing telecommuting workers at a regular basis and knowledge about the company and its software will *not* be preserved, to your own detriment. So have a little faith and pay those extra expenses in advance, trust your distant workforce to not watch television and accept that they too must go out of their homes now and then. If you accept all that I think that things will go extremely well because a distributed work force can mobilize a lot more diverse assets than a single main office. But that last point would be a topic for an entirely different post. I just wanted to end this dragon with a positive note :-) A. From chris.monsanto at gmail.com Sat May 19 19:23:16 2007 From: chris.monsanto at gmail.com (chris.monsanto at gmail.com) Date: 19 May 2007 16:23:16 -0700 Subject: mod_python performs several magnitudes slower than PHP? Message-ID: <1179616996.948606.319670@q75g2000hsh.googlegroups.com> Recently I've had to move my site to a new dedicated server running FreeBSD 6.1. After installing apache 2.0.59, python 2.4.4 and mod_python 3.3.1, I decided to bench a script in PHP vs one in Python. I found out that for some reason, my mod_python was performing extremely slow - magnitudes slower than it should. I scowered the internet for hours and asked a few friends and still haven't been able to find a solution to the problem. from mod_python import apache def handler(req): for i in xrange(1000): print >> req, "Yeah" return apache.OK and... when I ran ab on both using 1000 requests and a concurrency of 10, i got these results: python- Requests per second: 21.37 [#/sec] (mean) php- Requests per second: 1008.37 [#/sec] (mean) Any ideas would really be appreciated... I'm on my last leg. From afriere at yahoo.co.uk Thu May 17 02:18:21 2007 From: afriere at yahoo.co.uk (Asun Friere) Date: 16 May 2007 23:18:21 -0700 Subject: How do I count the number of spaces at the left end of a string? In-Reply-To: References: <1179351367.714864.47190@l77g2000hsb.googlegroups.com> Message-ID: <1179382701.371187.115790@e65g2000hsc.googlegroups.com> On May 17, 8:18 am, Steven Howe wrote: > walterbyrd wrote: > > I don't know exactly what the first non-space character is. I know the > > first non-space character will be * or an alphanumeric character. > > using builtin function rindex But only if there is a guarantee that are spaces nowhere else in the string: a = ' abc' print a.rindex(' ') + 1 => 4 Good, but ... b = ' ab c' b.rindex(' ') + 1 => 7 Ouch! The difference method suggested by Daniel Nogradi, seems the most obvious way. len(b) - len(b.lstrip()) => 4 Asun From iltchevi at gmail.com Sun May 6 17:36:19 2007 From: iltchevi at gmail.com (ici) Date: 6 May 2007 14:36:19 -0700 Subject: exporting a record from a database to a MS Word document. In-Reply-To: <1178470927.793357.204080@n76g2000hsh.googlegroups.com> References: <1178470927.793357.204080@n76g2000hsh.googlegroups.com> Message-ID: <1178487379.184541.27000@w5g2000hsg.googlegroups.com> Levi Campbell wrote: > Is there a way to export a record from a database kept with bsddb to > MS Word, possibly with some type of formatting data? import win32com.client try: import psyco; psyco.full() except ImportError: pass app = win32com.client.Dispatch("Word.Application") app.Visible = True doc = app.Documents.Add() para = doc.Paragraphs.Add() para.Range.Text = "DB Record" para.Range.Bold = True #... doc.Close(True) app.Quit() From marco.colombo at gmail.com Mon May 14 07:42:21 2007 From: marco.colombo at gmail.com (Marco Colombo) Date: 14 May 2007 04:42:21 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <1179142941.222428.113150@w5g2000hsg.googlegroups.com> I suggest we keep focused on the main issue here, which is "shoud non- ascii identifiers be allowed, given that we already allow non-ascii strings literals and comments?" Most arguments against this proposal really fall into the category "ascii-only source files". If you want to promote code-sharing, then you should enfore quite restrictive policies: - 7-bit only source files, so that everyone is able to correctly display and _print_ them (somehow I feel that printing foreign glyphs can be harder than displaying them) ; - English-only, readable comments _and_ identifiers (if you think of it, it's really the same issue, readability... I know no Coding Style that requires good commenting but allows meaningless identifiers). Now, why in the first place one should be allowed to violate those policies? One reason is freedom. Let me write my code the way I like it, and don't force me writing it the way you like it (unless it's supposed to be part of _your_ project, then have me follow _your_ style). Another reason is that readability is quite a relative term... comments that won't make any sense in a real world program, may be appropriate in a 'getting started with' guide example: # this is another way to increment variable 'a' a += 1 we know a comment like that is totally useless (and thus harmful) to any programmer (makes me think "thanks, but i knew that already"), but it's perfectly appropriate if you're introducing that += operator for the first time to a newbie. You could even say that most string literals are best made English- only: print "Ciao Mondo!" it's better written: print _("Hello World!") or with any other mean to allow the i18n of the output. The Italian version should be implemented with a .po file or whatever. Yet, we support non-ascii encodings for source files. That's in order to give authors more freedom. And freedom comes at a price, of course, as non-ascii string literals, comments and identifiers are all harmful to some extents and in some contexts. What I fail to see is a context in which it makes sense to allow non- ascii literals and non-ascii comments but _not_ non-ascii identifiers. Or a context in which it makes sense to rule out non-ascii identifiers but not string literals and comments. E.g. would you accept a patch with comments you don't understand (or even that you are not able to display correctly)? How can you make sure the patch is correct, if you can't read and understand the string literals it adds? My point being that most public open source projects already have plenty of good reasons to enforce an English-only, ascii-only policy on source files. I don't think that allowing non-ascii indentifiers at language level would hinder thier ability to enforce such a policy more than allowing non-ascii comments or literals did. OTOH, I won't be able to contribute much to a project that already uses, say, Chinese for comments and strings. Even if I manage to display the source code correctly here, still I won't understand much of it. So I'm not losing much by allowing them to use Chinese for identifiers too. And whether it was a mistake on their part not to choose an "English only, ascii only" policy it's their call, not ours, IMHO. .TM. From john at datavoiceint.com Tue May 8 22:30:24 2007 From: john at datavoiceint.com (HMS Surprise) Date: 8 May 2007 19:30:24 -0700 Subject: String parsing In-Reply-To: <1178677152.478615.79170@y80g2000hsf.googlegroups.com> References: <1178672992.522463.228620@l77g2000hsb.googlegroups.com> <1178677152.478615.79170@y80g2000hsf.googlegroups.com> Message-ID: <1178677824.923234.63890@l77g2000hsb.googlegroups.com> On May 8, 9:19 pm, HMS Surprise wrote: > Yes it could, after I isolate that one string. Making sure I that I > isolate that complete line and only that line is part of the problem. > It comes in as one large string... From steve at REMOVE.THIS.cybersource.com.au Tue May 8 18:44:44 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 09 May 2007 08:44:44 +1000 Subject: Muzzle Velocity (was: High resolution sleep (Linux) References: <1178274122.142071.91740@y5g2000hsa.googlegroups.com> Message-ID: On Tue, 08 May 2007 17:59:13 +0000, Dennis Lee Bieber wrote: >> Did you know that the first military smokeless powder >> round was for the French Lebel? - It threw a bronze >> ball, and could punch through a single brick wall. >> > Well, extreme high speed wouldn't help for that -- just get a > surface splatter. Heavy and slower... (or some sort of solid core -- > depleted uranium with a teflon coating) I remember a MythBusters episode that had the guys testing the old Hollywood staple of somebody trying to escape gunfire by swimming underwater. To their surprise, they found that modern high-velocity rounds basically hit the water and stopped dead, hardly penetrating at all, while an old musket shot they found actually penetrated the water furthest. Hmmm... musket? I may be confabulating that last bit, the rifle may not have been that old. World War One vintage perhaps? But it fired a heavy slow round, and everybody predicted it would penetrate the water the least, but it was the opposite. Anyway, the myth was confirmed. I guess that's why people don't go fishing with shotguns. -- Steven. From python-url at phaseit.net Mon May 28 08:57:53 2007 From: python-url at phaseit.net (Gabriel Genellina) Date: Mon, 28 May 2007 12:57:53 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (May 28) Message-ID: QOTW: "Good God! Is there *anything* that python does not already do? I hardly feel the need to write programs anymore ... Its really 80% like of the questions that are asked here get answered along the lines of: import some_fancy_module solution = some_fancy_module.exactly_the_right_function_to_solve(problem) " - Wildemar Wildenburger "Whenever you are tempted to create dynamically variables names, 99% of the time what you really want is a data structure, typically a dict or a list." - George Sakkis An example shows how much more convenient it is to use cElementTree than to write a custom expat parser: http://mail.python.org/pipermail/python-list/2007-May/441995.html The Time Machine in action again: How to enumerate classes in a module, in the same order they were defined: http://mail.python.org/pipermail/python-list/2007-May/442009.html str.lower()/upper() may not work as expected even on familiar encodings like utf-8: http://mail.python.org/pipermail/python-list/2007-May/442195.html Steve Holden shows the power of __getattr__, modifying functions on-the-fly: http://mail.python.org/pipermail/python-list/2007-May/442432.html Learning by example: Ten small-but-useful programs increase from one line to ten lines in length and demonstrate key Python concepts: http://mail.python.org/pipermail/python-list/2007-May/442529.html http://wiki.python.org/moin/SimplePrograms Python cheerleading: http://opensource.sys-con.com/read/368040.htm http://www.devchix.com/2007/05/24/beautiful-python-the-programming-language-that-taught-me-how-to-love-again/ The advantages of using a module as a singleton - let Python do the hard work: http://mail.python.org/pipermail/python-list/2007-May/442640.html Debugging extension modules on Windows may be difficult without the proper (commercial) compiler. This topic shows how to do that using only freely available tools: http://groups.google.de/group/comp.lang.python/browse_thread/thread/e441a581a0d354ab Think before using inheritance: a Point is not a list: http://groups.google.de/group/comp.lang.python/browse_thread/thread/0cdfa8c65bf8c195 Michelle Simioniato on decorators again: functools makes it easy to decorate methods: http://mail.python.org/pipermail/python-list/2007-May/442057.html Tips on how to "sell" yourself as a freelancer: http://mail.python.org/pipermail/python-list/2007-May/442476.html ======================================================================== 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. The Python Papers aims to publish "the efforts of Python enthusiats". http://pythonpapers.org/ 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 gagsl-py2 at yahoo.com.ar Tue May 8 22:52:07 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 08 May 2007 23:52:07 -0300 Subject: change of random state when pyc created?? References: <1178408359.113807.181570@l77g2000hsb.googlegroups.com> <3U20i.2110$wy2.1466@trnddc03> Message-ID: En Tue, 08 May 2007 14:59:27 -0300, Alan Isaac escribi?: > What I have seen is: > > - when a test1.pyc file is present, I always get the > same outcome (result1) > - when a test1.pyc file is NOT present, I always get > the same outcome (result2) > - the two outcomes are different (result1 != result2) I've logged all Random calls (it appears to be only one shuffle call, after the initial seed) and in both cases they get the same numbers. So the program always starts with the same "shuffled" values. Perhaps there is a tiny discrepancy in the marshal representation of some floating point values. When there is no .pyc, Python parses the literal from source; when a .pyc is found, Python loads the value from there; they could be slightly different. I'll investigate further... tomorrow. -- Gabriel Genellina From gmtrojan at comcast.net Tue May 29 18:17:09 2007 From: gmtrojan at comcast.net (George Trojan) Date: Tue, 29 May 2007 18:17:09 -0400 Subject: setting environment from shell file in python Message-ID: <2Nidnd3PW_X7O8HbnZ2dnUVZ_g-dnZ2d@comcast.com> Is there a utility to parse a Bourne shell environment file, such as .bashrc, and set the environmental variables from within a Python script? What I mean is an equivalent to shell dot command. I don't think it would be too difficult to write a shell parser, but if such thing already exists... George From jussij at zeusedit.com Thu May 10 01:25:18 2007 From: jussij at zeusedit.com (JussiJ) Date: 9 May 2007 22:25:18 -0700 Subject: preferred windows text editor? In-Reply-To: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> References: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> Message-ID: <1178774718.211217.35100@y80g2000hsf.googlegroups.com> On May 10, 4:06 am, "T. Crane" wrote: > Right now I'm using Notepad++. What are other people using? Zeus: http://www.zeusedit.com From nospam at invalid.com Sun May 27 12:13:06 2007 From: nospam at invalid.com (Jack) Date: Sun, 27 May 2007 09:13:06 -0700 Subject: Large Amount of Data References: <1180228756.574525.16110@q19g2000prn.googlegroups.com> <1180229680.523041.128650@o11g2000prd.googlegroups.com> Message-ID: John, thanks for your reply. I will then use the files as input to generate an index. So the files are temporary, and provide some attributes in the index. So I do this multiple times to gather different attributes, merge, etc. "John Machin" wrote in message news:1180229680.523041.128650 at o11g2000prd.googlegroups.com... > On May 27, 11:24 am, "Jack" wrote: >> I'll save them in a file for further processing. > > Further processing would be what? > Did you read the remainder of what I wrote? > From pydecker at gmail.com Wed May 23 12:35:42 2007 From: pydecker at gmail.com (Peter Decker) Date: Wed, 23 May 2007 12:35:42 -0400 Subject: dabo framework dependancies In-Reply-To: <46532f57$0$32303$426a34cc@news.free.fr> References: <1179761984.704369.116310@b40g2000prd.googlegroups.com> <46532f57$0$32303$426a34cc@news.free.fr> Message-ID: On 5/22/07, daniel gadenne wrote: > I'm considering moving over to dabo for wxpython development. > However I do not write traditional database applications > ? la foxpro (I'm a 20 years user of fox...) anymore. > Only xml-fed applications. > > I'm a bit hesitant to jump onboard since dabo seemns to carry > over its own lot of database connectivity dependancy. > > Can you reasonably use dabo for plain datafree application? That's exactly how I use it. I write apps that don't use database servers, and don't have any database programs installed. I just want the dabo.ui stuff, since it makes wxPython so easy to work with. -- # p.d. From deets at nospam.web.de Tue May 22 08:53:28 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 22 May 2007 14:53:28 +0200 Subject: omniORBpy: Error 0x41540002 References: <1179833439.210564.191810@x18g2000prd.googlegroups.com> Message-ID: <5bg7e8F2svqcaU1@mid.uni-berlin.de> Samuel wrote: > Hi, > > I am trying to get the files from this tutorial to work: > http://www.grisby.org/presentations/py10code.html > > Direct link to the files: > http://www.grisby.org/presentations/py10code/adder.idl > http://www.grisby.org/presentations/py10code/adderServer.py > > It produces the following error: > > $ omniidl -bpython adder.idl && python adderServer.py > Traceback (most recent call last): > File "adderServer.py", line 23, in > nameRoot = nameRoot._narrow(CosNaming.NamingContext) > File "/usr/lib/python2.5/site-packages/omniORB/CORBA.py", line 667, > in _narrow > return _omnipy.narrow(self, dest._NP_RepositoryId) > omniORB.CORBA.TRANSIENT: Minor: 0x41540002, COMPLETED_NO. > > According to Google this might mean "Connect failed", however, I don't > understand why the server would open a connection. I expected it to > simply listen on a socket, but I probably just don't understand how it > works. > > Can anyone please explain this? Please see my answer to your first post. Diez From george.sakkis at gmail.com Sun May 20 23:21:52 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 20 May 2007 20:21:52 -0700 Subject: Python assignment loop In-Reply-To: References: Message-ID: <1179717712.491520.288060@z24g2000prd.googlegroups.com> On May 20, 10:33 pm, "Silver Rock" wrote: > i need to do something like this: > > ### > import wx > x=number > for i in range(500): > "var"+str(i)=ClassXYZ(...,x+i,...) > > #.... code > y=number > for i in range(y): > ClassAAAA(object_called_by_the_string("var"+str(i)),...) > > ### > i can't figure out how to do this, and could not find it on the web. > c. Whenever you are tempted to create dynamically variables names, 99% of the time what you really want is a data structure, typically a dict or a list. In your example, a list will do: x=number xyz_objects = [ClassXYZ(...,x+i,...) for i in xrange(500)] #.... code y=number aaaa_objects = [ClassAAAA(object_called_by_the_string(xyz,...) for xyz in xyz_objects[:y]] If you can't figure out what this does, lookup for "list comprehensions". By the way, I hope these were shortened examples and you're not actually using names such as 'ClassAAAA' or 'ClassXYZ' in your actual code... George From sjmachin at lexicon.net Tue May 29 20:28:59 2007 From: sjmachin at lexicon.net (John Machin) Date: 29 May 2007 17:28:59 -0700 Subject: updates in sqlite3 do not work In-Reply-To: References: <723eb6930705291530w190a7818i71f49d976217f38@mail.gmail.com> Message-ID: <1180484939.739126.113380@d30g2000prg.googlegroups.com> On May 30, 8:43 am, "Stefan Sonnenberg-Carstens" wrote: > Did you try a commit() ? > > SQLite3 works in autocommit mode by default, Errrrmmmm .... IF it worked in auto-commit mode, then the OP wouldn't need to use Connection.commit(-:) The underlying SLQite3 may work in auto-commit mode, but the Python interface should not. See PEP 249 : """Note that if the database supports an auto-commit feature, this must be initially off.""" Consequently the user of any/every DPAPIv2.0-compliant package should be calling commit. HTH, John From vmaslov at swsoft.com Mon May 14 05:51:30 2007 From: vmaslov at swsoft.com (Vyacheslav Maslov) Date: Mon, 14 May 2007 16:51:30 +0700 Subject: multi threaded SimpleXMLRPCServer Message-ID: <46483122.2030901@swsoft.com> Hi, all! I need multi threaded version of SimpleXMLRPCServer. Does python library already have implementation of this one? Or i need to implement multi threading by myself? Which way is the simpliest? From usenet-nospam at well-adjusted.de Wed May 16 08:50:26 2007 From: usenet-nospam at well-adjusted.de (Jochen Schulz) Date: Wed, 16 May 2007 14:50:26 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649dd55$0$23144$9b4e6d93@newsspool1.arcor-online.net> <464a25e9$0$10188$9b4e6d93@newsspool4.arcor-online.net> <1179291296.561359.286230@h2g2000hsg.googlegroups.com> <464ab64f$0$10185$9b4e6d93@newsspool4.arcor-online.net> <464AB9F2.60906@web.de> <464ac189$0$20297$9b4e6d93@newsspool3.arcor-online.net> <464ac493$0$6394$9b4e6d93@newsspool2.arcor-online.net> <464add30$0$6401$9b4e6d93@newsspool2.arcor-online.net> Message-ID: * Ren?? Fleschenberg: > Stefan Behnel schrieb: >> >> [...] They are just tools. Even if you do not >> understand English, they will not get in your way. You just learn them. > > I claim that this is *completely unrealistic*. When learning Python, you > *do* learn the actual meanings of English terms like "open", > "exception", "if" and so on if you did not know them before. This is certainly true for easy words like "open" and "in". But there are a lot of counterexamples. When learning something new, you always learn a lot of new concepts and you get to know how they are called in this specific context. For example, when you learn to program, you might stumble upon the idea of "exceptions", which you can raise/throw and except/catch. But even if you know how to use that concept and understand what it does, you do not necessarily know the "usual" meaning of the word outside of your domain. As far as I can tell, quite often these are the terms that even enter the native language without any translation (even though there are perfect translations for the words in their original meaning). German examples are "exceptions", "client" and "server", "mail", "hub" and "switch", "web" and many, many more. Nobody who uses these terms has to know their exact meaning in his native language as long as he speaks to Germans or stays in the domain where he learned them. I read a lot of English text every day but I am sometimes still surprised to learn that a word I already knew has a meaning outside of computing. "Hub" is a nice example for that. I was very surprised to learn that even my bike has this. ;-) J. -- If I was Mark Chapman I would have shot John Lennon with a water pistol. [Agree] [Disagree] From dzawer at gmail.com Fri May 18 07:03:30 2007 From: dzawer at gmail.com (dzawer at gmail.com) Date: 18 May 2007 04:03:30 -0700 Subject: A best approach to a creating specified http post body Message-ID: <1179486210.398916.251970@o5g2000hsb.googlegroups.com> Hi all, I'm rather new to python but not exaclty without programming experience and not quite get best pyhton practices. I have a following problem that it seems I cannot find a way to solve correctly. I need to build a special http post body that consists of : name=value +\r\n strings. Problem is that depending on operations the number of name,value pairs can increase and decrease. Values need to be initialized at runtime, so storing premade text files is not possible. The worst thing that some operations must be at beginning, so dictionary approach with classes is kinda out. Could you please provide some examples or descriptions on how you would solve such problem ? Thanks in advance. From mcl.office at googlemail.com Thu May 31 11:17:51 2007 From: mcl.office at googlemail.com (mosscliffe) Date: 31 May 2007 08:17:51 -0700 Subject: HTML Form/Page and Navigation with multiple buttons In-Reply-To: <465edbfa$0$784$426a34cc@news.free.fr> References: <1180617750.709628.180070@p77g2000hsh.googlegroups.com> <465edbfa$0$784$426a34cc@news.free.fr> Message-ID: <1180624671.896662.174390@m36g2000hse.googlegroups.com> Excellent - thanks for all your help. I now have a form created by a python script executing an HTML page, doing everything I need, except for Session Data (probably use hidden fields ?? future research) and the actual paging logic !!! If I use a link. I have to add all my hidden fields to the query string, otherwise cgi.FieldStorage(), does not return the hidden fields. This would also mean users see all the hidden field data. Is there another way, other than a cookie ? Why is a link better than a button ? I have been using 'post' for my form, to eliminate the displaying of field values. I accept I am quite niave about FORM/HTML logic. Richard On 31 May, 15:30, Bruno Desthuilliers wrote: > mosscliffe a ?crit : > > > > > I am struggling to find a python example of the scenario - I have. > > > I have a python script, which generates a page with a search button > > (actually an input field). > > > The data from the above submissions is interrogated and the same > > script produces a new search option and the a page of results from the > > previous search request. - as done by Google's Main search page. > > > The user then has the option of a new search or navigating to a > > different page of results with the usual Start, Previous, Next and > > Last Buttons. > > > How can I identify which button has been pressed. Do I need a > > separate form for each button and hide all the relevant session fields > > in each form or is there a way of identifying which button has been > > pressed on the page. > > This is not really a Python problem - would be the same with any > server-side techno... > > You shouldn't use buttons for navigation, but links. The simplest > solution is to pass all the relevant data into the query string (the > ?key=val&key2=val2&etc=etc part of the url). In your case, this would be > something like resending all the search params, and adding the current > page and the action (ie 'action=next' or 'action=first' etc...) > From vinay_sajip at yahoo.co.uk Tue May 1 06:25:59 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 1 May 2007 03:25:59 -0700 Subject: logging SMTPHandler and Authentication In-Reply-To: <1177978114.284934.27140@l77g2000hsb.googlegroups.com> References: <1177978114.284934.27140@l77g2000hsb.googlegroups.com> Message-ID: <1178015159.827754.92520@n76g2000hsh.googlegroups.com> On May 1, 1:08 am, james.p.n... at gmail.com wrote: > I'm new to Python, but I've been thrown into coding a pretty > complicated regression testing script. I need to email the log of the > daily test to the code owners. I thought I could use SMTPHandler for > this, but our email system requires authentication. I have not been > able to figure out how to log in using SMTPHandler. I found the > following post on comp.lang.python: > > http://groups.google.com/group/comp.lang.python/browse_frm/thread/ef8... > > However, I haven't been able to translate this to anything I can use. > I've also looked at the source code for the SMTPHandler, but I don't > want to edit that. > > Has anyone else dealt with this? > > Thanks much, > James I've enhanced SMTPHandler in Python SVN (trunk) to accept a (username, password) tuple in a credentials argument to SMTPHandler.__init__(). The credentials, if specified, are used to do a login() call before the sendmail() call. Regards, Vinay From romain.feuillette at st.com Wed May 9 10:01:14 2007 From: romain.feuillette at st.com (Romain FEUILLETTE) Date: Wed, 09 May 2007 16:01:14 +0200 Subject: IDLE can't import Tkinter Message-ID: <4641D42A.7090201@st.com> Hello, I'have just install Python 2.5.1 on Linux and the IDLE doesn't seem to works because it didn't find Tcl/Tk Is there someone to explain how to modify the file "setup.py" to tell the install that Tcl/Tk are at the paht : "/usr/bin/tclsh" and "usr/bin/wish/" ? I have attached to log file of my terminal. Thanks a lot in advance. Romain -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: idle_error.log URL: From sjmachin at lexicon.net Wed May 2 18:58:44 2007 From: sjmachin at lexicon.net (John Machin) Date: 2 May 2007 15:58:44 -0700 Subject: How to check if a string is empty in python? In-Reply-To: References: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> Message-ID: <1178146724.605100.253080@y5g2000hsa.googlegroups.com> On May 3, 8:50 am, Steven D'Aprano wrote: > On Wed, 02 May 2007 13:35:47 -0700, noagbodjivictor wrote: > > How to check if a string is empty in python? > > if(s == "") ?? > > In no particular order, all of these methods will work: > [snip] > > # test that s has none of any character > if not filter(None, [1 + s.find(chr(n)) for n in range(256)]): > > That last one is really only good for wasting CPU cycles. Have you considered if not re.match(".+$", s): ? From deets at nospam.web.de Wed May 23 06:09:16 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 23 May 2007 12:09:16 +0200 Subject: Module listing in order. References: <1179905562.541601.264400@m36g2000hse.googlegroups.com> Message-ID: <5bii6cF2st2goU1@mid.uni-berlin.de> Ramashish Baranwal wrote: > Hi, > > I want to get a module's contents (classes, functions and variables) > in the order in which they are declared. Using dir(module) therefore > doesn't work for me as it returns a list in alphabetical order. As an > example- > > # mymodule.py > class B: pass > class A: pass > class D: pass > > # test.py > import mymodule > # This returns['A', 'B', 'D', '__builtins__', '__doc__', '__file__', > '__name__'] > contents = dir(mymodule) > > I want a way to get the contents in the order of their declaration, > i.e. [B, A, D]. Does anyone know a way to get it? Whatfor do you actually need this? Is it a general interest - then things get difficult. But for certain usecases, metaclasses might come to the rescue. But that depends on what you want to do. Diez From showell30 at yahoo.com Mon May 28 17:50:01 2007 From: showell30 at yahoo.com (Steve Howell) Date: Mon, 28 May 2007 14:50:01 -0700 (PDT) Subject: itertools.groupby In-Reply-To: <7xveecr5xx.fsf@ruckus.brouhaha.com> Message-ID: <734320.91071.qm@web33506.mail.mud.yahoo.com> --- Paul Rubin <"http://phr.cx"@NOSPAM.invalid> wrote: > > > But that is what groupby does, except its notion of > uniqueness is > limited to contiguous runs of elements having the > same key. It occurred to me that we could also rename the function uniq(), or unique(), after its Unix counterpart, but then I though better of it. As one of the folks who was making a bit of noise about the groupby() semantics before, I'm really fine with the name now that the docs make it a little more clear how it behaves. ____________________________________________________________________________________ Park yourself in front of a world of choices in alternative vehicles. Visit the Yahoo! Auto Green Center. http://autos.yahoo.com/green_center/ From rene at korteklippe.de Tue May 15 07:28:01 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 15 May 2007 13:28:01 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <4649882E.3060005@web.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476081.7080609@web.de> <46498514$0$6402$9b4e6d93@newsspool2.arcor-online.net> <4649882E.3060005@web.de> Message-ID: <46499940$0$10199$9b4e6d93@newsspool4.arcor-online.net> Stefan Behnel schrieb: > Sounds like high time for an editor that supports the project team in their > work, don't you think? I think your argument about "isolated projects" is flawed. It is not at all unusual for code that was never intended to be public, whose authors would have sworn that it will never ever be need to read by anyone except themselves, to surprisingly go public at some point in the future. Moreover, wether it uses ASCII-only identifiers or not might actually be a factor in deciding wether it can then become useful for the community as a whole or not. If only some few projects that are so very very isolated from the rest of the world profit from the change this PEP proposes, then it should IMHO be feasible to require them to use a special Python branch. That would keep the burden of all the possible problems away from the rest of the Python community. -- Ren? From aspineux at gmail.com Thu May 24 15:20:35 2007 From: aspineux at gmail.com (aspineux) Date: 24 May 2007 12:20:35 -0700 Subject: modifying values of List or Dictionary when iterating on them In-Reply-To: References: <1180026141.723991.303810@p47g2000hsd.googlegroups.com> Message-ID: <1180034435.527565.248950@u30g2000hsc.googlegroups.com> On 24 mai, 19:21, "Christopher Anderson" wrote: > > d=dict(a=1, b=2, c=3) > > for k, v in d.iteritems(): > > d[k]=d[k]+1 > > You might as well do: d[k] = v + 1, like for the list. ops, yes it was a typo From aisaac at american.edu Sat May 5 19:30:41 2007 From: aisaac at american.edu (Alan Isaac) Date: Sat, 05 May 2007 23:30:41 GMT Subject: change of random state when pyc created?? References: <1178388186.631422.290580@w5g2000hsg.googlegroups.com> <008%h.379$HR1.364@trnddc01> <1178406414.901845.223410@y80g2000hsf.googlegroups.com> Message-ID: "John Machin" wrote in message news:1178406414.901845.223410 at y80g2000hsf.googlegroups.com... > You can't say that you have "documented" the behaviour when you > haven't published files that exhibit the alleged behaviour. Fine. I have "observed" this behavior. The files are not appropriate for posting. I do not yet have a "minimum" case. But surely I am not the first to notice this! Alan Isaac PS I'll send you the files off list. From john at datavoiceint.com Tue May 8 10:13:26 2007 From: john at datavoiceint.com (HMS Surprise) Date: 8 May 2007 07:13:26 -0700 Subject: No module named urllib In-Reply-To: References: <1178575589.059564.226060@q75g2000hsh.googlegroups.com> <87tzuop8s2.fsf@gmail.com> <1178577562.498615.222340@e51g2000hsg.googlegroups.com> <87ps5cp816.fsf@gmail.com> <1178578923.067315.14440@q75g2000hsh.googlegroups.com> <1178580280.902179.248000@w5g2000hsg.googlegroups.com> <1178630341.147781.39380@y5g2000hsa.googlegroups.com> Message-ID: <1178633606.618416.155600@e51g2000hsg.googlegroups.com> > To summarize the summary, are you sure you need to use Jython instead of > standard CPython? > Thanks for all your help Carsten, you have been more than patient with me. To answer your question I must admit I do not know. I am trying to use a tool called maxq (maxq.tigris.org) that has limited documentation, or limited in the depth needed by a python/jython neophyte such as me. Maxq acts an http proxy and generates jython scripts for playback testing of web apps. So far I have gained a lot of ground referring to python documentation and even testing code snippets in python shells. So lacking the knowledge of what is jython/maxq/python and being of at best moderate intellect I find myself easily overwhelmed and generally not sure what must be used where. Maxq does not have a tool for parsing the web pages, therefore I wanted to add some library calls to pick off some timestamps I must have. Perhaps I should start looking for another tool, such as twill maybe. I will fetch an older python and see if that helps. Thanks again, jh From gherron at islandtraining.com Mon May 7 03:16:08 2007 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 07 May 2007 00:16:08 -0700 Subject: N00b question on Py modules In-Reply-To: <1178521238.333095.111370@h2g2000hsg.googlegroups.com> References: <1178521238.333095.111370@h2g2000hsg.googlegroups.com> Message-ID: <463ED238.2030501@islandtraining.com> lokesh.jagasia at gmail.com wrote: > Hi. Sorry to sound like a noob but that's what I am when it comes to > Python. I just wrote the below module and it behaves funny. > > My python module: > > _exitcode = 0 > > def setExitCode(): > _exitcode = 1 > > if __name__ == '__main__': > print _exitcode > setExitCode() > print _exitcode > > Actual O/P: > 0 > 0 > > I expected to see an output of 0 followed by 1. But it turns out that > the _exitcode variable is not changed at all. It seems that > setExitCode() might be editing a local copy of the _exitcode variable. > But then, how do I tell it to change the value of the module variable > and not its local variable. > > I've been through the modules section of Python docs and a few ebooks > as well, all suggest that it shouldn't be working this way. > > Please help out ppl. > It's a scoping problem. The line _exitcode = 0 creates a (module level) global object. But in def setExitCode(): _exitcode = 1 you are running into Python's default presumption that variables assigned to in a function are *local* to that function. And like all local variables, they can be set and used within the function, but are independent of objects outside the function. If you want to assign to a global object from within a function, then you must explicitly say so: def setExitCode(): global _exitcode _exitcode = 1 See: http://docs.python.org/ref/global.html Gary Herron > Thanks > > From carl at personnelware.com Thu May 24 12:55:53 2007 From: carl at personnelware.com (Carl K) Date: Thu, 24 May 2007 11:55:53 -0500 Subject: installing cx_Oracle. In-Reply-To: References: Message-ID: Dennis Lee Bieber wrote: > On Thu, 24 May 2007 09:07:07 -0500, Carl K > declaimed the following in comp.lang.python: > >> Getting closer, thanks Bill and Diez. >> >> $ export ORACLE_HOME >> $ ORACLE_HOME=/usr/lib/oracle/xe/app/oracle/product/10.2.0/client > > Don't those lines need to be reversed? Set the variable in the > current shell, and /then/ export it? whoops - I may have cut/pasted too fast. Carl K From mail at timgolden.me.uk Wed May 9 09:25:53 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 09 May 2007 14:25:53 +0100 Subject: Specification for win32com.client package In-Reply-To: <1178715787.220103.245060@e65g2000hsc.googlegroups.com> References: <23617.87850.qm@web63415.mail.re1.yahoo.com> <1178715787.220103.245060@e65g2000hsc.googlegroups.com> Message-ID: <4641CBE1.8010700@timgolden.me.uk> kyosohma at gmail.com wrote: > The wiki idea sounds like a good one. I was thinking about doing some > kind of Python site about the modules and I think the popular 3rd > party ones would be a good place to start, maybe starting with win32. > How much information do you think would need to be on a site like this > to start out with? Someone did start a Python Win32 Wiki recently (check the python-win32 archives for location etc.) I did mean to put things on there myself, but real life has taken over. Often, these things just need someone with a bit of oomph to at least get the thing going. I think what's needed (if you're offering :) is for someone to put a *framework* in place on such a site which would make it easy for anyone to come along and fill in the gaps with their particular 3rd-party app or brand of knowledge. As I say, someone did start something, but I've not heard anything from him since then and I haven't found the time myself. If you were to kick something off and actually get it going I wouldn't say no. TJG From zhaodapu at gmail.com Sun May 6 16:11:04 2007 From: zhaodapu at gmail.com (zdp) Date: 6 May 2007 13:11:04 -0700 Subject: WebBrowser: How to cast the document object Message-ID: <1178482264.678509.58730@p77g2000hsh.googlegroups.com> Hi, all, My project is based on wxPython, and I need an IE control (i.e. WebBrowser ActiveX control). Although the wxPython implements a wrapped version (wx.lib.iewin.IEHtmlWindow), but it doesn't meet all my demands, because I need to custom many behaviors of the control. So I thought I should use it through ActiveXWrapper directly. So I use makepy to make the typelib of "Microsoft Internet Controls" and "Microsoft HTML Object Library". Now I can get the document object of the WebBrowser, and I can cast it into any interface I need like IHtmlDocument2, IHtmlDocument3... So far, so good. The document object also implements a COM interface IPersistStreamInit, which has a *Load* method. Calling this method can load any stream into the browser control. Here is the a example using this method in visual c++: IPersistStreamInit* spPSI = NULL; CStreamOnCString stream(szHTML); if (m_pHtmlDoc) { m_hResult = m_pHtmlDoc->QueryInterface(IID_IPersistStreamInit, (void**)&spPSI); if( SUCCEEDED(m_hResult) && spPSI ) { m_hResult = spPSI->Load(static_cast(&stream)); spPSI->Release(); } } Now I need to call this method on my document object, my code is just like stream = win32com.client.CastTo(doc, "IPersistStreamInit") stream.Load(somestr) But I got an error: ValueError: The interface name 'IPersistStreamInit' does not appear in the same library as object '' I googled and someones says only interfaces inherit from IDispatch can be used by pythoncom. But IPersistStreamInit interface inherits from IUnknown. But I just need to use this interface. However, I also noted that the class wx.lib.iewin.IEHtmlWindow has a *LoadStream* method, I thought it's a wrapper of IPersistStreamInit's Load method. So I trace the source code, but only found the implement is in the c++ base class. Could anybody tell me how to do it? Any clues is helpful. Dapu From mail.ciju.cherian at gmail.com Fri May 11 01:29:08 2007 From: mail.ciju.cherian at gmail.com (ciju) Date: 10 May 2007 22:29:08 -0700 Subject: searching algorithm In-Reply-To: References: <7dydnfjNWbo9H97bnZ2dnUVZ_oupnZ2d@comcast.com> Message-ID: <1178861348.204066.293820@o5g2000hsb.googlegroups.com> On May 11, 3:12 am, Neil Cerutti wrote: > On 2007-05-10, Gordon Airporte wrote: > > > > > > >> For the above (abrideged) dictionary, you would generate (use a > >> fixed-width "programmers" font so the tree looks good): > > >> a > >> | > >> b > >> | > >> s > >> / \ > >> i o > >> / / \ > >> n l r > >> / / \ \ > >> t u v b->(absorbirati, crpisti) > >> / | | > >> (pelin)<-h t e->(odrije?iti, osloboditi) > >> | | > >> (pelin)<-e e->(apsolutan, apsolutni kod) > > >> As the user enter letters, you just march down the tree, printing > >> all the words held in leaf nodes held in the current node. > > > Call me dense, but how does one do this in Python - which > > doesn't have pointers? Dictionaries with dictionaries within > > dictionaries... (with each letter as the key and the its > > children as values) is going to be extremely space inefficient, > > right? > > Unfortunately, I don't know the space tradeoffs in Python > offhand. Lists and tuples make excellent trees. > > The above might be stored as follows: > > Every node is a tuple of its letter, a list of its children, and > a list of its words. So the two 'pelin' nodes would be (with 'e' > referenced in the 'h' node): > > ('h', [('e', [], ['pelin'])], ['pelin']) > > That would in turn be "stored" in the t, n, i and s nodes. > > ('s', > [('i', > [('n', > [('t', > [('h', [('e', [], ['pelin'])], ['pelin']) > [])] > [])] > []), ('o' trie (thanks Terry) omitted for my sanity)]) > > It's a lot harder to write by hand than it would be to use. > > My intuition says it shouldn't be terribly hard on resources for > for a 180K dictionary, but I could be wrong. I'm too lazy to > measure. ;) > > If it does turn out to be unreasonably huge, then you'd fall back > on solving the problem completely with a binary search returning > a range (I'm not sure of the name), which would be more expensive > at run time, but might be fast enough, and would use a minimal > amount of 'resources'. > > -- > Neil Cerutti The problem that I see here is that each time user types a letter, all the leaf nodes in the subtree would have to be traversed again. This computation was already done for all the letters user typed before the last one. My suggestion would be to have two data structures. The first one similar to the tree mentioned above, but leaf nodes need not have Croatian translations, and each node should also have total number of leafs in both left siblings and right siblings of that node. The second data structure would be list of English:Croatian word pairs. As the user types a new letter, we just have to remove(not show), the number of leaf elements in the left and/or right siblings, from left and/or right of the second data structure. So we just have to keep track of the node we r currently at(in the tree) and the start, end index for the second data structure(basically the list to be shown to the user). By the way, both data structures could be implemented as tuple in python, for I suppose, if only lookup is needed tuple gives better performance than list. ciju From joshusdog at gmail.com Tue May 15 12:15:44 2007 From: joshusdog at gmail.com (joshusdog at gmail.com) Date: 15 May 2007 09:15:44 -0700 Subject: multi-line input? In-Reply-To: References: <1179179435.410251.303530@u30g2000hsc.googlegroups.com> Message-ID: <1179245743.949771.78260@p77g2000hsh.googlegroups.com> Ah, thanks. Using the information you provided, I found the following page: http://archives.free.net.ph/message/20000303.091004.4da616bf.en.html It's not perfect, but it's close enough for what I need. From steve at REMOVE.THIS.cybersource.com.au Thu May 31 12:20:45 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 01 Jun 2007 02:20:45 +1000 Subject: c[:]() References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> Message-ID: On Thu, 31 May 2007 07:59:35 -0700, Warren Stringer wrote: > Still I prefer > > funcs[:]() > > Because, I can describe it in English as "call everything that funcs has" But that's not what it says. It says, "call a copy of funcs". The simplest, most straightforward way of calling everything that funcs has is simply: for func in funcs: func() By the way... if you're worried about saving keystrokes on your mobile phone, why don't you do your development on a PC and upload it to the phone when it is done? Or have I misunderstood? -- Steven. From gagsl-py2 at yahoo.com.ar Tue May 8 00:21:37 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 08 May 2007 01:21:37 -0300 Subject: interesting exercise References: <1178595952.641173.76540@y80g2000hsf.googlegroups.com> Message-ID: En Tue, 08 May 2007 00:45:52 -0300, Michael Tobis escribi?: > I want a list of all ordered permutations of a given length of a set > of tokens. Each token is a single character, and for convenience, they > are passed as a string in ascending ASCII order. This is what I come, no tricks, no special optimizations, just plain Python (including your constraints): def permute(values, n): def _permute(values, n): if n==1: for letter in values: yield [letter] else: for letter in values: for others in _permute(values, n-1): yield [letter]+others if not sorted(values): raise ValueError("unsorted values") if len(set(values))!=len(values): raise ValueError("duplicate values") return list(''.join(item) for item in _permute(values, n)) -- Gabriel Genellina From newsgroups at nospam.demon.co.uk Thu May 31 03:57:56 2007 From: newsgroups at nospam.demon.co.uk (Douglas Woodrow) Date: Thu, 31 May 2007 08:57:56 +0100 Subject: c[:]() References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> Message-ID: On Wed, 30 May 2007 23:23:22, Warren Stringer wrote > >def a(): return 'b' >def b(): print 'polly! wakey wakey' >c = {} >c['a'] = b >c[a()]() #works! (typo correction for other easily-confused newbies like myself) I think you mean ,---- | c['a']() #works! `---- -- Doug Woodrow From jim at reallykillersystems.com Mon May 7 10:55:55 2007 From: jim at reallykillersystems.com (James Beck) Date: Mon, 7 May 2007 10:55:55 -0400 Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> <08qk33t594ih0ulmjmev90d22lkfnotgoe@4ax.com> <463C2A3A.8332D211@hotmail.com> <0k8p33h90bp5tfajedb4bmd2eik8gfi2ho@4ax.com> Message-ID: In article <0k8p33h90bp5tfajedb4bmd2eik8gfi2ho at 4ax.com>, quasi at null.set says... > On Sat, 05 May 2007 07:54:50 +0100, Eeyore > wrote: > > > > > > >quasi wrote: > > > >> Gib Bogle wrote: > >> > >> >Ah, so the firefighters were in on the conspiracy! > >> > >> No, but the firefighters are very much aware that there is more to > >> 9/11 than has been officially revealed. > >> > >> This is even more true at Pentagon. The firefighters there brought > >> dogs trained to search for survivors and/or remains > > > >Sounds like good practice. > > > > > >> and found nothing. > > > >And the significance of this is ? > > The plane was supposed to have passengers. > > quasi > Yep, and they found them all, therefore, there were none for the dogs to find. From frederic.pica at gmail.com Thu May 31 09:15:18 2007 From: frederic.pica at gmail.com (frederic.pica at gmail.com) Date: 31 May 2007 06:15:18 -0700 Subject: Python memory handling In-Reply-To: References: <1180611604.247696.149060@h2g2000hsg.googlegroups.com> Message-ID: <1180617317.969977.115660@u30g2000hsc.googlegroups.com> On 31 mai, 14:16, Marc 'BlackJack' Rintsch wrote: > In <1180611604.247696.149... at h2g2000hsg.googlegroups.com>, frederic.pica > wrote: > > > So as I can see, python maintain a memory pool for lists. > > In my first example, if I reparse the xml file, the memory doesn't > > grow very much (0.1 Mb precisely) > > So I think I'm right with the memory pool. > > > But is there a way to force python to release this memory ?! > > AFAIK not. But why is this important as long as the memory consumption > doesn't grow constantly? The virtual memory management of the operating > system usually takes care that only actually used memory is in physical > RAM. > > Ciao, > Marc 'BlackJack' Rintsch Because I'm an adept of small is beautiful, of course the OS will swap the unused memory if needed. If I daemonize this application I will have a constant 40 Mb used, not yet free for others applications. If another application need this memory, the OS will have to swap and loose time for the other application... And I'm not sure that the system will swap first this unused memory, it could also swap first another application... AFAIK. And these 40 Mb are only for a 7 Mb xml file, what about parsing a big one, like 50 Mb ? I would have preferred to have the choice of manually freeing this unused memory or setting manually the size of the memory pool Regards, FP From mike.klaas at gmail.com Wed May 9 20:36:59 2007 From: mike.klaas at gmail.com (Klaas) Date: 9 May 2007 17:36:59 -0700 Subject: File I/O In-Reply-To: <1178746990.587898.122080@y80g2000hsf.googlegroups.com> References: <1178745198.392518.56840@q75g2000hsh.googlegroups.com> <1178746525.499358.179550@w5g2000hsg.googlegroups.com> <1178746990.587898.122080@y80g2000hsf.googlegroups.com> Message-ID: <1178757419.637944.128540@q75g2000hsh.googlegroups.com> On May 9, 2:43 pm, HMS Surprise wrote: > > [lst.append(list(line.split())) for line in file] > > Thanks, this is the direction I wanted to go, BUT I must use v2.2 so > the line above gives me the error: > > AttributeError: __getitem__ > > But the write format will be helpful. (change to file.xreadlines(). Btw that snippet will fail miserably for most data). Instead, use pickle: import pickle pickle.dump(lst_of_lst, open('outfile', 'wb')) lst_of_lst = pickle.load(open('outfile', 'rb')) -Mike From steve at REMOVE.THIS.cybersource.com.au Wed May 30 22:38:42 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 31 May 2007 12:38:42 +1000 Subject: Create a new class on the fly References: <1180568447.449581.250500@g37g2000prf.googlegroups.com> Message-ID: On Wed, 30 May 2007 17:44:06 -0700, py_genetic wrote: > > Is this possible or is there a better way. I need to create a new > class during runtime to be used inside a function. The class > definition and body are dependant on unknows vars at time of exec, > thus my reasoning here. You might want a class factory, a function that returns a class, or a metaclass, a class that returns classes. Building the class definition as a string at runtime and then using exec (not eval) to create the class is probably the most obvious way of doing it, but it isn't very convenient, and if you are getting any part of the string from a source not under your control (e.g. a web form) you're opening yourself up to a world of security holes. The cleaner, safer, more convenient ways of building classes at runtime is to use the Python metaclass machinery, perhaps wrapped in a function for convenience. See here for examples: http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html -- Steven. From gagsl-py2 at yahoo.com.ar Mon May 21 03:55:40 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 21 May 2007 04:55:40 -0300 Subject: Cycle detection and object memory usage? References: Message-ID: En Sun, 20 May 2007 23:54:15 -0300, Jim Kleckner escribi?: > I understand from the documentation that types with a finalizer method > that participate in cycles can't be collected. Yes; older Python versions could not manage any kind of cycles, now only objects with __del__ cause problems. You can explicitely break the cycle (removing the reference, ensuring that some finalization method is always called, maybe using try/finally) or you may use weak references (by example, in a tree-like structure, a node might hold a weak reference to its parent). > What is the best way to go about finding these cycles? > Googling gives a variety of methods none of which seem terribly > mainstream for such a common problem. Avoid them in the first place :) Use the gc module: after a call to gc.collect(), see if something remains in gc.garbage > Object memory usage: > > Has anyone written a function to sweep out an object to discover how > much memory it and all the objects it references is using? This would > be great for performance tuning. A rough estimate may be the object's pickle size. But it's hard to measure precisely; by example, strings are immutable and you may have thousands of shared references to the same string, and they require just a few bytes each. -- Gabriel Genellina From jstroud at mbi.ucla.edu Sat May 19 07:17:22 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 19 May 2007 11:17:22 GMT Subject: converting strings to most their efficient types '1' --> 1, 'A' ---> 'A', '1.2'---> 1.2 In-Reply-To: <464E6F32.7070200@lexicon.net> References: <1179529661.555196.13070@k79g2000hse.googlegroups.com> <464E6F32.7070200@lexicon.net> Message-ID: <61B3i.6880$H_.138@newssvr21.news.prodigy.net> John Machin wrote: > The approach that I've adopted is to test the values in a column for all > types, and choose the non-text type that has the highest success rate > (provided the rate is greater than some threshold e.g. 90%, otherwise > it's text). > > For large files, taking a 1/N sample can save a lot of time with little > chance of misdiagnosis. Why stop there? You could lower the minimum 1/N by straightforward application of Bayesian statistics, using results from previous tables as priors. James From showell30 at yahoo.com Mon May 28 13:58:50 2007 From: showell30 at yahoo.com (Steve Howell) Date: Mon, 28 May 2007 10:58:50 -0700 (PDT) Subject: itertools.groupby In-Reply-To: <1180373388.112182.225700@i13g2000prf.googlegroups.com> Message-ID: <80503.24653.qm@web33505.mail.mud.yahoo.com> --- Raymond Hettinger wrote: > That's not for everyone, so it isn't a loss if > someone sticks > with writing plain, clear everyday Python instead of > an itertool. > I know most of the module is fairly advanced, and that average users can mostly avoid it, but this is a very common-antipattern that groupby() solves: group = [] lastKey = None for item in items: newKey = item.key() if newKey == lastKey: group.append(item) elif group: doSomething(group) group = [] lastKey = newKey if group: doSomething(group) See this recent thread, for example: http://mail.python.org/pipermail/python-list/2007-May/442602.html ____________________________________________________________________________________ The fish are biting. Get more visitors on your site using Yahoo! Search Marketing. http://searchmarketing.yahoo.com/arp/sponsoredsearch_v2.php From mike.klaas at gmail.com Tue May 8 17:42:58 2007 From: mike.klaas at gmail.com (Klaas) Date: 8 May 2007 14:42:58 -0700 Subject: How safe is a set of floats? In-Reply-To: <1178298957.102330.50060@u30g2000hsc.googlegroups.com> References: <1178288509.067493.5140@e65g2000hsc.googlegroups.com> <1hxkw5d.1ipc1zfocmqm9N%aleax@mac.com> <1178294650.738576.205690@q75g2000hsh.googlegroups.com> <1178297450.812110.322140@q75g2000hsh.googlegroups.com> <1178298957.102330.50060@u30g2000hsc.googlegroups.com> Message-ID: <1178660578.170195.168500@y80g2000hsf.googlegroups.com> On May 4, 10:15 am, Paul McGuire wrote: > Just to beat this into the ground, "test for equality" appears to be > implemented as "test for equality of hashes". So if you want to > implement a class for the purposes of set membership, you must > implement a suitable __hash__ method. It is not sufficient to > implement __cmp__ or __eq__, which I assumed "test for equality" would > make use of. Not having a __hash__ method in my original class caused > my initial confusion. overriding __hash__ (even to raise NotImplementedError) is always wise if you have override __eq__. And of course __hash__ is necessary for using hashtable-based structures (how else could it determine whether objects are equal? compare against every existing element?) Finally, two objects which return the same __hash__ but return False for __eq__ are, of course, unequal. sets/dicts do not simply "test for equality of hashes" > So would you suggest that any class implemented in a general-purpose > class library should implement __hash__, since one cannot anticipate > when a user might want to insert class instances into a set? (It > certainly is not on my current checklist of methods to add to well- > behaved classes.) a class should be only inserted into a set if it is immutable, and thus designed to such. User's might also execute 'del x.attr', so perhaps you should start each method with a series of hasattr() checks... -Mike From istvan.albert at gmail.com Thu May 17 10:30:14 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: 17 May 2007 07:30:14 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179333797.634234.245830@k79g2000hse.googlegroups.com> <1179344264.595644.136440@h2g2000hsg.googlegroups.com> Message-ID: <1179412214.130756.225450@p77g2000hsh.googlegroups.com> On May 16, 11:09 pm, Gregor Horvath wrote: > sjdevn... at yahoo.com schrieb: > > > On May 16, 12:54 pm, Gregor Horvath wrote: > >> Istvan Albert schrieb: > > >> So the solution is to forbid Chinese XP ? Who said anything like that? It's just an example of surprising and unexpected difficulties that may arise even when doing trivial things, and that proponents do not seem to want to admit to. > Should computer programming only be easy accessible to a small fraction > of privileged individuals who had the luck to be born in the correct > countries? > Should the unfounded and maybe xenophilous fear of loosing power and > control of a small number of those already privileged be a guide for > development? Now that right there is your problem. You are reading a lot more into this than you should. Losing power, xenophilus(?) fear, privileged individuals, just step back and think about it for a second, it's a PEP and people have different opinions, it is very unlikely that there is some generic sinister agenda that one must be subscribed to i. From ivoras at __fer.hr__ Sat May 26 17:22:19 2007 From: ivoras at __fer.hr__ (Ivan Voras) Date: Sat, 26 May 2007 23:22:19 +0200 Subject: __dict__ for instances? In-Reply-To: <46484bb9$0$22850$426a74cc@news.free.fr> References: <46472764$0$23138$9b4e6d93@newsspool1.arcor-online.net> <46477c9d$0$1408$426a74cc@news.free.fr> <46484bb9$0$22850$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: >> The error (not an exception, only the message appears and the handler >> doesn't work): >> >> ** (finstall.py:7551): WARNING **: handler for 'on_button_next_clicked' >> not callable or a tuple > > Is this the full message, or did you skip the preceding lines ? The full message. >> (the file has some 20 lines, not 7551) >> > Is "finstall.py" the name of your file ? If yes, I'd suspect something > wrong with your sys.path or like... This is the name of my file - and it IS executed, only the error message is weird. -- (\__/) (O.o) (> < ) This is Bunny. Copy Bunny into your signature to help him on his way to world domination! -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 258 bytes Desc: OpenPGP digital signature URL: From jjcrump at myuw.net Wed May 30 12:45:16 2007 From: jjcrump at myuw.net (Jon Crump) Date: Wed, 30 May 2007 09:45:16 -0700 (PDT) Subject: google maps api for py? In-Reply-To: <2387F0EED10A4545A840B231BBAAC722F11AB7@slcimail1.slcgov.com> References: <2387F0EED10A4545A840B231BBAAC722F11AB7@slcimail1.slcgov.com> Message-ID: Kev, Geopy is pretty cool: http://exogen.case.edu/projects/geopy/ On Wed, 30 May 2007, Bell, Kevin wrote: > I see that the weapon of choice for google maps is javascript... Is > there anything for python? > > > > Kev > > From duncan.booth at invalid.invalid Tue May 22 15:15:04 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 22 May 2007 19:15:04 GMT Subject: Lists vs tuples (newbie) References: Message-ID: "Hendrik van Rooyen" wrote: > Aside from the hashing issue, there is nothing that a tuple can do > that can't be done as well or better by a list. There are a few other cases where you have to use a tuple, for example in a try..except statement the exception specification must be an exception to be caught or a tuple of exception specifications: a list won't work to catch multiple exceptions. From tony.meyer at gmail.com Tue May 8 01:11:13 2007 From: tony.meyer at gmail.com (Tony Meyer) Date: 7 May 2007 22:11:13 -0700 Subject: getmtime differs between Py2.5 and Py2.4 In-Reply-To: <463FA51D.1060600@v.loewis.de> References: <463FA51D.1060600@v.loewis.de> Message-ID: <1178601073.116993.8030@u30g2000hsc.googlegroups.com> On May 8, 10:15 am, "Martin v. L?wis" wrote: > that you are mistaken: There is NO difference between the outcome > of os.path.getmtime between Py2.5 and Py2.4. It always did return > UTC, and always will. In revision 42230, you checked in a change to posixmodule.c with the following code comment: /* The CRT of Windows has a number of flaws wrt. its stat() implementation: - time stamps are restricted to second resolution - file modification times suffer from forth-and-back conversions between UTC and local time Therefore, we implement our own stat, based on the Win32 API directly. */ (See http://svn.python.org/view/python/trunk/Modules/posixmodule.c?rev=42230&view=log ) Different results are indeed obtained, as others have demonstrated (other than the irrelevant float/int distinction). The following C sample program illustrates: C:\>a d:\temp.txt Time modified : Thu Feb 08 10:08:44 2007 Time modified : 02/07/2007 22:08:44 UTC Time modified : 02/08/2007 11:08:44 Local C:\>c:\python24\python -c "import os;import time;print time.ctime(os.path.getmtime('temp.txt'))" Thu Feb 08 10:08:44 2007 C:\>c:\python25\python -c "import os;import time;print time.ctime(os.path.getmtime('temp.txt'))" Thu Feb 08 11:08:44 2007 (My local time is UTC-12). This doesn't happen with every file: C:\>c:\python24\python -c "import os;import time;print time.ctime(os.path.getmtime('temp2.txt'))" Tue May 08 16:59:22 2007 C:\>c:\python25\python -c "import os;import time;print time.ctime(os.path.getmtime('temp2.txt'))" Tue May 08 16:59:22 2007 C:\>a d:\temp2.txt Time modified : Tue May 08 16:59:22 2007 Time modified : 05/08/2007 04:59:22 UTC Time modified : 05/08/2007 16:59:22 Local A key fact here, I believe, is that in February (when temp.txt was last modified), my local time was UTC-11. I expect this is the suffering that your comment in posixmodule.c refers to (it looks to me like Python 2.5 is correct). Cheers, Tony --- #include #include #include #include #include int main( int argc, char **argv ) { WIN32_FILE_ATTRIBUTE_DATA lpFileInformation; SYSTEMTIME stUTC, stLocal; struct __stat64 buf; int result; /* Python 2.4 style */ result = _stat64( argv[1], &buf ); if( result != 0 ) perror( "Problem getting information" ); else printf( "Time modified : %s", _ctime64( &buf.st_mtime ) ); /* Python 2.5+ */ GetFileAttributesEx(argv[1], GetFileExInfoStandard, &lpFileInformation); FileTimeToSystemTime(&lpFileInformation.ftLastWriteTime, &stUTC); printf("Time modified : %02d/%02d/%d %02d:%02d:%02d UTC\n", stUTC.wMonth, stUTC.wDay, stUTC.wYear, stUTC.wHour, stUTC.wMinute, stUTC.wSecond); SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal); printf("Time modified : %02d/%02d/%d %02d:%02d:%02d Local\n", stLocal.wMonth, stLocal.wDay, stLocal.wYear, stLocal.wHour, stLocal.wMinute, stLocal.wSecond); } From jm.suresh at gmail.com Fri May 4 04:23:49 2007 From: jm.suresh at gmail.com (jm.suresh@no.spam.gmail.com) Date: 4 May 2007 01:23:49 -0700 Subject: Getting some element from sets.Set In-Reply-To: References: <1178258913.095438.173020@h2g2000hsg.googlegroups.com> Message-ID: <1178267029.258868.219800@h2g2000hsg.googlegroups.com> On May 4, 11:34 am, Peter Otten <__pete... at web.de> wrote: > jm.sur... at no.spam.gmail.com wrote: > > It is not possible to index set objects. That is OK. > > But, what if I want to find some element from the Set. > > > from sets import Set > > s = Set( range(12 ) > > > if I do pop, that particular element gets removed. > > I do not want to remove the element, but get some element > > from the Set. > > > s.some_element() # Is not available > > > Is there a way to do this. I am doing it like this: > > > for x in s: break > > > Now x is /some_element/ from s. > > A set is probably not the appropriate container then. What is your use case? > > Peter Peter, I need to do a lot of union and intersection operations on these elements. So, set is a must for me in this case. In the particular case, I have to read an attribute from any one of the elements, which one doesn't matter because this attribute value is same across all elements in the set. - Suresh From saif.shakeel at gmail.com Tue May 8 07:23:34 2007 From: saif.shakeel at gmail.com (saif.shakeel at gmail.com) Date: 8 May 2007 04:23:34 -0700 Subject: replacing string in xml file Message-ID: <1178623414.092046.91120@y5g2000hsa.googlegroups.com> Hi, I need to replace a string in xml file with something else.Ex - rate rate - Here i have opened an xml file(small part is pasted here).I want to replace the word 'localId' with 'dataPackageID' wherever it comes in xml file.I tried this but didnt work: import sys file_input = raw_input("Enter The ODX File Path:") input_xml = open(file_input,'r') input_xml.replace('localId','dataPackageId') This gives error ---> AttributeError: 'file' object has no attribute 'replace' Can someone help me . Thanks From larry.bates at websafe.com Thu May 31 13:01:25 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 31 May 2007 12:01:25 -0500 Subject: Using PIL to find separator pages Message-ID: I have a project that I wanted to solicit some advice on from this group. I have millions of pages of scanned documents with each page in and individual .JPG file. When the documents were scanned the people that did the scanning put a colored (hot pink) separator page between the individual documents. I was wondering if there was any way to utilize PIL to scan through the individual files, look at some small section on the page, and determine if it is a separator page by somehow comparing the color to the separator page color? I realize that this would be some sort of percentage match where 100% would be a perfect match and any number lower would indicate that it was less likely that it was a coverpage. Thanks in advance for any thoughts or advice. Regards, Larry Bates From bernhard.voigt at gmail.com Fri May 18 06:44:52 2007 From: bernhard.voigt at gmail.com (bernhard.voigt at gmail.com) Date: 18 May 2007 03:44:52 -0700 Subject: pyhdf In-Reply-To: <1179336974.691021.106680@k79g2000hse.googlegroups.com> References: <1179336974.691021.106680@k79g2000hse.googlegroups.com> Message-ID: <1179485092.164879.129180@q75g2000hsh.googlegroups.com> Hi, I can't help here, just a recommendation: I am using pytables (http://www.pytables.org) build upon hdf5. If you're not bound to hdf4, go and try pytables instead of pyhdf. Bernhard From Graham.Dumpleton at gmail.com Sat May 19 21:50:27 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: 19 May 2007 18:50:27 -0700 Subject: mod_python performs several magnitudes slower than PHP? In-Reply-To: <4dM3i.3287$y_7.725@newssvr27.news.prodigy.net> References: <1179616996.948606.319670@q75g2000hsh.googlegroups.com> <4dM3i.3287$y_7.725@newssvr27.news.prodigy.net> Message-ID: <1179625827.647353.50840@p77g2000hsh.googlegroups.com> On May 20, 10:01 am, John Nagle wrote: > That's puzzling, because withmod_python, you're only invoking > the compiler once per Apache restart. With CGI programs, you pay > the loading penalty on every request. > > John Nagle > > chris.monsa... at gmail.com wrote: > > Recently I've had to move my site to a new dedicated server running > > FreeBSD 6.1. After installing apache 2.0.59, python 2.4.4 and > >mod_python3.3.1, I decided to bench a script in PHP vs one in Python. > > I found out that for some reason, mymod_pythonwas performing > > extremely slow - magnitudes slower than it should. I scowered the > > internet for hours and asked a few friends and still haven't been able > > to find a solution to the problem. > > > frommod_pythonimport apache > > > def handler(req): > > for i in xrange(1000): > > print >> req, "Yeah" > > return apache.OK > > > and... > > > > for ($i = 0; $i < 1000; $i++) > > echo "Yeah\n" ; > > ?> > > > when I ran ab on both using 1000 requests and a concurrency of 10, i > > got these results: > > > python- Requests per second: 21.37 [#/sec] (mean) > > php- Requests per second: 1008.37 [#/sec] (mean) > > > Any ideas would really be appreciated... I'm on my last leg. The original poster also asked the same question on the mod_python mailing list. As pointed out there, the examples aren't equivalent as the mod_python example would have resulted in data being flushed to the client after every call to 'print'. A more suitable example for comparison would have been: def handler(req): for i in xrange(1000): req.write('Yeah\n, 0) return apache.OK The second argument of 0 to req.write() will allow Apache to buffer data in an appropriate way and avoid lots of socket writes with small amounts of data, plus avoid triggering of Apache's filter mechanism every time. Graham From mtobis at gmail.com Wed May 23 13:25:07 2007 From: mtobis at gmail.com (Michael Tobis) Date: 23 May 2007 10:25:07 -0700 Subject: CP4E revival Message-ID: <1179941107.366354.101860@h2g2000hsg.googlegroups.com> Is education Python's killer app? I think it could be. I used the occasion of the Python Papers to motivate my efforts, and you can see what I came up with here on pages 8-15. The part that makes me especially queasy is the CP4E section on pages 10-11. I wish I had more to say there. It's fairly clear to those of us who weren't there that there were some problems, but it's not especially clear what they were or what we should learn from them. I'd very much appreciate input from those who were actually there! Anyway http://tinyurl.com/yr62r3 seems to short-circuit some pointless hoop-jumping to get you to the article. If that doesn't work, try going to http://pyjournal.cgpublisher.com/ and looking for the spring 2007 edition. I suggest a concerted effort by the community toward leveraging the OLPC/Sugar momentum to revive the idea of Python as tool for teaching some programming as a useful part of universal education. mt From deets at nospam.web.de Wed May 30 07:41:41 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 30 May 2007 13:41:41 +0200 Subject: writing to a file In-Reply-To: <1180515758.671628.43200@k79g2000hse.googlegroups.com> References: <1180515758.671628.43200@k79g2000hse.googlegroups.com> Message-ID: <5c5681F2t82noU1@mid.uni-berlin.de> montyphyton at gmail.com schrieb: > as i understand there are two ways to write data to a file: using > f.write("foo") and print >>f, "foo". > what i want to know is which one is faster (if there is any difference > in speed) since i'm working with very large files. of course, if there > is any other way to write data to a file, i'd love to hear about it You should look at the mmap-module. Diez From mediocre_person at hotmail.com Thu May 24 18:18:46 2007 From: mediocre_person at hotmail.com (Medi Ochre) Date: Thu, 24 May 2007 17:18:46 -0500 Subject: Tkinter help, please... Message-ID: <465602f8$0$16302$88260bb3@free.teranews.com> I've been away from Python for some time, and I'm just starting to look at Tkinter. Just so you know, I'm coming from Visual Basic, where this would, I *think*, not have been a problem, so it must be a case of getting my head around the Tkinter way of doing things. In a nutshell, I've written an app wherein I wish to update the display often. What's happening is that I get *no* display until main() hits win.mainloop(). I've indicated the things I've tried (round about line 180). At the risk of exposing myself, here's the whole thing. If you have a thought, I'd sure appreciate it! Nick. from random import * from Tkinter import * ''' Score the "good jack" ''' def jack(h, f): hand = h[:] hand.remove(f) for card in hand: if card.rank == 10 and card.suit == f.suit: return 1 return 0 ''' Count and return 2 for each combination that adds up to 15 ''' def fifteen(h): if h[0].value() + h[1].value() + h[2].value() + h[3].value() + h[4].value() == 15: return 2 # 4-card combos score = 0 for a in range(0,2): for b in range(a+1,3): for c in range(b+1,4): for d in range(c+1,5): if h[a].value() + h[b].value() + h[c].value() + h[d].value() == 15: score += 2 # 3-card combos for a in range(0,3): for b in range(a+1,4): for c in range(b+1,5): if h[a].value() + h[b].value() + h[c].value() == 15: score += 2 # 2-card combos for a in range(0,4): for b in range(a+1,5): if h[a].value() + h[b].value() == 15: score += 2 return score ''' Simplified flush rules: Try the 4 flush and 5 flush, give the best score. ''' def flushes(h, f): # 5-flush suit = h[0].suit total = 0 for card in h: if card.suit == suit: total += 1 #end if #end for if total == 5: return 5 # 4-flush hand = h[:] hand.remove(f) suit = hand[0].suit total = 0 for card in hand: if card.suit == suit: total += 1 if total == 4: return 4 return 0 ''' 1 Point per card per run ''' def runs(h): # Is there a 5-run? if h[0].rank == h[1].rank-1 and h[1].rank == h[2].rank-1 and \ h[2].rank == h[3].rank-1 and h[3].rank == h[4].rank-1 : return 5 # Look for 4-runs: score = 0 for a in range(0,2): for b in range(a+1,3): for c in range(b+1,4): for d in range(c+1,5): if h[a].rank == h[b].rank-1 and h[b].rank == h[c].rank-1 \ and h[c].rank == h[d].rank-1: score += 4 if score != 0: return score #Look for 3-runs for a in range(0,3): for b in range(a+1,4): for c in range(b+1,5): if h[a].rank == h[b].rank-1 and h[b].rank == h[c].rank-1: score += 3 return score ''' Two points per pair ''' def pairs(h): ''' Tally me hand ''' score = 0 for left in range(0,4): for right in range(left+1, 5): if h[left].rank == h[right].rank: score += 2 return score def tally(h, f): return pairs(h) + runs(h) + flushes(h, f) + fifteen(h) + jack(h, f) class Card: def __init__(self, r, s): self.rank = r self.suit = s def value(self): return min([self.rank+1, 10]) def __repr__(self): s = "HSCD"[self.suit] r = "A23456789TJQK"[self.rank] return r+s __str__ = __repr__ class Deck: def __init__(self): self.deck = [] for r in range(13): for s in range(4): self.deck.append(Card(r,s)) shuffle(self.deck) #self.card = 0 def deal(self): #self.card += 1 if len(self.deck) == 2: self.deck = [] for r in range(13): for s in range(4): self.deck.append(Card(r,s)) shuffle(self.deck) return self.deck.pop() class Cribbage: def __init__(self, win): #Draw the interface self.f = Frame(win) self.f.grid() self.cardpix = [Label(self.f), Label(self.f), Label(self.f), Label(self.f), Label(self.f)] clr = ["red", "blue"] n = 1 for c in self.cardpix: c.configure(width=10, height=10, bg=clr[n%2], text="card "+str(n)) c.grid(row=0, column=n-1) n += 1 self.scorebox = Label(self.f) self.scorebox.configure(height=5, bg="green", text="Score: 0") self.scorebox.grid(row=1, column=0, columnspan=5) def play(self, win): d = Deck() hand = [d.deal(), d.deal(), d.deal(), d.deal()] flipped = d.deal() hand.append(flipped) hand.sort() score = tally(hand, flipped) self.scorebox.configure(text= "Score: " + str(score)) #Eventually, display the actual card images, but for now... for c, x in zip(hand, self.cardpix): x.configure(text = str(c)) #I've tried both of these, to no avail. win.iconify() self.f.update_idletasks() return score def main(): win = Tk() run = Cribbage(win) score = 0 best = 0 while score < 24: score = run.play(win) if score >= best: best = score win.mainloop() main() -- Posted via a free Usenet account from http://www.teranews.com From walterbyrd at iname.com Thu May 10 16:48:57 2007 From: walterbyrd at iname.com (walterbyrd) Date: 10 May 2007 13:48:57 -0700 Subject: Newbie look at Python and OO In-Reply-To: <464380c4$0$25791$426a74cc@news.free.fr> References: <1178812734.860473.236370@y80g2000hsf.googlegroups.com> <464380c4$0$25791$426a74cc@news.free.fr> Message-ID: <1178830137.877510.290070@w5g2000hsg.googlegroups.com> Thanx for all the replies, I may be slowly getting it. But, can anybody explain this? >>> a = 'hello' >>> b = 'hello' >>> a is b True >>> a = 'hello there' >>> b = 'hello there' >>> a is b False From theller at ctypes.org Wed May 9 13:14:52 2007 From: theller at ctypes.org (Thomas Heller) Date: Wed, 09 May 2007 19:14:52 +0200 Subject: ctypes: Problems using Windows-DLL from VB example code In-Reply-To: <4641fd20$1@news.broadpark.no> References: <4641fd20$1@news.broadpark.no> Message-ID: Noralf Tr?nnes schrieb: > Hi > > I'm trying to use a DLL from Python using ctypes. > The call to dso_lib.capture_hold_chk() does return 232. So it seem to work. > The call to dso_lib.port_init(init_data) gives: > WindowsError: exception: access violation reading 0x00000006 > > Any suggestions? > Have you tried to pass the structure by reference? dso_lib.port_init(byref(init_data)) Thomas From rohitsethidce at gmail.com Mon May 7 18:41:08 2007 From: rohitsethidce at gmail.com (rohit) Date: 7 May 2007 15:41:08 -0700 Subject: randomly write to a file In-Reply-To: References: <1178567497.042096.82940@w5g2000hsg.googlegroups.com> Message-ID: <1178577668.670941.250790@p77g2000hsh.googlegroups.com> hi gabriel, i am utilizing file names and their paths which are written to a file on a singe line. now if i use records that would be wasting too much space as there is no limit on the no. of characters (at max) in the path. next best approach i can think of is reading the file in memory editing it and writing the portion that has just been altered and the followiing lines but is there a better approach you can highlight? > You can only replace a line in-place with another of exactly the same > length. If the lengths differ, you have to write the modified line and all > the following ones. > If all your lines are of fixed length, you have a "record". To read record > N (counting from 0): > a_file.seek(N*record_length) > return a_file.read(record_length) > And then you are reinventing ISAM. > > -- > Gabriel Genellina From ramashish.lists at gmail.com Fri May 25 15:06:56 2007 From: ramashish.lists at gmail.com (Ramashish Baranwal) Date: 25 May 2007 12:06:56 -0700 Subject: Module listing in order. In-Reply-To: References: <1179905562.541601.264400@m36g2000hse.googlegroups.com> Message-ID: <1180120016.349259.9540@x18g2000prd.googlegroups.com> > > I want a way to get the contents in the order of their declaration, > > i.e. [B, A, D]. Does anyone know a way to get it? > > My suggestion would be to actually parse the text of the module. "Brute > force" is what it's called ;). But doing so with, say, pyparsing > shouldn't be *very* difficult. > > Just out of curiosity: Why do you need the order? > Thank you for your replies, and sorry for my late response. Gabriel, unfortunately I am not a python expert so don't know how to play with module creation. I tried to look into __import__ function, but can't see a way to get what I want. Wildemar, your approach seems workable. I am going to have a look at it. Well, my requirement doesn't turn out to be an actual requirement now.:) I am using a web framework Django, that lets you define classes for database tables. The classes so defined can refer to other classes representing db tables. It also allows you to export those table data in a db-neutral format e.g. xml via the python classes so defined. Exporting does not require an order, but I thought that importing the data back may require data of classes which are referred by other classes to be present. I just verified that its not so. So I don't need to do it immediately. Nevertheless, it would be interesting to see how it can be done.:) -Ram From steve at REMOVEME.cybersource.com.au Thu May 3 21:11:15 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Fri, 04 May 2007 11:11:15 +1000 Subject: NewB: Glob Question References: <1178213910.976263.207630@e65g2000hsc.googlegroups.com> Message-ID: On Thu, 03 May 2007 10:38:31 -0700, J wrote: > Greetings Group- > > I'm trying to put together a pattern matching script that scans a > directory tree for tif images contained in similar folder names, but > running into a NewB problem already. Is it the way I'm trying to join > multiple paths? Any help would be greatly appericated. Thanks, J! No no, don't tell us what problem you found! We love guessing!!! Let's see... did it reformat your hard drive? If you join multiple paths wrong, Python will reformat your hard drive as punishment. I tell you, you soon learn not to do that! -- Steven D'Aprano From maric at aristote.info Wed May 23 19:21:00 2007 From: maric at aristote.info (Maric Michaud) Date: Thu, 24 May 2007 01:21:00 +0200 Subject: Can I reference 1 instance of an object by more names ? rephrase In-Reply-To: References: <4654289a$0$2326$426a74cc@news.free.fr> Message-ID: <4654CC5C.7070509@aristote.info> Stef Mientki a ?crit : > hi Bruno, > > after study it carefully, > it's much more complex than I thought > (I can't understand it completely, which is of less importance). > Your solution works great, > but I need one little extension, > which I can create, but just at the cost of a lot of code. > Maybe you can give me another hint. > >> In the first case, this is *really* a binding, and that's one of the few >> things that Python won't let you mess with. In the two last cases, it's >> in fact a method call - as the use of __[get|set]item__ should make >> obvious. >> >> here's an example using a property: >> >> class cpu_ports(object): >> def __init__(self, value=0): >> self._d = value >> @apply >> def value(): >> def fset(self, value): >> print 'vv' >> self._d = value >> def fget(self): >> return self._d >> return property(**locals()) > > # I need to read and write the individual bits of the byte object > # so I can create 8 blocks of code like this, one for each bit position > # I use it, like this > # name1 = cpu_ports() > # name1.p5 = True > # or > # name1.p[5] = True > > @apply # read / write bit 5 > def p5(): > def fset(self, value): > index = 5 > value = ( value & 1L ) << index > mask = ( 1L ) << index > self._d = ( self._d & ~mask ) | value > def fget(self): > index = 5 > return ( self._d >> index ) & 1 > return property(**locals()) > > I can optimize the above code a little bit, > but I've the feeling that I don't need to repeat this code 8 times. something like that should just work (untested) : def bit(): def fset(self, value): index = 5 value = ( value & 1L ) << index mask = ( 1L ) << index self._d = ( self._d & ~mask ) | value def fget(self): index = 5 return ( self._d >> index ) & 1 return property(**locals()) class cpu_ports(object) : p1 = bit() p2 = bit() p3 = bit() p4 = bit() p5 = bit() But i wonder if you shouldn't use arrays instead : In [6]:import array In [7]:help(array) From axjacob at comcast.net Tue May 8 19:52:47 2007 From: axjacob at comcast.net (axjacob at comcast.net) Date: Tue, 08 May 2007 23:52:47 +0000 Subject: FW: Re: e-mailing multiple values Message-ID: <050820072352.447.46410D4F0009B8BD000001BF22058864420D010C0E06A10407020E@comcast.net> Thanks. That does help. When teh script sends a mail of the list item(all_data), the data shows up like this: [(' Ham \n', ' eggs \n'), (' chicken \n', ' thighs \n')] So I have to figure out a way to cleanup the content Thanks Anil > -------------- Forwarded Message: -------------- > From: "Ian Clark" > To: python-list at python.org > Subject: Re: e-mailing multiple values > Date: Tue, 8 May 2007 23:20:44 +0000 > > On 5/8/07, anil_jacob at comcast.net wrote: > > > > > > I have a script which has a method which returns multiple strings at once > > using the yield. I would like to send an e-mail of these values in a single > > e-mail instead of a mail for each string. How would I be able to do that? > > > > > > Thanks > > > AJ > > > > Are you looking for something like the following? If not, try posting > > a small sampling of your code. > > > > >>> def get_data(): > > ... data = ['ham', 'eggs', 'spam'] > > ... for item in data: > > ... yield item > > ... > > >>> all_data = [item for item in get_data()] > > >>> all_data > > ['ham', 'eggs', 'spam'] > > > > Ian > > -- > > http://mail.python.org/mailman/listinfo/python-list > From jstroud at mbi.ucla.edu Fri May 4 06:26:17 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 04 May 2007 03:26:17 -0700 Subject: Firefighters at the site of WTC7 "Move away the building is going to blow up, get back the building is going to blow up." In-Reply-To: <1hlj33p6aq838o2urk1dv6h75b5is4i2vd@4ax.com> References: <1178161820.731367.264500@y80g2000hsf.googlegroups.com> <1hlj33p6aq838o2urk1dv6h75b5is4i2vd@4ax.com> Message-ID: <3TD_h.219$mR2.195@newssvr22.news.prodigy.net> default wrote: > On 2 May 2007 20:10:20 -0700, Midex wrote: > >> LIES LIES LIES LIES LIES > > Trying to understand the World Trade Center events is like waking up > to act fifteen of a long Greek Tragedy. It needs a complex fabric of > description to give a full picture. In explaining this crisis, we will > be showing how the situation rests on layers of historical > developments, layers of crises and solutions. > > shamelessly taken from: > http://www.againstsleepandnightmare.com/ASAN/ASAN7/ASAN7.html > > The World After September 11th, 2001 > > The Old Mole > > By the time you read this, a crisis different from September 11th may > well be foremost in people's minds. Read on. For us today, all the > crises merge to one and we can see the form of Enron's Collapse or the > Iraq War within September 11th and vice-versa. Now, beyond the death > and destruction, the horror of an event like September 11th is the > horror of losing control of your world. This feeling is an extension > of the ordinary experience of being a resident of modern capitalist > society. Here, work, commuting, shopping, and television are > transmitted to you in ways that are beyond any individual or > collective control. > > Damn good read. Marxist trash. From ivoras at __fer.hr__ Sat May 26 17:23:19 2007 From: ivoras at __fer.hr__ (Ivan Voras) Date: Sat, 26 May 2007 23:23:19 +0200 Subject: PyGTK and HTML rendering? Message-ID: Hi! Is there an easy off-the-shelf way to get HTML formatting inside the TextArea widget? I've looked at TextBuffer but it appears to have only support for manual applying of attributes to portions of text. I don't need anything complex, bold, italic and font-size would be enough. -- (\__/) (O.o) (> < ) This is Bunny. Copy Bunny into your signature to help him on his way to world domination! -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 258 bytes Desc: OpenPGP digital signature URL: From steve at REMOVE.THIS.cybersource.com.au Mon May 28 08:57:14 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 28 May 2007 22:57:14 +1000 Subject: What's the best way to iniatilize a function References: <7NmdncRrFaG3WMTbnZ2dnUVZ_gWdnZ2d@comcast.com> Message-ID: On Mon, 28 May 2007 11:01:26 +0200, Gregor Horvath wrote: > Jack schrieb: > >> I didn't call del explicitly. I'm expecting Python to call it when >> the program exits. I put a logging line in __del__() but I never >> see that line printed. It seems that __del__() is not being called >> even when the program exits. Any idea why? >> >> > > http://effbot.org/pyfaq/my-class-defines-del-but-it-is-not-called-when-i-delete-the-object.htm > > better solutions: > > http://docs.python.org/ref/try.html > http://docs.python.org/whatsnew/pep-343.html They might be better solutions, but not for the Original Poster's problem. The O.P. has a library that has to hang around for long time, not just a call or two, and then needs to be closed. try...except and with define *blocks of code*, not long-lasting libraries with data, functions, etc. Maybe you could shoe-horn the O.P.'s problem into a with block, but the result would surely be ugly and fragile. -- Steven. From sjmachin at lexicon.net Sun May 27 17:55:42 2007 From: sjmachin at lexicon.net (John Machin) Date: 27 May 2007 14:55:42 -0700 Subject: Newbie question - better way to do this? In-Reply-To: References: <1180273441.455227.120170@g4g2000hsf.googlegroups.com> Message-ID: <1180302942.215945.58090@a26g2000pre.googlegroups.com> On May 28, 12:46 am, Steven D'Aprano wrote: > On Sun, 27 May 2007 06:44:01 -0700, Eric wrote: > > words is a big long array of strings. What I want to do is find > > consecutive sequences of words that have the first letter capitalized, > > and then call doSomething on them. (And you can ignore the fact that > > it won't find a sequence at the very end of words, that is fine for my > > purposes). > > Assuming the list of words will fit into memory, and you can probably > expect to fit anything up to millions of words comfortably into memory, > something like this might be suitable: > > list_of_words = "lots of words go here".split() > > accumulator = [] > for word in list_of_words: > if word.istitle(): > accumulator.append(word) > else: > doSomething(accumulator) > accumulator = [] > Bzzzt. Needs the following code at the end: if accumulator: doSomething(accumulator) From robert.rawlins at thinkbluemedia.co.uk Fri May 18 04:49:16 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Fri, 18 May 2007 09:49:16 +0100 Subject: App Leaving 'sh ' Everywhere Message-ID: <003b01c79929$6b2b30d0$41819270$@rawlins@thinkbluemedia.co.uk> Hello Guys, I've got an application that seems to leave 'sh ' in my os processes list. I'm running it on Debian, albeit a stripped down embedded version. I'm not sure what the cause of this is, My application starts several threads and also uses popen2.popen3() to run a few CMD commands. Any ideas why I'm getting this, or if it's even something to be concerned about. Thanks, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From victor.lebrun at gmail.com Wed May 2 21:04:09 2007 From: victor.lebrun at gmail.com (vml) Date: 2 May 2007 18:04:09 -0700 Subject: python,win32com,scipy and vb 6 : no module named scipy In-Reply-To: <1178141865.741042.202250@l77g2000hsb.googlegroups.com> References: <1178141865.741042.202250@l77g2000hsb.googlegroups.com> Message-ID: <1178154249.606843.198050@q75g2000hsh.googlegroups.com> On 2 mai, 23:37, vml wrote: > Hello, > > I am really new in python scipy win32com and scipy I tried to setup a > COM server to interact with vb 6 the pythom COM server is : > > from win32com.server import exception, register > import pythoncom, win32pdhutil, winerror > import math > import numpy > import sys > > sys.path.append('D:\\soft\python25\\Lib\\site-packages\\') > > #from scipy import linalg > > class Fop: > _public_methods_ = [ 'SqVal' ] > def SqVal(self,*val): > import sys > sys.path.append('D:\\soft\python25\\Lib\\site-packages\\') > import scipy > #print sys.path > #mat=numpy.bmat(val) > #linalg.inv(mat) > return sys.path > > _reg_verprogid_ = "Python.Fop.3" > _reg_progid_ = "Python.Fop" > _reg_desc_ = "Python Fop" > _reg_clsid_ = "{30BD3490-2632-11cf-AD5B-524153480001}" > > def Register(): > import win32com.server.register > return win32com.server.register.UseCommandLine(Fop) > > if __name__=='__main__': > print "Registering COM server..." > Register() > > the vb 6 code is > > Private Sub Form_Load() > > Set obj = CreateObject("Python.Fop") > > Dim ty(1, 1) As Variant > > ty(0, 0) = 1 > ty(1, 1) = 2 > ty(1, 0) = 3 > ty(0, 1) = 4 > > toto = obj.SqVal(ty) > > End Sub > > I have a problem when I launch the vb 6 code : no module named > scipy .... it is quite strange and I do not understand that Do you > have any ideas ? > > thank you very much ! solved ... problem in the installation From sjmachin at lexicon.net Sun May 6 21:52:18 2007 From: sjmachin at lexicon.net (John Machin) Date: 6 May 2007 18:52:18 -0700 Subject: msbin to ieee In-Reply-To: <1178487847.671199.108140@h2g2000hsg.googlegroups.com> References: <1178487847.671199.108140@h2g2000hsg.googlegroups.com> Message-ID: <1178502738.104124.3840@h2g2000hsg.googlegroups.com> On May 7, 7:44 am, revuesbio wrote: > Hi > Does anyone have the python version of the conversion from msbin to > ieee? > Thank u Yes, Google has it. Google is your friend. Ask Google. It will lead you to such as: http://mail.python.org/pipermail/python-list/2005-August/337817.html HTH, John From martin at v.loewis.de Thu May 17 06:56:27 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 17 May 2007 12:56:27 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de><1179160242.787344.48060@h2g2000hsg.googlegroups.com> <1179258692.237438.110860@p77g2000hsh.googlegroups.com> <464ad4a2$0$23143$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <464C34DB.4010903@v.loewis.de> > Now look me in the eye and tell me that you find > the mix of proper German and English keywords > beautiful. I can't admit that, but I find that using German class and method names is beautiful. The rest around it (keywords and names from the standard library) are not English - they are Python. (look me in the eye and tell me that "def" is an English word, or that "getattr" is one) Regards, Martin From nyamatongwe+thunder at gmail.com Tue May 1 06:59:53 2007 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Tue, 01 May 2007 10:59:53 GMT Subject: Python-URL! - weekly Python news and links (Apr 30) In-Reply-To: <961ig4-hti.ln1@lairds.us> References: <1177963548_23061@sp12lax.superfeed.net> <961ig4-hti.ln1@lairds.us> Message-ID: Cameron Laird: > ... but the *references* in that object are unlikely to be > meaningful on the second machine (or, in many cases, on the > original machine, if at a sufficiently later time). The marshaling of the object is responsible for persisting any contained references in a format that can be revivified on the second machine. Sometimes these are references to 'short lived' objects in the original process, in which case they should have been addrefed which will also lock the process alive. Other times they may be monikers to stable objects which can be reloaded. Neil From gagsl-py2 at yahoo.com.ar Tue May 1 05:51:17 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 01 May 2007 06:51:17 -0300 Subject: Qustion about struct.unpack References: <1178007769.831101.238210@u30g2000hsc.googlegroups.com> Message-ID: En Tue, 01 May 2007 05:22:49 -0300, eC escribi?: > On Apr 30, 9:41 am, Steven D'Aprano > wrote: >> On Mon, 30 Apr 2007 00:45:22 -0700, OhKyu Yoon wrote: >> > I have a really long binary file that I want to read. >> > The way I am doing it now is: >> >> > for i in xrange(N): # N is about 10,000,000 >> > time = struct.unpack('=HHHH', infile.read(8)) >> > # do something >> > tdc = struct.unpack('=LiLiLiLi',self.lmf.read(32)) >> >> Disk I/O is slow, so don't read from files in tiny little chunks. Read a >> bunch of records into memory, then process them. >> >> # UNTESTED! >> rsize = 8 + 32 # record size >> for i in xrange(N//1000): >> buffer = infile.read(rsize*1000) # read 1000 records at once >> for j in xrange(1000): # process each record >> offset = j*rsize >> time = struct.unpack('=HHHH', buffer[offset:offset+8]) >> # do something >> tdc = struct.unpack('=LiLiLiLi', buffer[offset+8:offset+rsize]) >> # do something >> >> (Now I'm just waiting for somebody to tell me that file.read() already >> buffers reads...) > > I think the file.read() already buffers reads... :) Now we need someone to actually measure it, to confirm the expected behavior... Done. --- begin code --- import struct,timeit,os fn = r"c:\temp\delete.me" fsize = 1000000 if not os.path.isfile(fn): f = open(fn, "wb") f.write("\0" * fsize) f.close() os.system("sync") def smallreads(fn): rsize = 40 N = fsize // rsize f = open(fn, "rb") for i in xrange(N): # N is about 10,000,000 time = struct.unpack('=HHHH', f.read(8)) tdc = struct.unpack('=LiLiLiLi', f.read(32)) f.close() def bigreads(fn): rsize = 40 N = fsize // rsize f = open(fn, "rb") for i in xrange(N//1000): buffer = f.read(rsize*1000) # read 1000 records at once for j in xrange(1000): # process each record offset = j*rsize time = struct.unpack('=HHHH', buffer[offset:offset+8]) tdc = struct.unpack('=LiLiLiLi', buffer[offset+8:offset+rsize]) f.close() print "smallreads", timeit.Timer("smallreads(fn)","from __main__ import fn,smallreads,fsize").repeat(3,1) print "bigreads", timeit.Timer("bigreads(fn)", "from __main__ import fn,bigreads,fsize").repeat(3,1) --- end code --- Output: smallreads [4.2534193777646663, 4.126013885559789, 4.2389176672125458] bigreads [1.2897319939456011, 1.3076018578892405, 1.2703250635695138] So in this sample case, reading in big chunks is about 3 times faster than reading many tiny pieces. -- Gabriel Genellina From pillappa at hotmail.com Sun May 6 15:28:46 2007 From: pillappa at hotmail.com (pillappa at hotmail.com) Date: 6 May 2007 12:28:46 -0700 Subject: Error when using Custom Exception defined in a different python module. In-Reply-To: References: <1178475284.092656.103710@e65g2000hsc.googlegroups.com> Message-ID: <1178479726.200854.79830@w5g2000hsg.googlegroups.com> On May 6, 11:23 am, Rob Williscroft wrote: > wrote innews:1178475284.092656.103710 at e65g2000hsc.googlegroups.comin > comp.lang.python: > > > Hi, > > > I am hitting this error consistently and don't know why it's > > happening. I would like to define all exceptions for my project in one > > file and use them across the project. Here's a sample - > > > exceptions.py - > > from exceptions import * > > raise MyException("Raise custom error") > > > When the above is run, I get the following error - > > NameError: global name 'MyException' is not defined > > When you get this kind of error, goto a python prompt > (type python at a command prompt, or click on IDLE) > and try this: > > >>> import exceptions > >>> help( exceptions ) > > I got this response (clipped): > > Help on built-in module exceptions: > > NAME > exceptions - Python's standard exception class hierarchy. > > Another common module name to avoid is "test". > > Rob. > --http://www.victim-prime.dsl.pipex.com/ Doh! Thanks for correcting my error Rob. From larry.bates at websafe.com Thu May 3 12:11:08 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 03 May 2007 11:11:08 -0500 Subject: _csv.Error: string with NUL bytes In-Reply-To: <1178204593.280648.208040@c35g2000hsg.googlegroups.com> References: <1178204593.280648.208040@c35g2000hsg.googlegroups.com> Message-ID: fscked wrote: > Anyone have an idea of what I might do to fix this? I have googled adn > can only find some random conversations about it that doesn't make > sense to me. > > I am basically reading in a csv file to create an xml and get this > error. > > I don't see any empty values in any fields or anything... > You really should post some code and the actual traceback error your get for us to help. I suspect that you have an ill-formed record in your CSV file. If you can't control that, you may have to write your own CSV dialect parser. -Larry From dejanews at email.com Tue May 29 23:06:06 2007 From: dejanews at email.com (samwyse) Date: Tue, 29 May 2007 22:06:06 -0500 Subject: Rats! vararg assignments don't work Message-ID: I'm a relative newbie to Python, so please bear with me. After seeing how varargs work in parameter lists, like this: def func(x, *arglist): and this: x = func(1, *moreargs) I thought that I'd try this: first, *rest = arglist Needless to say, it didn't work. That leaves me with two questions. First, is there a good way to do this? For now, I'm using this: first, rest = arglist[0], arglist[1:] but it leaves a bad taste in my mouth. Second, is there any good reason why it shouldn't work? It seems like such an obvious idiom that I can't believe that I'm the first to come up with the idea. I don't really have the time right now to go source diving, so I can't tell if it would be wildly inefficient to implement. Thanks! From mail at timgolden.me.uk Wed May 16 13:39:29 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 16 May 2007 18:39:29 +0100 Subject: pymssql query In-Reply-To: <1179332801.800883.318590@h2g2000hsg.googlegroups.com> References: <1179332801.800883.318590@h2g2000hsg.googlegroups.com> Message-ID: <464B41D1.2000307@timgolden.me.uk> m.biddiscombe at gmail.com wrote: > Hi, > > I'm trying to use pymssql to execute a stored procedure. Currently, I > have an Excel spreadsheet that uses VBA in this manner: > > Private Function CreateNewParrot(connDb As ADODB.Connection) As Long > Dim objCommand As ADODB.Command > Dim iParrot As Long > Dim bSuccess As Boolean > > Set objCommand = CreateObject("ADODB.Command") > objCommand.ActiveConnection = connDb > objCommand.CommandText = "create_new" > objCommand.CommandType = adCmdStoredProc > objCommand.Parameters.Refresh > On Error Resume Next > Err.Clear > objCommand.Execute > bSuccess = (Err.Number = 0) > On Error GoTo 0 > If (bSuccess) Then > If (IsNull(objCommand("@parrot"))) Then > iParrot = 0 > Else > iParrot = CLng(objCommand("@parrot")) > End If > Else > iParrot = 0 > End If > Set objCommand = Nothing > CreateNewParrot = iParrot > End Function Depending on what you're after, why not transliterate it into Python? import win32com.client command = win32com.client.Dispatch ("ADODB.Command") etc. > My attempts to translate this into a python script using pymssql have > so far been fruitless. Here is what I have tried: >>>> import pymssql >>>> con = pymssql.connect(host='blah', user='blah', password='blah', database='blah') >>>> cur = con.cursor() >>>> command = 'exec create_new_parrot' >>>> cur.execute(command, '@parrot') > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Program Files\Python\lib\site-packages\pymssql.py", line > 127, in execute > self.executemany(operation, (params,)) > File "C:\Program Files\Python\lib\site-packages\pymssql.py", line > 153, in executemany > raise DatabaseError, "internal error: %s" % self.__source.errmsg() > pymssql.DatabaseError: internal error: SQL Server message 8114, > severity 16, state 5, procedure create_new_parrot, line 0: > Error converting data type nvarchar to int. > DB-Lib error message 10007, severity 5: > General SQL Server error: Check messages from the SQL Server. Well, I'm not connected to a SQL Server here (so this is untested) but I don't believe pymssql handles stored procedure calls differently from any other SQL. Which is a problem here because, as far as I can make out from your code above, @parrot is an output parameter for the create_new stored proc. Is that right? If it's an input-only param, then just do the usual: import pymssql db = pymssql.connect (...) q = db.cursor () q.execute ( "EXECUTE create_new @parrot = %s", ["parrot-thing"] ) I'm not aware of any of the MSSQL dbapi modules which allow for output parameters in stored procedures. pyodbc (one of the most recent entrants) tantalisingly offers a .callproc but then comments "not yet supported". If the ADO approach works, I'd use that if I were you! TJG From nospam at noemailhere.nowhere Thu May 17 20:15:20 2007 From: nospam at noemailhere.nowhere (Anthony Irwin) Date: Fri, 18 May 2007 10:15:20 +1000 Subject: problem with import in python 2.2.3 In-Reply-To: References: Message-ID: Hi Guys, Thanks for the replies I ended up rewriting my code to use the time.strftime() library but unfortunately the MySQLdb module I use needs python 2.3 or higher so it looks like I have to update python on the older system anyway. -- Kind Regards, Anthony Irwin http://www.irwinresources.com http://www.makehomebusiness.com email: anthony at above domains, - www. From python at hope.cz Thu May 3 10:44:13 2007 From: python at hope.cz (Johny) Date: 3 May 2007 07:44:13 -0700 Subject: How to replace the last (and only last) character in a string? In-Reply-To: <1178203052.794524.223790@o5g2000hsb.googlegroups.com> References: <1178202464.201578.211150@c35g2000hsg.googlegroups.com> <1178203052.794524.223790@o5g2000hsb.googlegroups.com> Message-ID: <1178203453.579755.323410@p77g2000hsh.googlegroups.com> On May 3, 4:37 pm, kyoso... at gmail.com wrote: > On May 3, 9:27 am, Johny wrote: > > > Let's suppose > > s='12345 4343 454' > > How can I replace the last '4' character? > > I tried > > string.replace(s,s[len(s)-1],'r') > > where 'r' should replace the last '4'. > > But it doesn't work. > > Can anyone explain why? > > > Thanks > > L. > > I think the reason it's not working is because you're doing it kind of > backwards. For one thing, the "string" module is deprecated. I would > do it like this: > > s = s.replace(s[len(s)-1], 'r') > > Although that is kind of hard to read. But it works. > > Mike Mike it does NOT work for me. >>> s.replace(s[len(s)-1], 'r') '123r5 r3r3 r5r' I need only the last character to be replaced From stefan.behnel-n05pAM at web.de Tue May 15 13:00:32 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 15 May 2007 19:00:32 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179247724.234869.47310@l77g2000hsb.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649BC4C.10200@web.de> <1179238847.407605.4620@w5g2000hsg.googlegroups.com> <4649C63C.1030508@web.de> <1179242328.800088.246620@h2g2000hsg.googlegroups.com> <4649D4A5.5060102@web.de> <1179247724.234869.47310@l77g2000hsb.googlegroups.com> Message-ID: <4649E730.9000609@web.de> Paul Boddie wrote: > Does it really happen, or do IBM's engineers in China > or India (for example) have to write everything strictly in ASCII? I assume they simply use american keyboards. They're working for an american company after all. That's like the call-center people in India who learn the superball results by heart before they go to their cubicle, just to keep north-american callers from realising they are not connected to the shop around the corner. Stefan From joshua at eeinternet.com Tue May 22 21:20:08 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Tue, 22 May 2007 17:20:08 -0800 Subject: Module imports fine from interactive, not from script Message-ID: <46538a79$0$16264$88260bb3@free.teranews.com> Yes, I've read this: http://mail.python.org/pipermail/python-list/2006-August/395943.html That's not my problem. I installed PlanetPlanet via the package's "setup.py install" command (as root). planet.py will not run, however, giving me this error: Traceback (most recent call last): File "/usr/local/bin/planet.py", line 167, in ? main() File "/usr/local/bin/planet.py", line 124, in main planet.logging.basicConfig() AttributeError: 'module' object has no attribute 'logging' But, from interactive session: jkugler at europa:~/www$ ls -l # to show that the modules are not in the current dir total 20 -rw-r--r-- 1 jkugler jkugler 2247 2007-05-22 15:26 atom.xml.tmpl -rw-r--r-- 1 jkugler jkugler 2089 2007-05-22 15:25 index.html.tmpl -rw-r--r-- 1 jkugler jkugler 564 2007-05-22 15:43 planet.ini -rw-r--r-- 1 jkugler jkugler 1128 2007-05-22 15:26 rss10.xml.tmpl -rw-r--r-- 1 jkugler jkugler 838 2007-05-22 15:26 rss20.xml.tmpl jkugler at europa:~/www$ python Python 2.4.3 (#2, Oct 6 2006, 07:52:30) [GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import planet >>> planet.logging >>> planet.logging.basicConfig() >>> The contents of /usr/local/lib/python2.4/site-packages/planet jkugler at europa:~/www$ ls -la /usr/local/lib/python2.4/site-packages/planet/ total 270 drwxr-sr-x 4 root staff 1024 2007-05-22 16:59 . drwxrwsr-x 4 root staff 1024 2007-05-22 15:18 .. -rw-r--r-- 1 root staff 4315 2006-07-26 15:53 atomstyler.py -rw-r--r-- 1 root staff 8887 2006-07-26 15:53 cache.py -rw-r--r-- 1 root staff 126446 2006-07-26 15:53 feedparser.py -rw-r--r-- 1 root staff 58705 2006-07-26 15:53 htmltmpl.py -rw-r--r-- 1 root staff 38145 2006-07-26 15:53 __init__.py drwxr-xr-x 2 root staff 1024 2007-05-22 16:59 logging -rw-r--r-- 1 root staff 13904 2006-07-26 15:53 sanitize.py drwxr-xr-x 2 root staff 1024 2007-05-22 16:59 tests -rw-r--r-- 1 root staff 12681 2006-07-26 15:53 timeoutsocket.py planet.py is simply executing: import planet . . . # Activate logging planet.logging.basicConfig() I've checked permissions, I've checked import statements, everything I know to check. Is there something terribly simple I'm missing? Thanks! j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE -- Posted via a free Usenet account from http://www.teranews.com From pecora at anvil.nrl.navy.mil Sun May 6 11:02:03 2007 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Sun, 06 May 2007 11:02:03 -0400 Subject: Plot with scipy References: <1178283196.755609.241790@n59g2000hsh.googlegroups.com> <1178287027.434242.230170@h2g2000hsg.googlegroups.com> Message-ID: In article <1178287027.434242.230170 at h2g2000hsg.googlegroups.com>, redcic wrote: > I've already got this package. I just wanted to try something new. > > However, since you talk about it, I've got a question regarding this > package. The execution of the code stops after the line: > pylab.show() > which is off course the last line of my code. My problem is that I > have to close the figure window in order to launch my program another > time. I'd like to be able to launch my program many times with > different parameters without having to close the figure windows before > each launch. > Just so you know, I'm using TkAgg backend. > > Any hint ? Here's what I do and it works well. I am using a Mac so the text programs I mention are available there, but I bet you can find similar programs on Windows, Linus, or Unix (I think Emacs can do this, too). I use a text editor to write the source code and launch it in a Terminal window. On the Mac BBEdit does this and you can get its free version TextWrangler. I can launch a program to do a plot, go back to the editor to change somehting and launch it again all while the first plot window is still open. I get two terminal windows waiting on the closing of their respective plot windows. I can click on each plot window and bring them to the front for comparison. Of course, I can continue to launch more and compare many plot windows. Works for me. Maybe there are other approaches that others can tell about. From duncan.booth at invalid.invalid Tue May 15 13:30:58 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 15 May 2007 17:30:58 GMT Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> <4648294F.2000704@web.de> <46487a6c$0$2400$426a74cc@news.free.fr> Message-ID: Donn Cave wrote: > [Spanish in Brazil? Not as much as you might think.] Sorry temporary[*] brain failure, I really do know it is Portugese. [*] I hope. From aisaac at american.edu Wed May 9 21:25:29 2007 From: aisaac at american.edu (Alan Isaac) Date: Thu, 10 May 2007 01:25:29 GMT Subject: change of random state when pyc created?? References: <5ae25fF2oggbqU1@mid.uni-berlin.de> Message-ID: >> Robert Kern wrote: >>> http://docs.python.org/lib/typesmapping.html >>> """ >>> Keys and values are listed in an arbitrary order which is non-random, varies >>> across Python implementations, and depends on the dictionary's history of >>> insertions and deletions. >>> """ > Alan G Isaac wrote: >> Even this does not tell me that if I use a specified implementation >> that my results can vary from run to run. That is, it still does >> not communicate that rerunning an *unchanged* program with an >> *unchanged* implementation can produce a change in results. "Robert Kern" wrote in message news:mailman.7488.1178744519.32031.python-list at python.org... > The last clause does tell me that. 1. About your reading of the current language: I believe you, of course, but can you tell me **how** it tells you that? To be concrete, let us suppose parallel language were added to the description of sets. What about that language should allow me to anticipate Peter's example (in this thread)? 2. About possibly changing the docs: You are much more sophisticated than ordinary users. Did this thread not demonstrate that even sophisticated users do not see into this "implication" immediately? Replicability of results is a huge deal in some circles. I think the docs for sets and dicts should include a red flag: do not use these as iterators if you want replicable results. (Side note to Carsten: this does not require listing "every little thing".) Cheers, Alan Isaac From mail at microcorp.co.za Thu May 17 08:29:49 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 17 May 2007 14:29:49 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de><1179160242.787344.48060@h2g2000hsg.googlegroups.com> <1179258692.237438.110860@p77g2000hsh.googlegroups.com> <464ad4a2$0$23143$9b4e6d93@newsspool1.arcor-online.net> <464C34DB.4010903@v.loewis.de> Message-ID: <008901c79880$0282a260$03000080@hendrik> > > Now look me in the eye and tell me that you find > > the mix of proper German and English keywords > > beautiful. > > I can't admit that, but I find that using German > class and method names is beautiful. The rest around > it (keywords and names from the standard library) > are not English - they are Python. > > (look me in the eye and tell me that "def" is > an English word, or that "getattr" is one) > > Regards, > Martin LOL - true - but a broken down assembler programmer like me does not use getattr - and def is short for define, and for and while and in are not German. Looks like you have stirred up a hornets nest... - Hendrik From paul at science.uva.nl Thu May 31 10:22:20 2007 From: paul at science.uva.nl (Paul Melis) Date: Thu, 31 May 2007 16:22:20 +0200 Subject: Python memory handling In-Reply-To: <1180611604.247696.149060@h2g2000hsg.googlegroups.com> References: <1180611604.247696.149060@h2g2000hsg.googlegroups.com> Message-ID: Hello, frederic.pica at gmail.com wrote: > I've some troubles getting my memory freed by python, how can I force > it to release the memory ? > I've tried del and gc.collect() with no success. [...] > The same problem here with a simple file.readlines() > #Python interpreter memory usage : 1.1 Mb private, 1.4 Mb shared > import gc #no memory change > f=open('primary.xml') #no memory change > data=f.readlines() #meminfo: 12 Mb private, 1.4 Mb shared > del data #meminfo: 11.5 Mb private, 1.4 Mb shared > gc.collect() # no memory change > > But works great with file.read() : > #Python interpreter memory usage : 1.1 Mb private, 1.4 Mb shared > import gc #no memory change > f=open('primary.xml') #no memory change > data=f.read() #meminfo: 7.3Mb private, 1.4 Mb shared > del data #meminfo: 1.1 Mb private, 1.4 Mb shared > gc.collect() # no memory change > > So as I can see, python maintain a memory pool for lists. > In my first example, if I reparse the xml file, the memory doesn't > grow very much (0.1 Mb precisely) > So I think I'm right with the memory pool. > > But is there a way to force python to release this memory ?! This is from the 2.5 series release notes (http://www.python.org/download/releases/2.5.1/NEWS.txt): "[...] - Patch #1123430: Python's small-object allocator now returns an arena to the system ``free()`` when all memory within an arena becomes unused again. Prior to Python 2.5, arenas (256KB chunks of memory) were never freed. Some applications will see a drop in virtual memory size now, especially long-running applications that, from time to time, temporarily use a large number of small objects. Note that when Python returns an arena to the platform C's ``free()``, there's no guarantee that the platform C library will in turn return that memory to the operating system. The effect of the patch is to stop making that impossible, and in tests it appears to be effective at least on Microsoft C and gcc-based systems. Thanks to Evan Jones for hard work and patience. [...]" So with 2.4 under linux (as you tested) you will indeed not always get the used memory back, with respect to lots of small objects being collected. The difference therefore (I think) you see between doing an f.read() and an f.readlines() is that the former reads in the whole file as one large string object (i.e. not a small object), while the latter returns a list of lines where each line is a python object. I wonder how 2.5 would work out on linux in this situation for you. Paul From afriere at yahoo.co.uk Tue May 22 03:27:04 2007 From: afriere at yahoo.co.uk (Asun Friere) Date: 22 May 2007 00:27:04 -0700 Subject: howto check does module 'asdf' exist? (is available for import) In-Reply-To: <1179753436.736228.321400@x35g2000prf.googlegroups.com> References: <1179753436.736228.321400@x35g2000prf.googlegroups.com> Message-ID: <1179818823.916836.226090@r3g2000prh.googlegroups.com> On May 21, 11:17 pm, dmitrey wrote: > howto check does module 'asdf' exist (is available for import) or no? try : import asdf del asdf except ImportError : print "module asdf not available" else : print "module asdf available for loading" You can generalise this, but at the expense of a couple of exec statements: def is_module_available (module) : try : exec('import %s' % module) exec('del %s' % module) except ImportError : return False else : return True > (without try/cache of course) Oops sorry, you wanted it done in some non-obvious way! Why?! From walterbyrd at iname.com Sat May 19 12:01:11 2007 From: walterbyrd at iname.com (walterbyrd) Date: 19 May 2007 09:01:11 -0700 Subject: Python compared to other language In-Reply-To: References: <1179540061.598417.13870@y80g2000hsf.googlegroups.com> <1179555855.410877.51390@k79g2000hse.googlegroups.com> Message-ID: <1179590470.964307.105720@l77g2000hsb.googlegroups.com> On May 19, 7:23 am, Steve Holden wrote: > The reason you can do this with Python is precisely because the > developers have ironed out the wrinkles between platforms by putting the > requisite conditionals in the C source. But that is my point. With Python, the language itself takes care of the platform differences, so the same Python code will run on different platforms. I realize that, at a lower level, everything is done is C. But, from the developers point of view: developing code in C requires more attention to platform specifics, than does developing code in Python. From aisaac at american.edu Sat May 5 20:20:04 2007 From: aisaac at american.edu (Alan Isaac) Date: Sun, 06 May 2007 00:20:04 GMT Subject: change of random state when pyc created?? References: <1178408359.113807.181570@l77g2000hsb.googlegroups.com> Message-ID: "John Machin" wrote in message news:1178408359.113807.181570 at l77g2000hsb.googlegroups.com... > (a) module1 imports random and (MyClass from module2) Right. > It's a bit of a worry that you call the first file "module1" and not > "the_script". Does module2 import module1, directly or indirectly? No. I call a module any file meant to be imported by others. Many of my modules include a "main" function, which allow the module to be executed as a script. I do not think this is unusual, even as terminology. > Should you not expect to get the same result each time? Is that not > the point of setting a constant seed each time you run the script? Yes. That is the problem. If I delete module2.pyc, I do not get the same result. > With all due respect to your powers of description :-) no, it can't be > explained properly, without seeing the contents of the source files. I sent them to you. What behavior did you see? > from random import seed > seed(314) > class Trivial: > pass > === > Is module2 ... doing that? > Is module1 importing itself (directly or indirectly)? No. Separate issue ============== > Here's a suggestion for how you should structure scripts: > > def main(): > # All productive code is inside a function to take advantage > # of access to locals being faster than access to globals > import mymodule > mymodule.do_something() > if __name__ == "__main__": > main() > else: > raise Exception("Attempt to import script containing nothing > importable") > > and your modules should *start* with: > if __name__ == "__main__": > raise Exception("Attempt to execute hopefully-pure module as a > script") I'm not going to call this a bad practice, since it has clear virtues. I will say that it does not seem to be a common practice, although that may be my lack of exposure to other's code. And it still does not address the common need of playing with a "package in progress" or a "package under consideration" without installing it. Cheers, Alan Isaac From nick at craig-wood.com Sun May 20 01:35:09 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Sun, 20 May 2007 00:35:09 -0500 Subject: zipfile stupidly broken References: Message-ID: Martin Maney wrote: > Nick Craig-Wood wrote: > > You don't need to do that, you can just "monkey patch" the _EndRecData > > function. > > For a quick & dirty test, sure. If I were certain I'd only ever use > this on one machine for a limited time (viz, no system upgrades that > replace zipfile.py) it might suffice. But that doesn't generalize > worth a damn. >From the above I don't think you've understood the concept of monkey patching - it is run time patching. You patch the zipfile module from your code - no messing with the installed python needed. Eg something like :- ------------------------------------------------------------ import zipfile OriginalEndRecData = zipfile._EndRecData def MyEndRecData(fpin): """ Return data from the "End of Central Directory" record, or None. """ # Try the builtin one first endrec = OriginalEndRecData(fpin) if endrec is None: # didn't work so do something extra # you fill this bit in! pass return endrec zipfile._EndRecData = MyEndRecData # Now use your run time patched zipfile module as normal ------------------------------------------------------------ It isn't ideal, but it certainly does generalise. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From gherron at islandtraining.com Wed May 30 02:38:38 2007 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 29 May 2007 23:38:38 -0700 Subject: Rats! vararg assignments don't work In-Reply-To: References: Message-ID: <465D1BEE.6090501@islandtraining.com> samwyse wrote: > I'm a relative newbie to Python, so please bear with me. After seeing > how varargs work in parameter lists, like this: > def func(x, *arglist): > and this: > x = func(1, *moreargs) > I thought that I'd try this: > first, *rest = arglist > Needless to say, it didn't work. That leaves me with two questions. > > First, is there a good way to do this? For now, I'm using this: > first, rest = arglist[0], arglist[1:] > but it leaves a bad taste in my mouth. > Well, your moreargs parameter is a tuple, and there are innumerable ways to process a tuple. (And even more if you convert it to a list.) If you are just interested in extracting only the first arg, then your code is quite Pythonic. However, if you are going to do that in a loop to successively process each arg, the you have several better options: For instance: for arg in moreargs: # Loop through each arg or for i in range(len(moreargs)): # Extract ith arg or argslist = list(moreargs) while argslist: firstarg = argslist.pop(0) # Extract first arg Gary Herron > Second, is there any good reason why it shouldn't work? It seems like > such an obvious idiom that I can't believe that I'm the first to come up > with the idea. I don't really have the time right now to go source > diving, so I can't tell if it would be wildly inefficient to implement. > > Thanks! > From vito.detullio at gmail.com Tue May 15 01:15:21 2007 From: vito.detullio at gmail.com (ZeD) Date: Tue, 15 May 2007 05:15:21 GMT Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <7x4pmg716p.fsf@ruckus.brouhaha.com> <4648EC26.8020907@v.loewis.de> Message-ID: Neil Hodgson wrote: > Ada 2005 allows Unicode identifiers and even includes the constant > '?' in Ada.Numerics. this. is. cool. (oh, and +1 for the pep) -- Under construction From JYOUNG79 at kc.rr.com Thu May 24 09:08:38 2007 From: JYOUNG79 at kc.rr.com (JYOUNG79 at kc.rr.com) Date: Thu, 24 May 2007 08:08:38 -0500 Subject: A few questions Message-ID: Just wanted to send a quick "Thank You!" to everyone who helped answer my questions. This list is awesome!! I'm currently reading "How to Think Like a Computer Scientist" (thanks Basilisk96) and it's got some excellent tutorial info. I still want to take a look at "Dive into Python" as well as the other books you all mentioned. I'll continue working with wxPython and py2app too... these are some cool apps!! Again, thank you all for taking the time to help me with all this. I really appreciate it! Jay From cam.ac.uk at mh391.invalid Thu May 31 06:59:48 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 31 May 2007 11:59:48 +0100 Subject: Good Python style? In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > It would probably be easier to read with more readable names and a few > comments: [...] > Splitting it into multiple lines is self-documenting: > > blankless_lines = filter(None, [line.strip() for line in input_lines]) > first_words = [line.split()[0] for line in blankless_words] > some_set = frozenset(first_words) Re-writing code so that it is self-documenting is almost always a better approach. Premature optimization is the root of all evil. -- Michael Hoffman From timr at probo.com Tue May 22 02:40:20 2007 From: timr at probo.com (Tim Roberts) Date: Tue, 22 May 2007 06:40:20 GMT Subject: i/o prob revisited References: <1179471963.303052.136690@q23g2000hsg.googlegroups.com> <1179478218.518917.309490@u30g2000hsc.googlegroups.com> <1179478706.505015.176490@w5g2000hsg.googlegroups.com> Message-ID: saif.shakeel at gmail.com wrote: > >ok i am able to trace the error ...It says: >Traceback (most recent call last): > File "C:\Projects\ODX Import\code_ini\odxparse_mod.py", line 294, in > > input_xml_sec = open(output_file,'r') >TypeError: coercing to Unicode: need string or buffer, file found > Any solutions. I don't see how the error could possibly make it any clearer. "open" expects a file name. "output_file" is not a file NAME. It is a file OBJECT. If you want to reopen that file, then pass the file NAME here. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From gdonald at gmail.com Mon May 21 18:34:51 2007 From: gdonald at gmail.com (Greg Donald) Date: Mon, 21 May 2007 17:34:51 -0500 Subject: Installing Python in a path that contains a blank In-Reply-To: <46521C71.8010602@lexicon.net> References: <46521C71.8010602@lexicon.net> Message-ID: <15e66e4e0705211534w2876b365n176c759a9ccc15e3@mail.gmail.com> On 5/21/07, John Machin wrote: > Is there not a similar trick on MacOS X? It's called a symlink: ln -s /Users/gdonald /foo -- Greg Donald http://destiney.com/ From manishk at cybage.com Tue May 15 04:38:13 2007 From: manishk at cybage.com (Manish Kumar) Date: Tue, 15 May 2007 14:08:13 +0530 Subject: Needs help to install ZOracleDA Message-ID: Hi All, How can I install ZOracleDA on Red Hat Linux machine? Configuration of my system is as below: Zope-2.7 Python-2.3.5 Oracle-9i I have tried to install ZOracleDA but installable needed rh-7.1-python-1.5.2-dco2.so file which is not present in Binaries directory. Any help from you people is appreciable. Regards, Manish Kumar "Legal Disclaimer: This electronic message and all contents contain information from Cybage Software Private Limited which may be privileged, confidential, or otherwise protected from disclosure. The information is intended to be for the addressee(s) only. If you are not an addressee, any disclosure, copy, distribution, or use of the contents of this message is strictly prohibited. If you have received this electronic message in error please notify the sender by reply e-mail to and destroy the original message and all copies. Cybage has taken every reasonable precaution to minimize the risk of malicious content in the mail, but is not liable for any damage you may sustain as a result of any malicious content in this e-mail. You should carry out your own malicious content checks before opening the e-mail or attachment." www.cybage.com From gagsl-py2 at yahoo.com.ar Fri May 4 00:56:50 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 04 May 2007 01:56:50 -0300 Subject: passing an array of variant in vb to a python COM object = win32com bug ? References: <1178178883.246149.279780@c35g2000hsg.googlegroups.com> <1178196117.469260.12770@e65g2000hsc.googlegroups.com> Message-ID: En Thu, 03 May 2007 09:41:57 -0300, vml escribi?: > On 3 mai, 14:20, "Gabriel Genellina" wrote: >> En Thu, 03 May 2007 04:54:43 -0300, vml >> escribi?: >> >> > I have a python com object which contains a method to inverse an array >> > in vb 6 the definition of the class is : >> > I just tried to replace the *val by SqVal(self,val) and call the > method in vb but it crashes down : > > "when refilling safe array the sequence must have the same number of > dimension as the existing array" That can't happen with your Python code below, so it must be on the caller. Maybe you wrote something like: xx=something.SqVal(yy) and xx,yy are declared of different sizes. > def SqVal(self,val): > ## ... > return val > > By the way Do you have any idea to debug the com server script ? ( I > would like to know if a can access the value in the function while > calling it from vb 6) Write a log file as suggested, or use OutputDebugString with the DebugView program from www.sysinternals.com -- Gabriel Genellina From mensanator at aol.com Tue May 15 13:01:20 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 15 May 2007 10:01:20 -0700 Subject: Interesting list Validity (True/False) In-Reply-To: References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> <1178914190.166662.285410@p77g2000hsh.googlegroups.com> <1178915791.584216.293130@l77g2000hsb.googlegroups.com> <1178918808.091358.233740@o5g2000hsb.googlegroups.com> <1179017740.656323.209590@e51g2000hsg.googlegroups.com> <1179020634.130689.171960@o5g2000hsb.googlegroups.com> <1179031812.090768.248750@l77g2000hsb.googlegroups.com> <1179168081.603409.39970@e51g2000hsg.googlegroups.com> <1179203827.881205.287910@l77g2000hsb.googlegroups.com> Message-ID: <1179248480.350553.4430@n59g2000hsh.googlegroups.com> On May 15, 12:30 am, "Gabriel Genellina" wrote: > En Tue, 15 May 2007 01:37:07 -0300, mensana... at aol.com > escribi?: > > >> > > >> > Sec 2.2.3: > >> > Objects of different types, *--->except<---* different numeric types > >> > and different string types, never compare equal; > >> > > > >> The exceptions you mean are not exceptions to "'X==Y' means 'X equals > >> Y'". > > > I never said they were. I said they were exceptions to > > "Obbjects of different types never compare equal". > > This is an unfortunate wording, and perhaps should read: "For most builtin > types, objects of different types never compare equal; such objects are > ordered consistently but arbitrarily (so that sorting a heterogeneous > sequence yields a consistent result). The exceptions being different > numeric types and different string types, that have a special treatment; > see section 5.9 in the Reference Manual for details." > > And said section 5.9 should be updated too: "The objects need not have the > same type. If both are numbers or strings, they are converted to a common > type. Except when they aren't. >>> import gmpy >>> a = 2**177149-1 >>> b = gmpy.mpz(2**177149-1) >>> a==b True >>> print '%d' % (b) Traceback (most recent call last): File "", line 1, in print '%d' % (b) TypeError: int argument required So although the comparison operator is smart enough to realize the equivalency of numeric types and do the type conversion, the print statement isn't so smart. > Otherwise, objects of different builtin types always compare > unequal, and are ordered consistently but arbitrarily. You can control > comparison behavior of objects of non-builtin types by defining a __cmp__ > method or rich comparison methods like __gt__, described in section 3.4." > > I hope this helps a bit. Your performance issues don't have to do with the > *definition* of equal or not equal, I didn't say that, I said the performance issues were related to type conversion. Can you explain how the "definition" of equal does not involve type conversion? > only with how someone decided to write the mpz class. I'm beginning to think there's a problem there. > > -- > Gabriel Genellina From pc at p-cos.net Fri May 4 06:04:30 2007 From: pc at p-cos.net (Pascal Costanza) Date: Fri, 04 May 2007 12:04:30 +0200 Subject: Why stay with lisp when there are python and perl? In-Reply-To: <463a9668$0$8719$ed2619ec@ptn-nntp-reader02.plus.net> References: <1178155239.007219.205020@y5g2000hsa.googlegroups.com> <1178219732.127815.3260@y80g2000hsf.googlegroups.com> <463a9668$0$8719$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: <5a0epfF2mtevoU1@mid.individual.net> Jon Harrop wrote: > It is worth noting that eager, statically-typed languages like OCaml and F# > are many times faster than the other languages at this task. This is > precisely the forte of OCaml and F#, manipulating trees and graphs. Here is a page that sums up some important observations about benchmarks: http://www.ccs.neu.edu/home/will/Twobit/bmcrock.temp.html Especially: - "With modern superscalar architectures, 5-level memory hierarchies, and wide data paths, changing the alignment of instructions and data can easily change the performance of a program by 20% or more, and Hans Boehm has witnessed a spectacular 100% variation in user CPU time while holding the executable file constant. Since much of this alignment is determined by the linker, loader, and garbage collector, most individual compiler optimizations are in the noise. To evaluate a compiler properly, one must often look at the code that it generates, not the timings." - "The execution time of a program is often dominated by the time spent in very small pieces of code. If an optimizing compiler happens to do a particularly good job of optimizing these hot spots, then the program will run quickly. If a compiler happens to do an unusually poor job of optimizing one or more of these hot spots, then the program will run slowly." - "If the hot spots occur within library routines, then a compiler may not affect the performance of the program very much. Its performance may be determined by those library routines." - "The performance of a benchmark, even if it is derived from a real program, may not help to predict the performance of similar programs that have different hot spots." Pascal -- My website: http://p-cos.net Common Lisp Document Repository: http://cdr.eurolisp.org Closer to MOP & ContextL: http://common-lisp.net/project/closer/ From cbtube03 at gmail.com Fri May 11 16:37:48 2007 From: cbtube03 at gmail.com (cbtube03 at gmail.com) Date: 11 May 2007 13:37:48 -0700 Subject: name capitalization of built-in types, True, and False Message-ID: <1178915868.650553.219430@h2g2000hsg.googlegroups.com> I see that naming conventions are such that classes usually get named CamelCase. So why are the built-in types named all lowercase (like list, dict, set, bool, etc.)? And names for instances of classes are usually written in lowercase, like foo in ``foo = CamelCase()``. So why are True and False (instances of bool) capitalized? Shouldn't they be "true" and "false"? Same goes for None. From bj_666 at gmx.net Thu May 31 08:16:31 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 31 May 2007 14:16:31 +0200 Subject: Python memory handling References: <1180611604.247696.149060@h2g2000hsg.googlegroups.com> Message-ID: In <1180611604.247696.149060 at h2g2000hsg.googlegroups.com>, frederic.pica wrote: > So as I can see, python maintain a memory pool for lists. > In my first example, if I reparse the xml file, the memory doesn't > grow very much (0.1 Mb precisely) > So I think I'm right with the memory pool. > > But is there a way to force python to release this memory ?! AFAIK not. But why is this important as long as the memory consumption doesn't grow constantly? The virtual memory management of the operating system usually takes care that only actually used memory is in physical RAM. Ciao, Marc 'BlackJack' Rintsch From ian.team.python at saltmob.com Thu May 10 04:06:04 2007 From: ian.team.python at saltmob.com (ian.team.python at saltmob.com) Date: 10 May 2007 01:06:04 -0700 Subject: elegant python style for loops In-Reply-To: <1178784055.673575.173600@u30g2000hsc.googlegroups.com> References: <1178776272.535735.166540@h2g2000hsg.googlegroups.com> <5afrsmF2o97gcU1@mid.uni-berlin.de> <1178779594.588153.49620@n59g2000hsh.googlegroups.com> <1178784055.673575.173600@u30g2000hsc.googlegroups.com> Message-ID: <1178784364.099349.209550@n59g2000hsh.googlegroups.com> On May 10, 6:00 pm, ian.team.pyt... at saltmob.com wrote: > thank you everybody....very well answered.....just one question > remains.... > where do i find documentation on zip ...i was looking for a function > like this, but could not even find a relevant list of functions!! ooops...even that was answered. again, thanks From victor.lebrun at gmail.com Thu May 3 03:54:43 2007 From: victor.lebrun at gmail.com (vml) Date: 3 May 2007 00:54:43 -0700 Subject: passing an array of variant in vb to a python COM object = win32com bug ? Message-ID: <1178178883.246149.279780@c35g2000hsg.googlegroups.com> I have a python com object which contains a method to inverse an array in vb 6 the definition of the class is : class Fop: _public_methods_ = [ 'SqVal' ] def SqVal(self,*val): #vol=(val[0][0],val[0][1]) #mat1=mat((vol)) #up=linalg.inv(mat1) return str(val)#up _reg_verprogid_ = "Python.Fop.3" _reg_progid_ = "Python.Fop" _reg_desc_ = "Python Fop" _reg_clsid_ = "{30BD3490-2632-11cf-AD5B-524153480001}" I pass to this method an array of variant which is the matrix to invert like that: vb6 code : Set obj = CreateObject("Python.Fop") Dim ty(1, 1) As Variant ty(0, 0) = 1 ty(1, 0) = 2 ty(0, 1) = 3 ty(1, 1) = 4 toto = obj.SqVal(ty) when I dispaly toto as str(val) I obtain the following tuple "(((1, 3), (2, 4)),)" which is not usable .... Do you have an idea to explain this strange behaviour ? thank you ! From kelvin.you at gmail.com Tue May 29 02:46:52 2007 From: kelvin.you at gmail.com (=?gb2312?B?yMvR1MLkyNXKx8zs0cSjrM37vKvM7NHEsru8+7zS?=) Date: 28 May 2007 23:46:52 -0700 Subject: how to print the GREEK CAPITAL LETTER delta under utf-8 encoding In-Reply-To: <465BBB49.6000803@v.loewis.de> References: <1180414659.066482.236370@i38g2000prf.googlegroups.com> <465BBB49.6000803@v.loewis.de> Message-ID: <1180421212.151587.118020@r19g2000prf.googlegroups.com> On 5?29?, ??1?34?, "Martin v. Lo"wis" wrote: > ??????????????? schrieb: > > > I lookup the utf-8 form of delta from the link. > >http://www.fileformat.info/info/unicode/char/0394/index.htm > > > and then I want to print it in the python ( I work under windows) > > > #!/usr/bin/python > > #coding=utf-8 > > > print "\xce\x94" > > > but the result is not the 'delta' but an unknown character. > > I assume you print to the terminal (cmd.exe). This cannot work; > the terminal (usually) does not interpret the characters in UTF-8. > Instead, you should print a Unicode string, e.g. > > print u"\N{GREEK CAPITAL LETTER DELTA}" > > or > > print u'\u0394' > > This should work as long as your terminal supports printing > the letter at all. > > Regards, > Martin yes, it could print to the terminal(cmd.exe), but when I write these string to file. I got the follow error: File "E:\Tools\filegen\filegen.py", line 212, in write self.file.write(data) UnicodeEncodeError: 'ascii' codec can't encode character u'\u0394' in position 0 : ordinal not in range(128) but other text, in which include "chinese characters" got from os.listdir(...), are written to the file OK. why? From email at christoph-haas.de Sun May 13 08:13:44 2007 From: email at christoph-haas.de (Christoph Haas) Date: Sun, 13 May 2007 14:13:44 +0200 Subject: Real globals inside a module In-Reply-To: <11e49df10705130241s179297f9q68bb799f8d1ec1b3@mail.gmail.com> References: <11e49df10705130241s179297f9q68bb799f8d1ec1b3@mail.gmail.com> Message-ID: <20070513121344.GB4875@laptux.workaround.org> On Sun, May 13, 2007 at 11:41:12AM +0200, Jorgen Bodde wrote: > I am wrestling with some architecture inside my app. Let's say I have > a tunings collection, which contains e.g. 23 types of guitar tunings. > In my song object I want to restore a relation between one of the > tuning objects inside the tunings module. > > I already figured out I need somethign like a global collection inside > the tunings module,. but how global is it? When I am inside my app > object, and import the tunings module, can I access the same global > class as when I am inside my songs module and load the tunings module? You are on the right way. If you import the same module a second time in another place of your application you get access to the exact same data. That is called a "singleton". I often use such a singleton for global configuration data. > So basically I want to access the same global list in both modules, > but not re-create the list in every module since it should be restored > by the database layer once. Import your global module and just run the initalisation once. That should do it. > Thanks for any advice, I do not want to make a global manager object > that I need to pass around all the time, that would be silly.. Indeed. That would suck. Christoph From transfire at gmail.com Thu May 3 10:41:28 2007 From: transfire at gmail.com (Trans) Date: 3 May 2007 07:41:28 -0700 Subject: Library Naming Message-ID: <1178203288.888165.169130@y80g2000hsf.googlegroups.com> I'm taking a pole on how best to name programming library packages. If you have a second, please have a look. http://7ranscode.blogspot.com/2007/05/library-poll.html Thanks, T. From steve at holdenweb.com Sun May 27 16:01:45 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 27 May 2007 16:01:45 -0400 Subject: Why isn't this query working in python? In-Reply-To: <1180279833.131269.136770@w5g2000hsg.googlegroups.com> References: <1180103946.552760.239200@p47g2000hsd.googlegroups.com> <6e42ec490705250751i89d3cf3v3a3062690d0284aa@mail.gmail.com> <1180207521.072958.322770@p47g2000hsd.googlegroups.com> <1180225290.235515.274000@q19g2000prn.googlegroups.com> <1180279833.131269.136770@w5g2000hsg.googlegroups.com> Message-ID: erikcw wrote: > On May 26, 8:21 pm, John Machin wrote: >> On May 27, 5:25 am, erikcw wrote: >> >> >> >>> On May 25, 11:28 am, Carsten Haese wrote: >>>> On Fri, 2007-05-25 at 09:51 -0500, Dave Borne wrote: >>>>>> I'm trying to run the following query: >>>>> ... >>>>>> member_id=%s AND expire_date > NOW() AND completed=1 AND (product_id >>>>> Shouldn't you be using the bind variable '?' instead of '%s' ? >>>> The parameter placeholder for MySQLdb is, indeed and unfortunately, %s. >>>> The OP is using parameter substitution correctly, though in an >>>> obfuscated fashion. 'sql' is a misnamed tuple containing both the query >>>> string *and* the parameters, which is being unpacked with '*' into two >>>> arguments to the execute call. >>>> The only problem I see is that the parameters should be a sequence, i.e. >>>> (self.uid,) instead of just (self.uid). >>>> HTH, >>>> -- >>>> Carsten Haesehttp://informixdb.sourceforge.net >>> I tried adding the comma to make it a sequence - but now change. >>> ('SELECT payment_id FROM amember_payments WHERE member_id=%s AND >>> expire_date > NOW() AND completed=1 AND (product_id >11 AND product_id >>> <21)', (1608L,)) >>> () >>> What else could it be? >> Possibly a type mismatch. How is member_id declared in the CREATE >> TABLE? For diagnostic purposes, try passing in (1608,) and ('1608',). > > Here is a copy of the table schema and the first 2 rows. > > -- phpMyAdmin SQL Dump > -- version 2.9.0.2 > -- http://www.phpmyadmin.net > -- > -- Host: localhost > -- Generation Time: May 27, 2007 at 11:29 AM > -- Server version: 5.0.27 > -- PHP Version: 4.4.2 > -- > -- Database: `lybp_lybp` > -- > > -- -------------------------------------------------------- > > -- > -- Table structure for table `amember_payments` > -- > > CREATE TABLE `amember_payments` ( > `payment_id` int(11) NOT NULL auto_increment, > `member_id` int(11) NOT NULL default '0', > `product_id` int(11) NOT NULL default '0', > `begin_date` date NOT NULL default '0000-00-00', > `expire_date` date NOT NULL default '0000-00-00', > `paysys_id` varchar(32) NOT NULL default '', > `receipt_id` varchar(32) NOT NULL default '', > `amount` decimal(12,2) NOT NULL default '0.00', > `completed` smallint(6) default '0', > `remote_addr` varchar(15) NOT NULL default '', > `data` text, > `time` timestamp NOT NULL default CURRENT_TIMESTAMP on update > CURRENT_TIMESTAMP, > `aff_id` int(11) NOT NULL default '0', > `payer_id` varchar(255) NOT NULL default '', > `coupon_id` int(11) NOT NULL default '0', > `tm_added` datetime NOT NULL default '0000-00-00 00:00:00', > `tm_completed` datetime default NULL, > `tax_amount` decimal(12,2) NOT NULL default '0.00', > PRIMARY KEY (`payment_id`), > KEY `member_id` (`member_id`), > KEY `payer_id` (`payer_id`), > KEY `coupon_id` (`coupon_id`), > KEY `tm_added` (`tm_added`,`product_id`), > KEY `tm_completed` (`tm_completed`,`product_id`) > ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=11020 ; > > -- > -- Dumping data for table `amember_payments` > -- > > INSERT INTO `amember_payments` VALUES (423, 107, 1, '2004-10-01', > '2004-10-21', 'authorize_aim', '5687944', 3.95, 1, '', NULL, > '2004-11-30 19:21:43', 0, '', 0, '2004-11-30 19:21:43', '2004-11-30 > 19:21:43', 0.00); > INSERT INTO `amember_payments` VALUES (422, 107, 1, '2004-10-22', > '2004-11-21', 'authorize_aim', '5873225', 9.95, 1, '', NULL, > '2004-11-30 19:22:18', 0, '', 0, '2004-11-30 19:20:13', '2004-11-30 > 19:20:13', 0.00); > > Thanks for your help! > Erik > I feel obliged to point out that there ARE no rows meeting the criteria you query specified! mysql> SELECT expire_date, NOW() FROM amember_payments; +-------------+---------------------+ | expire_date | NOW() | +-------------+---------------------+ | 2004-10-21 | 2007-05-27 15:59:21 | | 2004-11-21 | 2007-05-27 15:59:21 | +-------------+---------------------+ 2 rows in set (0.02 sec) mysql> So I am not sure how you managed to get a manual query to work, but do be sure that the Python query you mentioned at the start of the thread sql = """SELECT payment_id FROM amember_payments WHERE member_id=%s AND expire_date > NOW() AND completed=1 AND (product_id > >11 AND product_id <21)""", (self.uid) doesn't stand a chance of returning any results unless you use a time machine to go back almost three years! 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From sjmachin at lexicon.net Sat May 19 21:47:35 2007 From: sjmachin at lexicon.net (John Machin) Date: Sun, 20 May 2007 11:47:35 +1000 Subject: regex matching question In-Reply-To: <1179620336.327038.253920@h2g2000hsg.googlegroups.com> References: <1179595319.239229.262160@l77g2000hsb.googlegroups.com> <464F86F0.8080100@lexicon.net> <1179620336.327038.253920@h2g2000hsg.googlegroups.com> Message-ID: <464FA8B7.9070408@lexicon.net> On 20/05/2007 10:18 AM, bullockbefriending bard wrote: >> Instead of the "or match.group(0) != results" caper, put \Z (*not* $) at >> the end of your pattern: >> mobj = re.match(r"pattern\Z", results) >> if not mobj: > > as the string i am matching against is coming from a command line > argument to a script, is there any reason why i cannot get away with > just $ given that this means that there is no way a newline could find > its way into my string? No way? Famous last words :-) C:\junk>type showargs.py import sys; print sys.argv C:\junk>\python25\python 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 subprocess >>> subprocess.call('\\python25\\python showargs.py teehee\n') ['showargs.py', 'teehee\n'] 0 >>> certainly passes all my unit tests as well as > \Z. or am i missing the point of \Z ? > From steven.bethard at gmail.com Wed May 9 12:41:45 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 09 May 2007 10:41:45 -0600 Subject: Getting some element from sets.Set In-Reply-To: <1178725344.400736.210280@n59g2000hsh.googlegroups.com> References: <1178258913.095438.173020@h2g2000hsg.googlegroups.com> <1178267029.258868.219800@h2g2000hsg.googlegroups.com> <1178316417.371855.63170@p77g2000hsh.googlegroups.com> <1178725344.400736.210280@n59g2000hsh.googlegroups.com> Message-ID: tutufan at gmail.com wrote: > I've also previously run into the same need as the original poster. I > no longer recall the details, but I think maybe I was implementing a > union/find type algorithm. This basically involves partitioning a > universe set into partitions, where any element of a partition can be > used as a name/handle/etc for the partition in question. Sets are the > obvious representation for these partitions, esp since they implement > union efficiently. And given this representation, it's very obvious > to want to generate a "name" when you have a set in hand. Since any > element of the set serves as a name (and you know the sets are all non- > empty), it'd be very nice to have a .element() method, or some such. > I guess "iter(s).next()" works okay, but it's not very readable, and I > wonder if it's efficient. You can find out:: $ python -m timeit -s "s = set('abcdef')" "x = iter(s).next()" 1000000 loops, best of 3: 0.399 usec per loop $ python -m timeit -s "s = set('abcdef')" "x = s.pop(); s.add(x)" 1000000 loops, best of 3: 0.339 usec per loop So it looks like it's more efficient to use s.pop() + s.add(). STeVe From bdesth.quelquechose at free.quelquepart.fr Sun May 13 09:52:36 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 13 May 2007 15:52:36 +0200 Subject: __dict__ for instances? In-Reply-To: References: Message-ID: <46470dff$0$19237$426a74cc@news.free.fr> Ivan Voras a ?crit : > While using PyGTK, I want to try and define signal handlers > automagically, without explicitly writing the long dictionary (i.e. I > want to use signal_autoconnect()). > > To do this, I need something that will inspect the current "self" and > return a dictionary that looks like: > > { > "method_name" : self.method_name > } > > Class.__dict__ does something very similar, but when I use it, either > I'm doing something wrong or it doesn't return methods bound to "self", > and python complains a wrong number of arguments is being passed to the > methods (one instead of two). You're not doing anything wrong, that's just how Python works. "methods" are wrapper objects around function objects attributes. The wrapping only happens at lookup time, and returns different kind of "method" wrapper (resp. unbound or bound methods) if the attribute is looked up on an instance or a class (there are also the staticmethod/classmethod things, but that's not your problem here). You can build the dict you're looking for using dir() and getattr(): from types import MethodType autoconnect_dict = {} for name in dir(self): attr = getattr(self, name) if isinstance(attr, MethodType): autoconnect_dict[name] = attr return autoconnect_dict > instance.__dict__ on the other hand returns an empty dictionary. the instance's __dict__ only stores per-instance attributes. While it's technically possible to attach methods per-instance, it's definitively a corner case. From mcPas.De.Spam at mclaveauPas.De.Spam.com Wed May 2 15:29:51 2007 From: mcPas.De.Spam at mclaveauPas.De.Spam.com (Michel Claveau) Date: Wed, 02 May 2007 21:29:51 +0200 Subject: Microsoft's Dynamic Languages Runtime (DLR) References: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> Message-ID: Hi! DLR is include in SilverLight. See my message of yesterday. For instant, DLR is for IronPython & JScript. Others languages are only promised. You can install SilverLight 1.1, and make your tests. -- @-salutations Michel Claveau From tfb+google at tfeb.org Fri May 4 05:13:26 2007 From: tfb+google at tfeb.org (Tim Bradshaw) Date: 4 May 2007 02:13:26 -0700 Subject: Why stay with lisp when there are python and perl? In-Reply-To: <463a9668$0$8719$ed2619ec@ptn-nntp-reader02.plus.net> References: <1178155239.007219.205020@y5g2000hsa.googlegroups.com> <1178219732.127815.3260@y80g2000hsf.googlegroups.com> <463a9668$0$8719$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: <1178270006.399908.275470@y5g2000hsa.googlegroups.com> On May 4, 3:06 am, Jon Harrop wrote: > > Lisp compilers are much more advanced, for one thing. Though I hesitate to respond in this thread (and I didn't actually read the rest of the article) there's actually a valid point here. The last programming job I did involved doing some search stuff in Python. I think Python had been chosen for almost (but actually not) good reasons - people really wanted to use Lisp but it would have been too hard (politically and technically), and the same people had recent first-hand experience of some of the worse horrors of J2EE programming so were negative about Java. Finally Python actually had the required stuff (the ability to mmap files was critical to the proposed technique for doing the search). (The reasons were actually not good because Java could have done it as well, and if we'd had the courage we could have done a POJO-style Java thing which would have been fine and set a good example to other people, which as it was we failed dismally to do. On the other hand they'd not have hired me - despite the fact that even by then I didn't care about language choice with a few exceptions (C++), I didn't look enough like a Java person (and still don't of course).) Anyway the experience of writing in Python was kind of interesting. It had the usual single-implementation issues common to such things which meant we depended on the right version (and I think a later version than the one shipped with the OS since they'd decided to change semantics in some quite major way at some point). But apart from that writing programs that performed well (for us - we actually had performance issues since we wanted to look at a lot of data) turned out to be a matter of making sure that all the performance- critical bits were done in libraries (in C) with Python merely a kind of elaborate glue to get in the way. It was a bit like writing code for an array processor or a DSP or something, except without any good hardware reason for it. So one of the things I learned was "use a language with a decent compiler"[*] I think. --tim [*] No glib comments about Java not having a decent compiler: actually typical implementations do now (or did in 2004/5 and I bet they are better now). From ebgssth at gmail.com Sun May 13 06:01:11 2007 From: ebgssth at gmail.com (js ) Date: Sun, 13 May 2007 19:01:11 +0900 Subject: Popen and wget, problems In-Reply-To: <4645a6a6$0$8615$dbd49001@news.wanadoo.nl> References: <4645a6a6$0$8615$dbd49001@news.wanadoo.nl> Message-ID: Hi Jesse. > cmd_set = ['wget', '-nv', '-O dir/cpan.txt', 'http://search.span.org'] [snip] >proc = Popen(cmd_set, stdout=PIPE, stderr=PIPE) wget will treat this as $ wget -nv '-O dir/cpan.txt' "http://search.cpan.org" And will emit the following error because there's no pathname ' dir/cpan.txt'. (Note the pathname has a trailing space.) dir/cpan.txt: No such file or directory Replace '-O dir/cpan.txt" with '-Odir/cpan.txt' or '-O', 'dir/cpan.txt' and it should work. Hope this helps From josh at laculine.com Fri May 25 14:00:46 2007 From: josh at laculine.com (Josh West) Date: Fri, 25 May 2007 19:00:46 +0100 Subject: Proxying every function in a module In-Reply-To: References: Message-ID: <4657244E.5000006@laculine.com> > > First off, don't attempt to start a new thread by replying to a previous > one. Many newsreaders will merge the two, confusing the hell out of > everyone and generally not helping. > Ahh, yes. I see what you mean. Explains why it didn't appear the first time I posted (until later..). Sorry for bother and thanks for the advice. > Second, what makes you think you need a module? I'd have thought an > instance of some user-defined class would have been better, as that way > you can redefine the __getattr__() method to return appropriate functions. > The functions are ported from a java class static methods. I was trying to be "pythonic" - since my 100 functions don't share state, I thought they should be packaged as a module rather than as a class of bunch of effectively static methods. > This seems to work, though I haven't tested it extensively (i.e. I have > called one instance precisely once ;-) > > >>> import re > >>> pat = re.compile("([a-z]+)(.+)") > >>> class myRewriter: > ... def srt(self, s): > ... m = pat.match(s) > ... if not m: raise ValueError(s) > ... return m.group(1), m.group(2).lower() > ... def __getattr__(self, name): > ... n1, n2 = name.split("_") > ... def f(val): > ... s1, s2 = self.srt(val) > ... return "/%s/%s/?sort=%s_%s" % \ > ... (n1, n2, s1, s2) > ... return f > ... > >>> r = myRewriter() > >>> r.organisations_list('dateCreated') > '/organisations/list/?sort=date_created' > >>> > > regards > Steve > Genius! Embarrassingly, I hadn't realised that __getattr__() is called when a method is invoked, thus making the method name (attribute name) so easily available as a string. I was therefore thinking in terms of gnarly introspection/reflection things. This is much better. Thanks very much From michael at jedimindworks.com Thu May 17 16:25:27 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Thu, 17 May 2007 15:25:27 -0500 Subject: FreeType In-Reply-To: <1179431247.954420.219690@q75g2000hsh.googlegroups.com> References: <1179422948.600593.117310@p77g2000hsh.googlegroups.com> <1179431247.954420.219690@q75g2000hsh.googlegroups.com> Message-ID: <397DF4A1-A882-4B90-ADE1-8D3F3BC408F6@jedimindworks.com> On May 17, 2007, at 2:47 PM, Glich wrote: > I've been there. All the code is in C/C++, don't I need it in python? > I will explore the software. I dismissed this because there was no > python. I am knew to all of this. Thanks for your reply. The c stuff (freetype) is what you need (it gets installed as a library that can be used by python or any other software entity that needs its functionality). It may seem a little weird, but lots of the stuff you call from python is written in c. More than likely, your python interpreter is also written in c :-) From vmaslov at swsoft.com Mon May 7 07:30:26 2007 From: vmaslov at swsoft.com (Vyacheslav Maslov) Date: Mon, 07 May 2007 18:30:26 +0700 Subject: assisging multiple values to a element in dictionary In-Reply-To: <1178535831.870912.44220@p77g2000hsh.googlegroups.com> References: <1178535831.870912.44220@p77g2000hsh.googlegroups.com> Message-ID: <463F0DD2.4090105@swsoft.com> > I have a dictionary which is something like this: > id_lookup={ > 16:'subfunction', > 26:'dataId', > 34:'parameterId', > 39:'subfunction', > 44:'dataPackageId', > 45:'parameterId', > 54:'subfunction', > 59:'dataId', > 165:'subfunction', > 169:'subfunction', > 170:'dataPackageId', > 174:'controlParameterId' > } > How do i assign multiple values to the key here.Like i want the > key 170 to take either the name 'dataPackageID' or the name > 'LocalId'. In general dictionary define strong relation between keys and values, key should have only one associated value, but in your case value can be a tuple or list. Anyway, i think that your question contradict to dictionary concept, because is impossilbe to assign for some key multiple values. -- Vyacheslav Maslov From isaac.rodriguez at comcast.net Fri May 4 08:53:10 2007 From: isaac.rodriguez at comcast.net (Isaac Rodriguez) Date: 4 May 2007 05:53:10 -0700 Subject: How to find the present working directory using python. In-Reply-To: <1178262224.269446.69410@c35g2000hsg.googlegroups.com> References: <1178262224.269446.69410@c35g2000hsg.googlegroups.com> Message-ID: <1178283189.969214.33700@q75g2000hsh.googlegroups.com> > how to find out the present working directory using python. > Try this: import os os.getcwd() It returns the current working directory. Thanks, - Isaac. From tchur at optushome.com.au Mon May 28 04:26:39 2007 From: tchur at optushome.com.au (Tim Churches) Date: Mon, 28 May 2007 18:26:39 +1000 Subject: Flags of the world In-Reply-To: References: <1180299312.207986.4340@k79g2000hse.googlegroups.com> <1180299814.129770.93220@o11g2000prd.googlegroups.com> Message-ID: <465A923F.3060005@optushome.com.au> http://shaheeilyas.com/flags/ Scroll to the bottom to see why this is not entirely off-topic. Are there other public examples in which Python has been used to harvest and represent public information in useful and/or interesting ways? Ideas for some more? Tim C From venner at gmail.com Sun May 27 09:44:01 2007 From: venner at gmail.com (Eric) Date: 27 May 2007 06:44:01 -0700 Subject: Newbie question - better way to do this? Message-ID: <1180273441.455227.120170@g4g2000hsf.googlegroups.com> I have some working code, but I realized it is just the way I would write it in C, which means there is probably a better (more pythonic) way of doing it. Here's the section of code: accumulate = firstIsCaps = False accumStart = i = 0 while i < len(words): firstIsCaps = firstIsCapitalized(words[i]) if firstIsCaps and not accumulate: accumStart, accumulate = i, True elif accumulate and not firstIsCaps: doSomething(words[accumStart : i]) accumulate = False i += 1 words is a big long array of strings. What I want to do is find consecutive sequences of words that have the first letter capitalized, and then call doSomething on them. (And you can ignore the fact that it won't find a sequence at the very end of words, that is fine for my purposes). Thanks, Eric From sturlamolden at yahoo.no Thu May 10 09:45:28 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 10 May 2007 06:45:28 -0700 Subject: Towards faster Python implementations - theory In-Reply-To: <1210i.7468$2v1.2505@newssvr14.news.prodigy.net> References: <1210i.7468$2v1.2505@newssvr14.news.prodigy.net> Message-ID: <1178804728.527486.196400@y80g2000hsf.googlegroups.com> On May 8, 5:53 pm, John Nagle wrote: > The point here is that we don't need language changes or declarations > to make Python much faster. All we need are a few restrictions that > insure that, when you're doing something unusual, the compiler can > tell. Franz, CMUCL, SBCL and GCL teams made Lisp almost as fast as C. A dynamic language can be fast if the implementation is good. If you look at SBCL and GCL, no code is interpreted. It's all compiled on the fly to native machine code. The compiler begins with some code and some input data, and compiles as much as it can. Then the RT executes the machine code, compiles again, etc. Often long stretches of code can be compiled without break, and tight performance critical loops are usually compiled only once. In addition to this, one needs an efficient system to cache compiled code, in order to do the compilation work only once. making a dynamic language fast is not rocket science. We should have somthing like "GPython", a Python RT on top of a GCC backend, similar to what the GCL team did for Lisp. There is no obvious reason as to why Lisp should have better performance than Python. From a.schmolck at gmail.com Tue May 8 14:16:19 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: Tue, 08 May 2007 19:16:19 +0100 Subject: Emacs and pdb after upgrading to Ubuntu Feisty References: <1178426788.614637.209400@w5g2000hsg.googlegroups.com> <1178638304.190312.177150@u30g2000hsc.googlegroups.com> Message-ID: levander writes: > Okay, thanks Alexander and Bernstein. I'll lookinto Emacs 23, but I'm > worried about compatibility with modes. Does all the stuff that works > in Emacs 21 work in 23? I've switched from 21 to 23 a few weeks ago and don't recall any particular issues (and I'm a fairly hardcore emacs user with pretty complex configuration and many third-party packages -- my emacs config has 182 matches for require\|autoload). > Like even that ipython.el file, does it work in Emacs 23? I think as the author I would have noticed by now if it didn't :) > And, I probably will report a bug to either Ubuntu's Launchpad or to > Debian's package maintainer for pdb mode (which apparently has been > integrated into just the gud mode stuff, at least that's how it looks from > looking around on my system). Does Debian have a web site for reporting bugs > like Ubuntu does? Or, do I just email the package maintainer? > > I'm messing around with ipython.el and ipython now. It looks like if > you just want to step through some code that isn't throwing any > execption, you have to modify the source code of your script to tell > ipython to stop on this line and start debugging here? Nope. Try ``run -d myscript`` (and ``?run`` for more info). I must admit that this doesn't work properly for me though -- I don't get stepping through the corresponding source in emacs. ``M-x pdb`` works with pdb as debugger but not with pydb; maybe the problem is missing pydb support in the relevant regexps? I can't devote any time to this at the moment, but I'd be pretty interested in having this working -- so I'd appreciate a note if someone figures out what's going on (and if a change to ipython.el is needed I'll make sure it gets in). > With all the raving about ipython, I'm sure it's a great product. But, this > thing about having to modify your source code really sounds like it sucks. > I'd be surprised if it were difficult to implement a command line option for > ipython that tells it to open this file and then start debugging it from the > top. It's already there -- I'm using 0.7.4 svn (which is the ubuntu feisty package), so I think it should also work for you. > And, have the emacs mode operate much like it does with pdb, where emacs > remembers your command line when you invoked pdb, so you just hit "M-x pdb > RET RET RET ..." to open up your file. But, maybe I just haven't foud it > yet? I'd type something like ``run -+

`` (with M-p bound to `comint-previous-matching-input-from-input') or M-r, which is even fewer keystrokes. 'as From rNOSPAMon at flownet.com Thu May 17 14:09:05 2007 From: rNOSPAMon at flownet.com (Ron Garret) Date: Thu, 17 May 2007 11:09:05 -0700 Subject: Is wsgi ready for prime time? Message-ID: The wsgiref module in Python 2.5 seems to be empty: [ron at mickey:~/Sites/modpy]$ python Python 2.5 (r25:51908, Mar 1 2007, 10:09:05) [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import wsgiref >>> dir(wsgiref) ['__builtins__', '__doc__', '__file__', '__name__', '__path__'] >>> So... is wsgi considered ready for production use, or is it still on the bleeding edge? And if the former, which implementation should one use? rg From roman.yakovenko at gmail.com Wed May 9 13:47:56 2007 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Wed, 9 May 2007 19:47:56 +0200 Subject: Boost python : get the shape of a numpy ndarray in C++ code. In-Reply-To: <1178723326.174384.180690@y5g2000hsa.googlegroups.com> References: <1178723326.174384.180690@y5g2000hsa.googlegroups.com> Message-ID: <7465b6170705091047m2f4a6820y6158cdc00b43428@mail.gmail.com> On 9 May 2007 08:08:46 -0700, TG wrote: > Hi there. > > I'm strugling here with some boost python code (damn I hate C++) : > > All I want to do is to initialize the content of an array with a numpy > ndarray parameter. I have this, which actually works. But I want to > add some kind of data check such as : > > * is array two dimensional ? This question has nothing to do with Boost.Python > * are the dimensions corresponding to map's width / height ? Same as above > * is array field with floats or ints ? Read "extract" documentation http://boost.org/libs/python/doc/v2/extract.html > void > Layer::set_potentials (numeric::array& array) > { > for (int h=0; hheight; h++){ > for (int w=0; wwidth; w++){ > units[w+h*map->width]->potential = > extract(array[make_tuple(w,h)]); > } > } > } > > > Some help is very welcome here ... thanks. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From levander404 at gmail.com Tue May 8 11:31:44 2007 From: levander404 at gmail.com (levander) Date: 8 May 2007 08:31:44 -0700 Subject: Emacs and pdb after upgrading to Ubuntu Feisty In-Reply-To: References: <1178426788.614637.209400@w5g2000hsg.googlegroups.com> Message-ID: <1178638304.190312.177150@u30g2000hsc.googlegroups.com> Okay, thanks Alexander and Bernstein. I'll lookinto Emacs 23, but I'm worried about compatibility with modes. Does all the stuff that works in Emacs 21 work in 23? Like even that ipython.el file, does it work in Emacs 23? And, I probably will report a bug to either Ubuntu's Launchpad or to Debian's package maintainer for pdb mode (which apparently has been integrated into just the gud mode stuff, at least that's how it looks from looking around on my system). Does Debian have a web site for reporting bugs like Ubuntu does? Or, do I just email the package maintainer? I'm messing around with ipython.el and ipython now. It looks like if you just want to step through some code that isn't throwing any execption, you have to modify the source code of your script to tell ipython to stop on this line and start debugging here? With all the raving about ipython, I'm sure it's a great product. But, this thing about having to modify your source code really sounds like it sucks. I'd be surprised if it were difficult to implement a command line option for ipython that tells it to open this file and then start debugging it from the top. And, have the emacs mode operate much like it does with pdb, where emacs remembers your command line when you invoked pdb, so you just hit "M-x pdb RET RET RET ..." to open up your file. But, maybe I just haven't foud it yet? From ptmcg at austin.rr.com Sat May 26 23:36:27 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 26 May 2007 20:36:27 -0700 Subject: Is PEP-8 a Code or More of a Guideline? Message-ID: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> I'm starting a new thread for this topic, so as not to hijack the one started by Steve Howell's excellent post titled "ten small Python programs". In that thread, there was a suggestion that these examples should conform to PEP-8's style recommendations, including use of lower_case_with_underscores style for function names. I raised some questions about this suggestion, since I liked the names the way they were, but as a result, part of the discussion has drifted into a separate track about PEP-8, and naming styles. I was under the impression that lower_case_with_underscores was a dated recommendation, and that recent practice is more inclusive of mixedCase style identifiers. On the contrary, Steven Bethard straightened me out, saying that PEP-8 used to accept either style, but has been amended to accept only lower_case_with_underscores. My latest thought on the topic relates back to the Martin v. L?wis thread-that-would-not-die requesting feedback about PEP 3131, on adding support for non-ASCII identifiers in Py3K. I posted an out-of- curiosity comment asking about how underscore separators mix with Unicode identifiers, including the mechanics of actually typing an underscore on a non-US keyboard. At this point, I realized that I was taking things too far off-topic, so I decided to start a new thread. Steve, sorry for taking your thread down a rathole. I hope we can move any further PEP-8-related discussion (if the point merits any) to this thread. -- Paul From steven at REMOVE.THIS.cybersource.com.au Wed May 16 00:33:37 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 16 May 2007 04:33:37 GMT Subject: Newbie Question: Getting a list of files References: Message-ID: On Tue, 15 May 2007 17:12:01 -0700, Brian wrote: > How do I, in Python, obtain a recursive list of files in a specified > directory, including the subdirectories, etc? For example, in the old > MS-DOS days, we could specify at the command prompt "DIR /S" and this > would provide a listing of all files, including those in subdirectories, > no matter how far down the branch they were. How can this be done with > Python? In MS DOS days, you were dealing with a small number of files. Python has to deal with file systems that could contain billions of files. If each file name has an average of eight characters, your recursive list of files could require a gigabyte of memory just to hold the file names. (It might not, of course -- it depends on the file system in use.) I suggest you have a look at the os module, in particular os.listdir and os.walk. -- Steven. From juanhu_yang at hotmail.com Wed May 16 21:58:41 2007 From: juanhu_yang at hotmail.com (yangjh) Date: Thu, 17 May 2007 09:58:41 +0800 Subject: _ctypes.so for aix 5.3 Message-ID: Hi all, I want to use the ctypes module on AIX 5.3, I download the lastest 2.5.1 from python.org, but build failed with cc_r(gcc not installed). download activepython 2.5.1 for aix, but it don't contail the ctypes module, Is there a binary version _ctypes.so for aix 5.3 in the web ? Thanks. Juanhu.yang. _________________________________________________________________ ?????? MSN Messenger? http://imagine-msn.com/messenger/launch80/default.aspx?locale=zh-cn&source=wlmailtagline -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul at boddie.org.uk Mon May 7 08:34:40 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 7 May 2007 05:34:40 -0700 Subject: Bastion/rexec use cases? In-Reply-To: References: <1178534949.324994.60870@l77g2000hsb.googlegroups.com> Message-ID: <1178541280.523576.181130@n59g2000hsh.googlegroups.com> On 7 Mai, 14:01, Duncan Booth wrote: > Paul Miller wrote: > > Bastion and rexec have been deprecated since Python 2.2, so it seems > > we (the Python community) have gotten along well enough without them. > > Have these modules not been reimplemented because: > > > a) There are no valid use cases for them. > > b) Doing so would be difficult and prone to breakage as new features > > are introduced into the language. > > c) Nobody has any idea how to do it. > > d) Nobody cares. > > e) Guido thinks it's a bad idea. > > > or, some combination of these? > > I think it is mostly 'b' plus partly nobody cares sufficiently to put the > time, money and effort behind it. I'd agree with this, adding that (c) is increasingly starting to apply to CPython as new features make any potential sandboxing strategy less coherent. Brett Cannon appears to be tackling this situation head-on, however. > The recent release of Silverlight means that there is now a way to run > Python in a secure sandbox. Also possible with Jython for a long time, I believe. Meanwhile, others (including non-Python developers) have turned to other kinds of solutions including virtualisation at different levels. See this page for more discussion: http://wiki.python.org/moin/SandboxedPython I've experimented somewhat with a chroot-based solution, although I'm reluctant to make it available because of an uncertainty as to whether it really offers proper "jailing" of the executed code, along with concerns that people may consider it secure without doing their own homework on the matter. Ideally, I'd want to trim the Python interpreter right down to the very basic virtual machine (without I/O) and then build the different extensions back on in a security-oriented framework, but I guess this is what Mr Cannon has in mind. Paul From kyosohma at gmail.com Mon May 7 16:38:11 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 7 May 2007 13:38:11 -0700 Subject: randomly write to a file In-Reply-To: <1178567497.042096.82940@w5g2000hsg.googlegroups.com> References: <1178567497.042096.82940@w5g2000hsg.googlegroups.com> Message-ID: <1178570291.117629.192100@w5g2000hsg.googlegroups.com> On May 7, 2:51 pm, rohit wrote: > hi, > i am developing a desktop search.For the index of the files i have > developed an algorithm with which > i should be able to read and write to a line if i know its line > number. > i can read a specified line by using the module linecache > but i am struck as to how to implement writing to the n(th) line in a > file EFFICIENTLY > which means i don't want to traverse the file sequentially to reach > the n(th) line > > Please help. > Regards > Rohit Hi, Looking through the archives, it looks like some recommend reading the file into a list and doing it that way. And if they file is too big, than use a database. See links below: http://mail.python.org/pipermail/tutor/2006-March/045571.html http://mail.python.org/pipermail/tutor/2006-March/045572.html I also found this interesting idea that explains what would be needed to accomplish this task: http://mail.python.org/pipermail/python-list/2001-April/076890.html Have fun! Mike From carsten at uniqsys.com Tue May 29 00:08:36 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 29 May 2007 00:08:36 -0400 Subject: Circular imports In-Reply-To: <003801c7a1a3$e048d840$6701a8c0@aristotle> References: <003801c7a1a3$e048d840$6701a8c0@aristotle> Message-ID: <20070529034901.M60755@uniqsys.com> On Mon, 28 May 2007 23:46:00 -0400, Ron Provost wrote > [...] python is not happy about my circular imports [...] A circular import is not a problem in itself. I'm guessing you're running into a situation like this: Module A imports module B and then defines an important class. Module B imports A (which does nothing because A is already partially imported) and then defines a class that depends on the class that is defined in module A. That causes a NameError. The root of the problem is that all statements are executed in the order in which they appear, and B is imported before A had a chance to define the class that B depends on. Note that import statements don't have to be at the top of the file. Try moving each import statement to the latest possible point in the code, i.e. right before the first occurence of whatever names you're importing from the respective modules. That way, each module gets to define as much as it possibly can before it gets side-tracked by importing other modules. If my guess doesn't help, you're going to have to post at least the exception/traceback you're getting, and you're probably going to have to post some code, too. Good luck, -- Carsten Haese http://informixdb.sourceforge.net From girish.14 at gmail.com Thu May 31 04:23:40 2007 From: girish.14 at gmail.com (Girish) Date: 31 May 2007 01:23:40 -0700 Subject: Embedding objects( txt, doc) into excel using python Message-ID: <1180599820.017532.45430@d30g2000prg.googlegroups.com> Hi, I want to embed a txt document into an excel using python. Here is my code, but i get an error message =================================================== Traceback (most recent call last): File "C:\Documents and Settings\kusumap\Desktop\Girish.py", line 7, in ? worksheet.OLEObjects.Add(Filename="C:\Documents and Settings \kusumap\My Documents\desktop.ini", Link=False,DisplayAsIcon=True, IconFileName="packager.exe", IconIndex=0, IconLabel="C:\Documents and Settings\kusumap\My Documents\desktop.ini").Select AttributeError: 'function' object has no attribute 'Add' =================================================== import win32com.client ExcelApp = win32com.client.Dispatch("Excel.Application") ExcelApp.visible = 1 workbook = ExcelApp.Workbooks.open("C:\Software\New Microsoft Excel Worksheet.xls") worksheet = workbook.Activesheet #worksheet.OLEObjects.Add(Filename="C:\Documents and Settings\p\My Documents\desk.txt", Link=False,DisplayAsIcon=True, IconFileName="packager.exe", IconIndex=0, IconLabel="C:\Documents and Settings\p\My Documents\desk.txt").Select Can anyone please whtz the problem with the code and how to overcome the same. Thanks Girish S From bdesth.quelquechose at free.quelquepart.fr Sun May 20 16:17:44 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 20 May 2007 22:17:44 +0200 Subject: How to do basic CRUD apps with Python In-Reply-To: <1179382415.366424.103980@e65g2000hsc.googlegroups.com> References: <1179098458.333666.307750@e65g2000hsc.googlegroups.com> <464848fa$0$465$426a74cc@news.free.fr> <1179197198.513508@smirk> <1179382415.366424.103980@e65g2000hsc.googlegroups.com> Message-ID: <4650a28b$0$3210$426a74cc@news.free.fr> half.italian at gmail.com a ?crit : (snip) > > Sounds like you're talking about rails. Do any of the python packages > compare with the ease of rails? Turbogears, Django and Pylons. From nanodust at gmail.com Thu May 24 16:14:37 2007 From: nanodust at gmail.com (nanodust at gmail.com) Date: 24 May 2007 13:14:37 -0700 Subject: trouble converting c++ bitshift to python equivalent Message-ID: <1180037677.633613.30160@u30g2000hsc.googlegroups.com> hello all i am relatively new to python, catching on, but getting stuck on simple thing: i have two string bytes i need to push into a single (short) int, like so in c: temp = strBuf[2]; temp = (temp<<7)+(strBuf[1]); c code works, but having trouble getting python to perform same function! keep getting type & operator errors (i apparently can't bitshift on str or int?) curious what the best way is to do this, in python... i'll stick w/ it & post when i sort it meanwhile, any help greatly appreciated From half.italian at gmail.com Wed May 2 03:03:56 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 2 May 2007 00:03:56 -0700 Subject: os.path.join In-Reply-To: References: <1178072869.844914.59010@u30g2000hsc.googlegroups.com> <1178083903.677905.32710@c35g2000hsg.googlegroups.com> Message-ID: <1178089436.202973.148650@h2g2000hsg.googlegroups.com> On May 1, 11:10 pm, "Gabriel Genellina" wrote: > En Wed, 02 May 2007 02:31:43 -0300, escribi?: > > > A better question is why this doesn't work. > > >>>> pathparts = ["/foo", "bar"] > >>>> os.path.join(pathparts) > > ['/foo', 'bar'] > > > This should return a string in my opinion. > > I think it's a bug, but because it should raise TypeError instead. > The right usage is os.path.join(*pathparts) > > -- > Gabriel Genellina Wow. What exactly is that * operator doing? Is it only used in passing args to functions? Does it just expand the list into individual string arguments for exactly this situation? Or does it have other uses? ~Sean From tim at tdw.net Tue May 15 10:25:45 2007 From: tim at tdw.net (Tim Williams) Date: Tue, 15 May 2007 15:25:45 +0100 Subject: Automatic login to website (newbie) In-Reply-To: References: Message-ID: <9afea2ac0705150725md811ed2lafd53571da93b2c3@mail.gmail.com> On 15 May 2007 06:38:45 -0700, phishboh at gmail.com wrote: > I'm trying to use PAMIE to login to a website: > > import cPAMIE > > # python.org - just a test, works fine > ie = cPAMIE.PAMIE() > website = "http://www.python.org" > ie.navigate(website) > ie.textBoxSet('q', 'pamie') > ie.buttonClick('submit') > > # expekt.com - this is what I want to do, but it fails > ie = cPAMIE.PAMIE() > website = "http://www.expekt.com/eng" > ie.navigate(website) > ie.textBoxSet('user', 'MyLogin') > ie.textBoxSet('pass', 'MyPassword') > ie.buttonClick('actn') I don't have PAMIE installed nor have I ever used it, but the login area is in a frame and I've had problems with other screen scrapers and frames. The frame URL is http://www.expekt.com/contenttop.jsp , you could try navigating directly to the frame to see if it helps website = "http://www.expekt.com/contenttop.jsp" ie.navigate(website) ie.textBoxSet('user', 'MyLogin') ie.textBoxSet('pass', 'MyPassword') ie.buttonClick('actn') HTH :) From ptmcg at austin.rr.com Sat May 26 23:37:51 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 26 May 2007 20:37:51 -0700 Subject: ten small Python programs In-Reply-To: <1180234739.661905.31890@q66g2000hsg.googlegroups.com> References: <1180229019.873381.52800@m36g2000hse.googlegroups.com> <1180234739.661905.31890@q66g2000hsg.googlegroups.com> Message-ID: <1180237071.351874.310020@q69g2000hsb.googlegroups.com> On May 26, 9:58 pm, Paul McGuire wrote: > Out of curiosity, how does this style jibe with the latest embracing > of Unicode identifiers? Ever tried to type an underscore on a non-US > keyboard? I have a heck of a time finding/typing the '_' character > when I visit our clients in Germany, but this may just be my own > personal Amerocentric issue (I also get messed up by the transposition > of Y and Z on German keyboards, but my German colleagues > understandably are not bothered by it). For someone already familiar > with that keyboard layout, is typing an underscore any more difficult > than my pressing Shift-_ on my US keyboard? > > -- Paul Steve, sorry for going so far off-topic. I've started a new thread on my questions about this aspect of PEP-8, and if there's more to say about this, people should post it there. -- Paul From duncan.booth at invalid.invalid Tue May 1 15:54:40 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 May 2007 19:54:40 GMT Subject: SilverLight, a new way for Python? References: <46378e49$0$27370$ba4acef3@news.orange.fr> Message-ID: "M?ta-MCI" wrote: > Re! > >>>> it can do much more than active scripting. > > Hummm.... Perhaps. > But, with ActiveScripting, I can define functions & class in Python, > Ruby(script), Jscript, VBscript, Perl. I can call these > functions/objects directly from Python, and share many objects (& > libraries). I am not sure to find these features in SilverLight. With Silverlight you can define functions & classes in Python, Ruby, JScript, C#, VB, C++, and other languages and use them interchangeably. They all run sandboxed on the client. One of the demos (the chess program) demonstrates the difference quite well: it has both JScript and C# implementations, with the JScript version examining about 500 nodes per move and the C# one about 1,500,000. > >>>> Have you at least run the demos? > > Yes, I downloaded two demos, and run-it. > I had look (quickly) the code. It's run. But it's too few for call > that a true "try". > However, these demos are nice & fun. > > > > Another thing: I have VS-2005. I had install the plug-in > SilverLight/VS ; OK, but I don't found it in VS. Perhaps because I use > a french version? (sorry, I don't speak english). As I understand it you have to install the new beta version of visual studio. So that is an 8Mb download for the Silverlight support in VS plus a 5.6Gb download for Visual Studio itself. From basilisk96 at gmail.com Mon May 21 23:48:52 2007 From: basilisk96 at gmail.com (Basilisk96) Date: 21 May 2007 20:48:52 -0700 Subject: how to use private method in a class In-Reply-To: References: Message-ID: <1179805732.686884.17300@l77g2000hsb.googlegroups.com> On May 21, 9:49 pm, "wang frank" wrote: > Hi, > > I am trying to write a python class with a new data type such as: > class Cc14: > def __init__(self, realpart, imagpart): > self.r=realart > self.i=imagpart > > def __saturator(x): > return x+1 > def out(self,x): > return Cc14(__saturator(x.r), __saturator(x,i)) > > When I use the method out such as: > z.out > > Python complains: > > global name '_Cc14_saturator' is not defined. > > Is the way put two underscore in front of the definitio making the method > becomes private? > > Why in the same clase, I could not use the __saturator method? > > Thanks > > Frank > It seems you have several issues here: (1) To avoid syntax errors, self.r=realart should be: self.r=realpart (2) Your __saturator method definition needs the reference to self: def __saturator(self, x): (3) And lastly, the body of the out() method needs two corrections: return Cc14(self.__saturator(x.r), self.__saturator(x.i)) Is it really necessary to "privatize" the saturator method? In Python, all class methods are public and visible by default. A method name __methodname in a class "foo" turns into "_foo__methodname" in an instance of the class. This is known as name mangling. It is simply a convention supported by Python when a class attribute name begins with two underscores. It prevents a programmer from calling something like C.__saturator(arg), but still allows calling C._Cc14__saturator(arg). IMHO, you could just leave the saturator definition as "def saturator(self, x):" Anyway, in your case the 3 fixes above will allow you now to do this: >>>C = Cc14(2,3) >>>result = C.out(C) >>>result.r, result.i (3, 4) Which is beginning to look like your design intent.. Cheers, -Basilisk96 From bhochstetler at gmail.com Thu May 3 09:01:01 2007 From: bhochstetler at gmail.com (bhochstetler at gmail.com) Date: 3 May 2007 06:01:01 -0700 Subject: hp 11.11 64 bit python 2.5 build gets error "import site failed" In-Reply-To: <4638fe11$0$1098$9b622d9e@news.freenet.de> References: <1178131203.719353.91360@y80g2000hsf.googlegroups.com> <4638fe11$0$1098$9b622d9e@news.freenet.de> Message-ID: <1178197261.294121.157120@h2g2000hsg.googlegroups.com> On May 2, 5:09 pm, "Martin v. L?wis" wrote: > > "import site failed" > > OverflowError: signed integer is greater than the maximum. > > > This is happening in the convertsimple() routine when it tries to > > return a signed int: > > > ival = PyInt_AsLong(arg) > > > the ival is larger than what is defined in INT_MAX. > > > Why is this happening in a standard HP 64 bit build? > > Can you provide a complete gdb/dbx backtrace? > > Some function tries to convert a Python int into a C int, > using the "i" conversion character. Python int uses C long > for internal representation, and that particular C long > happens to be larger than INT_MAX. This is quite reasonable > to happen in principle, but shouldn't happen on interpreter > startup. > > So the questions are: > - what are the callers of convertsimple here? (in particular, > where does the call to PyArg_ParseTuple come from?) > - what is the value of ival? > - where does that number come from? > > The first two questions are best answered with a C debugger. > Depending on the answer, the third question may nor may not > need an answer. > > Good luck, > Martin > > P.S. If you are asking in the more abstract sense "why is that > happening to me?", the answer is "because you are using an > uncommon platform on which Python sees little or no testing". > To work around, try a 32-bit build, or switch to Solaris, > OS X, Debian Linux, or (heaven forbid) MS Windows :-) > - what are the callers of convertsimple here? (in particular, > where does the call to PyArg_ParseTuple come from?) since the debugger locks up when I run, here is a printf call stack of where things are happening: import site # precompiled from ... builtin___import__ PyArg_ParseTupleAndKeywords vgetargskeywords: positional arg: 0 convertitem vgetargskeywords: positional arg: 1 convertitem vgetargskeywords: positional arg: 2 convertitem vgetargskeywords: positional arg: 3 convertitem vgetargskeywords: positional arg: 4 convertitem > - what is the value of ival? ival: 4294967295 > - where does that number come from? It is coming from the call to PyInt_AsLong. In that function there is a call to: PyInt_AS_LONG((PyIntObject*)op) which returns the value of ival. I wish we could just skip this port, but it is required for our product that we have HP 64 bit. This did not happen with python 2.3.1 or 2.0. Thanks for the help. Brad From steve at holdenweb.com Tue May 29 08:36:00 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 29 May 2007 08:36:00 -0400 Subject: multiline regular expression (replace) In-Reply-To: <465C0F4E.8080805@yahoo.co.uk> References: <1180432000.953227.144690@i13g2000prf.googlegroups.com> <465C0F4E.8080805@yahoo.co.uk> Message-ID: Zdenek Maxa wrote: > half.italian at gmail.com wrote: >> On May 29, 2:03 am, Zdenek Maxa wrote: >> >>> Hi all, >>> >>> I would like to perform regular expression replace (e.g. removing >>> everything from within tags in a XML file) with multiple-line pattern. >>> How can I do this? >>> >>> where = open("filename").read() >>> multilinePattern = "^ .... <\/tag>$" >>> re.search(multilinePattern, where, re.MULTILINE) >>> >>> Thanks greatly, >>> Zdenek >>> >> Why not use an xml package for working with xml files? I'm sure >> they'll handle your multiline tags. >> >> http://effbot.org/zone/element-index.htm >> http://codespeak.net/lxml/ >> >> ~Sean >> >> > > Hi, > > that was merely an example of what I would like to achieve. However, in > general, is there a way for handling multiline regular expressions in > Python, using presumably only modules from distribution like re? > > Thanks, > Zdenek So you mean you don't know how to *create* multiline patterns? One way is to use """ ... """ or ''' ... ''' quoting, which allows you to include newlines as part of your strings. Another is to use \n in your strings to represent newlines. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From mail at microcorp.co.za Sun May 6 04:15:26 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 6 May 2007 10:15:26 +0200 Subject: High resolution sleep (Linux) References: <1178274122.142071.91740@y5g2000hsa.googlegroups.com> Message-ID: <011201c78fb7$be8dce20$03000080@hendrik> "Tim Roberts" wrote" > Consider what you're asking here. The operating system can only age the > timer list and re-evaluate process ready states when a process goes into > kernel mode, either by releasing the CPU or hitting the end of its time > slice. In order to know that a process has reached the end of its time > slice, it has to be interrupted by something, typically the timer > interrupt. Yes > > In order to provide 10us sleep resolution, the timer interrupt would have > to fire every 10us. Not necessarily. see below > The overhead of handling the timer interrupt and > rescheduling that often is quite significant. Yes It is also possible to keep the timer list sorted by "expiry date", and to reprogram the timer to interrupt at the next expiry time to give arbitrary resolution, instead of implementing a regular 'tick'. But this also adds overhead and its a PITA to do efficiently, using a linked list of "next interrupt time". So its not normally done unless you *really* need it. Its easier to make a free running hardware counter and to read it and do the sums yourself, hogging the processor, if you need such fine resolution. Ten microseconds is not much time - Speed of light is about one foot per nanosecond, so that gives ten thousand feet of travel for a radio wave - less than two miles, or about three kilometres. A rifle bullet can travel at around 5000 feet per second. In ten microseconds it moves six tenths of an inch. A vehicle at 300 Km/h (about 187 MPH) will not move as much as a millimetre in that time. OTOH - if you are trying to make a software radar system to pick up intruders in your back yard, then ten microseconds is a hopelessly long time... - Hendrik From jmcmonagle at velseis.com.au Thu May 24 18:50:27 2007 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Fri, 25 May 2007 08:50:27 +1000 Subject: Tkinter help, please... In-Reply-To: <465602f8$0$16302$88260bb3@free.teranews.com> References: <465602f8$0$16302$88260bb3@free.teranews.com> Message-ID: <465616B3.4030606@velseis.com.au> I've made a couple of minor changes to your code from the Cribbage class down: class Cribbage: def __init__(self, win): self.parent = win # <---- make the toplevel Tk window an # <---- attribute of the class #Draw the interface self.f = Frame(self.parent) self.f.grid() self.cardpix = [Label(self.f), Label(self.f), Label(self.f), Label(self.f), Label(self.f)] clr = ["red", "blue"] n = 1 for c in self.cardpix: c.configure(width=10, height=10, bg=clr[n%2], text="card "+str(n)) c.grid(row=0, column=n-1) n += 1 self.scorebox = Label(self.f) self.scorebox.configure(height=5, bg="green", text="Score: 0") self.scorebox.grid(row=1, column=0, columnspan=5) def play(self): d = Deck() hand = [d.deal(), d.deal(), d.deal(), d.deal()] flipped = d.deal() hand.append(flipped) hand.sort() score = tally(hand, flipped) self.scorebox.configure(text= "Score: " + str(score)) #Eventually, display the actual card images, but for now... for c, x in zip(hand, self.cardpix): x.configure(text = str(c)) #I've tried both of these, to no avail. self.parent.update() <---- update the toplevel window return score def main(): win = Tk() run = Cribbage(win) score = 0 best = 0 while score < 24: score = run.play() if score >= best: best = score time.sleep(1) <--- short sleep to see what's happening win.mainloop() main() Regards, John From jaysherby at gmail.com Wed May 30 01:49:50 2007 From: jaysherby at gmail.com (BlueJ774) Date: 29 May 2007 22:49:50 -0700 Subject: "is" and == Message-ID: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> Can someone please explain to me the difference between the "is" keyword and the == boolean operator. I can't figure it out on my own and I can't find any documentation on it. I can't understand why this works: if text is None: and why this always returns false: if message is 'PING': even when message = 'PING'. What's the deal with that? From fuzzyman at gmail.com Fri May 4 17:17:08 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 4 May 2007 14:17:08 -0700 Subject: How do I get type methods? In-Reply-To: <1178220806.664557.245780@c35g2000hsg.googlegroups.com> References: <1178220806.664557.245780@c35g2000hsg.googlegroups.com> Message-ID: <1178313428.842839.41580@e65g2000hsc.googlegroups.com> On May 3, 8:33 pm, yavanna... at yahoo.com wrote: > Hello! > > If I do > > import uno > localContext=uno.getComponentContext() > dir(type(localContext)) Perhaps ? Fuzzyman http://www.voidspace.org.uk/ironpython/index.shtml > then localContext is of type > I guess it's a new type provided by PyUNO extension. > localContext.__class__ is None > Is there any way to list all methods of that new type, via Python C > API or through interpreter (other then dir(localContext) )? > What I want is to call localContext's methods like in the tutorial > example: > > x=MyClass() > MyClass.f(x) > > Thank you, > Dmitri From george.sakkis at gmail.com Wed May 23 17:19:30 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 23 May 2007 14:19:30 -0700 Subject: Parallel/distributed generator In-Reply-To: <1179948932.314833.34930@a35g2000prd.googlegroups.com> Message-ID: <1179955170.513189.272520@p77g2000hsh.googlegroups.com> On May 23, 3:35 pm, half.ital... at gmail.com wrote: > On May 23, 11:00 am, George Sakkis wrote: > > > > > I'm looking for any existing packages or ideas on how to implement the > > equivalent of a generator (in the Python sense, i.e.http://www.python.org/dev/peps/pep-0255/) in a parallel/distributed > > way. As a use case, imagine a function that generates a range of > > primes. I'd like to be able to do something along the following lines: > > > def iterprimes(start=1, end=None): > > # ... > > yield prime > > > # rpc-related initialization > > ... > > rpc_proxy = some_rpc_lib(iterprimes, start=1e6, end=1e12) > > for prime in proxy: > > print prime > > > Is there any module out there that does anything close to this ? > > > George > > Parellel Python? > > http://www.parallelpython.com/content/view/17/31/#SUM_PRIMES > > I've never used it, but looks like it does what you are looking for. > > ~Sean Looked promising, until I saw that it requires you to pass explicitly the dependent functions and the modules to be imported for the callable to work. I guess this has to be done recursively for all the dependent functions/modules, which is impractical for anything but toy examples. George From dejanews at email.com Wed May 30 06:42:08 2007 From: dejanews at email.com (samwyse) Date: Wed, 30 May 2007 05:42:08 -0500 Subject: Rats! vararg assignments don't work In-Reply-To: <1180496542.955320.5430@m36g2000hse.googlegroups.com> References: <1180496033.608791.35840@g37g2000prf.googlegroups.com> <1180496542.955320.5430@m36g2000hse.googlegroups.com> Message-ID: George Sakkis wrote: > On May 29, 11:33 pm, Matimus wrote: > > >>Your attemtp: >> >>[code] >>first, rest = arglist[0], arglist[1:] >>[/code] >> >>Is the most obvious and probably the most accepted way to do what you >>are looking for. As for adding the fucntionality you first suggested, >>it isn't likely to be implemented. The first step would be to write a >>PEP though. > > > The time machine did it again: http://www.python.org/dev/peps/pep-3132/. Thanks! Now I just need to wait for Py3K and all of my problems will be solved. ;-) Actually, I'm surprised that the PEP does as much as it does. If tuples are implemented as S-expressions, then something like this: car, *cdr = tuple while leaving cdr a tuple would be trivial to implement. Of course, I'm an old-school LISPer, so what I consider surprising behavior doesn't always surprise anyone else, and vice versa. From braindead at braindead.com Mon May 21 08:48:33 2007 From: braindead at braindead.com (enquiring mind) Date: Mon, 21 May 2007 12:48:33 GMT Subject: help - python can't find file Message-ID: <465194E3.FED4F65A@braindead.com> -learning python with limited knowledge of linux. -get error msg 21 "file or directory does not exist" -running Suse linux 10. -haven't had a problem before - rebooted several times. -python opened in shell/terminal program Konsole window like this user1 at linux!~ - shell - Konsole Sessions View Bookmark Settings Help -first line in window gives me a linux prompt: user1#linux:~> - whereupon I type python and get >>> a command line I think it is called or type python pyfilename.py and it runs/interprets/opens the file on screen - but now I get a error message 21 saying file or directory doesn't exist. - my py files are created with editor gedit - clicking on any py file and linux asks me to open it with what program and I choose utilities/editdors/gedit and it works. -all my py files contain the following lines at the beginning #! /usr/bin/env python # -*- coding: utf-8 -*- # filename: blankpy.py (for example of a file name) - my linux file structure is as follows shown under Konqueror window: rootfolder bin boot dev etc home user1 bin desktop documents lib media dvdrecorder floppy - (for example, and continues on, of course) - none of my python books or linux books show that I can type python /dev/sda/ blankpy.py and get python to open it like in windows98 or dos python A:\blankpy.py embarrassed and frustrated From msurel at comcast.net Thu May 3 16:17:32 2007 From: msurel at comcast.net (Mike) Date: 3 May 2007 13:17:32 -0700 Subject: adding methods at runtime and lambda In-Reply-To: <1178221975.149008.192410@y5g2000hsa.googlegroups.com> References: <1178221975.149008.192410@y5g2000hsa.googlegroups.com> Message-ID: <1178223452.562634.13730@n59g2000hsh.googlegroups.com> In the above example 'addm' should be 'AddMethod' superdict = AddMethod(dict(), lambda self, d: myUtils.HasDrive(d),"hasdrive") From mail at timgolden.me.uk Thu May 10 05:03:55 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 10 May 2007 10:03:55 +0100 Subject: How to convert Unicode string to raw string escaped with HTML Entities In-Reply-To: <1178787272.922167.79480@q75g2000hsh.googlegroups.com> References: <1178787272.922167.79480@q75g2000hsh.googlegroups.com> Message-ID: <4642DFFB.3000804@timgolden.me.uk> ldng wrote: > Hi, > > I'm looking for a way to convert en unicode string encoded in UTF-8 to > a raw string escaped with HTML Entities. I can't seem to find an easy > way to do it. > > Quote from urllib will only work on ascii (which kind of defeat the > purpose imho) and escape from cgi doesn't seems to do anything with my > string. Probably worth having a look at this: http://effbot.org/zone/unicode-convert.htm TJG From artdent at freeshell.org Thu May 10 18:09:09 2007 From: artdent at freeshell.org (Jacob Lee) Date: Thu, 10 May 2007 22:09:09 +0000 (UTC) Subject: Erlang style processes for Python References: <1178759792.268979.206630@p77g2000hsh.googlegroups.com> <1178784219.289832.204770@n59g2000hsh.googlegroups.com> Message-ID: On Thu, 10 May 2007 01:03:39 -0700, jkn wrote: > Have you seen Candygram? > > http://candygram.sourceforge.net/ > > > jon N I did look at Candygram. I wasn't so keen on the method of dispatch (a dictionary of lambdas that is passed to the receive function). It also only works with threads and doesn't communicate across processes. I definitely used Candygram as a reference point when determining what features to hoist from Erlang. -- Jacob Lee From paddy3118 at googlemail.com Sat May 19 01:36:24 2007 From: paddy3118 at googlemail.com (Paddy) Date: 18 May 2007 22:36:24 -0700 Subject: python shell In-Reply-To: <1179337107.842668.112690@k79g2000hse.googlegroups.com> References: <1179337107.842668.112690@k79g2000hse.googlegroups.com> Message-ID: <1179552984.466321.137550@u30g2000hsc.googlegroups.com> On May 16, 6:38 pm, Krypto wrote: > I have been using python shell to test small parts of the big program. > What other ways can I use the shell effectively. My mentor told me > that you can virtually do anything from testing your program to > anything in the shell. Any incite would be useful. Doctest! http://en.wikipedia.org/wiki/Doctest http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305292 - Paddy. From gagsl-py2 at yahoo.com.ar Sun May 6 02:24:31 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 06 May 2007 03:24:31 -0300 Subject: DiffLib Question References: <1178095577.190066.158960@y80g2000hsf.googlegroups.com> <1178097127.286181.216520@y80g2000hsf.googlegroups.com> <1178097973.516943.248720@y80g2000hsf.googlegroups.com> <1178272004.263635.146300@n59g2000hsh.googlegroups.com> Message-ID: En Fri, 04 May 2007 06:46:44 -0300, whitewave escribi?: > Thanks! It works fine but I was wondering why the result isn't > consistent. I am comparing two huge documents with several paragraphs > in it. Some parts in the paragraph returns the diff perfectly but > others aren't. I am confused. Differ objects do a two-level diff; depending on what kind of differences you are interested in, you feed it with different things. If the "line" concept is important to you (that is, you want to see which "lines" were added, removed or modified), then feed the Differ with a sequence of lines (file.readlines() would be fine). This way, if someone inserts a few words inside a paragraph and the remaining lines have to be reflushed, you'll see many changes from words that were at end of lines now moving to the start of next line. If you are more concerned about "paragraphs" and words, feed the Differ with a sequence of "paragraphs". Maybe your editor can handle it; assuming a paragraph ends with two linefeeds, you can get a list of paragraphs in Python using file.read().split("\n\n"). A third alternative would be to consider the text as absolutely plain, and just feed Differ with file.read(), as menctioned in an earlier post. -- Gabriel Genellina From paddy3118 at googlemail.com Sun May 20 12:04:40 2007 From: paddy3118 at googlemail.com (Paddy) Date: 20 May 2007 09:04:40 -0700 Subject: converting strings to most their efficient types '1' --> 1, 'A' ---> 'A', '1.2'---> 1.2 In-Reply-To: <46503B2E.6030902@lexicon.net> References: <1179529661.555196.13070@k79g2000hse.googlegroups.com> <1179551680.283157.19000@y80g2000hsf.googlegroups.com> <464FA156.2070704@lexicon.net> <1179658331.911424.173140@e65g2000hsc.googlegroups.com> <46503B2E.6030902@lexicon.net> Message-ID: <1179677080.830078.169270@p77g2000hsh.googlegroups.com> On May 20, 1:12 pm, John Machin wrote: > On 20/05/2007 8:52 PM, Paddy wrote: > > > > > On May 20, 2:16 am, John Machin wrote: > >> On 19/05/2007 3:14 PM, Paddy wrote: > > >>> On May 19, 12:07 am, py_genetic wrote: > >>>> Hello, > >>>> I'm importing large text files of data using csv. I would like to add > >>>> some more auto sensing abilities. I'm considing sampling the data > >>>> file and doing some fuzzy logic scoring on the attributes (colls in a > >>>> data base/ csv file, eg. height weight income etc.) to determine the > >>>> most efficient 'type' to convert the attribute coll into for further > >>>> processing and efficient storage... > >>>> Example row from sampled file data: [ ['8','2.33', 'A', 'BB', 'hello > >>>> there' '100,000,000,000'], [next row...] ....] > >>>> Aside from a missing attribute designator, we can assume that the same > >>>> type of data continues through a coll. For example, a string, int8, > >>>> int16, float etc. > >>>> 1. What is the most efficient way in python to test weather a string > >>>> can be converted into a given numeric type, or left alone if its > >>>> really a string like 'A' or 'hello'? Speed is key? Any thoughts? > >>>> 2. Is there anything out there already which deals with this issue? > >>>> Thanks, > >>>> Conor > >>> You might try investigating what can generate your data. With luck, > >>> it could turn out that the data generator is methodical and column > >>> data-types are consistent and easily determined by testing the > >>> first or second row. At worst, you will get to know how much you > >>> must check for human errors. > >> Here you go, Paddy, the following has been generated very methodically; > >> what data type is the first column? What is the value in the first > >> column of the 6th row likely to be? > > >> "$39,082.00","$123,456.78" > >> "$39,113.00","$124,218.10" > >> "$39,141.00","$124,973.76" > >> "$39,172.00","$125,806.92" > >> "$39,202.00","$126,593.21" > > >> N.B. I've kindly given you five lines instead of one or two :-) > > >> Cheers, > >> John > > > John, > > I've had cases where some investigation of the source of the data has > > completely removed any ambiguity. I've found that data was generated > > from one or two sources and been able to know what every field type is > > by just examining a field that I have determined wil tell me the > > source program that generated the data. > > The source program that produced my sample dataset was Microsoft Excel > (or OOo Calc or Gnumeric); it was induced to perform a "save as CSV" > operation. Does that help you determine the true nature of the first column? > > > > > I have also found that the flow generating some data is subject to > > hand editing so have had to both put in extra checks in my reader, and > > on some occasions created specific editors to replace hand edits by > > checked assisted hand edits. > > I stand by my statement; "Know the source of your data", its less > > likely to bite! > > My dataset has a known source, and furthermore meets your "lucky" > criteria (methodically generated, column type is consistent) -- I'm > waiting to hear from you about the "easily determined" part :-) > > Cheers, > John John, Open up your Excel spreadsheet and check what the format is for the column. It's not a contest. If you KNOW what generated the data then USE that knowledge. It would be counter-productive to do otherwise surely? (I know, don't call you Shirley :-) - Paddy. From manstey at csu.edu.au Sun May 20 20:55:52 2007 From: manstey at csu.edu.au (manstey) Date: 20 May 2007 17:55:52 -0700 Subject: list modification subclassing Message-ID: <1179708952.464667.47020@y18g2000prd.googlegroups.com> Hi, I have a simple subclass of a list: class CaListOfObj(list): """ subclass of list """ def __init__(self, *args, **kwargs): list.__init__(self, *args, **kwargs) a= CaListOfObj([1,2,3]) How do I write a method that does something EVERY time a is modified? Thanks From whamil1 at entergy.com Tue May 1 08:18:12 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Tue, 1 May 2007 07:18:12 -0500 Subject: re-importing modules In-Reply-To: Message-ID: <588D53831C701746A2DF46E365C018CE01D2CA83@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 John Nagle > Sent: Monday, April 30, 2007 7:32 PM > To: python-list at python.org > Subject: Re: re-importing modules > > kyosohma at gmail.com wrote: > > >>In addition to the warning that reload() does not recursively reload > >>modules that the reloaded module depends on, be warned that reloading a > >>module does not magically affect any functions or objects from the old > >>version that you may be holding on to. > > Maybe reloading modules should be deprecated. The semantics > are awful, and it interferes with higher-performance implementations. > I'd rather it weren't, personally. I'm using Python with a third-party application that provides an interactive prompt. Removing reload() would mean spending a good three minutes waiting for the application to restart any time I make the slightest change in a module supporting that application. --- -Bill Hamilton From johnmasters at oxtedonline.net Sun May 13 13:51:41 2007 From: johnmasters at oxtedonline.net (John K Masters) Date: Sun, 13 May 2007 18:51:41 +0100 Subject: GUI tutorial Message-ID: <20070513175141.GD4044@spookie1.spookiegate> Can someone point me in the direction of a good tutorial on programming python with a GUI? I'm just starting out with python and have written a few scripts successfully but would like to add a graphical front end to them to make it easier for my work colleagues, most of whom have never used a command line, to use. Regards, John -- War is God's way of teaching Americans geography Ambrose Bierce (1842 - 1914) From shandy.b at gmail.com Tue May 29 13:27:25 2007 From: shandy.b at gmail.com (shandy.b at gmail.com) Date: 29 May 2007 10:27:25 -0700 Subject: How to set a class inheritance at instance creation? In-Reply-To: <1180453971.556244.91370@q69g2000hsb.googlegroups.com> References: <1180453971.556244.91370@q69g2000hsb.googlegroups.com> Message-ID: <1180459645.803360.271750@r19g2000prf.googlegroups.com> Why not just have Lang1 and Lang2 inherit from WriteStruct as well? On May 29, 8:52 am, glomde wrote: > Hi I wonder if you can set what subclass a class should > have at instance creation. > > The problem is that I have something like: > > class CoreLang(): > def AssignVar(self, var, value): > pass > > class Lang1(CoreLang): > def AssignVar(self, var, value): > return var, "=", value > > class Lang2(CoreLang): > def AssignVar(self, var, value): > return var, "<=", value > > class WriteStruct(): > def Generate(self, vars): > for var in vars: > print self.AssignVar() > > The problem is that I want WriteStruct to sometimes be a subclass of > Lang1 and sometimes > of Lang2. > In the above example I could but the Generate Method in CoreLang. But > in my real > example I also want to able to subclass WriteStruct to be able to easy > customize WriteStruct. > Which I wouldnt be able to do if it was a method in CoreLang. > > So in code I would like to write something like: > > WriteStruct(Lang1).Generate(vars) > > Even better would be that if I in the Lang1 class could > just do WriteStruct().Generate(vars) and Lang1 class would > magically make WriteStruct a subclass of itself. > > Cheers, > > /T From gagsl-py2 at yahoo.com.ar Tue May 29 13:21:11 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 29 May 2007 14:21:11 -0300 Subject: Storing tracebacks References: <1180410412.643608.30050@q66g2000hsg.googlegroups.com> <1180446376.879439.55840@m36g2000hse.googlegroups.com> <1180457469.296553.291590@x35g2000prf.googlegroups.com> Message-ID: En Tue, 29 May 2007 13:51:09 -0300, George Sakkis escribi?: > The traceback module is handy if you want a text representation of the > traceback, not the actual traceback. The reason I want to store the > actual traceback is to make the exception transparent to the user, > i.e. not be able to tell whether the exception was thrown in the > current stack frame or in another thread or even process. > Unfortunately tracebacks are not pickleable, otherwise I could just > pickle them in process() and unpickle them in result(). A traceback contains a linked list of frames, each with its own globals and locals and lot of context info. I'm not sure that moving a traceback across processes has any sense; a textual representation should be enough, as t.b. are usually a debugging aid and not supposed to reach the final user. -- Gabriel Genellina From edoherty at darwinpartners.com Mon May 14 10:32:32 2007 From: edoherty at darwinpartners.com (Erin) Date: 14 May 2007 07:32:32 -0700 Subject: deployment scripts Message-ID: <1179153152.824262.146460@k79g2000hse.googlegroups.com> Does anyone have experience developing deployment scripts with Jython? From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed May 23 03:24:11 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 23 May 2007 09:24:11 +0200 Subject: Can I reference 1 instance of an object by more names ? In-Reply-To: References: Message-ID: <4653ec05$0$2422$426a74cc@news.free.fr> Stef Mientki a ?crit : > hello, > > I'm trying to build a simple functional simulator for JAL (a Pascal-like > language for PICs). > My first action is to translate the JAL code into Python code. > The reason for this approach is that it simplifies the simulator very much. > In this translation I want to keep the JAL-syntax as much as possible > intact, > so anyone who can read JAL, can also understand the Python syntax. > > One of the problems is the alias statement, assigning a second name to > an object. > I've defined a class IO_port, > and I create an instance of that port with the name port_D > > port_D = IO_port('D') > > Now I want to assign a more logical name to that port, > (In JAL: "var byte My_New_Name IS port_D") > > Is that possible ? > > I think the answer is "no", > because the object itself is not mutable. > Am I right ? You're wrong. The fact that an object is mutable or not is totally irrelevant here. In Python, 'variables' are in fact name=>ref_to_object pairs in a namespace (while this may not always be technically true, you can think of namespaces as dicts). So the name is nothing more than this: a name. And you can of course bind as many names as you want to a same object. port_D = IO_port('D') foo = port_D bar = foo bar is port_D => True From tmp123 at menta.net Thu May 3 10:14:04 2007 From: tmp123 at menta.net (tmp123) Date: 3 May 2007 07:14:04 -0700 Subject: newbie: copy base class fields Message-ID: <1178201644.920048.205400@y5g2000hsa.googlegroups.com> Hello, Thanks for your time. The following small program gives an error: #!/usr/bin/python # class A: def __init__(self): self.v1=1 def __repr__(self): return "v1=%d\n" % self.v1 class B(A): def __init__(self,a): self=a self.v2=2 def __repr__(self): return A.__repr__(self) + ("v2=%d\n" % self.v2) x=A() print x y=B(x) print y $ ./prueba.pl v1=1 Traceback (most recent call last): File "./prueba.pl", line 23, in print y File "./prueba.pl", line 17, in __repr__ return A.__repr__(self) + ("v2=%d\n" % self.v2) File "./prueba.pl", line 9, in __repr__ return "v1=%d\n" % self.v1 AttributeError: B instance has no attribute 'v1' It seems that the statement "self=a" is not the correct way to copy all the fields of the base class from the __init__ argument to the new object. Of course, it is not an option to copy one by one all the fields of class A inside the __init__ of B. Several variants of the program produces similar results. Please, could someone explain which way is the correct way? Thanks a lot. From stefan.behnel-n05pAM at web.de Tue May 15 11:41:25 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 15 May 2007 17:41:25 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179242328.800088.246620@h2g2000hsg.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649BC4C.10200@web.de> <1179238847.407605.4620@w5g2000hsg.googlegroups.com> <4649C63C.1030508@web.de> <1179242328.800088.246620@h2g2000hsg.googlegroups.com> Message-ID: <4649D4A5.5060102@web.de> Paul Boddie wrote: > On 15 May, 16:39, Stefan Behnel wrote: >> It's difficult to extract this analysis from Java. Most people I know from the >> Java world do not use this feature as it is error prone. Java does not have >> support for *explicit* source encodings, i.e. the local environment settings >> win. This is bound to fail e.g. on a latin-1 system where I would like to work >> with UTF-8 files (which tend to work better on the Unix build server, etc.) > > Here's a useful link on this topic: > > http://www.jorendorff.com/articles/unicode/java.html This is what I meant (quote from your link): """ When you compile this program with the command javac Hallo.java, the compiler does not know the encoding of the source file. Therefore it uses your platform's default encoding. You might wish to tell javac which encoding to use explicitly, instead. Use the -encoding option to do this: javac -encoding Latin-1 Hallo.java . If you do not specify the right encoding, javac will be confused and may or may not generate a lot of syntax errors as a result. """ >From a Python perspective, I would rather call this behaviour broken. Do I really have to pass the encoding as a command line option to the compiler? I find Python's source encoding much cleaner here, and even more so when the default encoding becomes UTF-8. Stefan From afaNOSPAM at neuf.fr Sun May 6 17:06:58 2007 From: afaNOSPAM at neuf.fr (Amaury Forgeot d'Arc) Date: Sun, 06 May 2007 23:06:58 +0200 Subject: c macros in python. In-Reply-To: <1178485280.394666.51970@n76g2000hsh.googlegroups.com> References: <1178485280.394666.51970@n76g2000hsh.googlegroups.com> Message-ID: noagbodjivictor at gmail.com a ?crit : > Hey, > > I'm writing a script to generate code. I'm a bit tired of typing > outfile.write(....). Does python have a way to c-like macros? Every > instance of o(...) in the code will be replaced by outfile.write(...)? First: Python has no macro facility. But in this particular case, it is very simple. Just add: o = outfile.write after the variable outfile is initialized. It is not a macro (just another name for a function object) but it looks the same... -- Amaury From aleax at mac.com Fri May 4 22:35:55 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 4 May 2007 19:35:55 -0700 Subject: Further adventures in array slicing. References: Message-ID: <1hxlsuz.1f2rb1du9xibyN%aleax@mac.com> Steven W. Orr wrote: ... > I need to unpack this into three seperate arrays called name, fields, > valid. The old code looked like this: You're using lists, not arrays. If you DID want arrays, you'd have to import standard library module array, and you'd be limited to a few elementary types as items; it's pretty obvious that this is not what you want -- nevertheless, why use the wrong name? > names = []; fields = []; valid = [] > for ii in mdict: > names.append(mdict[ii]['name']) > fields.append(mdict[ii]['fields']) > valid.append(mdict[ii]['valid']) The order of keys in dictionary mdict is totally arbitrary, therefore the order of items in those lists is going to be equally arbitrary; you sure you _want_ that? Normally order IS significant in lists. > I was very pleased with myself, except that the real world example of > 'fields' and 'valid' is that they can be (but not always) a sequence. Why would that make any difference at all? > e.g., > > mdefs = {0:{'name': 'Hello0', > 'fields':(('Address', 8), > ('Control', 8)), > 'valid': {'Address': (1,255), > 'Control': (33,44)}}, > 1:{'name': 'Hello1', > 'fields':'fields1', > 'valid': 'valid1'}, > 2:{'name': 'Hello2', > 'fields':'fields2', > 'valid': 'valid2'}} > > Is there a way to do this with possibly a more concise technique than the > first for loop above? not by much: names = [v['name'] for v in mdict.itervalues()] fields = [v['fields'] for v in mdict.itervalues()] valid = [v['valid'] for v in mdict.itervalues()] but this just saves a few characters, if that. Alex From cesar.gomes at gmail.com Sat May 12 14:01:50 2007 From: cesar.gomes at gmail.com (Cesar G. Miguel) Date: 12 May 2007 11:01:50 -0700 Subject: Basic question In-Reply-To: <1178991933.421386.58500@u30g2000hsc.googlegroups.com> References: <1178986686.510137.195490@p77g2000hsh.googlegroups.com> <1178991933.421386.58500@u30g2000hsc.googlegroups.com> Message-ID: <1178992910.318929.77790@e51g2000hsg.googlegroups.com> On May 12, 2:45 pm, Basilisk96 wrote: > On May 12, 12:18 pm, "Cesar G. Miguel" wrote: > > > > > I've been studying python for 2 weeks now and got stucked in the > > following problem: > > > for j in range(10): > > print j > > if(True): > > j=j+2 > > print 'interno',j > > > What happens is that "j=j+2" inside IF does not change the loop > > counter ("j") as it would in C or Java, for example. > > > Am I missing something? > > > []'s > > Cesar > > What is your real intent here? This is how I understand it after > reading your post: you want to create a loop that steps by an > increment of 2. If that's the case, then: > > >>> for j in range(0,10,2): > > ... print j > ... > 0 > 2 > 4 > 6 > 8 > > would be a simple result. > > Cheers, > -Basilisk96 Actually I'm trying to convert a string to a list of float numbers: str = '53,20,4,2' to L = [53.0, 20.0, 4.0, 2.0] As some of you suggested, using while it works: ------------------------------------- L = [] file = ['5,1378,1,9', '2,1,4,5'] str='' for item in file: j=0 while(j= len(item)): break if(str != ''): L.append(float(str)) str = '' j=j+1 print L ------------------------------------- But I'm not sure this is an elegant pythonic way of coding :-) Thanks for all suggestions! From steve at REMOVEME.cybersource.com.au Thu May 3 23:00:52 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Fri, 04 May 2007 13:00:52 +1000 Subject: How do I import a variable from another module? References: <1178242032.254096.316860@o5g2000hsb.googlegroups.com> Message-ID: On Thu, 03 May 2007 18:27:12 -0700, noagbodjivictor wrote: > I have a variable names actions in a module named qt_actions.py > > Well this is what I get: >>>> import qt_actions >>>> qt_actions.actions > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'module' object has no attribute 'actions' The error is clear -- you *don't* have an attribute named actions in the module. I'm going to guess that you've imported the module, then edited it, then imported it again. That doesn't help, because imported modules are cached. You need to reload(qt_actions). Either that, or you've got two modules named qt_actions, and only one of them has a variable 'actions'. The first module in the PYTHONPATH is imported. Or, you're mistaken about having such a variable. But my money is on the first one. Use reload(qt_actions). -- Steven D'Aprano From Glich.Glich at googlemail.com Thu May 17 15:47:28 2007 From: Glich.Glich at googlemail.com (Glich) Date: 17 May 2007 12:47:28 -0700 Subject: FreeType In-Reply-To: References: <1179422948.600593.117310@p77g2000hsh.googlegroups.com> Message-ID: <1179431247.954420.219690@q75g2000hsh.googlegroups.com> I've been there. All the code is in C/C++, don't I need it in python? I will explore the software. I dismissed this because there was no python. I am knew to all of this. Thanks for your reply. From collver at peak.org Thu May 3 09:49:26 2007 From: collver at peak.org (Ben Collver) Date: Thu, 03 May 2007 06:49:26 -0700 Subject: My Python annoyances In-Reply-To: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> Message-ID: I rewrote my code in Python and I found myself running into many of the same hassles that I run into with other languages: inaccurate and incomplete documentation, a maze of little platform-specific quirks to work around in the base classes, and a macho community of users. The python web site recommended Dive Into Python, so I learned by reading that. It has several examples that don't work because the Python base classes have changed behavior. I should have taken that as lesson. I tried to write portable Python code. The zlib CRC function returned different results on architectures between 32 bit and 64 bit architectures. I filed a bug report. It was closed, without a comment from the person who closed it. I get the unspoken message: bug reports are not welcome. I installed Cygwin on a Windows machine. I try to quit from an interactive Python session. It tells me that on my platform, I must press Control-Z to exit. I press Control-Z and it makes Python a background process. I tried to use the XML.minidom. The documentation here is minimal as well. So I read up on other web sites. It turns out that the interface has changed quite a bit from the documentation I found on other web sites. Where are the much loved docstrings? In 2.3 minidom, they are sparse and cryptic. Between 2.4 and 2.5, tempfile returns a different type of object. My code cannot have a single test, it has check for type(obj) == file or obj.__class__ == tempfile._TemporaryFileWrapper. I decided to make a tkinter front-end for a Python program. I decided to go with tkinter because it is included with many Python installations, so it maximizes the chance for my program to run out of the box. The tkinter documentation on the Python site mainly consists of loose notes and links to other sites. The documentation on other sites is great, if you already know how to use tkinter. I ran into bugs in TkAqua which make the grid layout unusable for me. So I will need to ask potential users to install Xcode, X11, and mac ports, if they want to run my program. In short, there is plenty of room for improvement. Admittedly these are not problems with the language definition. But I downloaded a Python distribution, and the problems are Python specific. From p.lavarre at ieee.org Thu May 31 17:33:32 2007 From: p.lavarre at ieee.org (p.lavarre at ieee.org) Date: 31 May 2007 14:33:32 -0700 Subject: FAQ: how to vary the byte offset of a field of a ctypes.Structure In-Reply-To: References: <1180634138.944362.88590@d30g2000prg.googlegroups.com> Message-ID: <1180647212.148062.321780@a26g2000pre.googlegroups.com> ctypes.sizeof(a) is still zero, as if ctypes.Structure.__init__ fetches a.__class__._fields_ rather than a._fields_ From klaus at seistrup.dk Tue May 8 11:40:14 2007 From: klaus at seistrup.dk (Klaus Alexander Seistrup) Date: Tue, 8 May 2007 15:40:14 +0000 (UTC) Subject: sys.path References: <1178638540.056691.161750@e65g2000hsc.googlegroups.com> Message-ID: HMS Surprise wrote: > Have I misused .extend? The .extend() method expects an iterable, try .append() instead. Cheers, -- Klaus Alexander Seistrup http://klaus.seistrup.dk/ From kinch1967 at gmail.com Sat May 19 20:20:57 2007 From: kinch1967 at gmail.com (bullockbefriending bard) Date: 19 May 2007 17:20:57 -0700 Subject: regex matching question In-Reply-To: References: <1179595319.239229.262160@l77g2000hsb.googlegroups.com> <1179614439.044253.141170@u30g2000hsc.googlegroups.com> Message-ID: <1179620457.129066.47980@l77g2000hsb.googlegroups.com> > Here "all pairs different" means "for each pair, both numbers must be > different", but they may appear in another pair. That is, won't flag > "1,2/3,4/3,5/2,6/8,3/1,2" as invalid, but this wasn't clear from your > original post. > > -- > Gabriel Genellina thanks! you are correct that the 'all pairs different' nomenclature is ambiguous. i require that each pair have different values, but is OK for different pairs to be identical... so exactly as per your code snippet. From ramashish.lists at gmail.com Tue May 29 02:33:50 2007 From: ramashish.lists at gmail.com (Ramashish Baranwal) Date: 28 May 2007 23:33:50 -0700 Subject: Periodic tasks. Message-ID: <1180420430.610215.96330@a26g2000pre.googlegroups.com> Hi, I am trying to execute some tasks periodically, those familiar with unix can think of it as equivalent to cron jobs. I have tried looking around, but couldn't find a way. Would appreciate any pointers or clues.. Thanks, -Ram From donn at u.washington.edu Thu May 24 13:10:15 2007 From: donn at u.washington.edu (Donn Cave) Date: Thu, 24 May 2007 10:10:15 -0700 Subject: 0 == False but [] != False? References: <1179982400.412340.178710@g4g2000hsf.googlegroups.com> <1179983482.452458.188690@q66g2000hsg.googlegroups.com> Message-ID: In article <1179983482.452458.188690 at q66g2000hsg.googlegroups.com>, Paul McGuire wrote: > This has *got* to rank up there among the VFAQ's of them all, along > with the mysterious shared default empty list argument. I think this > particular question has been asked in one form or another at least > twice a week for the past month! Anyone who finds this surprising, might enjoy reading this article from the time several years ago when the feature was being considered. When you have some time - it's long, but interesting. The present confusion is more directly addressed towards the end. Yes, it's the Laura Creighton article again: http://groups.google.com/group/comp.lang.python/msg/2de5e1c8384c0360 Donn Cave, donn at u.washington.edu From raffaelcavallaro at pas-d'espam-s'il-vous-plait-mac.com Sat May 5 11:13:50 2007 From: raffaelcavallaro at pas-d'espam-s'il-vous-plait-mac.com (Raffael Cavallaro) Date: Sat, 5 May 2007 11:13:50 -0400 Subject: Lisp for the C21 References: <1178155239.007219.205020@y5g2000hsa.googlegroups.com> <1178219732.127815.3260@y80g2000hsf.googlegroups.com> <1178269626.886617.214390@u30g2000hsc.googlegroups.com> <7x1whwwqo1.fsf@ruckus.brouhaha.com> Message-ID: <2007050511135016807-raffaelcavallaro@pasdespamsilvousplaitmaccom> On 2007-05-04 11:32:14 -0400, Paul Rubin said: > Anyone who didn't love lisp in the 20th century has no heart. > Anyone who still loves it in the 21st, has no head. By the same logic we should all be conservative Republicans. Given this implication, I'll stick with lisp, thanks. From tuom.larsen at gmail.com Thu May 10 14:25:12 2007 From: tuom.larsen at gmail.com (tuom.larsen at gmail.com) Date: 10 May 2007 11:25:12 -0700 Subject: Thread-safe dictionary In-Reply-To: References: Message-ID: <1178821512.229872.98120@n59g2000hsh.googlegroups.com> On May 10, 3:57 pm, Duncan Booth wrote: > IMHO you are probably best to write a thread-safe class which uses an > ordinary dict (and has a nicely limited interface) rather than trying to > produce a completely thread-safe dict type. thanks, sounds good! but that again: from __future__ import with_statement class safe_dict(dict): def __init__(self): self.lock = threading.Lock() self.d = {} def __getitem__(self, key): with self.lock: return self.d[key] def __setitem__(self, key, value): with self.lock: self.d[key] = value def __delitem__(self, key): with self.lock: del self.d[key] - in __getitem__, does it release the lock after returning the item? - wouldn't it be better to use threading.RLock, mutex, ... instead? From steve at holdenweb.com Thu May 17 10:40:34 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 17 May 2007 10:40:34 -0400 Subject: Trying to choose between python and java In-Reply-To: <1179381218.041519.93220@u30g2000hsc.googlegroups.com> References: <1179381218.041519.93220@u30g2000hsc.googlegroups.com> Message-ID: sjdevnull at yahoo.com wrote: > Cameron Laird wrote: >> In article , >> Terry Reedy wrote: >>> "Anthony Irwin" wrote in message >>> news:f2bghg$4q0$1 at news-01.bur.connect.com.au... >> . >> . >> . >>> | #5 someone said that they used to use python but stopped because the >>> | language changed or made stuff depreciated (I can fully remember >>> | which) and old code stopped working. Is code written today likely to >>> | still work in 5+ years or do they depreciate stuff and you have to >>> update? >>> >>> Most versions of Python are still available. You are free to use and >>> distribute your copies indefinitely. Several older versions are still in >>> use. >>> >>> Recent releases have added features but removed very little except bugs. >>> Unfortunately, bug removal sometimes breaks code. And feature additions >>> occasionally introduce bugs or otherwise break code, but that is why there >>> are alpha, beta, and candidate releases before a final release. >>> >>> Python3 will remove many things at once. A conversion tool is being >>> written. And there is no expectation that production code should be >>> immediately converted, if ever. >> . >> . >> . >> I'll answer even more aggressively: Python's record of >> backward compatibility is *better* than Java's. > > Although I objected earlier to the statement that Python has never had > a release breaking backward compatibility, I agree 100% with this--the > times that Python has broken backward compatibility have been preceded > by several releases of deprecation warnings. Java on several > occasions has simply broken working code in a new release with no > warning. I wouldn't be shocked if Python has done the same, but I've > never run into it in my code. > Ask the Twisted guys - they mentioned when 2.5 was released that several of their unit tests broke. Just the same, I do think Python's compatibility record is 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From sjmachin at lexicon.net Sun May 27 03:11:12 2007 From: sjmachin at lexicon.net (John Machin) Date: 27 May 2007 00:11:12 -0700 Subject: PyPI bdist_wininst upload failing In-Reply-To: References: Message-ID: <1180249872.007145.48030@a26g2000pre.googlegroups.com> On May 27, 4:20 pm, Steven Bethard wrote: > Steven Bethard wrote: > > I just tried to upload new versions of the argparse module to PyPI, but > > it seems like I can no longer upload Windows installers: [snip] > That seems a little weird to me. Are the bdist_wininst exe files really > zip files? Or did I just misunderstand what "content" is? > > STeVe They are exe files with a zip appended. Try out the above code on your file; it may just help you suss out what the problem is. E.g.: >>> import zipfile >>> zipfile.ZipFile('xlrd-0.6.1a4.win32.exe').namelist() ['PURELIB/xlrd-0.6.1a4-py2.5.egg-info', 'PURELIB/xlrd/biffh.py', ... snip ... 'SCRIPTS/xlrdnameAPIdemo.py'] >>> HTH, John From steven at REMOVE.THIS.cybersource.com.au Tue May 15 21:05:03 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 16 May 2007 01:05:03 GMT Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476081.7080609@web.de> <46476F6B.2000501@web.de> <4649844b$0$6402$9b4e6d93@newsspool2.arcor-online.net> Message-ID: On Tue, 15 May 2007 11:58:35 +0200, Ren? Fleschenberg wrote: > Unless you are 150% sure that there will *never* be the need for a > person who does not know your language of choice to be able to read or > modify your code, the language that "fits the environment best" is > English. Just a touch of hyperbole perhaps? You know, it may come to a surprise to some people that English is not the only common language. In fact, it only ranks third, behind Mandarin and Spanish, and just above Arabic. Although the exact number of speakers vary according to the source you consult, the rankings are quite stable: Mandarin, Spanish, then English. Any of those languages could equally have claim to be the world's lingua franca. And interestingly, with only one billion English speakers (as a first or second language) in the world, and 5.5 billion people who don't speak English, I think its probably fair to say that it is a small minority that speak English. -- Steven. From jiang.haiyun at gmail.com Wed May 2 07:24:27 2007 From: jiang.haiyun at gmail.com (jiang.haiyun at gmail.com) Date: 2 May 2007 04:24:27 -0700 Subject: Problem with PyQt4 In-Reply-To: <1177943540.857556.235210@y80g2000hsf.googlegroups.com> References: <1177943540.857556.235210@y80g2000hsf.googlegroups.com> Message-ID: <1178105067.551655.144700@y5g2000hsa.googlegroups.com> On Apr 30, 10:32 pm, "jiang.hai... at gmail.com" wrote: > Hi, > > I am having some serious problems with PyQT4, > when i run pyqt script, I always get 'Segmentation fault'. > > the script is simple: > ====================== > %less qttest.py > from PyQt4 import QtGui, QtCore > import sys > > if __name__ == '__main__': > app = QtGui.QApplication(sys.argv) > w = QtGui.QMainWindow() > w.show() > app.exec_() > ====================== > > When I run it , it crashes. > ====================== > %python qttest.py > Segmentation fault (core dumped) > ===================== > > And the output with '-v' argument is : > ========================= > %python -v qttest.py > # installing zipimport hook > import zipimport # builtin > # installed zipimport hook > # /usr/local/lib/python2.4/site.pyc matches /usr/local/lib/python2.4/ > site.py > import site # precompiled from /usr/local/lib/python2.4/site.pyc > # /usr/local/lib/python2.4/os.pyc matches /usr/local/lib/python2.4/ > os.py > import os # precompiled from /usr/local/lib/python2.4/os.pyc > import posix # builtin > # /usr/local/lib/python2.4/posixpath.pyc matches /usr/local/lib/ > python2.4/posixp > ath.py > import posixpath # precompiled from /usr/local/lib/python2.4/ > posixpath.pyc > # /usr/local/lib/python2.4/stat.pyc matches /usr/local/lib/python2.4/ > stat.py > import stat # precompiled from /usr/local/lib/python2.4/stat.pyc > # /usr/local/lib/python2.4/UserDict.pyc matches /usr/local/lib/ > python2.4/UserDic > t.py > import UserDict # precompiled from /usr/local/lib/python2.4/ > UserDict.pyc > # /usr/local/lib/python2.4/copy_reg.pyc matches /usr/local/lib/ > python2.4/copy_re > g.py > import copy_reg # precompiled from /usr/local/lib/python2.4/ > copy_reg.pyc > # /usr/local/lib/python2.4/types.pyc matches /usr/local/lib/python2.4/ > types.py > import types # precompiled from /usr/local/lib/python2.4/types.pyc > # /usr/local/lib/python2.4/warnings.pyc matches /usr/local/lib/ > python2.4/warning > s.py > import warnings # precompiled from /usr/local/lib/python2.4/ > warnings.pyc > # /usr/local/lib/python2.4/linecache.pyc matches /usr/local/lib/ > python2.4/lineca > che.py > import linecache # precompiled from /usr/local/lib/python2.4/ > linecache.pyc > import encodings # directory /usr/local/lib/python2.4/encodings > # /usr/local/lib/python2.4/encodings/__init__.pyc matches /usr/local/ > lib/python2 > .4/encodings/__init__.py > import encodings # precompiled from /usr/local/lib/python2.4/encodings/ > __init__. > pyc > # /usr/local/lib/python2.4/codecs.pyc matches /usr/local/lib/python2.4/ > codecs.py > import codecs # precompiled from /usr/local/lib/python2.4/codecs.pyc > import _codecs # builtin > # /usr/local/lib/python2.4/encodings/aliases.pyc matches /usr/local/ > lib/python2. > 4/encodings/aliases.py > import encodings.aliases # precompiled from /usr/local/lib/python2.4/ > encodings/a > liases.pyc > # /usr/local/lib/python2.4/encodings/gb2312.pyc matches /usr/local/lib/ > python2.4 > /encodings/gb2312.py > import encodings.gb2312 # precompiled from /usr/local/lib/python2.4/ > encodings/gb > 2312.pyc > dlopen("/usr/local/lib/python2.4/lib-dynload/_codecs_cn.so", 2); > import _codecs_cn # dynamically loaded from /usr/local/lib/python2.4/ > lib- > dynload / > _codecs_cn.so > dlopen("/usr/local/lib/python2.4/lib-dynload/_multibytecodec.so", 2); > import _multibytecodec # dynamically loaded from /usr/local/lib/ > python2.4/lib- > dy nload/ > _multibytecodec.so > Python 2.4.3 (#2, Oct 15 2006, 05:32:11) > [GCC 3.4.6 [FreeBSD] 20060305] on freebsd6 > Type "help", "copyright", "credits" or "license" for more information. > import PyQt4 # directory /usr/local/lib/python2.4/site-packages/PyQt4 > # /usr/local/lib/python2.4/site-packages/PyQt4/__init__.pyc matches / > usr/local/ > l ib/ > python2.4/site-packages/PyQt4/__init__.py > import PyQt4 # precompiled from /usr/local/lib/python2.4/site-packages/ > PyQt4/__i > nit__.pyc > dlopen("/usr/local/lib/python2.4/site-packages/PyQt4/QtGui.so", 2); > dlopen("/usr/local/lib/python2.4/site-packages/sip.so", 2); > import sip # dynamically loaded from /usr/local/lib/python2.4/site- > packages/ > sip. so > dlopen("/usr/local/lib/python2.4/site-packages/PyQt4/QtCore.so", 2); > import PyQt4.QtCore # dynamically loaded from /usr/local/lib/python2.4/ > site-pack > ages/PyQt4/QtCore.so > import PyQt4.QtGui # dynamically loaded from /usr/local/lib/python2.4/ > site-packa > ges/PyQt4/QtGui.so > Segmentation fault (core dumped) > %python -v qttest.py > # installing zipimport hook > import zipimport # builtin > # installed zipimport hook > # /usr/local/lib/python2.4/site.pyc matches /usr/local/lib/python2.4/ > site.py > import site # precompiled from /usr/local/lib/python2.4/site.pyc > # /usr/local/lib/python2.4/os.pyc matches /usr/local/lib/python2.4/ > os.py > import os # precompiled from /usr/local/lib/python2.4/os.pyc > import posix # builtin > # /usr/local/lib/python2.4/posixpath.pyc matches /usr/local/lib/ > python2.4/posixpath.py > import posixpath # precompiled from /usr/local/lib/python2.4/ > posixpath.pyc > # /usr/local/lib/python2.4/stat.pyc matches /usr/local/lib/python2.4/ > stat.py > import stat # precompiled from /usr/local/lib/python2.4/stat.pyc > # /usr/local/lib/python2.4/UserDict.pyc matches /usr/local/lib/ > python2.4/UserDict.py > import UserDict # precompiled from /usr/local/lib/python2.4/ > UserDict.pyc > # /usr/local/lib/python2.4/copy_reg.pyc matches /usr/local/lib/ > python2.4/copy_reg.py > import copy_reg # precompiled from /usr/local/lib/python2.4/ > copy_reg.pyc > # /usr/local/lib/python2.4/types.pyc matches /usr/local/lib/python2.4/ > types.py > import types # precompiled from /usr/local/lib/python2.4/types.pyc > # /usr/local/lib/python2.4/warnings.pyc matches /usr/local/lib/ > python2.4/warnings.py > import warnings # precompiled from /usr/local/lib/python2.4/ > warnings.pyc > # /usr/local/lib/python2.4/linecache.pyc matches /usr/local/lib/ > python2.4/linecache.py > import linecache # precompiled from /usr/local/lib/python2.4/ > linecache.pyc > import encodings # directory /usr/local/lib/python2.4/encodings > # /usr/local/lib/python2.4/encodings/__init__.pyc matches /usr/local/ > lib/python2.4/encodings/__init__.py > import encodings # precompiled from /usr/local/lib/python2.4/encodings/ > __init__.pyc > # /usr/local/lib/python2.4/codecs.pyc matches /usr/local/lib/python2.4/ > codecs.py > import codecs # precompiled from /usr/local/lib/python2.4/codecs.pyc > import _codecs # builtin > # /usr/local/lib/python2.4/encodings/aliases.pyc matches /usr/local/ > lib/python2.4/encodings/aliases.py > import encodings.aliases # precompiled from /usr/local/lib/python2.4/ > encodings/aliases.pyc > # /usr/local/lib/python2.4/encodings/gb2312.pyc matches /usr/local/lib/ > python2.4/encodings/gb2312.py > import encodings.gb2312 # precompiled from /usr/local/lib/python2.4/ > encodings/gb2312.pyc > dlopen("/usr/local/lib/python2.4/lib-dynload/_codecs_cn.so", 2); > import _codecs_cn # dynamically loaded from /usr/local/lib/python2.4/ > lib-dynload/_codecs_cn.so > dlopen("/usr/local/lib/python2.4/lib-dynload/_multibytecodec.so", 2); > import _multibytecodec # dynamically loaded from /usr/local/lib/ > python2.4/lib-dynload/_multibytecodec.so > Python 2.4.3 (#2, Oct 15 2006, 05:32:11) > [GCC 3.4.6 [FreeBSD] 20060305] on freebsd6 > Type "help", "copyright", "credits" or "license" for more information. > import PyQt4 # directory /usr/local/lib/python2.4/site-packages/PyQt4 > # /usr/local/lib/python2.4/site-packages/PyQt4/__init__.pyc matches / > usr/local/lib/python2.4/site-packages/PyQt4/__init__.py > import PyQt4 # precompiled from /usr/local/lib/python2.4/site-packages/ > PyQt4/__init__.pyc > dlopen("/usr/local/lib/python2.4/site-packages/PyQt4/QtGui.so", 2); > dlopen("/usr/local/lib/python2.4/site-packages/sip.so", 2); > import sip # dynamically loaded from /usr/local/lib/python2.4/site- > packages/sip.so > dlopen("/usr/local/lib/python2.4/site-packages/PyQt4/QtCore.so", 2); > import PyQt4.QtCore # dynamically loaded from /usr/local/lib/python2.4/ > site-packages/PyQt4/QtCore.so > import PyQt4.QtGui # dynamically loaded from /usr/local/lib/python2.4/ > site-packages/PyQt4/QtGui.so > Segmentation fault (core dumped) > ============================================= > > And the output of the gdb is : > =========================================== > %gdb --args python qttest.py > GNU gdb 6.1.1 [FreeBSD] > Copyright 2004 Free Software Foundation, Inc. > GDB is free software, covered by the GNU General Public License, and > you are > welcome to change it and/or distribute copies of it under certain > conditions. > Type "show copying" to see the conditions. > There is absolutely no warranty for GDB. Type "show warranty" for > details. > This GDB was configured as "i386-marcel-freebsd"...(no debugging > symbols found)... > (gdb) run > Starting program: /usr/local/bin/python qttest.py > (no debugging symbols found)...(no debugging symbols found)...(no > debugging symbols found)...(no debugging symbols found)...warning: > Unable to get location for thread creation breakpoint: generic error > [New LWP 100113] > (no debugging symbols found)...(no debugging symbols found)...[New > Thread 0x811f000 (LWP 100113)] > (no debugging symbols found)...(no debugging symbols found)...(no > debugging symbols found)... > Program received signal SIGSEGV, Segmentation fault. > [Switching to Thread 0x811f000 (LWP 100099)] > 0x2887cb6d in typeinfo name for sipQApplication () from /usr/local/lib/ > python2.4/site-packages/PyQt4/QtGui.so > (gdb) > ========================================== > > My system is FreeBSD 6.2 release, i386, all softwares were installed > from ports. > and the Qt4 examples/demos work perfectly. > > Please help me. > Thanks very much in advance. > Regards,jiang.haiyun I have rebuilded the PyQt4 from source, but the problem seems to be remaining. And I notice the notes for gettext on http://www.freshports.org/devel/gettext/: It says: "As a result of the upgrade to gettext-0.16.1, the shared library version of libintl has changed, so you will need to rebuild all ports that depend on gettext (ie: most of them, sorry): portupgrade -rf gettext " and PyQT4 have some dependence on gettext. Last night, I portupgraded gettext(it took a long time, though) and now the problem has disappeared. I tested the example script tetrix.py, it ran smoothly. Before portupgrade gettext, I have got a runtime error something like "shared library libintl.so.8 not found"(the system only has the libintl.so.6 that time) when ran PyQT4 script, and this was caused by the lower version of gettext, so I deleted it and reinstalled gettext0.16.1_1, then libintl.so.6 was replaces by libintl.so.8. But some other programs complained that they can't find libintl.so.6, so I linked libintl.so.8 to libintl.so.6. At that point, I got the preceding problem(PyQT4 script always crashes). So I think the problem may be caused by 'PyQt4' mismatches 'gettext'. And there may be a simple solution :) regards, jiang.haiyun From bbxx789_05ss at yahoo.com Thu May 3 00:52:46 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 2 May 2007 21:52:46 -0700 Subject: sqlite for mac? In-Reply-To: <1178041349.798184.268640@l77g2000hsb.googlegroups.com> References: <1177993261.572563.70370@n76g2000hsh.googlegroups.com> <1178039558.882802.214030@n59g2000hsh.googlegroups.com> <1178041349.798184.268640@l77g2000hsb.googlegroups.com> Message-ID: <1178167966.214962.211640@p77g2000hsh.googlegroups.com> > Did you install Xcode on your Mac? Yes, Xcode 2.4. From robert.rawlins at thinkbluemedia.co.uk Thu May 17 05:12:11 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Thu, 17 May 2007 10:12:11 +0100 Subject: Code Explanation Message-ID: <005f01c79863$74e8b320$5eba1960$@rawlins@thinkbluemedia.co.uk> Hello Guys, I'm currently working on a non-python project, and I'm trying to overcome a task of parsing a text file into a database and/or xml file. I've managed to find a parser example written in python, and I'm hoping to deconstruct the code methodology a bit so I can write it in another language. So I'm hoping someone can explain to me what these following bits of code are doing. lines = range(data.count("\n")) lined_data = data.split("\n") print "Read %i vendors, now processing" % data.count("(hex)") I've not used the split() function before, but it partly makes sense to me. What is that piece of code doing? 'Data' is the content of the text file, presumably the first line there is counting the number of lines in the file, but I don't get the rest of it. The rest of the code seems like a relatively simple set of loops, but it's just this splitting stuff that's got me confused. Thanks, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From luc.saffre at gmail.com Mon May 7 00:52:18 2007 From: luc.saffre at gmail.com (luc.saffre at gmail.com) Date: 6 May 2007 21:52:18 -0700 Subject: invoke user's standard mail client In-Reply-To: References: <1178266064.922925.125760@y80g2000hsf.googlegroups.com> Message-ID: <1178513538.133114.81940@p77g2000hsh.googlegroups.com> On May 6, 9:50 am, "Gabriel Genellina" wrote: > On Windows you can use MAPI. But how? I could not find any starting point. I found examples about sending mail directly, which gives me the impression that MAPI is just Microsoft's version of SMTP. This is not what I need. I need the user's client to start, so that the user may edit the message and decide herself whether she clicks on the Send button to really send it. Luc From grante at visi.com Thu May 31 10:53:51 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 31 May 2007 14:53:51 -0000 Subject: c[:]() References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> Message-ID: <135tobve86qj808@corp.supernews.com> On 2007-05-31, Warren Stringer wrote: > Oops! guess I should have tested my rather hasty complaint about executable > containers. This is nice: > > def a(): return 'b' > def b(): print 'polly! wakey wakey' > c = {} > c['a'] = b > c[a()]() #works! > > > c[a()]() is a switch statement with an amorphous selector- very handy in its > own right. But, using a() as a generator would be more expressive. This > seems to work: > > c = [a,a] > [d() for d in c] > > But that still isn't as simple or as direct as: > > c[:]() Why do you always use a _copy_ of c in your examples? As long as you're wishing, why not just c() -- Grant Edwards grante Yow! I'm meditating on at the FORMALDEHYDE and the visi.com ASBESTOS leaking into my PERSONAL SPACE!! From steve at holdenweb.com Tue May 29 07:39:26 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 29 May 2007 07:39:26 -0400 Subject: Periodic tasks. In-Reply-To: <87lkf8nfem.fsf@benfinney.id.au> References: <1180420430.610215.96330@a26g2000pre.googlegroups.com> <87lkf8nfem.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Ramashish Baranwal writes: > >> I am trying to execute some tasks periodically, those familiar with >> unix can think of it as equivalent to cron jobs. > > Can you not use cron? If not, why not? Is there an equivalent service > you can use? > >> I have tried looking around, but couldn't find a way. > > Using the services provided by the operating system would be far > preferable to re-inventing a scheduler service. > Alternatively, the user could make use of the already-existing "sched" module from the standard library. With a little threading that would do the job fine. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From gherron at islandtraining.com Wed May 2 11:25:43 2007 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 02 May 2007 08:25:43 -0700 Subject: Is it possible to determine what a function needs for parameters - In-Reply-To: <1178118792.289104.212670@l77g2000hsb.googlegroups.com> References: <1178115727.932794.100390@h2g2000hsg.googlegroups.com> <1178118792.289104.212670@l77g2000hsb.googlegroups.com> Message-ID: <4638AD77.3020700@islandtraining.com> rh0dium wrote: >> This is far more work than you need. Push an (args, kwargs) tuple into >> your arguments queue and call self.function(*args, **kwargs). >> > > No see I tried that and that won't work. > Won't work? How does it fail? > I'm assuming what you are referring to is this (effectively) > > Q.put(((),{a:"foo", b:"bar})) > > input = Q.get() > self.function( *input[0], **input[1]) > > This will obviously fail if several conditions aren't met - hence the > kludge. Am I missing something here? > > Obviously? Conditions? What conditions? We do things like this constantly, and in fact, it *does* work. Please tell us how it fails, or what is unsatisfactory about it. Gary Herron From whamil1 at entergy.com Thu May 10 13:30:35 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Thu, 10 May 2007 12:30:35 -0500 Subject: keyword checker - keyword.kwlist Message-ID: <588D53831C701746A2DF46E365C018CE01D2CA97@LITEXETSP001.etrsouth.corp.entergy.com> > From: tom at finland.com > F:\Ohjelmat\Python25\Lib\keyword.pyc That's your problem. Rename keyword.py to keywordcheck.py, and delete keyword.pyc in this directory, and it should work fine. --- -Bill Hamilton From evenprimes at gmail.com Wed May 16 13:33:08 2007 From: evenprimes at gmail.com (Chris Cioffi) Date: Wed, 16 May 2007 13:33:08 -0400 Subject: A bug in cPickle? In-Reply-To: <1179335180.786851.209900@y80g2000hsf.googlegroups.com> References: <1179335180.786851.209900@y80g2000hsf.googlegroups.com> Message-ID: On 16 May 2007 10:06:20 -0700, Victor Kryukov wrote: > Hello list, > > The following behavior is completely unexpected. Is it a bug or a by- > design feature? > > Regards, > Victor. > > ----------------- > > from pickle import dumps > from cPickle import dumps as cdumps > > print dumps('1001799')==dumps(str(1001799)) > print cdumps('1001799')==cdumps(str(1001799)) > > >>>>output:>>>> > True > False > Python 2.4 gives the same behavior on Windows: ActivePython 2.4.3 Build 12 (ActiveState Software Inc.) based on Python 2.4.3 (#69, Apr 11 2006, 15:32:42) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from pickle import dumps >>> from cPickle import dumps as cdumps >>> print dumps('1001799') == dumps(str(1001799)) True >>> print cdumps('1001799') == cdumps(str(1001799)) False >>> print cdumps('1001799') S'1001799' p1 . >>> print cdumps(str(1001799)) S'1001799' . >>> print dumps('1001799') S'1001799' p0 . >>> print dumps(str(1001799)) S'1001799' p0 . This does seem odd, at the very least. Chris -- "A little government and a little luck are necessary in life, but only a fool trusts either of them." -- P. J. O'Rourke From gagsl-py2 at yahoo.com.ar Mon May 28 04:30:25 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 28 May 2007 05:30:25 -0300 Subject: gui application on cross platform References: <1180332092.551838.258440@z28g2000prd.googlegroups.com> <1180335978.008908.51990@q69g2000hsb.googlegroups.com> <1180337330.434010.42210@z28g2000prd.googlegroups.com> Message-ID: En Mon, 28 May 2007 04:28:50 -0300, james_027 escribi?: > I am using delphi to develop gui application, and wish to make a shift > to python. here are some of my question/concern... Explore the Python wiki, specially and ChoosingGuiToolkits. Here you have and "Intelligent GUI chooser" Search previous posts on this group too as this is a recurring topic. -- Gabriel Genellina From afriere at yahoo.co.uk Mon May 21 23:07:07 2007 From: afriere at yahoo.co.uk (Asun Friere) Date: 21 May 2007 20:07:07 -0700 Subject: Types in Python (was: managed lists?) In-Reply-To: <87bqgdg0ry.fsf@benfinney.id.au> References: <87bqgdg0ry.fsf@benfinney.id.au> Message-ID: <1179803227.426771.137190@z24g2000prd.googlegroups.com> On May 22, 10:28 am, Ben Finney wrote: > "Jorgen Bodde" writes: > > Right now i have a list in a class that I export as a member > > variable to the outside world, it is a standard list (e.g. [] ) but > > I wish to have a stronger type checking when adding objects, that > > only some objects are allowed and others are not. > > This is a poor idiom in Python. The object system allows powerful > polymorphism: the only thing that your application should be checking > is if the objects *can be used* in a particular way, not that they > belong to a specific subset of the type hierarchy. And this very succintly sums up the nature of Python's polymorphism by interface (duck-typing). An understanding of this is central to groking the way typing and OO are done in python. "Jorgen Bodde" writes: > I solved it now, by using isinstance() and giving the class name as > argument to the list There may be some situations in which testing for class (or inheritance) are appropriate, however in the vast majority of cases doing so is a mistake. The object should itself know what to do in any given situation (or throw an exception if it doesn't). Similarly your program should be responding to exceptions rather than checking before hand whether its OK to go on. Instead of reaching for 'isinstance()' you should probably be using 'try : ... except: ...' > and it sometimes frustates me to no end that a wrongly given > argument explodes somewhere deep inside my application without > giving any clue why it blew up in the first place.. If by 'explode' you mean spitting out feedback (as opposed to hanging), you should find at least a few clues. At the very least, you now know one of the exceptions your code will need to handle. Asun From ramashish.lists at gmail.com Tue May 29 16:06:12 2007 From: ramashish.lists at gmail.com (Ramashish Baranwal) Date: 29 May 2007 13:06:12 -0700 Subject: SMTPAuthenticationError In-Reply-To: References: <1180457929.374281.168960@g37g2000prf.googlegroups.com> Message-ID: <1180469172.470577.185720@x35g2000prf.googlegroups.com> > > > I am trying to send a mail using smtplib. My server requires me to > > authenticate, for this I'm using SMTP.login function. However it > > fails- > > >>>> server = smtplib.SMTP(host='mail.domain', port=25) > >>>> server.login('username', 'password') > > Traceback (most recent call last): > > File "", line 1, in ? > > File "/usr/lib/python2.4/smtplib.py", line 587, in login > > raise SMTPAuthenticationError(code, resp) > > smtplib.SMTPAuthenticationError: (535, 'authorization failed > > (#5.7.0)') > > > I am sure that I am giving the correct credentials. The same works in > > Thunderbird. Am I missing something here or am I supposed to use some > > other library for this? > > > Thanks in advance, > > Ram > > Are you sure that your SMTP server uses this type of authentication? > Some SMTP servers use POP3 followed by SMTP to authenticate instead. > > use telnet to verify, this link might help. > > http://www.computerperformance.co.uk/exchange2003/exchange2003_SMTP_A... > Hi Larry, Thanks for the reply. I have worked according to the steps in the link you provided. From that it seems my server accepts base64 encoded username and password. I am able to login this way. How to give the same in smtplib? Ram From tjansson60 at gmail.com Sat May 12 13:47:47 2007 From: tjansson60 at gmail.com (Thomas Jansson) Date: 12 May 2007 10:47:47 -0700 Subject: Problems with grid() layout under tkinter In-Reply-To: <1178917599.072765.311830@u30g2000hsc.googlegroups.com> References: <1178917599.072765.311830@u30g2000hsc.googlegroups.com> Message-ID: <1178992067.781671.326600@e65g2000hsc.googlegroups.com> I found the error - some of the widgets belonged to "master" and some to "frame". So glad I found that Error - that took forever! :D Kind regards Thomas Jansson On 11 Maj, 23:06, Thomas Jansson wrote: > Dear all > > I am trying to make a small wrapper program for textbased program and > it is going well but I have one problem. Namely that I simply do not > understand how this grid thing work. I have assigned every widget a > specific placement in a grid but when I am running the program it > looks very strange. I hope you can help me. > > A example of the programhttp://tjansson.dyndns.dk/apache2-default/strange-grid.jpg > and the codehttp://tjansson.dyndns.dk/tjansson/gui.py > > Kind regards > Thomas Jansson From __peter__ at web.de Fri May 18 04:01:25 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 May 2007 10:01:25 +0200 Subject: Unusual i/o problems References: <1179325595.708882.289510@e65g2000hsc.googlegroups.com> <1179471578.531264.51220@u30g2000hsc.googlegroups.com> Message-ID: saif.shakeel at gmail.com wrote: > I am running the exe from command prompt,but i am not able to see > the error as it goes off very quickly. http://effbot.org/pyfaq/how-do-i-run-a-python-program-under-windows.htm > How do i capture the error (traceback).I tried putting an input prompt > after the expected line of error but wont work.Is there a command to > capture the error. You can redirect stderr to a file: http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx Peter From debajit1 at gmail.com Fri May 18 06:11:11 2007 From: debajit1 at gmail.com (Debajit Adhikary) Date: 18 May 2007 03:11:11 -0700 Subject: Cannot parse simple entity references using xml.sax Message-ID: <1179483071.944069.62790@q75g2000hsh.googlegroups.com> I'm writing a SAX parser using Python and need to parse XML with entity references. <> Only the last entity reference gets parsed. Why are startEntity() and endEntity() never called? I'm using the following code: http://pastie.textmate.org/62610 From Graham.Dumpleton at gmail.com Wed May 9 22:07:21 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: 9 May 2007 19:07:21 -0700 Subject: WSGI spec clarification regarding exceptions In-Reply-To: <1178749576.268576.146770@l77g2000hsb.googlegroups.com> References: <1178749576.268576.146770@l77g2000hsb.googlegroups.com> Message-ID: <1178762841.198053.303110@y80g2000hsf.googlegroups.com> On May 10, 8:26 am, Adam Atlas wrote: > I'm trying to figure out if there's any defined behaviour in PEP 333 > for instances where an application returns an iterable as usual > without error, but that iterable's next() method eventually raises an > exception. Since any data theretofore returned by the iterable must be > assumed to have already been written to the client, thus making it > impossible to replace the response with a 500 error or somesuch, does > the gateway just absorb the exception and cut off the response there? > It seems like that's pretty much all it could do, but I'm wondering if > that's explicitly specified anywhere (I couldn't find anything about > that in the PEP). Because the WSGI specification requires that a WSGI adapter for a web server always explicitly perform a flush after each string yielded from the iterator then simply cutting off the response at that point is all one can do as the first time a flush is done any response status and headers will also have to be written out. Now depending on the web server being used, all the client may see is the truncated page, or it might also see some form of error page appended to it by the underlying web server. For example, in Apache, if the WSGI adapter returns HTTP_INTERNAL_SERVER_ERROR back to the server, the server disregards whether anything has already been sent and tries to generate a 500 error page. Since the response status and headers have already been flushed though, the original status is received by the client, but the Apache error page content is still sent. Thus you might get output looking like: Hello World! 200 OK

OK

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator, you at example.com and inform them of the time the error occurred, and anything you might have done that may have caused the error.

More information about this error may be available in the server error log.


Apache/2.2.2 (Unix) mod_wsgi/1.0-TRUNK Python/2.3.5 Server at localhost Port 8002
It is actually hard to know what to do here. There are ways one could stop the appending of the error page content, but is returning just the truncated page any better. At least the error page content in there highlights an issue even if status wasn't 500, but then not being 500, the page content could get cached. This is where one wanders whether the WSGI way of always flushing is a good idea. It may be better to always use buffering unless one specifically knows that one wants to do streaming of data where size could be large or take some time to produce. Anyway, for WSGI matters, you are probably better off bringing them up on the Python WEB-SIG list. http://www.python.org/community/sigs/current/web-sig/ Graham From horpner at yahoo.com Fri May 25 09:05:42 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Fri, 25 May 2007 13:05:42 GMT Subject: just a bug (was: xml.dom.minidom: how to preserve CRLF's inside CDATA?) References: <1179841504.782279.86490@u36g2000prd.googlegroups.com> <1180082137.329142.45350@p77g2000hsh.googlegroups.com> Message-ID: On 2007-05-25, Richard Brodie wrote: > > "Marc 'BlackJack' Rintsch" wrote in message > news:pan.2007.05.25.09.45.22.373437 at gmx.net... > >> How did you verified that it is well formed? > > It appears to have a more fundamental problem, which is > that it isn't correctly encoded (presumably because the > CDATA is truncated in mid-character). I'm surprised > Mozilla lets it slip by. Web browsers are in the very business of reasonably rendering ill-formed mark-up. It's one of the things that makes implementing a browser take forever. ;) -- Neil Cerutti Potluck supper: prayer and medication to follow. --Church Bulletin Blooper From jeremy+complangpython at jeremysanders.net Thu May 24 03:59:53 2007 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Thu, 24 May 2007 08:59:53 +0100 Subject: ANN: Veusz-0.99.0 - a scientific plotting package Message-ID: I am pleased to announce a new beta of a largely rewritten Veusz plotting package. This now uses Qt4 and numpy, adding support for Windows. Windows and Linux binaries are provided. For details see below: Veusz 0.99.0 (new Qt4/numpy beta) ------------ Velvet Ember Under Sky Zenith ----------------------------- http://home.gna.org/veusz/ Veusz is Copyright (C) 2003-2007 Jeremy Sanders Licenced under the GPL (version 2 or greater). Veusz is a scientific plotting package written in Python, using PyQt4 for display and user-interfaces, and numpy for handling the numeric data. Veusz is designed to produce publication-ready Postscript/PDF output. The user interface aims to be simple, consistent and powerful. Veusz provides a GUI, command line, embedding and scripting interface (based on Python) to its plotting facilities. It also allows for manipulation and editing of datasets. Changes from 0.10: This is the first release of a much rewritten version of Veusz It has been updated to run under Qt4 and numpy, and now supports Windows The user interface is also signficantly easier to use Other useful features include: * Colorbars for images (better color scaling for images too) * Grids of graphs with different sized subgraphs * Much better import dialog * Antialiased screen output * Native PNG and PDF export * Separate formatting/properties dialog * Handling of INF/NaN in input data * Transparency of graphs (not for EPS output) Plus many more useful changes (see ChangeLog) Features of package: * X-Y plots (with errorbars) * Line and function plots * Contour plots * Images (with colour mappings and colorbars) * Stepped plots (for histograms) * Fitting functions to data * Stacked plots and arrays of plots * Plot keys * Plot labels * LaTeX-like formatting for text * EPS/PDF/PNG export * Scripting interface * Dataset creation/manipulation * Embed Veusz within other programs * Text, CSV and FITS importing Requirements: Python (2.3 or greater required) http://www.python.org/ Qt >= 4.1 (free edition) http://www.trolltech.com/products/qt/ PyQt >= 4.1 (SIP is required to be installed first) http://www.riverbankcomputing.co.uk/pyqt/ http://www.riverbankcomputing.co.uk/sip/ numpy >= 1.0 http://numpy.scipy.org/ Microsoft Core Fonts (recommended for nice output) http://corefonts.sourceforge.net/ PyFITS >= 1.1rc3 (optional for FITS import) http://www.stsci.edu/resources/software_hardware/pyfits For documentation on using Veusz, see the "Documents" directory. The manual is in pdf, html and text format (generated from docbook). Issues: * This is a new beta, so there are likely to be a number of bugs, even though it has been used by a couple of people for some time. * Can be very slow to plot large datasets if antialiasing is enabled. Right click on graph and disable antialias to speed up output. * Some older versions of Qt (<4.2.2) can produce very large postscript output and random crashes. This may not be completely resolved (especially on windows). * The embedding interface appears to crash on exiting. If you enjoy using Veusz, I would love to hear from you. Please join the mailing lists at https://gna.org/mail/?group=veusz to discuss new features or if you'd like to contribute code. The latest code can always be found in the SVN repository. Jeremy Sanders From cbtube03 at gmail.com Sat May 12 16:23:30 2007 From: cbtube03 at gmail.com (cbtube03 at gmail.com) Date: 12 May 2007 13:23:30 -0700 Subject: package rating system for the Cheese Shop In-Reply-To: References: <1178995430.511788.161150@e51g2000hsg.googlegroups.com> Message-ID: <1179001410.386588.35730@e51g2000hsg.googlegroups.com> On May 12, 2:49 pm, Steven Bethard wrote: > cbtub... at gmail.com wrote: > > Is there a package rating system for the Cheese Shop, like how Perl > > has cpanratings (http://cpanratings.perl.org/)? > > I don't know CPAN, but maybe this is what you're looking for: > > http://www.cheeserater.com/ > > ? > > STeVe Thanks for the link STeVe. Yes, this is the sort of thing I was looking for. Looks like there's no way to actually leave comments on a package though; just a (+) or (-) rating. No way to say something like, "I like x, y, and z about this package, but n, m, and especially o need to get fixed" though. One strength of cpanratings is you can leave those comments. A well- written review comment, like "I used this package, and here's how it worked out ... If you need , you might try instead of this one." is much more valuable than a thumbs-up or thumbs-down. From exarkun at divmod.com Tue May 15 16:32:53 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 15 May 2007 16:32:53 -0400 Subject: Moving class used in pickle In-Reply-To: Message-ID: <20070515203253.30678.36051646.divmod.quotient.599@ohm> On Tue, 15 May 2007 13:23:29 -0600, Jeffrey Barish wrote: >I have a class derived from string that is used in a pickle. In the new >version of my program, I moved the module containing the definition of the >class. Now the unpickle fails because it doesn't find the module. I was >thinking that I could make the unpickle work by putting a copy of the >module in the original location and then redefine the class by sticking a >__setstate__ in the class thusly: > >def __setstate__(self, state): > self.__dict__.update(state) > self.__class__ = NewClassName > >My plan was to specify the new location of the module in NewClassName. >However, when I do this I get the message "'class' object layout differs >from 'class'". I don't think that they do as the new module is a copy of >the old one. I suspect that I am not allowed to make the class assignment >because my class is derived from string. What is the best way to update >the pickle? The only thought I have is to read all the data with the old >class module, store the data in some nonpickle format, and then, with >another program, read the nonpickle-format file and rewrite the pickle with >the class module in the new location. This is one of the reasons pickle isn't very suitable for persistence of data over a long period of time: no schema (and so no schema upgrades), and few tools for otherwise updating old data. For your simple case, you can just make sure the module is still available at the old name. This will allow pickle to find it when loading the objects and automatically update the data to point at the new name when the object is re-pickled. This doesn't give you any straightforward way to know when the "upgrade" has finished (but maybe you can keep track of that in your application code), and you need to keep the alias until all objects have been updated. For example, if you had a/b.py and you renamed it to a/c.py, then you can do one of two things: in a/__init__.py, add a 'from a import b as c'. Now a.b is the same object as a.c, but if you have a class defined in a/c.py and you access it via a.b, it will still "prefer" a.c (ie, its __module__ will be 'a.c', not 'a.b'); alternatively you can have b.py and import the relevant class(es) from c.py into it - 'from a.c import ClassA'. You could also build a much more complex system in the hopes of being able to do real "schema" upgrades of pickled data, but ultimately this is likely a doomed endeavour (vis ). Hope this helps, Jean-Paul From IAmStarsky at gmail.com Thu May 3 13:28:34 2007 From: IAmStarsky at gmail.com (IAmStarsky at gmail.com) Date: 3 May 2007 10:28:34 -0700 Subject: _csv.Error: string with NUL bytes In-Reply-To: References: <1178204593.280648.208040@c35g2000hsg.googlegroups.com> <1178209090.674787.202970@o5g2000hsb.googlegroups.com> <1178211458.634214.306500@o5g2000hsb.googlegroups.com> Message-ID: <1178213314.203450.167350@n76g2000hsh.googlegroups.com> On May 3, 10:12 am, dus... at v.igoro.us wrote: > On Thu, May 03, 2007 at 09:57:38AM -0700, fscked wrote: > > > As Larry said, this most likely means there are null bytes in the CSV file. > > > > Ciao, > > > Marc 'BlackJack' Rintsch > > > How would I go about identifying where it is? > > A hex editor might be easiest. > > You could also use Python: > > print open("filewithnuls").read().replace("\0", ">>>NUL<<<") > > Dustin Hmm, interesting if I run: print open("test.csv").read().replace("\0", ">>>NUL<<<") every single character gets a >>>NUL<<< between them... What the heck does that mean? Example, here is the first field in the csv 89114608511, the above code produces: >>>NUL<<<8>>>NUL<<<9>>>NUL<<<1>>>NUL<<<1>>>NUL<<<4>>>NUL<<<6>>>NUL<<<0>>>NUL<<<8>>>NUL<<<5>>>NUL<<<1>>>NUL<<<1>>>NUL<<<, From bj_666 at gmx.net Tue May 15 12:25:01 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 15 May 2007 18:25:01 +0200 Subject: Storing and searching nodes of a tree References: <1179233407.473173.259110@h2g2000hsg.googlegroups.com> <1179243655.596897.6450@e51g2000hsg.googlegroups.com> Message-ID: In <1179243655.596897.6450 at e51g2000hsg.googlegroups.com>, jm.suresh at no.spam.gmail.com wrote: > If I have the tree in the dictionary, the code would like this, > def search(tree, path): > while path and not(tree.haskey(path)): > path = path[:-1] > if path: > return tree[path] > else: > raise KeyError('path not on tree') > > Another qn -- dict.haskey() takes logn time, am I right? No it's O(1). Dictionaries are implemented as hash tables. You may write the condition as: while path and path not in tree: That's a little easier to read and a bit faster too as a method lookup is spared. Ciao, Marc 'BlackJack' Rintsch From steve at REMOVE.THIS.cybersource.com.au Sun May 27 02:09:59 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 27 May 2007 16:09:59 +1000 Subject: ten small Python programs References: Message-ID: On Sat, 26 May 2007 18:48:45 -0700, Steve Howell wrote: > It also has a ComplexNumber class, but I don't want to > scare away mathphobes. Is it as short as this one-liner? ComplexNumber = complex -- Steven. From carsten at uniqsys.com Tue May 1 17:12:42 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 01 May 2007 17:12:42 -0400 Subject: I wish that [].append(x) returned [x] In-Reply-To: <1178053211.209905.154030@h2g2000hsg.googlegroups.com> References: <46379a41$0$25252$88260bb3@free.teranews.com> <1178053211.209905.154030@h2g2000hsg.googlegroups.com> Message-ID: <1178053962.3425.24.camel@dot.uniqsys.com> On Tue, 2007-05-01 at 14:00 -0700, Paul McGuire wrote: > On May 1, 3:45 pm, Tobiah wrote: > > I wanted to do: > > > > query = "query text" % tuple(rec[1:-1].append(extra)) > > > > but the append() method returns none, so I did this: > > > > fields = rec[1:-1] > > fields.append(extra) > > query = "query text" % tuple(fields) > > query = "query text" % tuple(rec[1:-1] + [extra]) > > should work. In addition to the above good advice, in case you are submitting a query to a DB-API compliant SQL database, you should use query parameters instead of building the query with string substitution. If you aren't querying an SQL database, never mind. -Carsten From aleax at mac.com Wed May 30 11:05:43 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 30 May 2007 08:05:43 -0700 Subject: Rats! vararg assignments don't work References: <1180496033.608791.35840@g37g2000prf.googlegroups.com> <1180496542.955320.5430@m36g2000hse.googlegroups.com> Message-ID: <1hyx2am.1txfo6o16tly4nN%aleax@mac.com> samwyse wrote: ... > Actually, I'm surprised that the PEP does as much as it does. If tuples > are implemented as S-expressions, then something like this: Tuples are implemented as compact arrays of pointer-to-PyObject (so are lists, BTW). So, for example, a 10-items tuple takes 40 bytes (plus a small overhead for the header) on a 32-bit build, not 80 as it would if implemented as a linked list of (pointer-to-object, pointer-to-next) pairs; addressing sometuple[N] is O(1), NOT O(N); etc, etc. Alex From basilisk96 at gmail.com Tue May 1 18:22:42 2007 From: basilisk96 at gmail.com (Basilisk96) Date: 1 May 2007 15:22:42 -0700 Subject: ScrolledText? In-Reply-To: <1178057529.486757.154860@y5g2000hsa.googlegroups.com> References: <1178057529.486757.154860@y5g2000hsa.googlegroups.com> Message-ID: <1178058162.274969.117340@o5g2000hsb.googlegroups.com> Would this work? self.text = wx.TextCtrl(panel, style=wx.TE_MULTILINE) ... line = '\n' + "Hello world!" self.text.AppendText(line) From mcepl at redhat.com Thu May 24 16:41:29 2007 From: mcepl at redhat.com (Matej Cepl) Date: Thu, 24 May 2007 22:41:29 +0200 Subject: email modul with writing to mboxes (and locking) for python 2.4.*? Message-ID: Is there somewhere support for the extension of email module, which would support writing to (and creating new) mbox folders (with all bells and whistles, like locking)? It seems to me that current (Python 2.4.*, I even tried email package 4.0.2 from python.org email SIG) implementation is read-only, am I right? Thanks for any reply, Matej Cepl From vatamane at gmail.com Mon May 7 05:23:35 2007 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 7 May 2007 02:23:35 -0700 Subject: Properties on old-style classes actually work? In-Reply-To: References: Message-ID: <1178529815.452754.298130@h2g2000hsg.googlegroups.com> On May 7, 4:44 am, Paul Melis wrote: > Hello, > > The python library docs read in section 2.1 > (http://docs.python.org/lib/built-in-funcs.html): > > " > ... > > property( [fget[, fset[, fdel[, doc]]]]) > Return a property attribute for new-style classes (classes that > derive from object). > > ... > " > > But in 2.4 at least properties also seem to work for old-style classes: > > class O: > > def __init__(self): > self._x = 15 > > def get_x(self): > return self._x > > x = property(get_x) > > o = O() > print o.x > > outputs "15" as expected for the property. > > Regards, > Paul Paul, Sorry to dissapoint, but properties don't work in old style classes. The 'get' property seems to work but as soon as you use the set property it fails and even 'get' won't work after that. It surely is deceiving, I wish it would just give an error or something. See below. -Nick Vatamaniuc >>> class O: ....: def __init__(self): ....: self._x=15 ....: def get_x(self): ....: print "in O.get_x()" ....: return self._x ....: def set_x(self,newx): ....: print "in O.set_x(newx)" ....: self._x=newx ....: x=property(get_x, set_x) ....: >>> o=O() >>> o._x 15 >>> o.x in O.get_x() in O.get_x() 15 >>> o.x=42 >>> #DANGER WILL ROBINSON, set_x NOT CALLED!!! >>> o.x 42 >>> #HMM... properties ARE BROKEN FROM NOW ON >>> o._x 15 >>> #...BROKEN INDEED >>> From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat May 12 15:34:48 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 12 May 2007 21:34:48 +0200 Subject: [Newbie] design question References: <1178992981.143066.279690@o5g2000hsb.googlegroups.com> Message-ID: <5amj6gF2pbeeuU1@mid.individual.net> idaku2 at gmail.com wrote: > Suppose I have class ShoppingCart which has one method called > buy(), and class Buyer who has one reference to ShoppingCart... > Can I also have method buy() in class Buyer, which will then > called ShoppingCard.buy(), and also do some other stuff? Is this > legal design pattern, have methods with same name? In principle, this is legal. But OTOH, how could a ShoppingCart "buy" something? In my world, Buyers "buy" when using ShoppingCarts. Regards, Bj?rn -- BOFH excuse #445: Browser's cookie is corrupted -- someone's been nibbling on it. From apatheticagnostic at gmail.com Wed May 30 19:51:01 2007 From: apatheticagnostic at gmail.com (kaens) Date: Wed, 30 May 2007 19:51:01 -0400 Subject: Off Topic: What is the good book to learn Python ? In-Reply-To: <1180549522.350380.276570@q66g2000hsg.googlegroups.com> References: <1180549522.350380.276570@q66g2000hsg.googlegroups.com> Message-ID: <163f0ce20705301651r43a6c50et15a4bc621b74f328@mail.gmail.com> On 30 May 2007 11:25:22 -0700, Katie Tam wrote: > I am new to this filed and begin to learn this langague. Can you tell > me the good books to start with ? > > > Katie Tam > Network administrator > http://www.linkwaves.com/main.asp > http://www.linkwaves.com > > -- > http://mail.python.org/mailman/listinfo/python-list > If you're experienced with other programming languages, I'd recommend python in a nutshell, or perhaps programming python. I personally just skimmed through the online tutorial, and kept the library and api references handy. Orielly publishers almost always have excellent books on learning new programming languages. I would also recommend to stay away from any "for dummies" or "in x (hours/days)" books. They can be decent introductory material, but unless you are really really new to programming, you probably wouldn't be getting enough information to justify the cost of the book (and a lot of times they have a lot of bad practices in them) Good luck! From grante at visi.com Wed May 16 17:58:31 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 16 May 2007 21:58:31 -0000 Subject: How do I tell the difference between the end of a text file, and an empty line in a text file? References: <1179352021.803070.200780@k79g2000hse.googlegroups.com> Message-ID: <134mvk7r3e7k55@corp.supernews.com> On 2007-05-16, walterbyrd wrote: > Python's lack of an EOF character is giving me a hard time. No it isn't. > s = f.readline() > while s: > . > . > s = f.readline() > s = f.readline() > while s != '' > . > . > s = f.readline() Neither one of your examples is legal Python. Please post real code. > In both cases, the loop ends as soon it encounters an empty line in > the file, i.e. No, it doesn't. Not if you've done something reasonable like this: f = open('testdata','r') while True: s = f.readline() if not s: break print repr(s) or this: f = open('testdata','r') s = f.readline() while s: print repr(s) s = f.readline() Please post real, runnable code. You've done something wrong and we've no way to guess what it was if you won't show us your code. -- Grant Edwards grante Yow! Is something VIOLENT at going to happen to a visi.com GARBAGE CAN? From khemkaamit at gmail.com Sat May 26 03:43:13 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Sat, 26 May 2007 13:13:13 +0530 Subject: Newbie help understanding... In-Reply-To: <1180164211.934421.64420@i38g2000prf.googlegroups.com> References: <1180164211.934421.64420@i38g2000prf.googlegroups.com> Message-ID: <1360b7230705260043q3f7a52b9kde0ca0d042d0f9aa@mail.gmail.com> On 26 May 2007 00:23:32 -0700, mark wrote: > Hi I am trying to get a piece of code to work based on an exercise in > a book. Any help appreciated. Can someone please explain what is going > on here. > > I am trying to read from a text file a list of cards with the > following format and sort firstly by suit and then by rank > > h 1 > d 2 > c 5 > s 9 > h2 > d3 > > etc... > > I get the following error; > Traceback (most recent call last): > File "F:/###UNI###/ITC106/ass2/cardread.py", line 25, in > t.append( t[0] + 400 ) > AttributeError: 'str' object has no attribute 'append' > def read_cards(filename): > cards = [] > for card in open(filename, 'r'): > cards.append(card.strip()) > return cards > > # read the deck of cards from a file > filename = 'cards.txt' > cards = read_cards(filename) > > > for t in read_cards(filename): > if t[1] == 'h': > t.append( t[0] + 100 ) > elif t[1] == 'd': > t.append( t[0] + 200 ) > elif t[1] == 'c': > t.append( t[0] + 300 ) > else: > t.append( t[0] + 400 ) In read_cards function you are appending a string in the list 'cards' , where i guess you wanted to append a list of suit and rank in list cards. def read_cards(filename): cards = [] for card in file(filename): cards.append(cards.split()) # i assume that suit and rank is separated by white space return cards or better still cards = [card.split() for card in file(filename)] Cheers, ---- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. From laxmikiran.bachu at gmail.com Thu May 24 00:34:38 2007 From: laxmikiran.bachu at gmail.com (laxmikiran.bachu at gmail.com) Date: 23 May 2007 21:34:38 -0700 Subject: ValueError: need more than 1 value to unpack Message-ID: <1179981278.089022.216960@q19g2000prn.googlegroups.com> ValueError: need more than 1 value to unpack . This is the error I get when I am using pyRXPU in the one of the scripts to get the strings from an application. Can anybody throw some light on this ..what might be the solution for this. If I use pyRXP iam not getting the mentioned error. Error information for the reference : Traceback (most recent call last): File "D:\LanguageScripts\Screens.py", line 106, in test_1_01_DoSomething TitlenSoftkeyfn() File "D:\LanguageScripts\EventLog_Screens.py", line 66, in TitlenSoftkeyfn titleBar = root.TitleBar.currentText File "D:\LanguageScripts\XmlWrapper.py", line 35, in __getattr__ tagName, attrs, children, spare = child ValueError: need more than 1 value to unpack From rowen at cesmail.net Wed May 2 15:38:13 2007 From: rowen at cesmail.net (Russell E. Owen) Date: Wed, 02 May 2007 12:38:13 -0700 Subject: Tcl-tk 8.5? References: <46382248$0$5105$ba4acef3@news.orange.fr> Message-ID: In article <46382248$0$5105$ba4acef3 at news.orange.fr>, "M?ta-MCI" wrote: > Hi! > > > See http://wiki.tcl.tk/10630 > > Any plan to integrate Tcl 8.5 in standard Python? I'm curious about the plans, also. But I can say this much...Tcl/Tk 8.5 is still in alpha (and has been for years). I have heard rumors that it works pretty well, but it is explicitly not feature stable. -- Russell From aleax at mac.com Fri May 4 22:19:37 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 4 May 2007 19:19:37 -0700 Subject: How to check if a string is empty in python? References: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> <1178154290.811928.208900@h2g2000hsg.googlegroups.com> <1hxia6q.18rflwk1mez8vhN%aleax@mac.com> Message-ID: <1hxls08.1821ogi1l0n338N%aleax@mac.com> Larry Bates wrote: ... > Isn't deprecated like depreciated but not quite to zero yet? No. "To deprecate" comes from a Latin verb meaning "to ward off a disaster by prayer"; when you're saying you deprecate something, you're saying you're praying for that something to disappear, go away; in a secular context, you're earnestly imploring people to NOT do it. "To depreciate" comes from a Latin verb meaning "to reduce the price"; when you're saying you depreciate something, you're saying you put on that something a lower price (and, by extension, a lower value) than it has (or, more commonly, used to have). You're not necessarily saying it's worth nothing at all (accountants sometimes deem an asset "fully depreciated" to mean something close to that, but the adverb "fully" is crucial to this meaning), just that it's worth "less than before". The two terms got somewhat entwined, no doubt because their spelling is so similar (even though etimology and pronunciation are poles apart), but the "correct" meanings and usage are still well distinct. Alex From dotancohen at gmail.com Sat May 19 16:05:48 2007 From: dotancohen at gmail.com (Dotan Cohen) Date: Sat, 19 May 2007 23:05:48 +0300 Subject: List Moderator In-Reply-To: References: <880dece00705172218n71123b55q531ec0c5e500f208@mail.gmail.com> <880dece00705190012g4f3d3ef6v4e6c87a156708bb0@mail.gmail.com> Message-ID: <880dece00705191305m203bc8ep804d647c17438581@mail.gmail.com> On 19/05/07, Steve Holden wrote: > I'm sorry, but you have no idea what you are talking about. Most of what > can be done *is* being done, which is why you see the relatively low > spam volumes you do. > I hope that I don't. I receive no less than 700 spams a day to my regular address (not gmail, which I use for mailing lists), but then again I've only twice gone over 2000 spams in a single day. I can only imagine the efforts used to keep the list clean. Maybe spamassasin, a few hundred procmail filters, and a last swipe with bogofilter for good measure? I don't mean to be pushy, but every day I add another procmail filter based upon what's been getting through (and they still do, I try to err on 'false negative'). Four filters "britney", "spears", "boobs" and "tits" would show the spammers that the moderators are serious about keeping this list clean. I'll go back to reading and not writing now, at least until I get to the point where either I feel that I can contribute, or until I get myself real stuck. Dotan Cohen http://lyricslist.com/lyrics/artist_albums/252/heaven_17.html http://what-is-what.com/what_is/operating_system.html From san.gujar at gmail.com Thu May 31 09:37:16 2007 From: san.gujar at gmail.com (sandeep patil) Date: 31 May 2007 06:37:16 -0700 Subject: WEATHER PROGRAMMING IN PYTHON Message-ID: <1180618635.925002.282080@n15g2000prd.googlegroups.com> how to diplay the weather condiction on my webpage suppose i want to read weather from www.bbc.co.uk/weather.html how i can read it usin program From newsuser at stacom-software.de Wed May 30 11:33:28 2007 From: newsuser at stacom-software.de (Alexander Eisenhuth) Date: Wed, 30 May 2007 17:33:28 +0200 Subject: Anyone else has seen "forrtl: error (200) ..." Message-ID: Hello, Ctrl+C is not passed to the interpreter (i guess it) while I'm executing a script. Instead i get: forrtl: error (200): program aborting due to control-C event If I start python in interactive mode Ctrl+C is passed: bash-3.2$ python Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> raw_input() Traceback (most recent call last): File "", line 1, in KeyboardInterrupt >>> Any idea ? Thanks Alexander From max at alcyone.com Tue May 29 19:04:43 2007 From: max at alcyone.com (Erik Max Francis) Date: Tue, 29 May 2007 16:04:43 -0700 Subject: 0 == False but [] != False? In-Reply-To: References: <1179982400.412340.178710@g4g2000hsf.googlegroups.com> <1179983482.452458.188690@q66g2000hsg.googlegroups.com> Message-ID: Donn Cave wrote: > "Not that it is of no historical interest" may have been too > hard to follow, my apologies. Yeah, my reading comprehension wasn't up to snuff that night. -- 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 A man that studieth revenge keeps his own wounds green. -- Francis Bacon From ptmcg at austin.rr.com Fri May 4 13:15:57 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 4 May 2007 10:15:57 -0700 Subject: How safe is a set of floats? In-Reply-To: <1178297450.812110.322140@q75g2000hsh.googlegroups.com> References: <1178288509.067493.5140@e65g2000hsc.googlegroups.com> <1hxkw5d.1ipc1zfocmqm9N%aleax@mac.com> <1178294650.738576.205690@q75g2000hsh.googlegroups.com> <1178297450.812110.322140@q75g2000hsh.googlegroups.com> Message-ID: <1178298957.102330.50060@u30g2000hsc.googlegroups.com> On May 4, 11:50 am, Arnaud Delobelle wrote: > On May 4, 5:04 pm, Paul McGuire wrote: > > > Does set membership test for equality ("==") or identity ("is")? I > > just did some simple class tests, and it looks like sets test for > > identity. > > Sets are like dictionaries, they test for equality: > > >>> a=1,2 > >>> b=1,2 > >>> a is b > False > >>> a in set([b]) > > True > > -- > Arnaud Just to beat this into the ground, "test for equality" appears to be implemented as "test for equality of hashes". So if you want to implement a class for the purposes of set membership, you must implement a suitable __hash__ method. It is not sufficient to implement __cmp__ or __eq__, which I assumed "test for equality" would make use of. Not having a __hash__ method in my original class caused my initial confusion. So would you suggest that any class implemented in a general-purpose class library should implement __hash__, since one cannot anticipate when a user might want to insert class instances into a set? (It certainly is not on my current checklist of methods to add to well- behaved classes.) -- Paul From carsten at uniqsys.com Mon May 7 08:59:31 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 07 May 2007 08:59:31 -0400 Subject: assisging multiple values to a element in dictionary In-Reply-To: <1178535831.870912.44220@p77g2000hsh.googlegroups.com> References: <1178535831.870912.44220@p77g2000hsh.googlegroups.com> Message-ID: <1178542771.3360.8.camel@dot.uniqsys.com> On Mon, 2007-05-07 at 04:03 -0700, saif.shakeel at gmail.com wrote: > Hi, > I have a dictionary which is something like this: > id_lookup={ > 16:'subfunction', > 26:'dataId', > 34:'parameterId', > 39:'subfunction', > 44:'dataPackageId', > 45:'parameterId', > 54:'subfunction', > 59:'dataId', > 165:'subfunction', > 169:'subfunction', > 170:'dataPackageId', > 174:'controlParameterId' > } > How do i assign multiple values to the key here.Like i want the > key 170 to take either the name 'dataPackageID' or the name > 'LocalId'.I use this in my code,and hence if either comes it should > work . That sounds to me like you're translating names to numbers. If that is true, you're much better off turning your dictionary around, making the name the key and the corresponding number the value. That way you'll have two keys pointing to the same value, which is perfectly legal, whereas having one key pointing to two values is not really possible. You could have one key pointing to a list or tuple of two values, but it's not obvious whether that would solve your problem. Hope this helps, -- Carsten Haese http://informixdb.sourceforge.net From gagsl-py2 at yahoo.com.ar Tue May 1 18:04:10 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 01 May 2007 19:04:10 -0300 Subject: SEO - Search Engine Optimization - Seo Consulting References: <1177808356.681710.42980@n76g2000hsh.googlegroups.com> <#O8fXGAjHHA.3700@TK2MSFTNGP06.phx.gbl> Message-ID: En Tue, 01 May 2007 16:23:44 -0300, Bob Phillips escribi?: > That is the oft-quoted, idiotic type of example. The reality is that if > we > follow the thread, we know the question, we only want to see the answer, > not > wade through a morass of stuff we have already seen. If we haven't seen > it, > guess what, we can go and read it. Would you all please stop this? It's absolutely off topic in all groups: microsoft.public.dotnet.framework.aspnet, uk.people.consumers.ebay, comp.lang.python, misc.writing, alt.consumers.uk-discounts.and.bargains -- Gabriel Genellina From nejtak... Thu May 31 17:27:20 2007 From: nejtak... (Troels Thomsen) Date: Thu, 31 May 2007 23:27:20 +0200 Subject: call function in console without paranthesis Message-ID: <465f3dbc$0$52092$edfadb0f@dread11.news.tele.dk> Hello, I am wondering if I can write some code, that allows me to call functions in the console , IDLE, without using the paranthesis notation. Like print. This will improve "intreractive'ness" serialOpen() # some magic is issued here !!! tx Hello instead of serialObj = mySerial(....) serialObj.Tx("Hello") thx in advance Troels From mail at microcorp.co.za Wed May 16 03:21:01 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 16 May 2007 09:21:01 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179226183.215907.140450@q75g2000hsh.googlegroups.com> Message-ID: <03f801c7979e$84f93520$03000080@hendrik> "HYRY" wrote: > If non-ASCII identifiers becomes true, I think it will be the best > gift for Children who donot know English. How do you feel about the mix of English keywords and Chinese? How does the English - like "sentences " look to a Chinese? Would you support the extension of this PEP to include Chinese Keywords? Would that be a lesser or greater gift? - Hendrik From steve at holdenweb.com Thu May 31 19:58:27 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 31 May 2007 19:58:27 -0400 Subject: c[:]() In-Reply-To: <001801c7a3cc$e9f0b270$240110ac@Muse> References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> <135tobve86qj808@corp.supernews.com> <135tru124pie2b3@corp.supernews.com> <135tv1bjqgbmsc9@corp.supernews.com> <003301c7a3ab$f2bdf960$240110ac@Muse> <001801c7a3cc$e9f0b270$240110ac@Muse> Message-ID: Warren Stringer wrote: > Quotes out of context with mistaken assumptions, now follow: > >>>>>> So c[:]() -- or the more recent go(c)() -- executes all those >>>>>> behaviors. >> No it doesn't. See below. >>> If c[:]() works, the so does this, using real world names >>> >>> orchestra[:].pickle() >>> orchestra[conductor()].sequence() >>> >>> Though, I'm already starting to prefer: >>> >>> do(orchestra).pickle() >>> do(orchestra(conductor)).sequence() >>> >> Yes, dammit, but c[:]() *DOESN'T WORK* unless you have made some pretty >> crufty changes to the underlying object. > > I started this thread asking why c[:]() doesn't work. > If you say so. Perhaps you didn't express yourself too clearly. >> This is what I'm having difficulty understanding. You said, in your >> original post (which, by the way, hijacked another thread about >> something completely different): > > What?!? I started this thread. > No you didn't. Your original post was a reply to a message whose subject line was 'Re: "is" and ==', and included the header In-Reply-To: <1180504773.374529.161740 at q66g2000hsg.googlegroups.com> >>> I want to call every object in a tupple, like so: >>> >> [By the way, that's "tuple", not "tupple"] >>> #------------------------------------------ >>> def a: print 'a' >>> def b: print 'b' >>> c = (a,b) >>> >>>>>>>>> c[:]() # i wanna >>> TypeError: 'tupple' object is not callable >>> >>>>>>>>> c[0]() # expected >>> a >>>>>>>>> c[:][0] # huh? >>> a > >> This is what I just don't believe. And, of course, the use of "tupple" >> above tells us that this *wasn't" just copied and pasted from an >> interactive session. > > Try it. > >>>>>>>>> [i() for i in c] # too long and ...huh? >>> a >>> b >>> [None,None] >>> #------------------------------------------ >> This is also clearly made up. > > I repeat: try it. > I don't need to. The function definitions contain syntax errors, and the error message couldn't have been produced by any interpreter that ever existed. >> In a later email you say: >> >>> why does c[:][0]() work but c[:]() does not? >> The reason for this ... > > Stated elsewhere, but thanks > >>> Why does c[0]() has exactly the same results as c[:][0]() ? >> The reason for this is that c is exactly the same as c[:]. The slicing >> notation "[:]" tells the interpreter to use a tuple consisting of >> everything in the tuple to which it's applied. Since the interpreter >> knows that tuples are immutable (can't be changed), it just uses the >> same tuple -- since the immutability there's no way that a difference >> could arise between the tuple and a copy of the tuple, Python doesn't >> bother to make a copy. >> >> This behavior is *not* observed with lists, because lists are mutable. > > But neither tupples or lists work, so immutability isn't an issue. > Good grief, man, c[0]() will work perfectly well as long as c is a list or a tuple of functions. Or, come to that, a dict of functions with a key of 0. >> I realise you are trying to find ways to make Python more productive for >> you, and there's nothing wrong with that. But consider the following, >> which IS copied and pasted: >> >> >>> def a(): >> ... print "A" >> ... >> >>> def b(): >> ... print "B" >> ... >> >>> c = (a, b) >> >>> c >> (, ) >> >>> c[:] >> (, ) >> >>> c[0]() >> A >> >>> c[1]() >> B >> >>> c() >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: 'tuple' object is not callable >> >>> c[:]() >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: 'tuple' object is not callable >> >>> > > I never said that c() would execute a list nor did I ever say that c[:]() > would execute a list. > >> I think the fundamental mistake you have made is to convince yourself that >> >> c[:]() >> >> is legal Python. It isn't, it never has been. > > In summation: > I started this thread asking why c[:]() wouldn't work > I did not hijack another thread > I posted working examples (with one typo, not quoted here) > I am extremely annoyed by this post > > Tis best not to assume what other people are thinking > > Probably best not to try to help them too, if this is the response. Next time you want assistance try to ensure that you copy and paste your examples instead of trying to duplicate them from memory. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From pc at p-cos.net Thu May 3 02:08:13 2007 From: pc at p-cos.net (Pascal Costanza) Date: Thu, 03 May 2007 08:08:13 +0200 Subject: Microsoft's Dynamic Languages Runtime (DLR) In-Reply-To: <1178145895.865828.18220@p77g2000hsh.googlegroups.com> References: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> <59s6kbF2kq8uoU1@mid.individual.net> <1178145895.865828.18220@p77g2000hsh.googlegroups.com> Message-ID: <59tcidF2lob6mU1@mid.individual.net> Fuzzyman wrote: > On May 2, 8:20 pm, Pascal Costanza wrote: >> sturlamolden wrote: >>> On Monday Microsoft announced a new runtime for dynamic languages, >>> which they call "DLR". It sits on top of the conventional .NET runtime >>> (CLR) and provides services for dynamically typed languages like >>> Python or Lisp (thus the cross-posting). Apparently is is distributed >>> under a BSD-like open-source license. >>> I am curious to know how it performs in comparison to CPython and an >>> efficient compiled Lisp like CMUCL. Speed is a major problem with >>> CPython but not with .NET or CMUCL, so it will be interesting to see >>> how the DLR performs in comparison. It would be great to finally see a >>> Python that runs on steroids, but knowing M$ bloatware my expectations >>> are not too high. >>> Has anyone looked at the DLR yet? What are your impression? >> So far, there is not a lot of information available. The only statement >> about the technology I have read so far is that the DLR is a thin layer >> on top of the CLR. This doesn't say a lot. >> >> So it's hard to tell whether this is a (good) marketing stunt or whether >> there are actual substantial improvement to the infrastructure. > > Well, they're now implementing four dynamic languages on top of the > DLR - not just IronPython. > > * IronPython > * IronRuby > * Java Script > * VBx (a dynamic version of VB) > > The DLR provides a dynamic type system and hosting environment for > dynamic languages. > > The nice part is that the DLR runs on top of the 'Core CLR' which > ships with Silverlight. This means that apps. that run in Silverlight > are secure - so you can run an IronPython console in the browser... That still doesn't explain what DLR actually does. You can implement these languages on top of the JVM as well. You could implement them on any Turing-complete language, for that matter. The interesting question how well integrated such an implementation is. However, Jim Hugunin seems to be willing to give more details on his blog - the recent entry gives hints that there is indeed something interesting going on. I'm still waiting for the meat, though... Pascal -- My website: http://p-cos.net Common Lisp Document Repository: http://cdr.eurolisp.org Closer to MOP & ContextL: http://common-lisp.net/project/closer/ From donn at u.washington.edu Tue May 29 16:31:14 2007 From: donn at u.washington.edu (Donn Cave) Date: Tue, 29 May 2007 13:31:14 -0700 Subject: 0 == False but [] != False? References: <1179982400.412340.178710@g4g2000hsf.googlegroups.com> <1179983482.452458.188690@q66g2000hsg.googlegroups.com> Message-ID: In article , Erik Max Francis wrote: > Donn Cave wrote: > > > Not that it is of no historical interest to review all these > > reasonable arguments, but allow me to restore the context quote > > from my follow-up: > > If the counterpoints are of no historical interest, then the original > point must be of no historical interest either, since it was not widely > granted as true. "Not that it is of no historical interest" may have been too hard to follow, my apologies. I should have said "It may be of historical interest ...". After that, you lost me, but I guess I'm not going to worry about it. Donn Cave, donn at u.washington.edu From girodt at gmail.com Wed May 9 11:08:46 2007 From: girodt at gmail.com (TG) Date: 9 May 2007 08:08:46 -0700 Subject: Boost python : get the shape of a numpy ndarray in C++ code. Message-ID: <1178723326.174384.180690@y5g2000hsa.googlegroups.com> Hi there. I'm strugling here with some boost python code (damn I hate C++) : All I want to do is to initialize the content of an array with a numpy ndarray parameter. I have this, which actually works. But I want to add some kind of data check such as : * is array two dimensional ? * are the dimensions corresponding to map's width / height ? * is array field with floats or ints ? void Layer::set_potentials (numeric::array& array) { for (int h=0; hheight; h++){ for (int w=0; wwidth; w++){ units[w+h*map->width]->potential = extract(array[make_tuple(w,h)]); } } } Some help is very welcome here ... thanks. From grant_ito at shaw.ca Tue May 8 11:14:12 2007 From: grant_ito at shaw.ca (Grant) Date: Tue, 08 May 2007 15:14:12 GMT Subject: pymacs Message-ID: Hi there. Does anyone out there know what's going on with pymacs currently? Thanks, Grant. From larry.bates at websafe.com Tue May 22 10:10:18 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 22 May 2007 09:10:18 -0500 Subject: Printing dots in sequence ('...') In-Reply-To: <1179820951.288587.142670@h2g2000hsg.googlegroups.com> References: <1179820951.288587.142670@h2g2000hsg.googlegroups.com> Message-ID: <6LOdnd3GvuZVZM_bnZ2dnUVZ_oDinZ2d@comcast.com> beertje wrote: > This is a very newbie question for my first post, perhaps > appropriately. > > I want to print '....' gradually, as a progress indicator. I have a > for-loop that every 10 steps executes: > print '.', > > This results in something like 'Loading. . . .', whereas I want > 'Loading....' > > A pet peeve, I can't for the life of me figure out how to get this > desired output. How do I print dots - or anything for that matter - in > sequence without a space being inserted in between? > > Thanks. > Bj?rn > I wrote this a donated to Python Cookbook some time ago, enjoy. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/299207 -Larry From claird at lairds.us Wed May 2 13:50:50 2007 From: claird at lairds.us (Cameron Laird) Date: Wed, 2 May 2007 17:50:50 +0000 Subject: Is it possible to determine what a function needs for parameters - References: <1178115727.932794.100390@h2g2000hsg.googlegroups.com> <1178124116.362731.248260@c35g2000hsg.googlegroups.com> Message-ID: In article , Chris Mellon wrote: >On 2 May 2007 09:41:56 -0700, rh0dium wrote: >> On May 2, 8:25 am, Gary Herron wrote: >> > rh0dium wrote: . . . >Thats because you put the wrong value into the arguments queue. >For this use case, we define the arguments queue as being a source of 2-tuples, >with an argument list and a kwargs dict. So you have to do: > >for x in range(lod): > myQ.put((random.random(), {})) > >(don't be afraid of indentation and newlines - I started to modify >your source to provide a working example and got frustrated >reformatting it so I could read it) > >Since you've now defined the external interface for your system (pass >it a queue of argument, kwargs tuples and a callable) it's the >responsibility of the caller to correctly satisfy that interface. While I agree with the programming analyses of Messrs. Herron and Mellon (and heartily recommend Queue for folks working in this nighborhood), it occurs to me that readers of this thread might also have an interest in tuplespaces . From jadestar at idiom.com Thu May 10 13:30:49 2007 From: jadestar at idiom.com (James T. Dennis) Date: Thu, 10 May 2007 17:30:49 -0000 Subject: Minor bug in tempfile module (possibly __doc__ error) References: <1178693438.689184@smirk> <4642ded5$0$20290$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <1178818249.25207@smirk> Marc Christiansen wrote: > James T. Dennis scribis: >> In fact I realized, after reading through tempfile.py in /usr/lib/... >> that the following also doesn't "work" like I'd expect: >> # foo.py >> tst = "foo" >> def getTst(arg): > If I change this line: >> return "foo-%s" % arg > to: > return "%s-%s" % (tst, arg) >> # bar.py >> import foo >> foo.tst = "bar" >> print foo.getTst("testing") >> foo-testing <<<----- NOT "bar-testing" > Then "python bar.py" prints "bar-testing". > 0:tolot at jupiter:/tmp> cat foo.py > tst = "foo" > def getTst(arg): > return "%s-%s" % (tst,arg) > 0:tolot at jupiter:/tmp> cat bar.py > import foo > foo.tst = "bar" > print foo.getTst("testing") > 0:tolot at jupiter:/tmp> python bar.py > bar-testing > And regarding the tempfile.template problem, this looks like a bug. > Because all functions in tempfile taking a prefix argument use "def > function(... , prefix=template, ...)", only the value of template at > import time matters. > Adia?, Marc I suppose my real sample code was def getTst(arg=tst): Oddly I've never come across that (the fact that defaulted arguments are evaluated during function definition) in my own coding and I guess there are two reasons for that: I try to avoid global variables and I usually use defaulted variables of the form: def (foo=None): if foo is None: foo = self.default_foo -- Jim Dennis, Starshine: Signed, Sealed, Delivered From researchbase at gmail.com Sat May 19 01:25:11 2007 From: researchbase at gmail.com (krishnakant Mane) Date: Sat, 19 May 2007 10:55:11 +0530 Subject: which is the comprehencive module for postgresql? Message-ID: hello all, some times having many choices often confuses the users. can some one plese tell me which is the most comprehencive, well documented and widely used and tested module to connect from python to postgresql database? I looked around PYPgsql but there seams to be very little documentation. and seams that PyGreSql is non-free? please suggest a suitable driver. by the way I will also be using bynary large objects. so that support must be included. regards, Krishnakant. From thorsten at thorstenkampe.de Tue May 15 07:53:43 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 15 May 2007 12:53:43 +0100 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> <4648294F.2000704@web.de> <46487a6c$0$2400$426a74cc@news.free.fr> Message-ID: * Eric Brunel (Tue, 15 May 2007 11:51:20 +0200) > On Tue, 15 May 2007 11:25:50 +0200, Thorsten Kampe > wrote: > > * Eric Brunel (Tue, 15 May 2007 10:52:21 +0200) > >> On Tue, 15 May 2007 09:38:38 +0200, Duncan Booth > >> wrote: > >> > Recently there has been quite a bit of publicity about the One Laptop > >> Per > >> > Child project. The XO laptop is just beginning rollout to children and > >> > provides two main programming environments: Squeak and Python. It is > >> an > >> > exciting thought that that soon there will be millions of children in > >> > countries such as Nigeria, Brazil, Uruguay or Nepal[*] who have the > >> > potential to learn to program, but tragic if the Python community is > >> too > >> > arrogant to consider it acceptable to use anything but English and > >> ASCII. > >> > >> You could say the same about Python standard library and keywords then. > > > > You're mixing apples and peaches: identifiers (variable names) are > > part of the user interface for the programmer and free to his > > diposition. > > So what? Does it mean that it's acceptable for the standard library and > keywords to be in English only, but the very same restriction on > user-defined identifiers is out of the question? Yes. > Why? If I can use my own > language in my identifiers, why can't I write: > > classe MaClasse: > d?finir __init__(moi_meme, maListe): > moi_meme.monDictionnaire = {} > pour i dans maListe: > moi_meme.monDictionnaire[i] = Rien > > For a French-speaking person, this is far more readable than: Because keywords are not meant meant to extended or manipulated or something similar by the programmers. Keywords are well known and only a limited set of words. That's why you can't use keywords as identifiers. On the contrary identifiers are for the user's disposition. The convention for naming them is: give them the name that makes the most sense in relation to the code. In a lot of cases this will mean english names and ASCII charset. And in some restricted environments this means naming identifiers with terms from the native language. And in this case it makes no sense at all to restrict these people to use ASCII characters to write words in their own language. There really is no difference to allow strings or comments in non- english languages and non-ASCII characters. Thorsten From knipknap at gmail.com Thu May 24 06:41:04 2007 From: knipknap at gmail.com (Samuel) Date: 24 May 2007 03:41:04 -0700 Subject: Simple omniORBpy example throws exception with error 0x41540002 In-Reply-To: References: <1179833680.255391.198490@x18g2000prd.googlegroups.com> <5bg40hF2moliaU1@mid.uni-berlin.de> <1179839519.216407.124960@z24g2000prd.googlegroups.com> Message-ID: <1180003263.993342.31790@g4g2000hsf.googlegroups.com> On May 22, 6:53 pm, Duncan Grisby wrote: > I think ORBit is configured to only listen on its proprietary Unix > domain socket protocol by default, not TCP, so omniORB doesn't know > how to talk to it. You should either tell ORBit to listen on TCP > (Google for how), or use omniORB's naming service, which listens on > TCP by default. Yay, after replacing orbit2-nameserver by omniorb4-nameserver everything works fine. Thanks a lot for your comment! -Samuel From elliot at bentlogic.net Wed May 2 00:22:31 2007 From: elliot at bentlogic.net (Elliot Peele) Date: Wed, 02 May 2007 00:22:31 -0400 Subject: os.path.join In-Reply-To: <5FC95F49-2E5E-40A8-B688-375E8BD77DBB@jedimindworks.com> References: <1178069795.3201.1.camel@localhost.localdomain> <5FC95F49-2E5E-40A8-B688-375E8BD77DBB@jedimindworks.com> Message-ID: <1178079751.3201.4.camel@localhost.localdomain> On Tue, 2007-05-01 at 21:26 -0500, Michael Bentley wrote: > On May 1, 2007, at 8:36 PM, Elliot Peele wrote: > > > Why does os.path.join('/foo', '/bar') return '/bar' rather than > > '/foo/bar'? That just seems rather counter intuitive. > > It's the leading slash in '/bar'. os.path.join('/foo', 'bar') > returns '/foo/bar'. Right, but that seems rather counter intuitive to what os.path.join says it should do. """ join(a, *p) Join two or more pathname components, inserting '/' as needed """ Elliot From s at get.it.off.to.reply.informa.pl Tue May 1 08:24:54 2007 From: s at get.it.off.to.reply.informa.pl (Sebastian Kaliszewski) Date: Tue, 01 May 2007 14:24:54 +0200 Subject: SEO - Search Engine Optimization - Seo Consulting In-Reply-To: References: <1177808356.681710.42980@n76g2000hsh.googlegroups.com> Message-ID: Bob Phillips wrote: > You bottom posters really are a bunch of supercilious, self-righteous > bigots. Whatever. When reading answers to some statements normal people like first to see the statement then the response, not the other way around. Just because you're using broken tool (Outlook Express) it does not excuse you of being rude. Besides, reposting that spamming site address is idiotic by itself, regardless of top posting or not. [...] > And regardless of his response, Mr Bruney IS an MVP, he is clearly > knowledgeable in his subject, and his book is well enough thought of to make > me consider buying it. Regardless of who Mr Bruney is, this if completely offtopic on comp.lang.python, misc.writing, alt.consumers.uk-discounts.and.bargains and uk.people.consumers.ebay Just notice that you're posting to *more than one* group. Just please learn to use the damn reader! Even Outlook Express allows to set Followup-To: header and limit the polution. EOT From fumanchu at amor.org Wed May 23 11:34:48 2007 From: fumanchu at amor.org (fumanchu) Date: 23 May 2007 08:34:48 -0700 Subject: Cherrypy setup questions In-Reply-To: Message-ID: <1179934488.347133.7010@q75g2000hsh.googlegroups.com> On May 23, 6:11 am, Brian Blais wrote: > fumanchu wrote: > > > On May 22, 6:38 pm, Brian Blais wrote: > >> I'd like to start trying out some cherrypy apps, but I've > >> been having some setup problems. I think I need some > >> bone-head simple example to clear my understanding. :) > >> 1) can I configure cherrypy to look at requests only > >> off a base url, like: > >> > >> http://www.provider.com:8080/~myusername/apps > > > > Yes, you can. Assuming you're using the "cherrypy.quickstart" > > function, supply the "base url" in the "script_name" argument; for > > example: > > > > sn = 'http://www.provider.com:8080/~myusername/apps' > > cherrypy.quickstart(Root(), sn, config) > > > > Thanks for your reply, but for some reason it is not > working as stated. I'm probably missing something. No, you're not missing anything; my fault. I wasn't very awake when I wrote that, I guess. Don't include the hostname, just write: sn = '/~myusername/apps' cherrypy.quickstart(Root(), sn, config) > When I start, I usually get: > The Application mounted at '' has an empty config. That's normal behavior; just a warning, not an error. Robert Brewer System Architect Amor Ministries fumanchu at amor.org From steven.bethard at gmail.com Sun May 27 15:01:54 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 27 May 2007 13:01:54 -0600 Subject: ten small Python programs In-Reply-To: References: Message-ID: Steve Howell wrote: > --- Steven Bethard wrote: > >> Steve Howell wrote: >>> --- Steven Bethard >> wrote: >>>> I think I would rewrite the current unit-testing >>>> example to use the >>>> standard library unittest module:: >>>> >>>> # Let's write reusable code, and unit test >> it. >>>> def add_money(amounts): >>>> # do arithmetic in pennies so as not to >>>> accumulate float errors >>>> pennies = sum([round(int(amount * 100)) >> for >>>> amount in amounts]) >>>> return float(pennies / 100.0) >>>> import unittest >>>> class TestAddMoney(unittest.TestCase): >>>> def test_float_errors(self): >>>> >> self.failUnlessEqual(add_money([0.13, >>>> 0.02]), 0.15) >>>> >> self.failUnlessEqual(add_money([100.01, >>>> 99.99]), 200) >>>> self.failUnlessEqual(add_money([0, >>>> -13.00, 13.00]), 0) >>>> if __name__ == '__main__': >>>> unittest.main() >>>> >>> Just a minor quibble, but wouldn't you want the >> import >>> and test class to only get executed in the >> ___main__ >>> context? >> That would be fine too. In the real world, I'd put >> the tests in a >> different module. >> > > Maybe this is the first good example that motivates a > hyperlink to alternatives. Would you accept the idea > that we keep my original example on the SimplePrograms > page, but we link to a UnitTestingPhilosophies page, > and we show your alternative there? Or vice versa, > show your example on the first page, but then show > mine on the hyperlinked page? Sure. Either way is fine. STeVe From pangj at juno.com Thu May 17 01:27:10 2007 From: pangj at juno.com (Jeff Pang) Date: Thu, 17 May 2007 05:27:10 GMT Subject: Python Newbie Suggestions Message-ID: <20070516.222731.833.1730723@webmail34.lax.untd.com> An embedded and charset-unspecified text was scrubbed... Name: not available URL: -------------- next part -------------- As a newbie, Python has my vote for beginners. It is easy to get started with some quick and satisfying scripts but tricky to learn good OOP form. That's why I highly recommend the Programming Python Part 1 article that just came out in the June 2007 Linux Journal. You can use some of the sections in it to explain classes and instances to the kids. And I'd cast a second vote for www.diveintopython.org. Teresa -------------- next part -------------- An HTML attachment was scrubbed... URL: From nagle at animats.com Sun May 6 21:09:32 2007 From: nagle at animats.com (John Nagle) Date: Mon, 07 May 2007 01:09:32 GMT Subject: My newbie annoyances so far In-Reply-To: <1hxp15f.1bvtgo11ydx3cvN%aleax@mac.com> References: <1177688082.758043.133920@r30g2000prh.googlegroups.com> <_9pYh.1787$uJ6.894@newssvr17.news.prodigy.net> <1178400807.051103.95690@q75g2000hsh.googlegroups.com> <1hxp15f.1bvtgo11ydx3cvN%aleax@mac.com> Message-ID: Alex Martelli wrote: > John Nagle wrote: > > >>igouy2 at yahoo.com wrote: >> >>>On Apr 27, 9:07 am, John Nagle wrote: >>> >>> >>>>The CPython implementation is unreasonably slow compared >>>>to good implementations of other dynamic languages such >>>>as LISP and JavaScript. >>> >>> >>>Why do you say CPython is slower than JavaScript? Please provide >>>examples. >> >> See >> >> http://www.mozilla.org/projects/tamarin/faq.html >> >>Tamarin is a just-in-time compiler for Javascript. > > > ...and is not yet released, as far as I can tell; this makes it kind of > diffcult to verify any kinds of claims about its speed. Tamarind is inside the current implementation of Flash, but it's not into Firefox yet, apparently. The current SpiderMonkey implementation is nothing to get excited about in terms of performance. My point is that there are optimizing hard-code compiler implementations of many dynamic languages, including LISP, Self, and Smalltalk, but not Python. John Nagle From rene at korteklippe.de Tue May 15 08:50:41 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 15 May 2007 14:50:41 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <464996b9$0$10193$9b4e6d93@newsspool4.arcor-online.net> <4649a72d$0$10186$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <4649aca1$0$23148$9b4e6d93@newsspool1.arcor-online.net> Thorsten Kampe schrieb: > Just by repeating yourself you don't make your point more valid. You are doing just the same. Your argument that encouraging code-sharing is not a worthwhile goal is an ideologic one, just as the opposite argument is, too (I do think that code sharing is very different from sharing of material goods). That is why I do not think it makes alot of sense to argue about it. If you don't consider code sharing to be a value of its own, then that is of course also not an argument against this PEP. I just happen to have different beliefs. -- Ren? From stefan.behnel-n05pAM at web.de Fri May 25 13:09:21 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Fri, 25 May 2007 19:09:21 +0200 Subject: extra xml header with ElementTree? In-Reply-To: References: Message-ID: <46571841.8090502@web.de> Tim Arnold wrote: > Hi, I'm using ElementTree which is wonderful. I have a need now to write out > an XML file with these two headers: > > > > My elements have the root named tocbody and I'm using: > newtree = ET.ElementTree(tocbody) > newtree.write(fname) > > I assume if I add the encoding arg I'll get the xml header: > newtree = ET.ElementTree(tocbody) > newtree.write(fname,encoding='utf-8') > > but how can I get the into the tree? Try ET.ProcessingInstruction("NLS", 'TYPE="..."') Or try lxml.etree instead, it's ET compatible but has very good support for PIs starting with 1.3beta. http://codespeak.net/lxml/dev/ Stefan From castironpi at gmail.com Sat May 5 20:47:11 2007 From: castironpi at gmail.com (castironpi at gmail.com) Date: 5 May 2007 17:47:11 -0700 Subject: module console In-Reply-To: <1178411361.485947.251940@w5g2000hsg.googlegroups.com> References: <1178411361.485947.251940@w5g2000hsg.googlegroups.com> Message-ID: <1178412431.108089.247430@y5g2000hsa.googlegroups.com> On May 5, 7:29 pm, castiro... at gmail.com wrote: > Can I get the console to behave like it's in a module? > > So far I have inspect.getsource() working by setting the filename and > linenumbers of the return from compiler.parse(). I'm looking too. -me This at least gets a instance loaded; we'll see. import imp m=imp.new_module('aname') class A: pass m.A=A from pickle import * m.A.__module__='aname' import sys sys.modules['aname']=m a=m.A() loads(dumps(a)) #fb: From bj_666 at gmx.net Tue May 8 11:00:37 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 08 May 2007 17:00:37 +0200 Subject: ipython environment question References: Message-ID: In , Shane Geiger wrote: > Run the script and then try to change the variable project_name from the > ipython prompt and then type create() > and the new value you assigned will *not* be used. I tried to use "def > create(project_name = project_name):" Even that didn't work. > > What slight of hand is necessary? > > import os, sys > > project_name = 'python_packages' > group_name = 'sgeiger' > repo = '/var/svn' > > def create(repo=repo,group_name=group_name,project_name=project_name): > #def create(): > #os.system("sudo mkdir -p " + repo ) > #os.system("sudo svnadmin create " + repo) > #os.system("sudo chown -R " + group_name + " " + repo) > print "sudo mkdir -p " + repo + '/' + project_name > print "sudo svnadmin create " + repo + '/' + project_name > print "sudo chown -R " + group_name + " " + repo + '/' + project_name > > if __name__ == '__main__': > sys.argv.append('-cl') > from IPython.Shell import IPShellEmbed > ipshell = IPShellEmbed() > print "Please set these variables: project_name, group_name ...and > then type create()" > ### I even tried to put all my > ipshell() # this call anywhere in your program will start IPython You have to call the function with arguments. The default values are only evaluated once when the ``def`` statement is executed, not every time the function is called. Ciao, Marc 'BlackJack' Rintsch From ignoramus12143 at NOSPAM.12143.invalid Thu May 3 11:01:21 2007 From: ignoramus12143 at NOSPAM.12143.invalid (Ignoramus12143) Date: Thu, 03 May 2007 10:01:21 -0500 Subject: ignorance and intolerance in computing communties References: <1178120019.271716.299590@e65g2000hsc.googlegroups.com> <1178203772.243333.24990@p77g2000hsh.googlegroups.com> Message-ID: It is not that difficult to those of us who know math. Obvious analogy to the function below exists in 'perl'. double vectorAngle( double x, double y ) { double r2 = x*x+y*y; if( r2 == 0 ) return -10; // error case int quadrant = x > 0 ? (y >= 0 : 0 : 3) : (y > 0 ? 1 : 2); return pi/2 * quadrant + asin( abs(y)/sqrt( r2 ) ); } From nospam1.reifenberg at gmx.de Wed May 30 14:49:56 2007 From: nospam1.reifenberg at gmx.de (Nebur) Date: 30 May 2007 11:49:56 -0700 Subject: How can an Exception pass over an "except" clause ? In-Reply-To: <1180549843.351694.279660@p77g2000hsh.googlegroups.com> References: <1180540010.548057.220270@m36g2000hse.googlegroups.com> <1180549843.351694.279660@p77g2000hsh.googlegroups.com> Message-ID: <1180550996.429955.243300@u30g2000hsc.googlegroups.com> > > @Tijs: I think when re-raising, the backtrace will always point to the > line where it was re-raised but not to line 1265. (Or can we re-raise > an exception so that it preserves the backtrace of the "original" > exception?) @Tijs: Because of distrusting my own text above, I've checked re- raising ... and indeed, you've been right. "raise" does _not_ produce a new backtrace but uses the old one. Learned something new about Python now... I think that clearifies all the "magic" behaviour. Thank you, Ruben From nagle at animats.com Wed May 2 01:15:01 2007 From: nagle at animats.com (John Nagle) Date: Wed, 02 May 2007 05:15:01 GMT Subject: pre-PEP: Standard Microthreading Pattern In-Reply-To: References: Message-ID: dustin at v.igoro.us wrote: > PEP: XXX > Title: Standard Microthreading Pattern You've reinvented Modula processes. Except that Wirth did it better in Modula I. John Nagle From j25bravo at gmail.com Sat May 26 03:23:32 2007 From: j25bravo at gmail.com (mark) Date: 26 May 2007 00:23:32 -0700 Subject: Newbie help understanding... Message-ID: <1180164211.934421.64420@i38g2000prf.googlegroups.com> Hi I am trying to get a piece of code to work based on an exercise in a book. Any help appreciated. Can someone please explain what is going on here. I am trying to read from a text file a list of cards with the following format and sort firstly by suit and then by rank h 1 d 2 c 5 s 9 h2 d3 etc... I get the following error; Traceback (most recent call last): File "F:/###UNI###/ITC106/ass2/cardread.py", line 25, in t.append( t[0] + 400 ) AttributeError: 'str' object has no attribute 'append' def read_cards(filename): cards = [] for card in open(filename, 'r'): cards.append(card.strip()) return cards # read the deck of cards from a file filename = 'cards.txt' cards = read_cards(filename) for t in read_cards(filename): if t[1] == 'h': t.append( t[0] + 100 ) elif t[1] == 'd': t.append( t[0] + 200 ) elif t[1] == 'c': t.append( t[0] + 300 ) else: t.append( t[0] + 400 ) print read_cards(filename) Regards J From laurent.pointal at wanadoo.fr Tue May 1 10:24:30 2007 From: laurent.pointal at wanadoo.fr (Laurent Pointal) Date: Tue, 01 May 2007 16:24:30 +0200 Subject: Why are functions atomic? References: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> Message-ID: <46374c50$0$5112$ba4acef3@news.orange.fr> Michael wrote: > Why are functions atomic? (I.e. they are not copied.) > > For example, I would like to make a copy of a function so I can change > the default values: > >>>> from copy import copy >>>> f = lambda x: x >>>> f.func_defaults = (1,) >>>> g = copy(f) >>>> g.func_defaults = (2,) >>>> f(),g() > (2, 2) > > I would like the following behaviour: > >>>> f(),g() > (1,2) > > I know I could use a 'functor' defining __call__ and using member > variables, but this is more complicated and quite a bit slower. (I > also know that I can use new.function to create a new copy, but I > would like to know the rational behind the decision to make functions > atomic before I shoot myself in the foot;-) > > Thanks, > Michael. This dont make functions copiable but may resolve your default arguments problem. Under Python 2.5, see functools.partial(). http://docs.python.org/lib/partial-objects.html From jaywgraves at gmail.com Thu May 3 10:49:25 2007 From: jaywgraves at gmail.com (jay graves) Date: 3 May 2007 07:49:25 -0700 Subject: How to replace the last (and only last) character in a string? In-Reply-To: <1178202464.201578.211150@c35g2000hsg.googlegroups.com> References: <1178202464.201578.211150@c35g2000hsg.googlegroups.com> Message-ID: <1178203765.153466.51740@e65g2000hsc.googlegroups.com> On May 3, 9:27 am, Johny wrote: > Let's suppose > s='12345 4343 454' > How can I replace the last '4' character? > I tried > string.replace(s,s[len(s)-1],'r') > where 'r' should replace the last '4'. > But it doesn't work. > Can anyone explain why? Instead of doing it that way, you should use slicing. >>> s='12345 4343 454' >>> s = s[:-1] + 'r' >>> print s 12345 4343 45r >>> See http://docs.python.org/tut/node5.html#strings HTH. Jay Graves From vsapre80 at gmail.com Wed May 30 03:47:31 2007 From: vsapre80 at gmail.com (Vishal) Date: 30 May 2007 00:47:31 -0700 Subject: binascii.unhexlify ... not clear about usage, and output Message-ID: <1180511251.625790.280260@h2g2000hsg.googlegroups.com> Hi, I have a file with a long list of hex characters, and I want to get a file with corresponding binary characters here's what I did: >>> import binascii >>> f1 = 'c:\\temp\\allhex.txt' >>> f2 = 'c:\\temp\\allbin.txt' >>> sf = open(f1, 'rU') >>> df = open(f2, 'w') >>> slines = sf.readlines() >>> for line in slines: ... x = line.rstrip('\n') ... y = binascii.unhexlify(x) ... df.write(y) ... >>> df.close() >>> sf.close() But what I get is all garbage, atleast textpad and notepad show that I tried doing it for only one string, and this is what I am seeing on the interpreter: >>> x '0164' >>> y '\x01d' I was expecting 'y' would come out as a string with binary characters!!! What am i missing here? Can someone please help. Thanks and best regards, Vishal From ratchetgrid at googlemail.com Fri May 18 03:02:39 2007 From: ratchetgrid at googlemail.com (Nathan Harmston) Date: Fri, 18 May 2007 08:02:39 +0100 Subject: alternative to eclipse [ python ide AND cvs ] In-Reply-To: References: Message-ID: <676224240705180002w2259b48ds8bf8743a82330ad7@mail.gmail.com> I have had very few problems with eclipse on ubuntu with pydev installed. Is it still running under the gnu jvm, not the sun one? It was crashing on me until I changed them around, detials about changing it around on ubuntu anyway http://ubuntuguide.org/wiki/Ubuntu_Edgy#How_to_install_Java_Integrated_Development_Environment_.28Eclipse.29 Hope this helps, Nathan From gagsl-py2 at yahoo.com.ar Sat May 19 16:15:11 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 19 May 2007 17:15:11 -0300 Subject: _PyObject_New / PyObject_Init / PyInstance_New / etc? References: Message-ID: En Sat, 19 May 2007 10:54:32 -0300, Gre7g Luterman escribi?: > I'm so confuzzled! How do I instantiate my new C Python object from C? > I tried inserting some code with _PyObject_New and PyObject_Init: > > Then I compiled, went into the Python interpreter and tried it. I would > have expected Noddy_name to create and destroy a Noddy object just like > noddy2.Noddy() does from the interpreter, but it doesn't: From Python, you create a Noddy object by *calling* its type. Do the same in C: return PyObject_CallObject((PyObject *) &NoddyType, NULL); Or any other suitable variant of PyObject_CallXXX. (I've answered this same question yesterday, when I was not sure about this; then I've tried it and it appears to be working. But I've not read any docs telling this is *the* right way to create an object). > I've tried this as above, and with PyInstance_New, with PyObject_New (no > underscore), and PyObject_Call, but none of them work as I would expect. > So > what is the *CORRECT* way to do this? Obviously I'm neglecting something > important. PyInstance_New is for old style classes. PyObject_New only initializes the object structure, and this is enough for most builtin types that usually don't define __init__ (or tp_init). You were right with PyObject_Call, but maybe you didn't invoke it correctly. -- Gabriel Genellina From kyosohma at gmail.com Thu May 10 15:13:17 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 10 May 2007 12:13:17 -0700 Subject: Comparing dates problem In-Reply-To: <1178823142.101246.220660@l77g2000hsb.googlegroups.com> References: <1178746479.776908.319930@p77g2000hsh.googlegroups.com> <1178748764.663230.186570@y80g2000hsf.googlegroups.com> <1178823142.101246.220660@l77g2000hsb.googlegroups.com> Message-ID: <1178824397.102786.267560@l77g2000hsb.googlegroups.com> On May 10, 1:52 pm, kyoso... at gmail.com wrote: > On May 9, 5:12 pm, John Machin wrote: > > > > > On May 10, 7:34 am, kyoso... at gmail.com wrote: > > > > Hi, > > > > I am writing a reminder program for our Zimbra email client. One of > > > the requirements I was given was to automatically increment or > > > decrement the display to show something like the following: > > > > 5 minutes until appointment > > > > or > > > > 10 minutes past your appointment > > > > Either way, as each minute goes by, I need to increment it or > > > decrement it. I am having trouble finding a coherent way to take the > > > same date and compare just the number of minutes between them to find > > > the difference. Like if I have an appointment at 9:30 a.m. and the app > > > is loaded at 8 a.m., I need to know the number of minutes or hours and > > > minutes until the appointment. > > > > I have looked at the dateutils module and it has many comparison > > > methods, but they seem to only return the number of days or seconds. > > > Ermmm ... what's wrong with > > > minutes = seconds / 60.0 > > hours = minutes / 60.0 > > > ? > > I'm sure there is a hack for doing something like what you suggest, > but it would be messy. The problem is that I get a datetime object > returned and division really isn't something you can do to one of > those objects. Besides, if I had seconds returned, I would want to > multiply by 60, not divide. > > Maybe I misunderstand you. > > Mike Of course, after posting this, I felt very stupid... From ryntech at gmail.com Sat May 12 15:57:54 2007 From: ryntech at gmail.com (rynt) Date: 12 May 2007 12:57:54 -0700 Subject: Read from Windows Address Book (.wab file format) ? In-Reply-To: <1178994641.809507.127690@l77g2000hsb.googlegroups.com> References: <1178994641.809507.127690@l77g2000hsb.googlegroups.com> Message-ID: <1178999874.671116.318900@k79g2000hse.googlegroups.com> On May 12, 11:30?am, ??? wrote: > Hi all! > > I wonder if there's any Python module that could read from .wab file. > I googled but found nothing useful. Any idea? Thanks :) > > Rio Hi Rio, Don't know if there's a python module for this, but this link, http://msdn2.microsoft.com/en-us/library/ms629361.aspx defines the MS API for the address book, so you could roll your own. If all you need is to read the data though, you could export the address data into a CSV file (Python DOES have a module for this) or VCard format. IIRC, someone on this newsgroup was talking about VCard just the other day. HTH rynt From rurpy at yahoo.com Mon May 14 12:30:42 2007 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 14 May 2007 09:30:42 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <1179160242.787344.48060@h2g2000hsg.googlegroups.com> On May 14, 9:53 am, Michel Claveau wrote: > > - should non-ASCII identifiers be supported? why? > > - would you use them if it was possible to do so? in what cases? > > Yes. > And, more: yes yes yes > > Because: > > 1) when I connect Python to j(ava)Script, if the pages "connected" > contains objects with non-ascii characters, I can't use it ; snif... > > 2) when I connect Python to databases, if there are fields (columns) > with emphatic letters, I can't use class properties for drive these > fields. Exemples: > "cit?" (french translate of "city") > "t?l?phone" (for phone) > > And, because non-ASCII characters are possible, they are no-obligatory > ; consequently guys (snobs?) want stay in pure-ASCII dimension will > can. > > * sorry for my bad english * Can a discussion about support for non-english identifiers (1) conducted in a group where 99.9% of the posters are fluent speakers of english (2), have any chance of being objective or fair? Although probably not-sufficient to overcome this built-in bias, it would be interesting if some bi-lingual readers would raise this issue in some non-english Python discussion groups to see if the opposition to this idea is as strong there as it is here. (1) No quibbles about the distintion between non-english and non-ascii please. (2) Several posters have claimed non-native english speaker status to bolster their position, but since they are clearly at or near native-speaker levels of fluency, that english is not their native language is really irrelevant. From miles.chris at gmail.com Tue May 15 18:39:19 2007 From: miles.chris at gmail.com (Chris Miles) Date: 15 May 2007 15:39:19 -0700 Subject: PyObject_Print in gdb In-Reply-To: <1179234954.101397.247260@o5g2000hsb.googlegroups.com> References: <1179234954.101397.247260@o5g2000hsb.googlegroups.com> Message-ID: <1179268759.764304.37910@w5g2000hsg.googlegroups.com> I'm still not sure about PyObject_Print, but I found a better solution, using the Misc/gdbinit file from the Python source tree, which defines a pyo macro. Example: (gdb) pyo some_object object : [] type : list refcount: 1 address : 0x4b5940 $3 = void Cheers, Chris On May 15, 2:15 pm, Chris Miles wrote: > I've been using gdb to debug some Python extension modules lately, > which has been very handy, but cannot get PyObject_Print() to work > from within gdb, as recommended byhttp://wingware.com/doc/howtos/debugging-extension-modules-on-linux > > It recommends using "p PyObject_Print (obj, stderr, 0)" but stderr > (and stdout) symbols are never available for me. From bblais at bryant.edu Thu May 3 11:41:00 2007 From: bblais at bryant.edu (Brian Blais) Date: Thu, 03 May 2007 11:41:00 -0400 Subject: Organizing code - import question Message-ID: <463A028C.5020000@bryant.edu> Hello, I am trying to organize some of my code, and am having a little trouble with the import logic. I find I often have something like: MyPackage/ Part1/ # wants to use functions in Common/ __init__.py # does "from MyClass1 import MyClass1", etc,... MyClass1.py MyClass1a.py # depends on MyClass1 MyClass1b.py # depends on MyClass1 Part2/ # wants to use functions in Common/ __init__.py # does "from MyClass2 import MyClass2", etc,... MyClass2.py # depends on MyClass1 also, such as containing a list of MyClass1 MyClass2a.py # depends on MyClass2 MyClass2b.py # depends on MyClass2 Common/ __init__.py # does "import fun1,fun2", etc,... fun1.py fun2.py So I have some common utilities that both classes want to access, and I have two separate class definitions, of which one depends on the other. In MyClass2.py, I can't seem to do: import Common.fun1 or from Part1.MyClass1 import MyClass1 I think I am either missing some syntax/path thing, or I am thinking about the organization in entirely the wrong way. Currently, as a hack, I am simply copying the code from Common into the other two directories, and making a link to the Part1 directory in the Part2 so I can import it. There must be a better way, yes? thanks, Brian Blais -- ----------------- bblais at bryant.edu http://web.bryant.edu/~bblais From nogradi at gmail.com Wed May 16 18:24:50 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Thu, 17 May 2007 00:24:50 +0200 Subject: cPickle.dumps differs from Pickle.dumps; looks like a bug. In-Reply-To: <1179352356.025319.43310@w5g2000hsg.googlegroups.com> References: <1179335622.006820.22460@q23g2000hsg.googlegroups.com> <1179352356.025319.43310@w5g2000hsg.googlegroups.com> Message-ID: <5f56302b0705161524u5902320cy11e0f67a798e8089@mail.gmail.com> > > I've found the following strange behavior of cPickle. Do you think > > it's a bug, or is it by design? > > > > Best regards, > > Victor. > > > > from pickle import dumps > > from cPickle import dumps as cdumps > > > > print dumps('1001799')==dumps(str(1001799)) > > print cdumps('1001799')==cdumps(str(1001799)) > > > > outputs > > > > True > > False > > > > vicbook:~ victor$ 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.>>> > quit() > > > > vicbook:~ victor$ uname -a > > Darwin vicbook 8.9.1 Darwin Kernel Version 8.9.1: Thu Feb 22 20:55:00 > > PST 2007; root:xnu-792.18.15~1/RELEASE_I386 i386 i386 > > If you unpickle though will the results be the same? I suspect they > will be. That should matter most of all (unless you plan to compare > objects' identity based on their pickled version.) The OP was not comparing identity but equality. So it looks like a real bug, I think the following should be True for any function f: if a == b: f(a) == f(b) or not? Daniel From jadestar at idiom.com Mon May 14 17:17:51 2007 From: jadestar at idiom.com (James T. Dennis) Date: Mon, 14 May 2007 21:17:51 -0000 Subject: track cpu usage of linux application References: Message-ID: <1179177471.235450@smirk> Fabian Braennstroem wrote: > Hi, > I would like to track the cpu usage of a couple of > programs using python. Maybe it works somehow with > piping 'top' to python read the cpu load for a greped > application and clocking the the first and last > appearence. Is that a good approach or does anyone have > a more elegant way to do that? > Greetings! > Fabian If you're on a Linux system you might be far better accessing the /proc/$PID/stat files directly. The values you'd find therein are documented: http://www.die.net/doc/linux/man/man5/proc.5.html (among other places). Of course you could write you code to look for file and fall back to use the 'ps' command if it fails. In addition you can supply arguments to the 'ps' command to limit it to reporting just on the process(es) in which you are interested ... and to eliminate the header line and irrelevant columns of output. -- Jim Dennis, Starshine: Signed, Sealed, Delivered From michal.lipinski at gmail.com Fri May 25 18:43:31 2007 From: michal.lipinski at gmail.com (Michal Lipinski) Date: Sat, 26 May 2007 00:43:31 +0200 Subject: problem with eval while using PythonCard In-Reply-To: <1180130703.577624.167360@u30g2000hsc.googlegroups.com> References: <1180130097.439585.308510@g4g2000hsf.googlegroups.com> <1180130703.577624.167360@u30g2000hsc.googlegroups.com> Message-ID: <3203440c0705251543g106115bdhbfdff2f009833918@mail.gmail.com> now it's working just fine. but still I dont know why eval dont work ? and thx for help 25 May 2007 15:05:03 -0700, 7stud : > Here's a complete example: > > ################### > #create object 's': > > class S(object):pass > class X(object):pass > class Y(object):pass > > s = S() > s.components = X() > s.components.d1 = Y() > s.components.d2 = Y() > s.components.d3 = Y() > ###################### > > ###################### > set some initial values: > for i in range(1, 4): > obj = getattr(s.components, "d" + str(i)) > obj.text = "hello world" > ##################### > > ##################### > #change the values: > for i in range(1, 4): > getattr(s.components, "d" + str(i)).text = "goodybe" > ##################### > > ##################### > #print out the new values: > for i in range(1, 4): > print getattr(s.components, "d" + str(i)).text > ##################### > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Pozdrawiam Micha? Lipi?ski http://lipton.kom.pl From default at defaulter.net Fri May 4 09:16:20 2007 From: default at defaulter.net (default) Date: Fri, 04 May 2007 09:16:20 -0400 Subject: Firefighters at the site of WTC7 "Move away the building is going to blow up, get back the building is going to blow up." References: <1178161820.731367.264500@y80g2000hsf.googlegroups.com> <1hlj33p6aq838o2urk1dv6h75b5is4i2vd@4ax.com> <3TD_h.219$mR2.195@newssvr22.news.prodigy.net> Message-ID: On Fri, 04 May 2007 03:26:17 -0700, James Stroud wrote: >default wrote: >> On 2 May 2007 20:10:20 -0700, Midex wrote: >> >>> LIES LIES LIES LIES LIES >> >> Trying to understand the World Trade Center events is like waking up >> to act fifteen of a long Greek Tragedy. It needs a complex fabric of >> description to give a full picture. In explaining this crisis, we will >> be showing how the situation rests on layers of historical >> developments, layers of crises and solutions. >> >> shamelessly taken from: >> http://www.againstsleepandnightmare.com/ASAN/ASAN7/ASAN7.html >> >> The World After September 11th, 2001 >> >> The Old Mole >> >> By the time you read this, a crisis different from September 11th may >> well be foremost in people's minds. Read on. For us today, all the >> crises merge to one and we can see the form of Enron's Collapse or the >> Iraq War within September 11th and vice-versa. Now, beyond the death >> and destruction, the horror of an event like September 11th is the >> horror of losing control of your world. This feeling is an extension >> of the ordinary experience of being a resident of modern capitalist >> society. Here, work, commuting, shopping, and television are >> transmitted to you in ways that are beyond any individual or >> collective control. >> >> Damn good read. > >Marxist trash. We've been conditioned to think in those terms and the web site is communist. The philosophy of communism isn't so bad, it is the people and application that are the problem. Capitalism works right out of the box then begins to fray and deteriorate - again due to people and application. Either system creates an elite class and poor class with little or no middle ground. Each system is, ultimately, a failure. I'm not advocating either system, both are flawed as long as people can gain and hold power. Somewhere in there is a solution to the problems - I wouldn't presume to know the right course. Our politicians presume to know the right course - but they have no idea what is happening in the real world just their own political world. We have a mix of socialism and capitalism in the US no matter what the government/media hype says it is. Free market capitalism? hardly. -- ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From zykhou at gmail.com Wed May 2 20:38:52 2007 From: zykhou at gmail.com (Paul Kozik) Date: Wed, 2 May 2007 17:38:52 -0700 Subject: Handling Infinite Loops on Server Applications Message-ID: <60e9f3330705021738v7896e3a8hc9e9d6e2199369e3@mail.gmail.com> I'm working with a small server program I'm writing for a small video game. The main class constructor starts a thread that handles socket connections, which itself starts new threads for each user connection. The actual server program itself however needs to wait in the background, but continue looping as not to close the running threads. The problem is, simply running a [while True: pass] main loop in this style eats precious CPU cycles (and for nothing). If it waits for input, such as a socket.accept() or raw_input(), this problem does not occur (obviously because it's not constantly looping). What would be the best way to handle this, perhaps in a fashion similar to how most server programs are handled (with arguments such as [apache start], [apache stop])? Any guides towards this type of application development? From ken at theoryyalgebra.com Wed May 2 20:45:30 2007 From: ken at theoryyalgebra.com (Ken Tilton) Date: Wed, 02 May 2007 20:45:30 -0400 Subject: Microsoft's Dynamic Languages Runtime (DLR) In-Reply-To: <1178151574.302703.205560@l77g2000hsb.googlegroups.com> References: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> <1178151313.421106.43130@o5g2000hsb.googlegroups.com> <1178151574.302703.205560@l77g2000hsb.googlegroups.com> Message-ID: sturlamolden wrote: > On May 3, 2:15 am, Kaz Kylheku wrote: > > >>Kindly refrain from creating any more off-topic, cross-posted threads. >>Thanks. > > > The only off-topic posting in this thread is your own (and now this > one). > Begone. FWIW, I took Kaz's remark to be more of a joke than an actual cease-desist thing, partly because we here recorgnize that every nod to dynamic languages brings us one day closer to the ascendance of Common Lisp to Its Rightful Place on the throne and all other languages being pushed into the sea, and partly because we all actually enjoy long, drawn-out, flamewars with other NGs. For example, my guess is that the DLR/Iron Python just proves that the CLR had enough chops to support a hack like Python, but not enough to support The Greatness of Common Lisp. See how that works? :) kenny -- http://www.theoryyalgebra.com/ "Algebra is the metaphysics of arithmetic." - John Ray "As long as algebra is taught in school, there will be prayer in school." - Cokie Roberts "Stand firm in your refusal to remain conscious during algebra." - Fran Lebowitz "I'm an algebra liar. I figure two good lies make a positive." - Tim Allen From nagle at animats.com Mon May 14 00:44:29 2007 From: nagle at animats.com (John Nagle) Date: Mon, 14 May 2007 04:44:29 GMT Subject: BeautifulSoup vs. real-world HTML comments - possible fix In-Reply-To: References: <1175711322.448629.20300@y80g2000hsf.googlegroups.com> <1175717833.872281.6300@l77g2000hsb.googlegroups.com> <1175724136.054215.249970@p77g2000hsh.googlegroups.com> Message-ID: John Nagle wrote: > Note what happens when a bad declaration is found. > SGMLParser.parse_declaration > raises SGMLParseError, and the exception handler just sucks up the rest > of the > input (note that "rawdata[i:]"), treats it as unparsed data, and advances > the position to the end of input. > > That's too brutal. One bad declaration and the whole parse is messed up. > Something needs to be done at the BeautifulSoup level > to get the parser back on track. Maybe suck up input until the next ">", > treat that as data, then continue parsing from that point. That will do > the right thing most of the time, although bad declarations containing > a ">" will still be misparsed. > > How about this patch? > > except SGMLParseError: # bad decl, must recover > k = self.rawdata.find('>', i) # find next ">" > if k == -1 : # if no find > k = len(self.rawdata) # use entire string > toHandle = self.rawdata[i:k] # take up to ">" as data > self.handle_data(toHandle) # treat as data > j = i + len(toHandle) # pick up parsing after ">" > I've been testing this, and it's improved parsing considerably. Now, common lines like don't stop parsing. John Nagle From eugene.vandenbulke at gmail.com Wed May 9 15:16:48 2007 From: eugene.vandenbulke at gmail.com (EuGeNe Van den Bulke) Date: Wed, 09 May 2007 21:16:48 +0200 Subject: preferred windows text editor? References: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> Message-ID: T. Crane wrote: > Right now I'm using Notepad++. What are other people using? > > trevis > > VIM here as well ... here we go again :P EuGeNe -- http://www.3kwa.com From wgwigw at gmail.com Sat May 26 22:00:45 2007 From: wgwigw at gmail.com (momobear) Date: 26 May 2007 19:00:45 -0700 Subject: a bug in python windows service? Message-ID: <1180231245.444827.171390@g37g2000prf.googlegroups.com> I feel really puzzled about fellowing code, please help me finger out what problem here. import threading class workingthread(threading.Thread): def __init__(self): self.quitEvent = threading.Event() self.waitTime = 10 threading.Thread.__init__(self) def run(self): while not self.quitEvent.isSet(): self.quitEvent.wait(self.waitTime) def join(self, timeout = None): self.quitEvent.set() threading.Thread.join(self, timeout) import win32serviceutil import win32event class testTime(win32serviceutil.ServiceFramework): _svc_name_ = "testTime" _svc_display_name_ = "testTime" _svc_deps_ = ["EventLog"] def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) self.thread = workingthread() def SvcStop(self): win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): self.thread.run() win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) self.thread.join() if __name__ == '__main__': win32serviceutil.HandleCommandLine(testTime) each time I got the fellowing result, anyone can point out what's wrong in it? E:\code\monitor2>testTime.py debug Debugging service testTime- press Ctrl+C to stop. Stopping debug service. Error 0xC0000003 - The instance's SvcRun() method failed File "C:\Python24\Lib\site-packages\win32\lib\win32serviceutil.py", line 785, in SvcRun self.SvcDoRun() File "E:\code\monitor2\testTime.py", line 35, in SvcDoRun self.thread.run() File "E:\code\monitor2\testTime.py", line 12, in run self.quitEvent.wait(self.waitTime) File "C:\Python24\lib\threading.py", line 348, in wait self.__cond.wait(timeout) File "C:\Python24\lib\threading.py", line 222, in wait _sleep(delay) exceptions.IOError: (4, 'Interrupted function call') From robert.rawlins at thinkbluemedia.co.uk Tue May 1 23:19:27 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Wed, 2 May 2007 04:19:27 +0100 Subject: test In-Reply-To: References: Message-ID: <001801c78c68$b112df80$13389e80$@rawlins@thinkbluemedia.co.uk> Test response :-D -----Original Message----- 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 Ray Sent: 02 May 2007 04:05 To: python-list at python.org Subject: test test only -- http://mail.python.org/mailman/listinfo/python-list From schliep at molgen.mpg.de Thu May 10 10:52:59 2007 From: schliep at molgen.mpg.de (Alexander Schliep) Date: Thu, 10 May 2007 16:52:59 +0200 Subject: Designing a graph study program References: <1178619753.077639.112510@q75g2000hsh.googlegroups.com> <1178801172.772583.287050@q75g2000hsh.googlegroups.com> Message-ID: andrea writes: > On 9 Mag, 09:10, Alexander Schliep wrote: >> Check outhttp://gato.sf.net(LGPL license). It does exactly what you >> want to do and there is a binary for MacOS X. Algorithms are implemented >> using Gato's graph class and rudimentary visualizations you get for free >> by replacing standard data structures (e.g., a vertex queue) by >> animated ones (AnimatedVertexQueue). >> > Very very nice well done! Thanks. > I'd like to do something similar, just to learn something new... Gato is open source and I'd be happy to collaborate. There are quite a few areas (e.g. SVG export, displays for data structure contents, more complete 3D support, polygon edges, running backwards?) which need work. > Could you explain me how you designed it?? How is the step mechanism > done?? The algorithm is executed by a subclass of the Python debugger (see Gato.py). A Tk event mechanism is used to step to the next line if you are in running mode. Otherwise the user steps manually. The visualizations are done with animated data structures, which animate changes to their internal state with respect to the graph: e.g., when you add or remove v to/from an AnimatedVertexQueue it changes v's color. Tk has a canvas which does object-oriented drawing. A line is not just a bunch of pixels but rather an object which you can move, scale, has callbacks. I dislike Tcl, but Tk is amazing, even it it looks 1980s. There is a paper http://algorithmics.molgen.mpg.de/preprints/2000-CATBox-MTCM.pdf describing the ideas. Best, Alexander From howe.steven at gmail.com Fri May 4 17:39:58 2007 From: howe.steven at gmail.com (Steven Howe) Date: Fri, 04 May 2007 14:39:58 -0700 Subject: Microsoft's Dynamic Languages Runtime (DLR) In-Reply-To: <1178313159.059210.97560@y80g2000hsf.googlegroups.com> References: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> <1178151313.421106.43130@o5g2000hsb.googlegroups.com> <1178151574.302703.205560@l77g2000hsb.googlegroups.com> <1178296035.993859.183720@n59g2000hsh.googlegroups.com> <1178313159.059210.97560@y80g2000hsf.googlegroups.com> Message-ID: <463BA82E.8040400@gmail.com> Fuzzyman wrote: > On May 4, 5:27 pm, Kaz Kylheku wrote: > >> On May 2, 5:19 pm, sturlamolden wrote: >> >> >>> On May 3, 2:15 am, Kaz Kylheku wrote: >>> >>>> Kindly refrain from creating any more off-topic, cross-posted threads. >>>> Thanks. >>>> >>> The only off-topic posting in this thread is your own (and now this >>> one). >>> >> You are making a very clumsy entrance into these newsgroups. So far >> you have started two cross-posted threads. The first is only topical >> in comp.lang.python (how to emulate macros in Python). This one is >> topical in neither one, since it is about Microsoft DLR. >> >> It's quite possible that some Lisp and Python programmers have a >> strong interest in Microsoft DLR. Those people who have such an >> interest (regardless of whether they are Lisp and Python user also) >> and who like to read Usenet will almost certainly find a Microsoft DLR >> newsgroup for reading about and discussing Microsoft DLR. Do you not >> agree? >> >> > > Given that the DLR is a dynamic language framework, abstracted out of > the IronPython 1.0 release, and that it also runs on top of the core > CLR shipped with SilverLight meaning that for the first time sandboxed > Python scripts can run in the browser... > > It would seem entirely on topic for a Python newsgroup.... very on- > topic... > > Fuzzyman > http://www.voidspace.org.uk/ironpython/index.shtml > > > >> Also note that there is very rarely, if ever, any good reason for >> starting a thread which is crossposted among comp.lang.* newsgroups, >> even if the subject contains elements that are topical in all of them >> (yours does not). >> >> >>> Begone. >>> >> You are childishly beckoning Usenet etiquette to be gone so that you >> may do whatever you wish. But I trust that you will not, out of spite >> for being rebuked, turn a few small mistakes into a persistent style. >> > > > Thank goodness! I was getting ready to filter the DLR crap out. If it's from microsoft, it got to be crap. sph -- HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 From aisaac at american.edu Wed May 2 08:10:16 2007 From: aisaac at american.edu (Alan Isaac) Date: Wed, 02 May 2007 12:10:16 GMT Subject: relative import broken? References: <1hxa9x3.c0unyd1jw7vu9N%aleax@mac.com> <1hxcdkq.47p2r6beuctcN%aleax@mac.com> <1hxeg2v.1ct59rv3oyq87N%aleax@mac.com> <7nNZh.4420$st3.1414@trnddc06> <1hxgczf.1l5eh5j1vln0z9N%aleax@mac.com> Message-ID: "Alex Martelli" wrote in message news:1hxgczf.1l5eh5j1vln0z9N%aleax at mac.com... > So what do you think the answer should be? Well I'm clearly not seeing into the depths of this, so I'm not going to propose anything. But to stick close to my example, I am not clear why a script when executed could not do imports relative to __file__. This seems like natural behavior to me. Thanks, Alan Isaac From mail at timgolden.me.uk Thu May 10 03:37:43 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 10 May 2007 08:37:43 +0100 Subject: Comparing dates problem In-Reply-To: <1178746479.776908.319930@p77g2000hsh.googlegroups.com> References: <1178746479.776908.319930@p77g2000hsh.googlegroups.com> Message-ID: <4642CBC7.5060007@timgolden.me.uk> kyosohma at gmail.com wrote: > I am writing a reminder program for our Zimbra email client. One of > the requirements I was given was to automatically increment or > decrement the display to show something like the following: > > 5 minutes until appointment > > or > > 10 minutes past your appointment > > > Either way, as each minute goes by, I need to increment it or > decrement it. I am having trouble finding a coherent way to take the > same date and compare just the number of minutes between them to find > the difference. Like if I have an appointment at 9:30 a.m. and the app > is loaded at 8 a.m., I need to know the number of minutes or hours and > minutes until the appointment. Not the most elegant piece of code on earth, but this piece of code works for me (cut-and-pasted directly from a working project, so doesn't *exactly* match your requirement). def deltastamp (now, then): def pluralise (base, n): if n > 1: return "%d %ss" % (n, base) else: return "%d %s" % (n, base) if now > then: output_format = "%s ago" delta = now - then else: output_format = "in %s" delta = then - now days = delta.days if days <> 0: wks, days = divmod (days, 7) if wks > 0: output = pluralise ("wk", wks) else: output = pluralise ("day", days) else: mins, secs = divmod (delta.seconds, 60) hrs, mins = divmod (mins, 60) if hrs > 0: output = pluralise ("hr", hrs) elif mins > 0: output = pluralise ("min", mins) else: output = pluralise ("sec", secs) return output_format % output TJG From gh at gregor-horvath.com Wed May 16 23:09:52 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Thu, 17 May 2007 05:09:52 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179344264.595644.136440@h2g2000hsg.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179333797.634234.245830@k79g2000hse.googlegroups.com> <1179344264.595644.136440@h2g2000hsg.googlegroups.com> Message-ID: sjdevnull at yahoo.com schrieb: > On May 16, 12:54 pm, Gregor Horvath wrote: >> Istvan Albert schrieb: >> >> So the solution is to forbid Chinese XP ? >> > > It's one solution, depending on your support needs. > That would be a rather arrogant solution. You would consider dropping the language and culture of millions of users because a small number of support team staff does not understand it? I would recommend to drop the support team and the management that even considers this. This PEP is not a technical question. Technically it would no change much. The underlying question is a philosophical one. Should computer programming only be easy accessible to a small fraction of privileged individuals who had the luck to be born in the correct countries? Should the unfounded and maybe xenophilous fear of loosing power and control of a small number of those already privileged be a guide for development? Gregor From andrea.gavana at gmail.com Thu May 17 04:30:23 2007 From: andrea.gavana at gmail.com (Andrea Gavana) Date: Thu, 17 May 2007 09:30:23 +0100 Subject: PEP 3131: Supporting Non-ASCII Identifiers Message-ID: Hi All, > In summary, this PEP proposes to allow non-ASCII letters as > identifiers in Python. In primis, I would like to congratulate with Martin to have started one of the most active threads (flame wars? :- D ) in the python-list history. By scanning the list from January 2000 to now, this is the current Python Premier League for Posts (truncated at position 10): 01) merits of Lisp vs Python | 832 | Mark Tarver | December-2006 02) For review: PEP 308 - If-then-else expression | 728 | Guido van Rossum | February-2003 03) Python syntax in Lisp and Scheme | 665 | mike420 at ziplip.com | October-2003 04) Python from Wise Guy's Viewpoint | 495 | mike420 at ziplip.com | October-2003 05) Microsoft Hatred FAQ | 478 | Xah Lee | October-2005 06) Why is Python popular, while Lisp and Scheme aren't? | 430 | Oleg | November-2002 07) Xah Lee's Unixism | 397 | Pascal Bourguignon | August-2004 08) PEP 285: Adding a bool type | 361 | Guido van Rossum | March-2002 09) Jargons of Info Tech industry | 350 | Xah Lee | August-2005 10) PEP 3131: Supporting Non-ASCII Identifiers | 326 | Martin v. Lowis | May-2007 (It may come screwed up in the mail, so for those interested I attach the results in a small text file which contains the first 50 positions). It has been generated with a simple Python script: you can find it at the end of the message. It's slow as a turtle (mainly because of the use of urllib and the sloppiness of my internet connection yesterday evening), but it works. I obviously will accept all the suggestions for improvements on the script, as I am only a Python amateurish programmer. > So, please provide feedback, e.g. perhaps by answering these > questions: > - should non-ASCII identifiers be supported? why? +1, obviously. As an external observer, it has been extremely interesting to follow all the discussions that this PEP raised. It has also been funny, as by reading some of the posts it seemed to me that my grandmother knows more about unicode with respect to some conclusions depicted there :-D :-D . But keep them coming, they are a valuable resource for low-skilled programmers like me, there is always something new to learn, really. > - would you use them if it was possible to do so? in what cases? I will for my personal projects and for our internal applications that will not go public. As for the usual objection: > I think your argument about "isolated projects" is flawed. It is not at > all unusual for code that was never intended to be public, whose authors > would have sworn that it will never ever be need to read by anyone > except themselves, to surprisingly go public at some point in the future. raise NoWayItWillGoPublicError For Public Domain code, I will surely stick with the standard coding style we have right now. I thought we were all adults here. I really imagine what it would happen if we gather all together around a table for a Python-dining: as soon as PEP 3131 discussion pops in, we would start throwing food to each other like 5 years-old puckish boys :-D :-D Andrea. "Imagination Is The Only Weapon In The War Against Reality." http://xoomer.virgilio.it/infinity77/ -------------- next part -------------- *********************************** * Python Premier League For Posts * *********************************** POST SCORE AUTHOR DATE 01) merits of Lisp vs Python | 832 | Mark Tarver | December-2006 02) For review: PEP 308 - If-then-else expression | 728 | Guido van Rossum | February-2003 03) Python syntax in Lisp and Scheme | 665 | mike420 at ziplip.com | October-2003 04) Python from Wise Guy's Viewpoint | 495 | mike420 at ziplip.com | October-2003 05) Microsoft Hatred FAQ | 478 | Xah Lee | October-2005 06) Why is Python popular, while Lisp and Scheme aren't? | 430 | Oleg | November-2002 07) Xah Lee's Unixism | 397 | Pascal Bourguignon | August-2004 08) PEP 285: Adding a bool type | 361 | Guido van Rossum | March-2002 09) Jargons of Info Tech industry | 350 | Xah Lee | August-2005 10) PEP 3131: Supporting Non-ASCII Identifiers | 326 | "Martin v. Löwis" | May-2007 11) Xah's Edu Corner: What is Expressiveness in a Computer Langu | 306 | Xah Lee | March-2006 12) (no subject) | 296 | richer at eastmail.com | January-2000 13) PEP0238 lament | 276 | Arthur_Siegel at rsmi.com | July-2001 14) A critic of Guido's blog on Python's lambda | 260 | Xah Lee | May-2006 15) Could Python supplant Java? | 255 | netvegetable | August-2002 16) age of Python programmers | 250 | Lucas Raab | August-2004 17) What's better about Ruby than Python? | 246 | Brandon J. Van Every | August-2003 18) Why don't people like lisp? | 236 | Francis Avila | October-2003 19) Language change and code breaks | 226 | Terry Reedy | July-2001 20) Perl is worse! (was: Python is Wierd!) | 214 | Jonathan | July-2000 21) Case-sensitivity: why -- or why not? (was Re: Damnation!) | 212 | Guido van Rossum | May-2000 22) [EVALUATION] - E02 - Support for MinGW Open Source Compiler | 207 | Ilias Lazaridis | February-2005 23) anything like C++ references? | 201 | Tom Plunket | July-2003 24) Why are there no ordered dictionaries? | 192 | Christoph Zwerschke | November-2005 25) Autocoding project proposal. | 190 | Timothy Rue | January-2002 26) PEP-308 a "simplicity-first" alternative | 181 | holger krekel | February-2003 27) Class Variable Access and Assignment | 170 | Graham | November-2005 28) Python's simplicity philosophy (was Re: reduce()--what is it | 168 | Robin Becker | November-2003 39) What is a type error? | 168 | David Hopwood | June-2006 30) The Industry choice | 163 | Sridhar R | December-2004 31) Still no new license -- but draft text available | 163 | Guido van Rossum | August-2000 32) Wheel-reinvention with Python (was: Ten Essential Developm | 161 | en.karpachov at ospaz.ru | July-2005 33) Will python never intend to support private, protected and p | 159 | could ildg | September-2005 34) does python have useless destructors? | 159 | Michael P. Soulier | June-2004 35) What is Expressiveness in a Computer Language [off-topic] | 157 | David Hopwood | June-2006 36) Python to use a non open source bug tracker? | 155 | Giovanni Bajo | October-2006 37) PEP 255: Simple Generators | 154 | Tim Peters | June-2001 38) PEP 276 Simple Iterator for ints (fwd) | 149 | Lulu of the Lotus-Eaters | November-2001 39) Of what use is 'lambda'??? | 145 | tye4 | September-2000 40) python coding contest | 145 | Simon Hengel | December-2005 41) Could Emacs be rewritten in Python? | 145 | Patrick K. O'Brien | April-2003 42) Python vs. C++ Builder - speed of development | 143 | pu | January-2003 43) Typing system vs. Java | 143 | John Goerzen | July-2001 44) Let's Talk About Lambda Functions! | 143 | Britt A. Green | July-2002 45) proposed language change to int/int==float (was: PEP0238 lam | 142 | Skip Montanaro | July-2001 46) Favorite non-python language trick? | 141 | Joseph Garvin | June-2005 47) Unification of Methods and Functions | 141 | David MacQuigg | April-2004 48) Python's 8-bit cleanness deprecated? | 138 | Roman Suzi | February-2003 49) Status of PEP's? | 138 | Gonçalo Rodrigues | February-2002 Scanning Process Took: 01h:57m:34s Bye Bye From FlameWars :-D -------------- next part -------------- # -*- coding: utf-8 -*- import urllib import heapq import datetime import time from operator import itemgetter defaultUrl = '''http://mail.python.org/pipermail/python-list/%(postTime)s/thread.html''' MAXTHREADLEN = 60 def fractSec(s): min, s = divmod(s, 60) h, min = divmod(min, 60) return h, min, s def ReadUrl(url): pythonList = urllib.urlopen(url) pythonThreads = pythonList.read() pythonList.close() return pythonThreads.split("\n") def AssignThreads(singleThread, flameDict, postDate): for indx, thread in enumerate(singleThread): # We check only the messages embedded in the
  • tag if "
  • " not in thread: continue threadTitle = thread.split(">")[-1:] threadTitle = "".join(threadTitle) threadAuthor = singleThread[indx+2].replace("", "") # Check if the flameDict has this key keys = flameDict.keys() if threadTitle in keys: flameDict[threadTitle][0] += 1 else: # Try to find a renamed thread that still has # the original title in it renamedThread = False for key in keys: if threadTitle in key: flameDict[key][0] += 1 renamedThread = True break if not renamedThread: # That's really a new thread flameDict[threadTitle] = [1, threadAuthor, postDate] def FlameWars(): localtime = time.localtime() currentMonth, currentYear = localtime.tm_mon, localtime.tm_year months = xrange(1, 13) years = xrange(2000, currentYear+1) numScanned = 0 flameDict = {} # Loop over the selected years for year in years: # Loop over the selected months for month in months: # Don't go further than the current time if month > currentMonth and year == currentYear: return flameDict # Format the date for the web page theDate = datetime.date(year, month, 1) dateDict = dict(postTime=theDate.strftime("%Y-%B")) print "Examining Posts At", theDate.strftime("%B-%Y") # Build the url as a dog meal for urllib url = defaultUrl % dateDict singleThread = ReadUrl(url) # Here we go... scan for an esisting thread in Python newsgroup AssignThreads(singleThread, flameDict, theDate.strftime("%B-%Y")) numScanned += 1 if numScanned%4 == 0: # eliminate the less common posts older than 4 months # Here I am taking only the 50 most common one bestPost = heapq.nlargest(50, flameDict.iteritems(), itemgetter(1)) numScanned = 0 return flameDict def PrettyPrint(flameDict): print "\n\n***********************************" print "* Python Premier League For Posts *" print "***********************************\n" maxThreadLen = maxUserLen = 0 for key, values in flameDict: # Find the longest thread name maxThreadLen = min(MAXTHREADLEN, max(maxThreadLen, len(key))) # Find the longest user name maxUserLen = max(maxUserLen, len(values[1])) print "POST" + " "*maxThreadLen + " SCORE" + " "*3 + "AUTHOR" + \ " "*maxUserLen + "DATE\n" for indx, items in enumerate(flameDict): # Format a pretty print string # I know is a mess! lenThread = len(items[0][0:MAXTHREADLEN]) lenUser = len(items[1][1]) concat = "%02d"%(indx+1) + ") " + items[0][0:MAXTHREADLEN] + \ " "*(maxThreadLen-lenThread) + \ " | " + "%4s"%items[1][0] + " | " + items[1][1] + \ " "*(maxUserLen-lenUser) + " | " + items[1][2] print concat if __name__ == "__main__": startTime = time.time() print "\n\nFlameWars Started... It May Take A While :-D\n" flameDict = FlameWars() flameDict = heapq.nlargest(50, flameDict.iteritems(), itemgetter(1)) PrettyPrint(flameDict) endTime = time.time() h, m, s = fractSec(endTime-startTime) print "\nScanning Process Took: %02dh:%02dm:%02ds\n"%(h, m, s) print "\nBye Bye From FlameWars :-D\n" From S.Mientki-nospam at mailbox.kun.nl Fri May 18 17:22:34 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Fri, 18 May 2007 23:22:34 +0200 Subject: Python compared to other language In-Reply-To: References: Message-ID: <92e04$464e1855$d443bb3a$4136@news.speedlinq.nl> scott wrote: > Hi all, > > I have been looking at the various programming languages available. > I have programed in Basic since I was a teenager and I also have a basic > understanding of C, but I want something better. > > Can anybody tell me the benefits and weaknesses of using Python? > hi Scott, coming from Basic, I think Python might be a very good (maybe even th? best) choice. I've been searching for the past few years for a universal language, in which I can do everything, whether it's - a normal (graphical) user application, - a program which is downloaded in a small micro-controller - an interactive webpage design - performing educational / scientific calculations now this can all (well almost) be done in Python. (a year ago I thought it was PHP, but it can't do small micros and scientific work) The major disadvantage of Python, (at least if you compare it with Visual Basic, Delphi, Kylix, Lazarus), is the somewhat limited (or more difficult) building of a graphical user interface. I've rewritten a few pieces of code from both MatLab and Delphi (comparable with Basic), into Python, and it's really great, number of sourcecode lines decreased to about 30% !! But as others said, try it yourself. cheers, Stef Mientki From p.lavarre at ieee.org Thu May 31 17:36:19 2007 From: p.lavarre at ieee.org (p.lavarre at ieee.org) Date: 31 May 2007 14:36:19 -0700 Subject: FAQ: how to vary the byte offset of a field of a ctypes.Structure In-Reply-To: References: <1180634138.944362.88590@d30g2000prg.googlegroups.com> Message-ID: <1180647379.643469.39670@d30g2000prg.googlegroups.com> """ Thomas, Ouch ouch I must have misunderstood what you meant by "use the dynamic nature of Python, and (re-)define the data type after the required size is already known, on a case by case basis". Do you have an example of what you meant? I searched but did not find. Are those your words? Yes, to declare strings of strings in Python would be to express a familiar idea that I don't know how to say well in C. These are standard structs that I exchange with third parties, e.g., me editing Class files read later by a Java interpreter, so I can't avoid having to deal with this complexity designed into them. For discussion I've simplified the problem: back in real life I have a few dozen variations of structs like this to deal with. The following Python mostly works, but only at the cost of rewriting the small part of CTypes that I need for this app. """ import binascii import struct class Struct: def __init__(self, declarations = []): """Add initial values to self and list the names declared.""" names = [] for (initial, name) in declarations: names += [name] python = ' '.join(['self.' + name, '=', 'initial']) exec python self._names_ = names def _fields_(self): """List the fields.""" fields = [] for name in self._names_: python = 'self.' + name fields += [eval(python)] return fields def _pack_(self): """Pack a copy of the fields.""" packs = '' for field in self._fields_(): packs += field._pack_() return packs def _size_(self, bytes = None): """Count the bytes of the fields.""" return len(self._pack_()) def _unpack_(self, bytes): """Count the bytes of a copy of the fields.""" offset = 0 for field in self._fields_(): size = field._size_(bytes[offset:]) field._unpack_(bytes[offset:][:size]) offset += size if offset != len(bytes): why = ('_unpack_ requires a string argument' 'of length %d' % offset) raise struct.error(why) class Field(Struct): """Contain one value.""" def __init__(self, value = 0): self._value_ = value def _pack_(self): raise AttributeError('abstract') def _unpack_(self, bytes): raise AttributeError('abstract') class Byte(Field): """Contain one byte.""" def _pack_(self): return struct.pack('B', self._value_) def _unpack_(self, bytes): self._value_ = struct.unpack('B', bytes)[0] class ByteArray(Field): """Contain the same nonnegative number of bytes always.""" def _pack_(self): return self._value_ def _unpack_(self, bytes): if len(bytes) == len(self._value_): self._value_ = bytes else: why = ('_unpack_ requires a string argument' 'of length %d' % len(self._value_)) raise struct.error(why) class Symbol(Struct): """Contain a count of bytes.""" def __init__(self, value = ''): Struct.__init__(self, [ (Byte(), 'length'), (ByteArray(value), 'bytes')]) self._pack_() def _size_(self, bytes = None): return ord(bytes[0]) def _pack_(self): self.length = Byte(self.length._size_() + self.bytes._size_()) return Struct._pack_(self) class TwoSymbols(Struct): """Contain two Symbols.""" def __init__(self, values = ['', '']): Struct.__init__(self, [ (Symbol(values[0]), 'first'), (Symbol(values[1]), 'second')]) zz = Symbol() print binascii.hexlify(zz._pack_()).upper() # 01 zz = Symbol() zz.bytes = ByteArray('left') zz._unpack_(zz._pack_()) ; print repr(zz._pack_()) # '\x05left' zz = Symbol() zz.bytes = ByteArray('right') zz._unpack_(zz._pack_()) ; print repr(zz._pack_()) # '\x06right' zz = TwoSymbols() zz.first.bytes = ByteArray('hi') zz.second.bytes = ByteArray('bye') zz._unpack_(zz._pack_()) ; print repr(zz._pack_()) # '\x03hi\x04bye' print zz._size_() # 7 yy = ''' def yyFunc(self): return [self.length, self.bytes] ''' exec yy Symbol._fields_ = yyFunc zz = TwoSymbols(['alef', 'bet']) zz._unpack_(zz._pack_()) ; print repr(zz._pack_()) From martin at v.loewis.de Thu May 17 07:08:42 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 17 May 2007 13:08:42 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179160242.787344.48060@h2g2000hsg.googlegroups.com> Message-ID: <464C37BA.3010308@v.loewis.de> > A possible modification to the PEP would be to permit identifiers to > also include \uxxxx and \Uxxxxxxxx escape sequences (as some other > languages already do). Several languages do that (e.g. C and C++), but I deliberately left this out, as I cannot see this work in a practical way. Also, it could be added later as another extension if there is an actual need. > I think this would remove several of the objections: such as being > unable to tell at a glance whether someone is trying to spoof your > variable names, If you are willing to run a script on the patch you receive, you can perform that check even without having support for the \u syntax in the language - either you convert to the \u notation, and then check manually (converting back if all is fine), or you have an automated check (e.g. at commit time) that checks for conformance to the style guide. > or being unable to do minor maintenance on code using > character sets which your editor doesn't support: you just run the > script which would be included with every copy of Python to restrict the > character set of the source files to whatever character set you feel > happy with. The script should also be able to convert unrepresentable > characters in strings and comments (although that last operation > wouldn't be guaranteed reversible). Again, if it's reversible, you don't need support for it in the language. You convert to your editor's supported Unicode subset, edit, then convert back. However, I somewhat doubt that this case "my editor cannot display my source code" is likely to occur: if the editor cannot display it, you likely have a ban on those characters, anyway. Regards, Martin From steven.bethard at gmail.com Sun May 27 14:59:01 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 27 May 2007 12:59:01 -0600 Subject: ten small Python programs In-Reply-To: References: Message-ID: Steve Howell wrote: > --- Steven Bethard wrote: > >> I think I would rewrite the current unit-testing >> example to use the >> standard library unittest module:: >> >> # Let's write reusable code, and unit test it. >> def add_money(amounts): >> # do arithmetic in pennies so as not to >> accumulate float errors >> pennies = sum([round(int(amount * 100)) for >> amount in amounts]) >> return float(pennies / 100.0) >> import unittest >> class TestAddMoney(unittest.TestCase): >> def test_float_errors(self): >> self.failUnlessEqual(add_money([0.13, >> 0.02]), 0.15) >> self.failUnlessEqual(add_money([100.01, >> 99.99]), 200) >> self.failUnlessEqual(add_money([0, >> -13.00, 13.00]), 0) >> if __name__ == '__main__': >> unittest.main() >> >> I believe I've still kept it to 13 lines. >> > > I approve this change, although in a sense, it's > harder for a Python newbie, because it introduces > inheritance a little earlier than I would have liked. > > FWIW I'm in the minority (I think) of people that > prefer roll-your-own testing, but I don't want to > argue that, because I think it mostly comes down to > personal preference. Have you tried py.test? http://codespeak.net/py/dist/test.html I've heard good things about it, but haven't gotten around to trying it yet. Here's a two-line test suite from the page above: def test_answer(): assert 42 == 43 STeVe From maxwell at umiacs.umd.edu Wed May 2 13:37:40 2007 From: maxwell at umiacs.umd.edu (maxwell@ldc.upenn.edu) Date: 2 May 2007 10:37:40 -0700 Subject: gpp (conditional compilation) Message-ID: <1178127460.046945.254100@y80g2000hsf.googlegroups.com> I'm trying to use the gpp utility (Gnu points to http://en.nothingisreal.com/wiki/GPP) to do conditional compilation in Python, and I'm running into a problem: the same '#' character introduces Python comments and is used by default to introduce #ifdef etc. lines. Here's an example of what I'm trying to do: #ifdef DEBUG stderr.write("variable is...") #details of msg omitted #endif I'm using the following args to gpp: +s \" \" \" +s \' \' \' +c \\\# \\n -n The result is that the #ifdef and #endif lines get treated as comments, rather than instructions to gpp to keep or omit the lines in between. I tried just omitting the +c arg, but then I get msgs at the end of each file saying Input ended while scanning a comment/string apparently because I use apostrophes inside comments, and gpp thinks those are unterminated strings. I can think of some work-arounds, like "don't use apostrophes inside comments", or "don't use single-quoted strings (or define them for gpp)" or "use a different char for the first char of a gpp macro". But I'd rather not... Does anyone have a set of gpp args that plays well with Python? (Or makefiles, where I presume the same problem comes up.) Mike Maxwell CASL/ U MD From vasudevram at gmail.com Sat May 26 15:43:21 2007 From: vasudevram at gmail.com (vasudevram) Date: 26 May 2007 12:43:21 -0700 Subject: How to get started as a xhtml python mysql freelancer ? In-Reply-To: <1180184153.675202.272320@p77g2000hsh.googlegroups.com> References: <1180136893.220560.49340@q75g2000hsh.googlegroups.com> <1180140942.239003.94640@h2g2000hsg.googlegroups.com> <1180184153.675202.272320@p77g2000hsh.googlegroups.com> Message-ID: <1180208601.764182.74210@j4g2000prf.googlegroups.com> On May 26, 5:55 pm, "Eric_Dex... at msn.com" wrote: > On May 25, 7:55 pm, gert wrote: > > > > > > > On May 26, 2:09 am, Paul McNett wrote: > > > > gert wrote: > > > > I made something that i was hoping it could make people happy enough > > > > so i could make a living by providing support for commercial use of > > > >http://sourceforge.net/projects/dfo/ > > > > > But in reality i am a lousy sales men and was wondering how you people > > > > sell stuff as a developer ? > Some suggestions: - give more details on the front page of the sourceforge site, on what your product is about and its benefits. Consider creating a web site for it. -write articles about it / post on appropriate newsgroups about your product, giving code examples of how it can be used, and the benefits. - if you haven't already, create a personal web site - its better to get your own paid one than to use a free one, and put (objective) info there on your skills, your past experience, your open source work, your writings, etc. Give your contact info too. I've done this myself and it has resulted in getting leads for contracting work. Be patient though - work leads may not come in a hurry. - join sites like Elance.com or ODesk.com for getting work. Vasudev Ram Dancing Bison Enterprises http://www.dancingbison.com From steve at REMOVE.THIS.cybersource.com.au Fri May 11 22:26:06 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 12 May 2007 12:26:06 +1000 Subject: Newbie look at Python and OO References: <1178812734.860473.236370@y80g2000hsf.googlegroups.com> <1346hrvgve90nea@corp.supernews.com> Message-ID: On Thu, 10 May 2007 16:25:35 +0000, Grant Edwards wrote: >> I know why, but this is not what I would ordinarilly expect, > > Stop thinking in "C". ;) Dude! Did you miss the Original Poster's VERY FIRST SENTENCE??? "I learned to program with Pascal, way back when." He's thinking in Pascal, not C. -- Steven. From half.italian at gmail.com Fri May 11 19:09:56 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 11 May 2007 16:09:56 -0700 Subject: Path python versions and Macosx In-Reply-To: <1178915809.065874.133030@o5g2000hsb.googlegroups.com> References: <1178915809.065874.133030@o5g2000hsb.googlegroups.com> Message-ID: <1178924996.452067.308320@h2g2000hsg.googlegroups.com> On May 11, 1:36 pm, andrea wrote: > Hi everyone, > I use python on macosx with textmate as editor (great program). > > I also use macport to install unix programs from the command line and > I find it great too. > Well I would like to have all my modules in the path when I'm using > textmate AND when I use the commandline (ipython), but because > textmate and the command line use different python versions they also > search in different places.. > > I found somewhere to write .pythonrc.py like this > > #!/usr/bin/env python > import sys > PATH='/opt/local/lib/python2.4/site-packages/' > sys.path.append(PATH) > del sys > > But it doesn't work either, I also tried to append this > PATH="/Library/Frameworks/Python.framework/Versions/Current/bin:/opt/ > local/lib/python2.4/site-packages:${PATH} > to .bash_profile but nothing. > > Where should I set this variables?? > > Thanks a lot You can set environment variables for gui apps with this freeware: http://www.versiontracker.com/dyn/moreinfo/macosx/15073 You can edit some text files as well, but this thing just makes it much easier. ~Sean From peter.maas at somewhere.com Sat May 19 16:01:21 2007 From: peter.maas at somewhere.com (Peter Maas) Date: Sat, 19 May 2007 22:01:21 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46473267$0$31532$9b622d9e@news.freenet.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote: > Python code is written by many people in the world who are not familiar > with the English language, or even well-acquainted with the Latin > writing system. I believe that there is a not a single programmer in the world who doesn't know ASCII. It isn't hard to learn the latin alphabet and you have to know it anyway to use the keywords and the other ASCII characters to write numbers, punctuation etc. Most non-western alphabets have ASCII transcription rules and contain ASCII as a subset. On the other hand non-ascii identifiers lead to fragmentation and less understanding in the programming world so I don't like them. I also don't like non-ascii domain names where the same arguments apply. Let the data be expressed with Unicode but the logic with ASCII. -- Regards/Gruesse, Peter Maas, Aachen E-mail 'cGV0ZXIubWFhc0B1dGlsb2cuZGU=\n'.decode('base64') From lupe at localhost.localdomain Wed May 9 08:24:36 2007 From: lupe at localhost.localdomain (Luis P. Mendes) Date: Wed, 09 May 2007 13:24:36 +0100 Subject: psycopg2 error References: <46414b46$0$9746$9b622d9e@news.freenet.de> Message-ID: Hello Martin, Em Wed, 09 May 2007 06:17:09 +0200, Martin v. L?wis escreveu: >> ImportError: libpq.so.5: cannot open shared object file: No such file or >> directory >> >> libpq files are readable by the world: root at lince pgsql # ll lib/ -d >> drwxr-xr-x 3 postgres postgres 1528 2007-05-07 23:25 lib/ > > Don't try this as the root user, but as the one for whom it is failing: > What does "file /usr/local/psql/lib/libpq.so.5" say? The problem was that I couldn't issue this command. Permissions were set incorrectly: $ ll /usr/local/pg* -d drwxr-x--- 10 postgres postgres 712 2007-05-08 20:43 /usr/local/pgsql Once corrected to: $ ll /usr/local/pg* -d drwxr-xr-x 10 postgres postgres 712 2007-05-08 20:43 /usr/local/pgsql I can import psycopg2 fine. Thank you for your help! Best regards, Luis From bbxx789_05ss at yahoo.com Tue May 1 22:27:49 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 1 May 2007 19:27:49 -0700 Subject: os.path.join In-Reply-To: References: Message-ID: <1178072869.844914.59010@u30g2000hsc.googlegroups.com> On May 1, 7:36 pm, Elliot Peele wrote: > Why does os.path.join('/foo', '/bar') return '/bar' rather than > '/foo/bar'? That just seems rather counter intuitive. > > Elliot join( path1[, path2[, ...]]) Join one or more path components intelligently. If any component is an absolute path, all previous components (on Windows, including the previous drive letter, if there was one) are thrown away... From norman_remove_lorrain_remove_ at telusplanet.net Tue May 15 16:01:04 2007 From: norman_remove_lorrain_remove_ at telusplanet.net (Norman Lorrain) Date: Tue, 15 May 2007 20:01:04 GMT Subject: Vista: webbrowser module Message-ID: <2007051514011416807-normanremovelorrainremove@telusplanetnet> I don't have a Vista machine to test this on, but I have users reporting a problem with the following e.g. import webbrowser webbrowser.open('http://www.google.com') File "webbrowser.pyc", line 43, in open File "webbrowser.pyc", line 250, in open exceptions.WindowsError:[Errno 2] The system cannot find the file specified: Works on XP, OSX, Ubuntu. I find no reference to this problem. Is there a work-around? Thanks. From jeba.ride at gmail.com Wed May 16 14:25:30 2007 From: jeba.ride at gmail.com (Clement) Date: 16 May 2007 11:25:30 -0700 Subject: A new project. In-Reply-To: <1179302989.142733.257910@n59g2000hsh.googlegroups.com> References: <1179302989.142733.257910@n59g2000hsh.googlegroups.com> Message-ID: <1179339930.009586.258920@l77g2000hsb.googlegroups.com> On May 16, 1:09 pm, colin.barne... at gmail.com wrote: > I am interested in organizing and taking part in a project that would > create a virtual world much like the one described in Neal > Stephenson's 'Snow Crash'. I'm not necessarily talking about > something 3d and I'm not talking about a game either. Like a MOO, > only virtual. And each 'user' is allocated space with which they are > free to edit in any way, within the confines of that space. I know > Second Life and others come to mind when you think of this, but > Frankly Second Life came off as sloppy to me. I want people to be > able to code their own objects and environments with the ease of > Python. > > I don't know forget the suggestions, anything is on the table, but > there are just so many half-hearted and weak commercial attempts at > this I feel that it's time to get Python involved in the game and do > it right. > > If anyone has any interest, ideas, comments or otherwise, e-mail me. > If some interest is shown we'll start a board, a site, an IRC channel > or whatever we have to do to meet and get the ball rolling. :) > > Thanks. what do you really expect? From fsckedagain at gmail.com Tue May 1 18:47:52 2007 From: fsckedagain at gmail.com (fscked) Date: 1 May 2007 15:47:52 -0700 Subject: read list of dirnames and search for filenames In-Reply-To: <878xc8gr9w.fsf@smsnet.pl> References: <1178051721.935868.194700@o5g2000hsb.googlegroups.com> <87d51kgs4l.fsf@smsnet.pl> <878xc8gr9w.fsf@smsnet.pl> Message-ID: <1178059670.068911.279190@q75g2000hsh.googlegroups.com> On May 1, 2:36 pm, Rob Wolfe wrote: > Rob Wolfe writes: > > fscked writes: > > >> I cannot seem to get this to work. I am hyst trying to read in a list > >> of paths and see if the directory or any sub has a filename pattern. > >> Here is the code: > > >> import os, sys > >> from path import path > > >> myfile = open("boxids.txt", "r") > >> for line in myfile.readlines(): > > And you don't need to use ``readlines`` at all. > This is enough: > > for line in myfile: > > -- > HTH, > Rob Worked well, thanks! From steve at REMOVEME.cybersource.com.au Thu May 3 02:07:11 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Thu, 03 May 2007 16:07:11 +1000 Subject: FInd files with .so extension References: <1178168321.581307.284750@y5g2000hsa.googlegroups.com> Message-ID: On Wed, 02 May 2007 21:58:41 -0700, pradeep nair wrote: > HI, > > > How do i find files with .so extension using python . import os help(os.listdir) help(os.walk) help(os.path.splitext) That should give you all the tools you need. -- Steven D'Aprano From basilisk96 at gmail.com Tue May 1 23:20:42 2007 From: basilisk96 at gmail.com (Basilisk96) Date: 1 May 2007 20:20:42 -0700 Subject: ScrolledText? In-Reply-To: <1178062724.003188.56080@q75g2000hsh.googlegroups.com> References: <1178057529.486757.154860@y5g2000hsa.googlegroups.com> <1178058162.274969.117340@o5g2000hsb.googlegroups.com> <1178062724.003188.56080@q75g2000hsh.googlegroups.com> Message-ID: <1178076042.240549.134030@p77g2000hsh.googlegroups.com> Ah.. wx is wxPython in this case, a GUI toolkit like Tkinter, but based on wxWidgets. I don't know if Tk has a text control with a method similar to the AppendText method I showed here.. I used to have the exact same problem as you until I discovered that AppendText always kept the text box scrolled at the bottom :) How about this: >>>help(Tkinter.Text.see) Help on method see in module Tkinter: see(self, index) unbound Tkinter.Text method Scroll such that the character at INDEX is visible. It may be what you're looking for if you use 'end' for index ...? -Basilisk96 From yavannadil at yahoo.com Sat May 5 04:03:36 2007 From: yavannadil at yahoo.com (yavannadil at yahoo.com) Date: 5 May 2007 01:03:36 -0700 Subject: How do I get type methods? In-Reply-To: <1178313428.842839.41580@e65g2000hsc.googlegroups.com> References: <1178220806.664557.245780@c35g2000hsg.googlegroups.com> <1178313428.842839.41580@e65g2000hsc.googlegroups.com> Message-ID: <1178352216.510947.23480@w5g2000hsg.googlegroups.com> On May 5, 1:17 am, Fuzzyman wrote: > dir(type(localContext)) > Perhaps ? It gives ['__class__', '__cmp__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__'] while import sys dir(type(sys.modules)) gives ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__str__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values'] so I guess PyUNO extension doesn't provide proper introspection :-( From martin at v.loewis.de Mon May 14 18:02:46 2007 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Tue, 15 May 2007 00:02:46 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <4648DC86.8080709@v.loewis.de> > In , Nick Craig-Wood > wrote: > >> My initial reaction is that it would be cool to use all those great >> symbols. A variable called OHM etc! > > This is a nice candidate for homoglyph confusion. There's the Greek > letter omega (U+03A9) ? and the SI unit symbol (U+2126) ?, and I think > some omegas in the mathematical symbols area too. Under the PEP, identifiers are converted to normal form NFC, and we have py> unicodedata.normalize("NFC", u"\u2126") u'\u03a9' So, OHM SIGN compares equal to GREEK CAPITAL LETTER OMEGA. It can't be confused with it - it is equal to it by the proposed language semantics. Regards, Martin From steve at holdenweb.com Fri May 25 07:27:37 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 25 May 2007 07:27:37 -0400 Subject: stdlib doc for logger.findCaller() needs update. In-Reply-To: <1180080963.742418.170360@q75g2000hsh.googlegroups.com> References: <1179918325.803451.76820@o5g2000hsb.googlegroups.com> <1180080963.742418.170360@q75g2000hsh.googlegroups.com> Message-ID: <4656C829.1000001@holdenweb.com> Vinay Sajip wrote: > On May 23, 12:05 pm, jitu... at hotmail.com wrote: >> The logger objects findCaller() method is returning a "3" element >> tuple instead of "2" two as >> documented in the 2.4.4 Python Library Reference .DocString is showing >> it correctly. > > I've updated the docs - the next 2.4.x release should have them. > Thanks for the report. > Is a further 2.4 release planned? I'd have thought that unless a security issue appears the answer is likely to be "no". 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From bj_666 at gmx.net Tue May 15 02:54:42 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 15 May 2007 08:54:42 +0200 Subject: Trying to choose between python and java References: Message-ID: In , Anthony Irwin wrote: > #1 Does python have something like javas .jar packages. A jar file > contains all the program files and you can execute the program with > java -jar program.jar There are .egg files but usually distributing a program consisting of several files isn't a big problem. There is a mechanism to write a `setup.py` that copies the files into the correct locations. Look for `distutils` in the library docs. > #2 What database do people recommend for using with python that is > easy to distribute across linux, mac, windows. >From Python 2.5 the standard library contains SQLite support. There are third party libraries to many DBMSs like MySQL, PostgreSQL, Oracle etc. The situation with MySQL bindings under Windows was a bit troublesome recently. The author of the bindings doesn't use Windows and does not provide pre-built binaries. > #4 If I write a program a test it with python-wxgtk2.6 under linux are > the program windows likely to look right under windows and mac? Likely yes, but you better check. Same applies to Java GUIs. > #5 someone said that they used to use python but stopped because the > language changed or made stuff depreciated (I can fully remember > which) and old code stopped working. Is code written today likely to > still work in 5+ years or do they depreciate stuff and you have to update? That sounds odd because the language and standard library is very backwards compatible. There are some things deprecated with a comment in the docs and in some cases runtime warnings, but the code still works. With Python 3.0 some things will break, because there's some cruft in the language and library that accumulated over time, just because backwards compatibility was such a high priority. The 2.x series will be supported for some time parallel to 3.x, so there is enough time to migrate. Ciao, Marc 'BlackJack' Rintsch From tom at finland.com Thu May 10 16:03:13 2007 From: tom at finland.com (tom at finland.com) Date: Thu, 10 May 2007 20:03:13 GMT Subject: keyword checker - keyword.kwlist In-Reply-To: References: Message-ID: <5UK0i.237$Hb2.206@read3.inet.fi> Hamilton, William kirjoitti: >> From: tom at finland.com >> F:\Ohjelmat\Python25\Lib\keyword.pyc > > That's your problem. Rename keyword.py to keywordcheck.py, and delete > keyword.pyc in this directory, and it should work fine. > > --- > -Bill Hamilton I tried the trick but the error stays. I really don't know what to do anymore. And what about the print function. Why does it print newline even if there is colon after variable? I'm lost. I'm using Eclipe enviroment and Pydev for it. My python interpreter is 2.5.1. From john at datavoiceint.com Thu May 17 13:41:05 2007 From: john at datavoiceint.com (HMS Surprise) Date: 17 May 2007 10:41:05 -0700 Subject: try In-Reply-To: <1179406284.859454.167400@k79g2000hse.googlegroups.com> References: <1179350291.106871.25640@e65g2000hsc.googlegroups.com> <1179406284.859454.167400@k79g2000hse.googlegroups.com> Message-ID: <1179423665.147239.232470@n59g2000hsh.googlegroups.com> On May 17, 7:51 am, Dustan wrote: > On May 16, 4:22 pm, Robert Kern wrote: > > > > > HMS Surprise wrote: > > > I read in the ref man that try-except-finally did not work in earlier > > > versions, I am using jython 2.2. Does this imply that try-except > > > without finally does not work either? I get a syntax error on the else > > > below. Some of the functions embedded in the try section try to > > > convert strings to ints, etc and may fail on bad data, thus try seemed > > > like a good start for a workaround. > > > > Thanks, > > > > jh > > > > #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > > def restoreDevice(self, deviceId, closeTime = time()): > > > self.logon() > > > try: > > > lst = self.getLastUpdatedDevice(deviceId) > > > lastUpdated = lst[0] > > > incidentId = lst[1] > > > print 'L', lastUpdated, 'I', incidentId > > > self.restore(incidentId, lastUpdated) > > > except: > > > else: > > > print "couldn't find incident" > > > The except: block still needs something in it, even if it is just "pass". > > For sake of demonstration: > > def restoreDevice(self, deviceId, closeTime = time()): > self.logon() > try: > lst = self.getLastUpdatedDevice(deviceId) > lastUpdated = lst[0] > incidentId = lst[1] > print 'L', lastUpdated, 'I', incidentId > self.restore(incidentId, lastUpdated) > except: > pass > else: > print "couldn't find incident" > > > -- > > 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 Thanks folks. Found my error but I didn't know of pass option..... Wanted to get back in earlier and state I found the error but Google groups seemed to be down for half a day.... jvh From dustin at v.igoro.us Tue May 1 17:14:21 2007 From: dustin at v.igoro.us (dustin at v.igoro.us) Date: Tue, 1 May 2007 16:14:21 -0500 Subject: How can I get the ascii code of a charter in python? In-Reply-To: <1178053581.390873.65850@n76g2000hsh.googlegroups.com> References: <1178053581.390873.65850@n76g2000hsh.googlegroups.com> Message-ID: <20070501211421.GF11383@v.igoro.us> On Tue, May 01, 2007 at 02:06:21PM -0700, tedpottel at gmail.com wrote: > How can I get the ascii code of a charter in python? It's a builtin: >>> ord('*') 42 Dustin From jorgen.maillist at gmail.com Sun May 13 05:41:12 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Sun, 13 May 2007 11:41:12 +0200 Subject: Real globals inside a module Message-ID: <11e49df10705130241s179297f9q68bb799f8d1ec1b3@mail.gmail.com> Hi All, I am wrestling with some architecture inside my app. Let's say I have a tunings collection, which contains e.g. 23 types of guitar tunings. In my song object I want to restore a relation between one of the tuning objects inside the tunings module. I already figured out I need somethign like a global collection inside the tunings module,. but how global is it? When I am inside my app object, and import the tunings module, can I access the same global class as when I am inside my songs module and load the tunings module? So for some pseudo code: --- songs.py import tunings class Song(object): def __init__(self, tuning_id): # create relation with tuning object self._tuning = tunings.GetTuningById(tuning_id) -- app.py import tunings # get list of tunings for t in tunings._tuningCollection: print 'Tuning:', t._name ---- So basically I want to access the same global list in both modules, but not re-create the list in every module since it should be restored by the database layer once. Is this as simple as defining a global variable in the module tunings which is available on both imports, or should I do it different, and then my next question ofcourse is, how ? :-) Thanks for any advice, I do not want to make a global manager object that I need to pass around all the time, that would be silly.. Regards, - Jorgen From SuperM at ssiveBlackHoleAtTheCenterOfTheMilkyWayGalaxy.org Thu May 3 04:29:27 2007 From: SuperM at ssiveBlackHoleAtTheCenterOfTheMilkyWayGalaxy.org (SuperM at ssiveBlackHoleAtTheCenterOfTheMilkyWayGalaxy.org) Date: Thu, 03 May 2007 01:29:27 -0700 Subject: Video: Professor of Physics, Phd at Cal Tech says: 911 Inside Job References: <1177563723.864674.162300@s33g2000prh.googlegroups.com> <1178169967.232161.9710@y5g2000hsa.googlegroups.com> Message-ID: On 2 May 2007 22:26:07 -0700, lemnitzer at india.com Gave us: >> >> >http://www.911blogger.com/node/8101 >> What a lard ass... no wonder the Navy got rid of him. And he isn't from cal tech, he "teaches" in Iowa. Also, being a physicist, does NOT make him, in any way shape or form, a structural engineer. The guy is an idiot. From victor.lebrun at gmail.com Thu May 3 08:41:57 2007 From: victor.lebrun at gmail.com (vml) Date: 3 May 2007 05:41:57 -0700 Subject: passing an array of variant in vb to a python COM object = win32com bug ? In-Reply-To: References: <1178178883.246149.279780@c35g2000hsg.googlegroups.com> Message-ID: <1178196117.469260.12770@e65g2000hsc.googlegroups.com> On 3 mai, 14:20, "Gabriel Genellina" wrote: > En Thu, 03 May 2007 04:54:43 -0300, vml escribi?: > > > > > I have a python com object which contains a method to inverse an array > > in vb 6 the definition of the class is : > > > class Fop: > > _public_methods_ = [ 'SqVal' ] > > def SqVal(self,*val): > > #vol=(val[0][0],val[0][1]) > > #mat1=mat((vol)) > > #up=linalg.inv(mat1) > > return str(val)#up > > _reg_verprogid_ = "Python.Fop.3" > > _reg_progid_ = "Python.Fop" > > _reg_desc_ = "Python Fop" > > _reg_clsid_ = "{30BD3490-2632-11cf-AD5B-524153480001}" > > > I pass to this method an array of variant which is the matrix to > > invert like that: > > vb6 code : > > > Set obj = CreateObject("Python.Fop") > > Dim ty(1, 1) As Variant > > > ty(0, 0) = 1 > > ty(1, 0) = 2 > > ty(0, 1) = 3 > > ty(1, 1) = 4 > > > toto = obj.SqVal(ty) > > > when I dispaly toto as str(val) I obtain the following tuple "(((1, > > 3), (2, 4)),)" which is not usable .... > > > Do you have an idea to explain this strange behaviour ? > > This is the expected behaviour. Writing it completely in Python: > > py> def SqVal(*val): > ... return str(val) > ... > py> ty=((1,3),(2,4)) > py> SqVal(ty) > '(((1, 3), (2, 4)),)' > > The *val parameter receives a tuple, whose elements are the positional > arguments used when calling the function. As you call the function with a > single argument, val receives a tuple with a single element. > Perhaps you want to write it as: > > py> def SqVal(val): > ... print val[0][0] > ... print val[0][1] > ... print val[1][0] > ... print val[1][1] > ... > py> SqVal(ty) > 1 > 3 > 2 > 4 > > (Of course, if used as a Fop method, dont forget the "self" parameter) > > -- > Gabriel Genellina I just tried to replace the *val by SqVal(self,val) and call the method in vb but it crashes down : "when refilling safe array the sequence must have the same number of dimension as the existing array" my python code is now : def SqVal(self,val): ## volr=[val[0][0][i] for i in range(size(val,2))] ## voli=[val[0][1][i] for i in range(size(val,2))] ## mat1=mat(volr)+1j*mat(voli) ## up=linalg.pinv(mat1) ## out=up.real.tolist() ## out.extend(up.imag.tolist()) return val By the way Do you have any idea to debug the com server script ? ( I would like to know if a can access the value in the function while calling it from vb 6) tahnks a lot ! From sonmez at lavabit.com Wed May 9 17:30:58 2007 From: sonmez at lavabit.com (=?UTF-8?B?U8O2bm1leiBLYXJ0YWw=?=) Date: Thu, 10 May 2007 00:30:58 +0300 Subject: File I/O In-Reply-To: <1178745198.392518.56840@q75g2000hsh.googlegroups.com> References: <1178745198.392518.56840@q75g2000hsh.googlegroups.com> Message-ID: <46423D92.7050302@lavabit.com> Hi, As far as I know, Python doesn't have a specific thing to handle this. You could write a tiny function that would interpre element type of list's elements. It checks type, if it is a list then get that pair manually... If list is going like that 'a' - '1', 'b' - '2', you should use dictionary. -- S?nmez Kartal From afriere at yahoo.co.uk Thu May 17 02:02:55 2007 From: afriere at yahoo.co.uk (Asun Friere) Date: 16 May 2007 23:02:55 -0700 Subject: How do I tell the difference between the end of a text file, and an empty line in a text file? In-Reply-To: <1179352021.803070.200780@k79g2000hse.googlegroups.com> References: <1179352021.803070.200780@k79g2000hse.googlegroups.com> Message-ID: <1179381775.250428.82810@e65g2000hsc.googlegroups.com> On May 17, 7:47 am, walterbyrd wrote: > Python's lack of an EOF character is giving me a hard time. The difference is simply that an empty line contains a '\n' while EOF does not. If you strip() your line before testing you will have trouble. But the minimal cases you post (properly indented and with the missing ':' in place), should work (they just won't produce any output). Repairing the first , I'm using dots (aka stops, periods) for spaces here to stop the code getting munged : line = fobj.readline() while line : ....print line.strip() ....line = fobj.realine() This does work look at this output (and note the empty lines): line with stuff line with more stuff line after the empty line and before another last line In python it is more ideomatic to write this general kind of loop with a break statement, thus: while True : ....line = fobj.readline() ....if not line : break ....print line.strip() However since file has for a long time been an iterable the easiest and most readible way to write it is this: for line in fobj : ....print line.strip() Asun From irmen.NOSPAM at xs4all.nl Tue May 22 13:32:03 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Tue, 22 May 2007 19:32:03 +0200 Subject: Components for a client/server architecture In-Reply-To: <6CE4i.22920$JZ3.15279@newssvr13.news.prodigy.net> References: <5bd99qF2s85heU1@mid.uni-berlin.de> <6CE4i.22920$JZ3.15279@newssvr13.news.prodigy.net> Message-ID: <46532913$0$331$e4fe514c@news.xs4all.nl> John Nagle wrote: > You don't hear much about CORBA any more. It used to be derided > as a bulky way to marshall data, but then came XML. CORBA is much more than just a way to marshall data. GIOP (or its more often used implementation IIOP) is the marshaling protocolused in CORBA. And it is hardly bulky! Being a binary protocol, it is much faster and leaner than XML. --Irmen From mike.terrell at earthlink.net Tue May 8 22:32:50 2007 From: mike.terrell at earthlink.net (Michael A. Terrell) Date: Wed, 09 May 2007 02:32:50 GMT Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> <08qk33t594ih0ulmjmev90d22lkfnotgoe@4ax.com> <463C2A3A.8332D211@hotmail.com> <0k8p33h90bp5tfajedb4bmd2eik8gfi2ho@4ax.com> <4640CB37.907C9988@earthlink.net> Message-ID: <464132D5.8F6C0936@earthlink.net> James Beck wrote: > > In article <4640CB37.907C9988 at earthlink.net>, mike.terrell at earthlink.net > says... > > James Beck wrote: > > > > > > Yep, you must have access to better drugs than I do. > > > You get to hallucinate your stuff up. > > > Don't forget to adjust your tin beanie! > > > > > > Its not a beanie. He had his head tin plated. :( > > > I just the "How it's Made" that showed how they make bronzed baby shoes. > Maybe they can adapt that process to tin plate heads. > Would save these guys thousands of $$$ on foil. > > Jim Yeah, they wouldn't need it done very often. Only when the dead skin builds up so much it pushes the old one off their bald heads. -- Service to my country? Been there, Done that, and I've got my DD214 to prove it. Member of DAV #85. Michael A. Terrell Central Florida From sturlamolden at yahoo.no Thu May 10 09:50:58 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 10 May 2007 06:50:58 -0700 Subject: Single precision floating point calcs? In-Reply-To: <1343v0emvdjr545@corp.supernews.com> References: <1343v0emvdjr545@corp.supernews.com> Message-ID: <1178805058.231510.7480@u30g2000hsc.googlegroups.com> On May 9, 6:51 pm, Grant Edwards wrote: > Is there any way to do single-precision floating point > calculations in Python? Yes, use numpy.float32 objects. > I know the various array modules generally support arrays of > single-precision floats. I suppose I could turn all my > variables into single-element arrays, but that would be way > ugly... Numpy has scalars as well. >>> import numpy >>> a = numpy.float32(2.0) >>> b = numpy.float32(8.0) >>> c = a+b >>> print c 10.0 >>> type(c) >>> From paul at boddie.org.uk Sun May 27 11:05:05 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 27 May 2007 08:05:05 -0700 Subject: Help with PySMS In-Reply-To: <1180264285.477306.137830@r19g2000prf.googlegroups.com> References: <1180264285.477306.137830@r19g2000prf.googlegroups.com> Message-ID: <1180278305.556262.249710@q75g2000hsh.googlegroups.com> DJ Fadereu wrote: > > I need an SMS server running on my WinXP PC, as soon as possible. I'm > currently using a Nokia 6300 phone which has the S60 platform. I > downloaded the PySMS by Dave Berkeley from > http://www.wordhord.co.uk/pysms.html and started testing it, but I > haven't been able to get it working. Maybe I don't know how to do some > configurations before using it, I dunno. I'm pretty lost. Have you contacted the author? He might be able to help you out much more effectively than we can. [...] > My project is very simple - I will use incoming SMS to > generate a visualisation and automatic responder. This system will be > part of a multiplayer game that lots of people can play using SMS. I've extended the t616hack distribution to deal with messages - it contains a library which is used to communicate with Sony Ericsson telephones using AT commands - and that might give you some ideas about the principles involved. See here for the package: http://www.python.org/pypi/t616hack One significant enhancement made to t616hack is support for Bluetooth sockets, meaning that you don't need to worry about baud rates, serial devices and other low-level details. There's no direct support for a message server, but I have a Web application that I use personally for accessing messages on my telephone. Paul From revuesbio at gmail.com Mon May 7 09:37:55 2007 From: revuesbio at gmail.com (revuesbio) Date: 7 May 2007 06:37:55 -0700 Subject: msbin to ieee In-Reply-To: <1178542593.668743.71500@u30g2000hsc.googlegroups.com> References: <1178487847.671199.108140@h2g2000hsg.googlegroups.com> <1178502738.104124.3840@h2g2000hsg.googlegroups.com> <1178525916.145819.264070@n59g2000hsh.googlegroups.com> <1178536910.566119.6650@o5g2000hsb.googlegroups.com> <1178539202.316506.199940@p77g2000hsh.googlegroups.com> <1178542593.668743.71500@u30g2000hsc.googlegroups.com> Message-ID: <1178545075.530201.180120@u30g2000hsc.googlegroups.com> On 7 mai, 14:56, John Machin wrote: > On May 7, 10:00 pm, revuesbio wrote: > > > > > On 7 mai, 13:21, John Machin wrote: > > > > On May 7, 6:18 pm, revuesbio wrote: > > > > > On 7 mai, 03:52, John Machin wrote: > > > > > > On May 7, 7:44 am, revuesbio wrote: > > > > > > > Hi > > > > > > Does anyone have the python version of the conversion from msbin to > > > > > > ieee? > > > > > > Thank u > > > > > > Yes, Google has it. Google is your friend. Ask Google. It will lead > > > > > you to such as: > > > > > >http://mail.python.org/pipermail/python-list/2005-August/337817.html > > > > > > HTH, > > > > > John > > > > > Thank you, > > > > > I've already read it but the problem is always present. this script is > > > > for double precision MBF format ( 8 bytes). > > > > It would have been somewhat more helpful had you said what you had > > > done so far, even posted your code ... > > > > > I try to adapt this script for single precision MBF format ( 4 bytes) > > > > but i don't find the right float value. > > > > > for example : 'P\xad\x02\x95' will return '0.00024924660101532936' > > > > If you know what the *correct* value is, you might like to consider > > > shifting left by log2(correct_value/erroneous_value) :-) > > > > Do you have any known correct pairs of (mbf4 string, decimal_float > > > value)? My attempt is below -- this is based on a couple of > > > descriptive sources that my friend Google found, with no test data. I > > > believe the correct answer for the above input is 1070506.0 i.e. you > > > are out by a factor of 2 ** 32 > > > > def mbf4_as_float(s): > > > m0, m1, m2, m3 = [ord(c) for c in s] > > > exponent = m3 > > > if not exponent: > > > return 0.0 > > > sign = m2 & 0x80 > > > m2 |= 0x80 > > > mant = (((m2 << 8) | m1) << 8) | m0 > > > adj = 24 + 128 > > > num = mant * 2.0 ** (exponent - adj) > > > if sign: > > > return -num > > > return num > > > > HTH, > > > John > > > well done ! it's exactly what i'm waiting for !! > > > my code was:>>> from struct import * > > >>> x = list(unpack('BBBB','P\xad\x02\x95')) > > >>> x > > [80, 173, 2, 149] > > >>> def conversion1(bytes): > > > b=bytes[:] > > sign = bytes[-2] & 0x80 > > b[-2] |= 0x80 > > exp = bytes[-1] - 0x80 - 56 > > acc = 0L > > for i,byte in enumerate(b[:-1]): > > acc |= (long(byte)<<(i*8)) > > return (float(acc)*2.0**exp)*((1.,-1.)[sign!=0]) > > Apart from the 2**32 problem, the above doesn't handle *any* of the > 2**24 different representations of zero. Try feeding \0\0\0\0' to it > and see what you get. > > > > > >>> conversion1(x) > > > 0.00024924660101532936 > > > this script come from google groups but i don't understand bit-string > > manipulation (I'm a newbie). informations about bit-string > > manipulation with python is too poor on the net. > > The basic operations (and, or, exclusive-or, shift) are not specific > to any language. Several languages share the same notation (& | ^ << > > >>), having inherited it from C. > > > thank you very much for your script. > > Don't thank me, publish some known correct pairs of values so that we > can verify that it's not just accidentally correct for 1 pair of > values. pairs of values : (bytes string, mbf4_as_float(s) result) right float value ('P\xad\x02\x95', 1070506.0) 1070506.0 ('\x00\x00\x00\x02', 5.8774717541114375e-039) 0.0 ('\x00\x00\x00\x81', 1.0) 1.0 ('\x00\x00\x00\x82', 2.0) 2.0 ('\x00\x00@\x82', 3.0) 3.0 ('\x00\x00\x00\x83', 4.0) 4.0 ('\x00\x00 \x83', 5.0) 5.0 ('\xcd\xcc\x0c\x81', 1.1000000238418579) 1.1 ('\xcd\xcc\x0c\x82', 2.2000000476837158) 2.2 ('33S\x82', 3.2999999523162842) 3.3 ('\xcd\xcc\x0c\x83', 4.4000000953674316) 4.4 ('\x00\x00z\x8a', 1000.0) 1000.0 From nyamatongwe+thunder at gmail.com Sun May 6 23:01:35 2007 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Mon, 07 May 2007 03:01:35 GMT Subject: My newbie annoyances so far In-Reply-To: <1hxpfyw.oaolu9kesvabN%aleax@mac.com> References: <1177688082.758043.133920@r30g2000prh.googlegroups.com> <_9pYh.1787$uJ6.894@newssvr17.news.prodigy.net> <1178400807.051103.95690@q75g2000hsh.googlegroups.com> <1hxp15f.1bvtgo11ydx3cvN%aleax@mac.com> <1hxpfyw.oaolu9kesvabN%aleax@mac.com> Message-ID: Alex Martelli: > Can you run a generic benchmark "inside the current implementation of > Flash" to check out its Javascript performance? I can't, so, ... I can't either (without going to a lot of effort) so here is a page comparing SpiderMonkey and Tamarin from someone with an adobe.com address: http://www.playercore.com/pub/Tamarin/Avmplus_vs._javascript.htm The median improvement for Tamarin over SpiderMonkey is better than 2:1 and for Tamarin with type declarations better than 4:1. There are some tests with much more noticeable results but overall we're not looking at C or Lisp compiler levels of performance even with type declarations. Neil From nick at craig-wood.com Fri May 18 05:30:05 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Fri, 18 May 2007 04:30:05 -0500 Subject: How to convert a number to binary? References: <1179444832.775573.55830@y80g2000hsf.googlegroups.com> <1179445546.307017.275850@p77g2000hsh.googlegroups.com> <1179474308.939323.74720@p77g2000hsh.googlegroups.com> Message-ID: Lyosha wrote: > On May 17, 11:04 pm, Stargaming wrote: > [...] > > >>>Is there an *easy* way to convert a number to binary? > [...] > > > > Wrote this a few moons ago:: > > > > dec2bin = lambda x: (dec2bin(x/2) + str(x%2)) if x else '' > > This is awesome. Exactly what I was looking for. Works for other > bases too. Just don't pass it a negative number ;-) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From slava.maslov at gmail.com Mon May 7 03:49:12 2007 From: slava.maslov at gmail.com (Vyacheslav Maslov) Date: Mon, 7 May 2007 14:49:12 +0700 Subject: default test method name in unittest framework In-Reply-To: References: <271115400705061817u3c8ee950u3c7b0ec7ddcf6576@mail.gmail.com> Message-ID: <271115400705070049g7f41bb3atab98d45bcea9f67@mail.gmail.com> Yes, i general you are right. I meant following case, please look at my example Suppose i have following simple test case: import unittest class SomeTest(unittest.TestCase): def testAdd(self): self.assertEqual(2+2,4) if __name__=="__main__": unittest.TextTestRunner().run(SomeTest()) this code produce following exception: ValueError: no such test method in : runTest Because default test method name is "run", but TestCase class have constructor parameter testMethod with default value "runTest" not "run"! As result i always should explicitly pass testMethod name when create object of test case class: unittest.TextTestRunner().run(SomeTest("run")) Why i should do this? 2007/5/7, Gabriel Genellina : > > En Sun, 06 May 2007 22:17:44 -0300, Vyacheslav Maslov > escribi?: > > > i have question related to python's unit testing framework. > > > > Take a look at unittest.TestCase class. The main method which contains > > all > > code related to test case execution have name "run". But in the same > time > > constructor of unittest.TestCase class have param methodName with > default > > value "runTest", not "run"! Why? This leads to AttributeError exception > > if i > > do not explicitly set methodName to "run" during TestCase > initialization. > > No: method run is used by the framework, it internally calls the setUp, > tearDown, etc. You don't have to override run (you must not override > run!), instead, you provide the runTest method in your class. > Furthermore, instead of many similar TestCase classes, you can write a > single class with many methods named testXXX, and they will be found and > used by a TestLoader. > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From almadhu at gmail.com Mon May 7 00:33:34 2007 From: almadhu at gmail.com (Madhu Alagu) Date: 6 May 2007 21:33:34 -0700 Subject: Fingerprint Verification System Message-ID: <1178512414.266469.227460@w5g2000hsg.googlegroups.com> Hello, Any Fingerprint module for python. Is it possible to generate python module using FVS (http:// fvs.sourceforge.net/index.html) Thanks Madhu Alagu From steve at REMOVEME.cybersource.com.au Thu May 3 02:02:44 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Thu, 03 May 2007 16:02:44 +1000 Subject: How to check if a string is empty in python? References: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> <1178154290.811928.208900@h2g2000hsg.googlegroups.com> <1hxia6q.18rflwk1mez8vhN%aleax@mac.com> Message-ID: On Wed, 02 May 2007 21:59:56 -0700, Alex Martelli wrote: > Steven D'Aprano wrote: > >> On Wed, 02 May 2007 21:19:54 -0400, Roy Smith wrote: >> >> > for c in s: >> > raise "it's not empty" >> >> String exceptions are depreciated and shouldn't be used. >> >> http://docs.python.org/api/node16.html > > They're actually deprecated, not depreciated. Er, um... oh yeah... I knew that... I mean... yes, that was deliberate, to see who was paying attention. Well done Alex! -- Steven D'Aprano From sherrybove at gmail.com Tue May 8 01:20:24 2007 From: sherrybove at gmail.com (sherry) Date: 7 May 2007 22:20:24 -0700 Subject: interesting exercise In-Reply-To: References: <1178595952.641173.76540@y80g2000hsf.googlegroups.com> Message-ID: <1178601624.812907.23550@u30g2000hsc.googlegroups.com> On May 8, 9:31 am, Steven D'Aprano wrote: > On Mon, 07 May 2007 20:45:52 -0700, Michael Tobis wrote: > > I have a reasonably elegant solution but it's a bit verbose (a couple > > dozen lines which I'll post later if there is interest). Is there some > > clever Pythonism I didn't spot? > > Peering into my crystal ball, I see that your algorithm does the wrong > thing, and contains bugs too. You certainly don't need to partion the > sequence into three sub-sequences, or do that trick with the metaclass, > and it is more efficient to use list.extend() than sum. > > Hang on... stupid crystal ball... that's somebody else's code. Maybe you > should just post your code here, so we can look at it? > > In the meantime, here's a simple generator to do permutations with > repetition: > > def permute_with_repetitions(seq): > if len(seq) <= 1: > yield list(seq) > else: > for i, item in enumerate(seq): > for tail in permute_with_repetitions(seq[:i] + seq[i+1:]): > yield [item] + tail > > It doesn't do a test for the sequence containing duplicates, and I leave > it as anexerciseto do selections of fewer items. > > -- > Steven. Dear Steven I ran into your message quite accidentally while researching about some details on 'Exercise' and thought of sharing some of my findings. I've read at 'http://www.medical-health-care-information.com/Health- living/exercise/index.asp that Swimming, cycling, jogging, skiing, aerobic dancing, walking or any of dozens of other activities can help your heart. Whether it's included in a structured exercise program or just part of your daily routine, all physical activity adds up to a healthier heart. I hope the above is of some help to you as well. Regards, Sherrybove. From michael at jedimindworks.com Fri May 18 07:10:46 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Fri, 18 May 2007 06:10:46 -0500 Subject: App Leaving 'sh ' Everywhere In-Reply-To: <003b01c79929$6b2b30d0$41819270$@rawlins@thinkbluemedia.co.uk> References: <003b01c79929$6b2b30d0$41819270$@rawlins@thinkbluemedia.co.uk> Message-ID: <090C037E-FF4E-4455-B472-52B2ACEADE71@jedimindworks.com> On May 18, 2007, at 3:49 AM, Robert Rawlins - Think Blue wrote: > I?ve got an application that seems to leave ?sh ? in my os > processes list. I?m running it on Debian, albeit a stripped down > embedded version. I?m not sure what the cause of this is, My > application starts several threads and also uses popen2.popen3() to > run a few CMD commands. > > Any ideas why I?m getting this, or if it?s even something to be > concerned about. These processes have completed execution, but their parents have not read their exit status so they still have entries in the process table. They'll more than likely be reaped when the parent process goes away. If you'd rather not have zombies roaming around your system, use wait() to read the child's exit status. If, after the parent process exits, these processes persist -- run 'init -q' to get rid of them. hth, Michael --- "I would rather use Java than Perl. And I'd rather be eaten by a crocodile than use Java." ? Trouser -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Tue May 1 10:42:27 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 01 May 2007 16:42:27 +0200 Subject: Comparing bitmap images for differences? In-Reply-To: <1178024505.768505.262270@h2g2000hsg.googlegroups.com> References: <1178024505.768505.262270@h2g2000hsg.googlegroups.com> Message-ID: <59p1unF2lje91U1@mid.uni-berlin.de> lanwrangler at gmail.com schrieb: > I know it's a long shot but does anyone have any pointers to generic > algorithms - or, even better, Python code - for comparing images and > computing a value for the "difference" between them? > > What I want to do is to compare two bitmap images (taken from a > webcam, so I'll likely be using PIL) and get some idea of the > "difference" between them so I can tell if something in the image has > changed, eg, a person has entered the field of view. I've had a look > at the PIL documentation and all it really told me was how little I > knew about image processing :-) and I couldn't see any recipes in the > Python Cookbook that are aimed at this problem area. In a perfect > world I'd love a method such as CompareImage(Img1, Img2) which would > give a result of 255 if they're identical and 0 if not one pixel > matches with a sliding scale inbetween but I know I'm probably asking > for a lot there... > > Some ideas I've had is, maybe, increasing the contrast on both images > (to take out variation in lighting etc), then compressing the results > to get a hash value and comparing the hash, but that sounds likely to > produce a lot of false positives. I note that PIL provides a > histogram function for counting pixel colour values which sounds > potentially useful and if no-one's got any better ideas I'll probably > start working in that direction. Or, maybe, dump the bitmap data into > a numpy array and do some kind of FFT on that but that feels very CPU- > intensive. > > Those are my ideas so far but I thought it would be worth asking here > first in case there are some known-good algorithms for doing this kind > of thing rather than me trying to re-invent a wheel that ends up > triangular... There is the excellent OpenCV-library from intel which is FOSS and has a python-binding. Either using swig, or a ctypes-version: http://wwwx.cs.unc.edu/~gb/wp/blog/2007/02/04/python-opencv-wrapper-using-ctypes/ With that, you can approach your problem. What is usually done is that a sequence of background images is sampled & an average is built. Then the actual image is subtracted from that image, with an epsilon to account for noise. The result is then converted to a binary image for further processing. There are some blob-detection-recipes out there. Another approach is to use the motion-detection parts of the lib. Diez From duncan.booth at invalid.invalid Thu May 10 09:57:35 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 May 2007 13:57:35 GMT Subject: Thread-safe dictionary References: Message-ID: Jean-Paul Calderone wrote: >>- would I need to override another methods e.g. update() or items() in >>order to remain thread-safe or is this enough? No, you'll need to protect almost everything. items may be safe. update, clear, get, has_key, pop, and setdefault all need a lock in the general case. Also be aware that some Python internals bypass things like __getitem__ in dict subclasses, so the lock will be ignored if (for example) you use the dict as a namespace for exec. >>- in __getitem__, does it release the lock after returning the item? >>- wouldn't it be better to use threading.RLock, mutex, ... instead? >> > > The builtin dict type is already thread safe. It very much depends on what you mean by 'thread safe'. Calls to dict methods from multiple threads won't result in Python getting into an inconsistent state and crashing, but they aren't necessarily atomic either. In particular, any method which can modify the content of the dictionary could release an instance of a class with a __del__ method written in Python and other threads will be able to run at that point. Likewise any lookup in a dict where a key is an instance of a class with user-defined comparison method could allow Python code and therefore other threads to run. Of course if your particular dict objects all use simple types this may not matter, but it needs a careful programmer to use an ordinary Python dict (or list) safely across threads. IMHO you are probably best to write a thread-safe class which uses an ordinary dict (and has a nicely limited interface) rather than trying to produce a completely thread-safe dict type. From yucetekol at gmail.com Wed May 30 13:47:37 2007 From: yucetekol at gmail.com (yuce) Date: 30 May 2007 10:47:37 -0700 Subject: Creating a distro of python... What would you include in it? In-Reply-To: <1180538748.448426.182820@g4g2000hsf.googlegroups.com> References: <1180538748.448426.182820@g4g2000hsf.googlegroups.com> Message-ID: <1180547257.472087.198630@p77g2000hsh.googlegroups.com> re: BJ?rn, I think selecting a GPL license will increase the number of usable packages, since using Python license with GPL is perfectly fine as long as the whole software is licensed under GPL [I am not really sure it is a must to license the whole package under GPL] re: farksimm; I'd put (in nor particular order) - Python Imaging Library : http://www.pythonware.com/products/pil/ - wxPython : http://www.wxpython.org/ - ipython : http://ipython.scipy.org/moin/ - pycrypto : http://www.amk.ca/python/code/crypto - sqlalchemy : http://www.sqlalchemy.org/ - psycopg : http://www.initd.org/tracker/psycopg - docutils : http://docutils.sourceforge.net/ - NumPy/Numeric : http://numpy.scipy.org/ - if it's for Win32 also pywin32 : http://www.python.net/crew/mhammond/win32/ Yuce From hardcoded.software at gmail.com Sun May 13 18:03:28 2007 From: hardcoded.software at gmail.com (Virgil Dupras) Date: 13 May 2007 15:03:28 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46473267$0$31532$9b622d9e@news.freenet.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <1179093808.669586.76820@k79g2000hse.googlegroups.com> On May 13, 11:44?am, "Martin v. L?wis" wrote: > PEP 1 specifies that PEP authors need to collect feedback from the > community. As the author of PEP 3131, I'd like to encourage comments > to the PEP included below, either here (comp.lang.python), or to > python-3... at python.org > > In summary, this PEP proposes to allow non-ASCII letters as > identifiers in Python. If the PEP is accepted, the following > identifiers would also become valid as class, function, or > variable names: L?ffelstiel, chang?, ??????, or ??? > (hoping that the latter one means "counter"). > > I believe this PEP differs from other Py3k PEPs in that it really > requires feedback from people with different cultural background > to evaluate it fully - most other PEPs are culture-neutral. > > So, please provide feedback, e.g. perhaps by answering these > questions: > - should non-ASCII identifiers be supported? why? > - would you use them if it was possible to do so? in what cases? > > Regards, > Martin > > PEP: 3131 > Title: Supporting Non-ASCII Identifiers > Version: $Revision: 55059 $ > Last-Modified: $Date: 2007-05-01 22:34:25 +0200 (Di, 01 Mai 2007) $ > Author: Martin v. L?wis > Status: Draft > Type: Standards Track > Content-Type: text/x-rst > Created: 1-May-2007 > Python-Version: 3.0 > Post-History: > > Abstract > ======== > > This PEP suggests to support non-ASCII letters (such as accented > characters, Cyrillic, Greek, Kanji, etc.) in Python identifiers. > > Rationale > ========= > > Python code is written by many people in the world who are not familiar > with the English language, or even well-acquainted with the Latin > writing system. ?Such developers often desire to define classes and > functions with names in their native languages, rather than having to > come up with an (often incorrect) English translation of the concept > they want to name. > > For some languages, common transliteration systems exist (in particular, > for the Latin-based writing systems). ?For other languages, users have > larger difficulties to use Latin to write their native words. > > Common Objections > ================= > > Some objections are often raised against proposals similar to this one. > > People claim that they will not be able to use a library if to do so > they have to use characters they cannot type on their keyboards. > However, it is the choice of the designer of the library to decide on > various constraints for using the library: people may not be able to use > the library because they cannot get physical access to the source code > (because it is not published), or because licensing prohibits usage, or > because the documentation is in a language they cannot understand. ?A > developer wishing to make a library widely available needs to make a > number of explicit choices (such as publication, licensing, language > of documentation, and language of identifiers). ?It should always be the > choice of the author to make these decisions - not the choice of the > language designers. > > In particular, projects wishing to have wide usage probably might want > to establish a policy that all identifiers, comments, and documentation > is written in English (see the GNU coding style guide for an example of > such a policy). Restricting the language to ASCII-only identifiers does > not enforce comments and documentation to be English, or the identifiers > actually to be English words, so an additional policy is necessary, > anyway. > > Specification of Language Changes > ================================= > > The syntax of identifiers in Python will be based on the Unicode > standard annex UAX-31 [1]_, with elaboration and changes as defined > below. > > Within the ASCII range (U+0001..U+007F), the valid characters for > identifiers are the same as in Python 2.5. ?This specification only > introduces additional characters from outside the ASCII range. ?For > other characters, the classification uses the version of the Unicode > Character Database as included in the ``unicodedata`` module. > > The identifier syntax is `` *``. > > ``ID_Start`` is defined as all characters having one of the general > categories uppercase letters (Lu), lowercase letters (Ll), titlecase > letters (Lt), modifier letters (Lm), other letters (Lo), letter numbers > (Nl), plus the underscore (XXX what are "stability extensions" listed in > UAX 31). > > ``ID_Continue`` is defined as all characters in ``ID_Start``, plus > nonspacing marks (Mn), spacing combining marks (Mc), decimal number > (Nd), and connector punctuations (Pc). > > All identifiers are converted into the normal form NFC while parsing; > comparison of identifiers is based on NFC. > > Policy Specification > ==================== > > As an addition to the Python Coding style, the following policy is > prescribed: All identifiers in the Python standard library MUST use > ASCII-only identifiers, and SHOULD use English words wherever feasible. > > As an option, this specification can be applied to Python 2.x. ?In that > case, ASCII-only identifiers would continue to be represented as byte > string objects in namespace dictionaries; identifiers with non-ASCII > characters would be represented as Unicode strings. > > Implementation > ============== > > The following changes will need to be made to the parser: > > 1. If a non-ASCII character is found in the UTF-8 representation of the > ? ?source code, a forward scan is made to find the first ASCII > ? ?non-identifier character (e.g. a space or punctuation character) > > 2. The entire UTF-8 string is passed to a function to normalize the > ? ?string to NFC, and then verify that it follows the identifier syntax. > ? ?No such callout is made for pure-ASCII identifiers, which continue to > ? ?be parsed the way they are today. > > 3. If this specification is implemented for 2.x, reflective libraries > ? ?(such as pydoc) must be verified to continue to work when Unicode > ? ?strings appear in ``__dict__`` slots as keys. > > References > ========== > > .. [1]http://www.unicode.org/reports/tr31/ > > Copyright > ========= > > This document has been placed in the public domain. I don't think that supporting non-ascii characters for identifiers would cause any problem. Most people won't use it anyway. People who use non-english identifiers for their project and hope for it to be popular worldwide will probably just fail because of their foolish coding style policy choice. I put that kind of choice in the same ballpark as deciding to use hungarian notation for python code. As for malicious patch submission, I think this is a non issue. Designing tool to detect any non-ascii char identifier in a file should be a trivial script to write. I say that if there is a demand for it, let's do it. From skip at pobox.com Thu May 31 10:52:31 2007 From: skip at pobox.com (Skip Montanaro) Date: Thu, 31 May 2007 14:52:31 +0000 (UTC) Subject: Upgrading a largish group of packages w/ distutils References: <18014.55303.369800.765014@montanaro.dyndns.org> Message-ID: > export PYTHONPATH=$HOME/local/lib/python-2.4/site-packages > cd ~/src > cd numpy > python setup.py install --prefix=$PYTHONPATH > cd ../scipy > python setup.py install --prefix=$PYTHONPATH > cd ../matplotlib > python setup.py install --prefix=$PYTHONPATH > cd ../ipython > python setup.py install --prefix=$PYTHONPATH Ack! Make that: export PYTHONPATH=$HOME/local/lib/python-2.4/site-packages export PYTHONPFX=$HOME/local cd ~/src cd numpy python setup.py install --prefix=$PYTHONPFX cd ../scipy python setup.py install --prefix=$PYTHONPFX cd ../matplotlib python setup.py install --prefix=$PYTHONPFX cd ../ipython python setup.py install --prefix=$PYTHONPFX Skip From vegan16 at accesscomm.ca Thu May 3 02:14:37 2007 From: vegan16 at accesscomm.ca (malibu) Date: 2 May 2007 23:14:37 -0700 Subject: Firefighters at the site of WTC7 "Move away the building is going to blow up, get back the building is going to blow up." In-Reply-To: <1178163974.007362.13870@c35g2000hsg.googlegroups.com> References: <1178161820.731367.264500@y80g2000hsf.googlegroups.com> <1178163974.007362.13870@c35g2000hsg.googlegroups.com> Message-ID: <1178172877.755445.101340@q75g2000hsh.googlegroups.com> On May 2, 9:46 pm, Eric Gisse wrote: > On May 2, 7:10 pm, Midex wrote: > > [...] > > I guess the explanation that people were looking at the building and > watching its' structure deform is too rational. Also, that was a Larry Silverstein impostor who said they were going to 'pull it'. And the only reason he took out huge amounts of extra insurance on the buildings two months before this happened was because of global warming, because we all know a little bit of heat will bring down steel buildings. John From __peter__ at web.de Fri May 25 16:09:43 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 25 May 2007 22:09:43 +0200 Subject: csv.reader length? References: <1180118981.024036.163590@p47g2000hsd.googlegroups.com> <1180122583.282729.275840@p47g2000hsd.googlegroups.com> Message-ID: 7stud wrote: > On May 25, 12:49 pm, cjl wrote: >> reader = csv.reader(open('somefile.csv')) >> for row in reader: >> do something >> >> Any way to determine the "length" of the reader (the number of rows) >> before iterating through the rows? No. You have to read the records to know the length: rows = list(reader) print len(rows) for row in rows: # ... > How about: > > f = open("somefile.csv") > numlines = len(f.readlines()) No, a field in a csv file may contain newlines: >>> import csv >>> csv.writer(open("tmp.csv", "w")).writerows([["a", "b\nc"], ["d", "e"]]) >>> len(open("tmp.csv").readlines()) 3 # number of lines >>> len(list(csv.reader(open("tmp.csv")))) 2 # number of records Peter From dustin at v.igoro.us Sun May 13 12:00:46 2007 From: dustin at v.igoro.us (dustin at v.igoro.us) Date: Sun, 13 May 2007 11:00:46 -0500 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46473267$0$31532$9b622d9e@news.freenet.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <20070513160046.GC29172@v.igoro.us> On Sun, May 13, 2007 at 05:44:39PM +0200, "Martin v. L??wis" wrote: > - should non-ASCII identifiers be supported? why? The only objection that comes to mind is that adding such support may make some distinct identifiers visually indistinguishable. IIRC the DNS system has had this problem, leading to much phishing abuse. I don't necessarily think that the objection is strong enough to reject the idea -- programmers using non-ASCII symbols would be responsible for the consequences of their character choice. Dustin From mike.klaas at gmail.com Tue May 8 17:34:17 2007 From: mike.klaas at gmail.com (Klaas) Date: 8 May 2007 14:34:17 -0700 Subject: Python regular expressions just ain't PCRE In-Reply-To: <1178416665.895916.299360@p77g2000hsh.googlegroups.com> References: <1178323901.381993.47170@e65g2000hsc.googlegroups.com> <1178380335.646708.260540@h2g2000hsg.googlegroups.com> <1178401499.480169.140940@e65g2000hsc.googlegroups.com> <1178416665.895916.299360@p77g2000hsh.googlegroups.com> Message-ID: <1178660057.587786.95450@e51g2000hsg.googlegroups.com> On May 5, 6:57 pm, Wiseman wrote: > > There's also the YAGNI factor; most folk would restrict using regular > > expressions to simple grep-like functionality and data validation -- > > e.g. re.match("[A-Z][A-Z]?[0-9]{6}[0-9A]$", idno). The few who want to > > recognise yet another little language tend to reach for parsers, using > > regular expressions only in the lexing phase. > > Well, I find these features very useful. I've used a complex, LALR > parser to parse complex grammars, but I've solved many problems with > just the PCRE lib. Either way seeing nobody's interested on these > features, I'll see if I can expose PCRE to Python myself; it sounds > like the fairest solution because it doesn't even deal with the re > module - you can do whatever you want with it (though I'd rather have > it stay as it is or enhance it), and I'll still have PCRE. That's if I > find the time to do it though, even having no life. A polished wrapper for PCRE would be a great contribution to the python community. If it becomes popular, then the argument for replacing the existing re engine becomes much stronger. -Mike From gagsl-py2 at yahoo.com.ar Mon May 28 05:16:01 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 28 May 2007 06:16:01 -0300 Subject: Can python create a dictionary from a list comprehension? References: <1180299312.207986.4340@k79g2000hse.googlegroups.com> <465a90a8$0$55856$dbd43001@news.wanadoo.nl> <465a94a0$0$98669$dbd4f001@news.wanadoo.nl> Message-ID: En Mon, 28 May 2007 05:37:12 -0300, Wim Vogelaar escribi?: > I made the original list two elements longer: a = > [1,2,3,4,5,6,7,8,9,10,11,12] > > and to my surprise the output is now ordered, giving: {2: 3, 4: 5, 6: 7, > 8: > 9, 10: 11, 12: 13} > > I am running ActiveState ActivePython 2.5 Keys in a dictionary are listed in an arbitrary order; the *only* thing about the ordering you can say is that, given a FIXED dictionary (already constructed, and without any other intervening operation that could alter its content), when you iterate over its keys (using .keys(), .iterkeys()), its values (.values(), .itervalues()) or items (.items(), .iteritems()) you will always get the same things in the same order over and over. If you create the dictionary using a different sequence of insertions and deletions, you may get different results. If you insert and delete things afterwards, you may get different results. If you exit the program and run it again, you may get different results. The *only* guaranteed fact is that you will get the same results provided you don't modify the dictionary at all. See note (3) in http://docs.python.org/lib/typesmapping.html -- Gabriel Genellina From johnjsal at NOSPAMgmail.com Tue May 8 16:00:13 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 08 May 2007 16:00:13 -0400 Subject: Suggestions for how to approach this problem? In-Reply-To: References: <4640ca5b$0$23392$c3e8da3@news.astraweb.com> Message-ID: <4640d69b$0$31446$c3e8da3@news.astraweb.com> Marc 'BlackJack' Rintsch wrote: > I think I have vague idea how the input looks like, but it would be > helpful if you show some example input and wanted output. Good idea. Here's what it looks like now: 1. Levy, S.B. (1964) Isologous interference with ultraviolet and X-ray irradiated bacteriophage T2. J. Bacteriol. 87:1330-1338. 2. Levy, S.B. and T. Watanabe (1966) Mepacrine and transfer of R factor. Lancet 2:1138. 3. Takano, I., S. Sato, S.B. Levy and T. Watanabe (1966) Episomic resistance factors in Enterobacteriaceae. 34. The specific effects of the inhibitors of DNA synthesis on the transfer of R factor and F factor. Med. Biol. (Tokyo) 73:79-83. 4. Levy, S.B. (1967) Blood safari into Kenya. The New Physician 16:50-54. 5. Levy, S.B., W.T. Fitts and J.B. Leach (1967) Surgical treatment of diverticular disease of the colon: Evaluation of an eleven-year period. Annals Surg. 166:947-955. As you can see, any single citation is broken over several lines as a result of a line break. I want it to look like this: 1. Levy, S.B. (1964) Isologous interference with ultraviolet and X-ray irradiated bacteriophage T2. J. Bacteriol. 87:1330-1338. 2. Levy, S.B. and T. Watanabe (1966) Mepacrine and transfer of R factor. Lancet 2:1138. 3. Takano, I., S. Sato, S.B. Levy and T. Watanabe (1966) Episomic resistance factors in Enterobacteriaceae. 34. The specific effects of the inhibitors of DNA synthesis on the transfer of R factor and F factor. Med. Biol. (Tokyo) 73:79-83. 4. Levy, S.B. (1967) Blood safari into Kenya. The New Physician 16:50-54. 5. Levy, S.B., W.T. Fitts and J.B. Leach (1967) Surgical treatment of diverticular disease of the colon: Evaluation of an eleven-year period. Annals Surg. 166:947-955. Now, since this is pasted, it might not even look good to you. But in the second example, the numbers are meant to be bullets and so the indentation would happen automatically (in Word). But for now they are just typed. From knight at baldmt.com Tue May 29 10:36:31 2007 From: knight at baldmt.com (Steven Knight) Date: Tue, 29 May 2007 09:36:31 -0500 (CDT) Subject: ANNOUNCE: SCons 0.97 has been released Message-ID: SCons is a software construction tool (build tool, or make tool) written in Python. It is based on the design which won the Software Carpentry build tool competition in August 2000. Version 0.97 of SCons has been released and is available for download from the SCons web site: http://www.scons.org/download.php An RPM package and a Win32 installer are all available, in addition to the traditional .tar.gz and .zip files. A Debian package is available in Debian unstable. WHAT'S NEW IN THIS RELEASE? This release contains two fixes for problems discovered since 0.96.96 (the last testing version) was released. There are a HUGE number of fixes and new features since the last "stable" 0.96.1 release. If you are updating from 0.96.1 or an earlier version, BE SURE to read the release notes for important information about changes which may trigger rebuilds, or otherwise impact your configuration: http://www.scons.org/RELEASE.txt You can see a complete list of changes in the change log at: http://www.scons.org/CHANGES.txt ABOUT SCONS Distinctive features of SCons include: - a global view of all dependencies; no multiple passes to get everything built properly - configuration files are Python scripts, allowing the full use of a real scripting language to solve difficult build problems - a modular architecture allows the SCons Build Engine to be embedded in other Python software - the ability to scan files for implicit dependencies (#include files); - improved parallel build (-j) support that provides consistent build speedup regardless of source tree layout - use of MD5 signatures to decide if a file has really changed; no need to "touch" files to fool make that something is up-to-date - extensible through user-defined Builder and Scanner objects - build actions can be Python code, as well as external commands An SCons users' mailing list is available for those interested in getting started. You can subscribe by sending email to: users-subscribe at scons.tigris.org Alternatively, we invite you to subscribe to the low-volume SCons announcement mailing list to receive notification when new versions of SCons become available. Send email to: announce-subscribe at scons.tigris.org ACKNOWLEDGEMENTS Many, many thanks to all of the following people for their contributions during the entire protracted 0.97 development cycle, and its numerous pre-release testing versions: Anonymous, Anatoly, Matthias, Paul, Steve-o, Erling Andersen, Chad Austin, Stanislav Baranov, Timothee Besset, Joe Bloggs, Ken Boortz, John Calcote, Steve Christensen, Charles Crain, Matt Doar, Matthew Doar, Christopher Drexler, Bjorn Eriksson, Walter Franzini, Eric Frias, Gottfried Ganssauge, Dmitry Grigorenko, Helmut Grohne, Ralf W. Grosse-Kunstleve, David Gruener, Fawad Halim, Bob Halley, August H??randl, Steven Johnson, Stephen Kennedy, Jay Kint, James Y. Knight, Arve Knudsen, Carsten Koch, Jean-Baptiste Lab, Chen Lee, Wayne Lee, Baptiste Lepilleur, Ben Leslie, Clive Levinson, Ben Liblit, Christian Maaser, Adam MacBeth, Sanjoy Mahajan, Jeff Mahovsky, Rob Managan, Rob Managan, Shannon Mann, Michael McCracken, Patrick Mezard, Dmitry Mikhin, Georg Mischler, Joel B. Mohler, Elliot Murphy, Leanid Nazdrynau, Christian Neeb, Matthew A. Nicholson, Han-Wen Nienhuys, Jan Nieuwenhuizen, Jan Nijtmans, Greg Noel, Gary Oberbrunner, Kian Win Ong, Tom Parker, Gerard Patel, Chris Pawling, Karol Pietrzak, Chris Prince, John Pye, Asfand Yar Qazi, Kevin Quick, Jon Rafkind, Steve Robbins, Christoph Schulz, Craig Scott, Stefan Seefeld, Jose Pablo Ezequiel "Pupeno" Fernandez Silva, Adam Simpkins, Vaclav Smilauer, a smith, Sohail Somani, Jeff Squyres, Levi Stephen, Amir Szekely, Matthias Troffaes, Erick Tryzelaar, Jonathan Ultis, Dobes Vandermeer, David J. Van Maren, Atul Varma, Nicolas Vigier, Richard Viney, David Vitek, Edward Wang, Greg Ward, Thad Ward, Ben Webb, Christoph Wiedemann, Russell Yanofsky and Johan Zander. On behalf of the SCons team, --SK From deets at nospam.web.de Tue May 8 07:02:40 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 08 May 2007 13:02:40 +0200 Subject: Designing a graph study program References: <1178619753.077639.112510@q75g2000hsh.googlegroups.com> Message-ID: <5ab3mgF2o5bfbU1@mid.uni-berlin.de> > > Well then I wanted to draw graphs and I found that pydot is working > really nicely. > BUT I'd like to do this, an interactive program to see ho the > algorithms works... > For example in the breath search first, every time the algorithm > colors a node, the program should redraw the graphs. Which modules > should I use for graphics (I use macosX and I'd like something cross > platforms). Use the bundled Tkinter. I've implemented a similar thing back in my under graduation days using TCL/Tk, and Tk is perfectly suited for that task. Diez From knipknap at gmail.com Tue May 22 07:34:40 2007 From: knipknap at gmail.com (Samuel) Date: 22 May 2007 04:34:40 -0700 Subject: Simple omniORBpy example throws exception with error 0x41540002 Message-ID: <1179833680.255391.198490@x18g2000prd.googlegroups.com> Hi, I am trying to get the files from this tutorial to work: http://www.grisby.org/presentations/py10code.html Direct link to the files: http://www.grisby.org/presentations/py10code/adder.idl http://www.grisby.org/presentations/py10code/adderServer.py It produces the following error: $ omniidl -bpython adder.idl && python adderServer.py Traceback (most recent call last): File "adderServer.py", line 23, in nameRoot = nameRoot._narrow(CosNaming.NamingContext) File "/usr/lib/python2.5/site-packages/omniORB/CORBA.py", line 667, in _narrow return _omnipy.narrow(self, dest._NP_RepositoryId) omniORB.CORBA.TRANSIENT: Minor: 0x41540002, COMPLETED_NO. According to Google this might mean "Connect failed", however, I don't understand why the server would open a connection. I expected it to simply listen on a socket, but I probably just don't understand how it works. Can anyone please explain this? -Samuel From krypto.wizard at gmail.com Wed May 16 13:38:27 2007 From: krypto.wizard at gmail.com (Krypto) Date: 16 May 2007 10:38:27 -0700 Subject: python shell Message-ID: <1179337107.842668.112690@k79g2000hse.googlegroups.com> I have been using python shell to test small parts of the big program. What other ways can I use the shell effectively. My mentor told me that you can virtually do anything from testing your program to anything in the shell. Any incite would be useful. From steve at holdenweb.com Thu May 31 12:55:29 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 31 May 2007 12:55:29 -0400 Subject: c[:]() In-Reply-To: <135tv1bjqgbmsc9@corp.supernews.com> References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> <135tobve86qj808@corp.supernews.com> <135tru124pie2b3@corp.supernews.com> <135tv1bjqgbmsc9@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2007-05-31, Warren Stringer wrote: >>> How is it more expressive? In the context you're concerned >>> with, c[:] is the exactly same thing as c. You seem to be >>> worried about saving keystrokes, yet you use c[:] instead of c. >>> >>> It's like having an integer variable i and using ((i+0)*1) >>> instead of i. >> Nope, different. >> >> c[:] holds many behaviors that change dynamically. > > I've absolutely no clue what that sentence means. If c[:] does > behave differently than c, then somebody's done something > seriously weird and probably needs to be slapped around for > felonious overriding. > >> So c[:]() -- or the more recent go(c)() -- executes all those >> behaviors. > > Still no clue. > >> This is very useful for many performers. > > What are "performers"? > >> The real world example that I'm working one is a collaborative >> visual music performance. So c can contain wrapped MIDI events >> or sequencer behaviors. c may get passed to a scheduler to >> execute those events, or c may get passed to a pickler to >> persist the performance. > > I still don't see how c[:] is any different from c. > It isn't. The OP is projecting a wish for a function call on a list to be interpreted as a call on each member of the list with the same arguments. The all-members slice notation is a complete red herring. It would require a pretty fundamental re-think to give such a construct sensible and consistent semantics, I 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 ------------------ Asciimercial --------------------- Get on the web: Blog, lens and tag your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From doulos05 at gmail.com Tue May 1 19:03:28 2007 From: doulos05 at gmail.com (JonathanB) Date: 1 May 2007 16:03:28 -0700 Subject: Read and Write the same file Message-ID: <1178060601.700099.263240@y5g2000hsa.googlegroups.com> Ok, so this is the scenario. I need to create a simple, no-frills XML editor for non-technical users. It doesn't have to do anything fancy, what I want is a series of text boxes with the text contents of the elements pre-printed. Then the users can type their changes into the text boxes and click submit and it will load the changes in. So here is the problem, this means I need to open the same file as both read and write. How do I do this? I'm slowly learning the DOM stuff that I need to know to do this, but this file thing I haven't been able to find anywhere. JonathanB From duncan.booth at invalid.invalid Mon May 14 09:44:04 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 14 May 2007 13:44:04 GMT Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <7x4pmg716p.fsf@ruckus.brouhaha.com> <4648571B.9050102@web.de> Message-ID: Stefan Behnel wrote: >> Just to confirm that: IronPython does accept non-ascii identifiers. >> From "Differences between IronPython and CPython": >> >>> IronPython will compile files whose identifiers use non-ASCII >>> characters if the file has an encoding comment such as "# -*- >>> coding: utf-8 -*-". CPython will not compile such a file in any >>> case. > > Sounds like CPython would better follow IronPython here. I cannot find any documentation which says exactly which non-ASCII characters IronPython will accept. I would guess that it probably follows C# in general, but it doesn't follow C# identifier syntax exactly (in particular the leading @ to quote keywords is not supported). The C# identifier syntax from http://msdn2.microsoft.com/en-us/library/aa664670(VS.71).aspx I think it differs from the PEP only in also allowing the Cf class of characters: identifier: available-identifier @ identifier-or-keyword available-identifier: An identifier-or-keyword that is not a keyword identifier-or-keyword: identifier-start-character identifier-part-charactersopt identifier-start-character: letter-character _ (the underscore character U+005F) identifier-part-characters: identifier-part-character identifier-part-characters identifier-part-character identifier-part-character: letter-character decimal-digit-character connecting-character combining-character formatting-character letter-character: A Unicode character of classes Lu, Ll, Lt, Lm, Lo, or Nl A unicode-escape-sequence representing a character of classes Lu, Ll, Lt, Lm, Lo, or Nl combining-character: A Unicode character of classes Mn or Mc A unicode-escape-sequence representing a character of classes Mn or Mc decimal-digit-character: A Unicode character of the class Nd A unicode-escape-sequence representing a character of the class Nd connecting-character: A Unicode character of the class Pc A unicode-escape-sequence representing a character of the class Pc formatting-character: A Unicode character of the class Cf A unicode-escape-sequence representing a character of the class Cf For information on the Unicode character classes mentioned above, see The Unicode Standard, Version 3.0, section 4.5. From txtoth at gmail.com Mon May 14 17:30:09 2007 From: txtoth at gmail.com (txtoth at gmail.com) Date: 14 May 2007 14:30:09 -0700 Subject: swig %typemap generated list typeerror Message-ID: <1179178209.326540.282470@h2g2000hsg.googlegroups.com> I'm trying to map a security_context_t ** to a python list. After calling the method that returns this type when I process the returned list in a for loop I get: TypeError: expected string or Unicode object, NoneType found after processing the last list entry. Can anyone see what I'm doing wrong? Do I need to do something else to the list to somehow terminate it? %typemap(argout) security_context_t ** { PyObject *list_security_context = PyList_New(0); // Create the list. if (list_security_context) { security_context_t **p_p_security_context_t = arg3; while (*p_p_security_context_t) { // Move each string into the list. security_context_t *p_security_context_t = *p_p_security_context_t; if (PyList_Append(list_security_context, PyString_FromString((char *)*p_security_context_t)) < 0) { fprintf(stderr, "Fail to insert item in list.\n"); $result = -1; break; } p_p_security_context_t++; } } else { fprintf(stderr, "Fail to create list.\n"); $result = -1; } $result = SWIG_Python_AppendOutput($result, list_security_context); } From gigs at hi.t-com.hr Thu May 24 05:45:17 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Thu, 24 May 2007 11:45:17 +0200 Subject: function nested Message-ID: def f(start): stack = [] def f1(start): for fname in os.listdir(start): path = os.path.join(start, fname) if os.path.isfile(path): stack.append(path) else: f1(path) f1(start) return stack i feel s stupid right now forgot to call f1 any comments how to make this better? From stefan.behnel-n05pAM at web.de Sat May 26 04:02:06 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sat, 26 May 2007 10:02:06 +0200 Subject: Xml parser In-Reply-To: References: Message-ID: <4657E97E.90505@web.de> XiaQ wrote: > You can use DOM > http://diveintopython.org/, Chapter 9 > "ashish" wrote >> Hi All, >> >> I want to know weather is there any api available in python for parsing >> xml(XML parser) >> >> Regards >> Ashish Sure, you can use DOM, but if you want to get real work done with XML, lxml is what you actually want. http://codespeak.net/lxml/dev/ Stefan From martin at v.loewis.de Wed May 30 01:23:55 2007 From: martin at v.loewis.de (=?GB2312?B?Ik1hcnRpbiB2LiBMbyJ3aXMi?=) Date: Wed, 30 May 2007 07:23:55 +0200 Subject: How to print this character u'\u20ac' to DOS terminal In-Reply-To: <1180501468.957322.106650@z28g2000prd.googlegroups.com> References: <1180501468.957322.106650@z28g2000prd.googlegroups.com> Message-ID: <465D0A6B.1000203@v.loewis.de> ??????????????? schrieb: > Who could explain the follow issue ? >>>> print u'\u0394' > ? >>>> print u'\u20ac' > Traceback (most recent call last): > File "", line 1, in > UnicodeEncodeError: 'gbk' codec can't encode character u'\u20ac' in > position 0: > illegal multibyte sequence > > My terminal is cmd.exe under windows XP. > what's the different between the two character ? what can I do if I > want to print the u'\u20ac'? The problem is that your terminal uses (some form of) the GBK encoding; see http://zh.wikipedia.org/wiki/GBK for details on GBK. It seems that GBK (or, rather, code page 936) supports the delta character, but not the euro sign. To change that, you can use "chcp" in your terminal window. For example, if you do "chcp 850", you should be able to display the euro sign (but will simultaneously use the ability to display the letter delta, and the chinese letters). I don't know whether the terminal supports an UTF-8 code page; you can try setting the terminal's code page to 65001 (which should be UTF-8). Regards, Martin From clodoaldo.pinto at gmail.com Wed May 30 08:49:39 2007 From: clodoaldo.pinto at gmail.com (Clodoaldo) Date: 30 May 2007 05:49:39 -0700 Subject: Unicode to HTML entities In-Reply-To: References: <1180453921.357081.89500@n15g2000prd.googlegroups.com> Message-ID: <1180529379.586032.211560@q75g2000hsh.googlegroups.com> On May 30, 8:53 am, Tommy Nordgren wrote: > On 29 maj 2007, at 17.52, Clodoaldo wrote: > > > > > I was looking for a function to transform a unicode string into > > htmlentities. Not only the usual html escaping thing but all > > characters. > > > As I didn't find I wrote my own: > > > # -*- coding: utf-8 -*- > > from htmlentitydefs import codepoint2name > > > def unicode2htmlentities(u): > > > htmlentities = list() > > > for c in u: > > if ord(c) < 128: > > htmlentities.append(c) > > else: > > htmlentities.append('&%s;' % codepoint2name[ord(c)]) > > > return ''.join(htmlentities) > > > print unicode2htmlentities(u'S?o Paulo') > > > Is there a function like that in one of python builtin modules? If not > > is there a better way to do it? > > > Regards, Clodoaldo Pinto Neto > > In many cases, the need to use html/xhtml entities can be avoided by > generating > utf8- coded pages. Sure. All my pages are utf-8 encoded. The case I'm dealing with is an email link which subject has non ascii characters like in: Mail to Somehow when the user clicks on the link the subject goes to his email client with the non ascii chars as garbage. And before someone points that I should not expose email addresses, the email is only linked with the consent of the owner and the source is obfuscated to make it harder for a robot to harvest it. Regards, Clodoaldo From adamurbas at hotmail.com Sun May 13 11:10:08 2007 From: adamurbas at hotmail.com (adamurbas at hotmail.com) Date: 13 May 2007 08:10:08 -0700 Subject: need help with python In-Reply-To: <1178988911.443161.287350@k79g2000hse.googlegroups.com> References: <1178934447.719778.197150@h2g2000hsg.googlegroups.com> <1178988911.443161.287350@k79g2000hse.googlegroups.com> Message-ID: <1179069008.711095.301770@p77g2000hsh.googlegroups.com> On May 12, 11:55 am, BartlebyScrivener wrote: > I'm not sure how you installed Python, or how you are using it, but I > made something last year to help Windows XP users who are brand new to > Python and can't get things to run, etc. > > You might try either jumping into somewhere midway, or if you keep > having trouble, uninstall whatever you installed and start over using > this: > > http://www.richarddooling.com/index.php/2006/03/14/python-on-xp-7-min... > > If that link breaks, use this: > > http://tinyurl.com/w7wgp > > Good luck. > > rd That is one of my problems, I don't know exactly how the whole command line thing works. The other day, I got it to open python by itself, but I accidentally closed the window and couldn't get it to work again. I know how to do file paths and stuff but I'm not sure what to put directly after it says C:\Documents and Settings\HP_Owner>. Do I leave it like that and then put the next location in the line? Like this: C:\Documents and Settings\HP_Owner> Python 2.5.1\Python area.py Or is that wrong. I've already uninstalled and reinstalled because I couldn't copy and paste it to another location, so I just reinstalled it to HP_Owner. I'll try that link. Thanks. From saint.infidel at gmail.com Wed May 16 18:40:53 2007 From: saint.infidel at gmail.com (infidel) Date: 16 May 2007 15:40:53 -0700 Subject: A bug in cPickle? In-Reply-To: References: <1179335180.786851.209900@y80g2000hsf.googlegroups.com> Message-ID: <1179355253.180360.230410@u30g2000hsc.googlegroups.com> ActivePython 2.5.1.1 as well: PythonWin 2.5.1 (r251:54863, May 1 2007, 17:47:05) [MSC v.1310 32 bit (Intel)] on win32. Portions Copyright 1994-2006 Mark Hammond - see 'Help/About PythonWin' for further copyright information. >>> from pickle import dumps >>> from cPickle import dumps as cdumps >>> print dumps('10') S'10' p0 . >>> print dumps(str(10)) S'10' p0 . >>> print cdumps('10') S'10' p1 . >>> print cdumps(str(10)) S'10' . From steve at REMOVE.THIS.cybersource.com.au Sun May 27 10:46:46 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 28 May 2007 00:46:46 +1000 Subject: Newbie question - better way to do this? References: <1180273441.455227.120170@g4g2000hsf.googlegroups.com> Message-ID: On Sun, 27 May 2007 06:44:01 -0700, Eric wrote: > words is a big long array of strings. What I want to do is find > consecutive sequences of words that have the first letter capitalized, > and then call doSomething on them. (And you can ignore the fact that > it won't find a sequence at the very end of words, that is fine for my > purposes). Assuming the list of words will fit into memory, and you can probably expect to fit anything up to millions of words comfortably into memory, something like this might be suitable: list_of_words = "lots of words go here".split() accumulator = [] for word in list_of_words: if word.istitle(): accumulator.append(word) else: doSomething(accumulator) accumulator = [] -- Steven. From quasi at null.set Thu May 3 19:08:31 2007 From: quasi at null.set (quasi) Date: Thu, 03 May 2007 18:08:31 -0500 Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> Message-ID: <08qk33t594ih0ulmjmev90d22lkfnotgoe@4ax.com> On Fri, 04 May 2007 09:37:37 +1200, Gib Bogle wrote: >Ah, so the firefighters were in on the conspiracy! No, but the firefighters are very much aware that there is more to 9/11 than has been officially revealed. This is even more true at Pentagon. The firefighters there brought dogs trained to search for survivors and/or remains and found nothing. quasi From andre.roberge at gmail.com Tue May 1 07:47:47 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 1 May 2007 04:47:47 -0700 Subject: Launching an independent Python program in a cross-platform way (including mac) In-Reply-To: <1177979796.103422.316930@y5g2000hsa.googlegroups.com> References: <1177889540.489960.176380@u30g2000hsc.googlegroups.com> <1177890695.308785.165580@l77g2000hsb.googlegroups.com> <838d5$4635f634$4275d90a$5047@FUSE.NET> <1177944037.400933.291060@l77g2000hsb.googlegroups.com> <1177979796.103422.316930@y5g2000hsa.googlegroups.com> Message-ID: <1178020067.203708.31380@l77g2000hsb.googlegroups.com> My apologies about the last post; I posted my "test" code by mistake, with hard-coded path information. Here's for future reference something that is general and should work cross-platform. Andr? def exec_external(code=None, path=None): """execute code in an external process currently works under: * Windows NT (tested) * GNOME * OS X This also needs to be tested for KDE and implemented some form of linux fallback (xterm?) """ if path is None: path = os.path.join(os.path.expanduser("~"), "temp.py") if os.name == 'nt' or sys.platform == 'darwin': current_dir = os.getcwd() target_dir, fname = os.path.split(path) if code is not None: filename = open(path, 'w') filename.write(code) filename.close() if os.name == 'nt': os.chdir(target_dir) # change dir so as to deal with paths that # include spaces Popen(["cmd.exe", ('/c start python %s'%fname)]) os.chdir(current_dir) elif sys.platform == 'darwin': # a much more general method can be found # in SPE, Stani's Python Editor - Child.py activate = 'tell application "Terminal" to activate' script = r"cd '\''%s'\'';python '\''%s'\'';exit"%(target_dir, fname) do_script = r'tell application "Terminal" to do script "%s"'%script command = "osascript -e '%s';osascript -e '%s'"%(activate, do_script) os.popen(command) elif os.name == 'posix': try: os.spawnlp(os.P_NOWAIT, 'gnome-terminal', 'gnome- terminal', '-x', 'python', '%s'%path) except: try: # untested os.spawnlp(os.P_NOWAIT, 'konsole', 'konsole', '-x', 'python', '%s'%path) except: raise NotImplementedError else: raise NotImplementedError From tcrane at REMOVETHISuiuc.edu Fri May 18 13:20:27 2007 From: tcrane at REMOVETHISuiuc.edu (T. Crane) Date: Fri, 18 May 2007 17:20:27 GMT Subject: namespace question Message-ID: Hi, If I define a class like so: class myClass: import numpy a = 1 b = 2 c = 3 def myFun(self): print a,b,c return numpy.sin(a) I get the error that the global names a,b,c,numpy are not defined. Fairly straightforward. But if I am going to be writing several methods that keep calling the same variables or using the same functions/classes from numpy, for example, do I have to declare and import those things in each method definition? Is there a better way of doing this? thanks, trevis From showell30 at yahoo.com Sun May 27 17:54:54 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 27 May 2007 14:54:54 -0700 (PDT) Subject: itertools.groupby In-Reply-To: Message-ID: <536846.55823.qm@web33501.mail.mud.yahoo.com> --- paul wrote: > > > > Regarding the pitfalls of groupby in general (even > > assuming we had better documentation), I invite > people > > to view the following posting that I made on > > python-ideas, entitled "SQL-like way to manipulate > > Python data structures": > > > > LINQ? > Maybe. I think they're at least trying to solve the same problem as I am. ____________________________________________________________________________________ Expecting? Get great news right away with email Auto-Check. Try the Yahoo! Mail Beta. http://advision.webevents.yahoo.com/mailbeta/newmail_tools.html From jorgen.maillist at gmail.com Mon May 21 17:49:12 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Mon, 21 May 2007 23:49:12 +0200 Subject: [Fwd: Re: managed lists?] In-Reply-To: <4651fe96$0$24671$426a34cc@news.free.fr> References: <4651fe96$0$24671$426a34cc@news.free.fr> Message-ID: <11e49df10705211449k2a874ca0t8167632d683c22d@mail.gmail.com> Hi Bruno, Thanks for your answer. Well what I am after is a list of relations to some class type. And in that list I do not wish to have accidentally put ints, strings, only one type of object, or interface. Now I can make the list interface safe, but it is only meant for relational purposes only. So to illustrate: Song <>---->> Tab Song <>--->> Tuning I want a "tabs" collection only consisting of Tab objects. They are very specific so "mimicing" a tab interface is not something that will be done anytime soon. I'm a traditional C++ programmer, and maybe I go through some transitional phase I don't know but exposing my list as read / (over)write property to the "outside world" being the rest of my object model, is just asking for problems. So this "strong" typed list will ensure me at "add" time the exception occurs, rather then somewhere in my applciation who knows much later that something blows up because the "object" from that list is retrieved and something unpredictable goes wrong. Is that so weird to do? As I said earlier I am a python newbie, I love the language, but the fact it can blow up at unpredictable times, gives me shivers. > Everything in Python is an object. Including integers. And there's no > 'char' type in Python. The array type by the way says in the API that it can be constructed with a simple type like a char as in a "c" type, an int as in a "i" type etc.. See here: http://www.python.org/doc/1.5.2p2/lib/module-array.html So what I understand it's purpose is creating a buffer of some kind of a fixed type to maybe communicate with other DLL's or objects that require such a thing. As I said, I might be going through a transitional phase, but exposing my relation list as simply a list class where all kinds of objects can be dumped in, seems too much for me at this point ;-) Thanks, - Jorgen From mensanator at aol.com Thu May 3 16:30:37 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 3 May 2007 13:30:37 -0700 Subject: How to check if a string is empty in python? In-Reply-To: <463a31c0$0$6845$c3e8da3@news.astraweb.com> References: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> <1178138964.503290.254060@o5g2000hsb.googlegroups.com> <1178139155.260722.153750@n59g2000hsh.googlegroups.com> <463a31c0$0$6845$c3e8da3@news.astraweb.com> Message-ID: <1178224237.326531.254130@o5g2000hsb.googlegroups.com> On May 3, 2:03 pm, John Salerno wrote: > mensana... at aol.com wrote: > > On May 2, 3:49 pm, Basilisk96 wrote: > >> A simple > > >> if s: > >> print "not empty" > >> else: > >> print "empty" > > >> will do. > > > How do you know that s is a string? > > Seems like a fair assumption given the OP's question and example. A fair assumption for languages other than Python. Just because s was a string at some point in the past doesn't mean it's a string now. From peter_7003 at yahoo.com Mon May 7 11:17:32 2007 From: peter_7003 at yahoo.com (Peter Fischer) Date: Mon, 7 May 2007 08:17:32 -0700 (PDT) Subject: Specification for win32com.client package? Message-ID: <956651.70893.qm@web63414.mail.re1.yahoo.com> Hello, I am searching for documentation about the interface the win32com package provides, especially win32com.client. I searched the web and Mark Hammond?s homepage but only found example code using Dispatch() and DispatchEx() etc. Isn?t there a full list of the functions win32.com.client provides? Or do I have to use makepy to somehow generate documentation (how)? I would be thankful if someone could give me a hook about that. Best regards, Peter. --------------------------------- Need Mail bonding? Go to the Yahoo! Mail Q&A for great tips from Yahoo! Answers users. -------------- next part -------------- An HTML attachment was scrubbed... URL: From M.Waack at gmx.de Sat May 26 08:59:23 2007 From: M.Waack at gmx.de (Mathias Waack) Date: Sat, 26 May 2007 14:59:23 +0200 Subject: Compiling python extension on amd64 for 32 bit References: Message-ID: Andrew MacIntyre wrote: > Mathias Waack wrote: >> After switching my development environment to 64 bit I've got a >> problem with a python extension for a 32 bit application. > > {...} > >> Ok, thats fine. So why is python complaining? Or even more >> interesting, what do I have to do to compile the code? > > Is the Python your toolchain is referencing 32 or 64 bit? Based on > what I can see in pyport.h, I'd guess that you're finding a 64 bit > Python (ie SIZEOF_LONG == 8). There is no such thing as "the Python". A biarch environment offers both the 32 bit and the 64 bit versions of each library. And unique headers, because its assumed that the headers are independent of the architecture. Because of the -m32 Flag the pyport.h is used within a 32 bit env. Mathias From john at datavoiceint.com Tue May 8 12:54:31 2007 From: john at datavoiceint.com (HMS Surprise) Date: 8 May 2007 09:54:31 -0700 Subject: Atttribute error In-Reply-To: References: <1178641784.974581.14000@p77g2000hsh.googlegroups.com> Message-ID: <1178643271.048991.83730@u30g2000hsc.googlegroups.com> PS > Add this directly after the ``import`` to see what's happening: > > print urllib.__file__ > print dir(urllib) > C:\maxq\bin\testScripts\.\urllib.py ['__doc__', '__file__', '__name__', 'string'] From http Sun May 20 01:28:59 2007 From: http (Paul Rubin) Date: 19 May 2007 22:28:59 -0700 Subject: What is deployment? References: <68m4i4-9a4.ln1@lairds.us> <7x4pm8tf6v.fsf@ruckus.brouhaha.com> <87646o3yrb.fsf@benfinney.id.au> Message-ID: <7x8xbkjc6c.fsf@ruckus.brouhaha.com> Ben Finney writes: > Agreed. I usually discuss "deployment" as meaning "everything required > to take something from the point of working in a vendor's lab > environment, to an actual working installation in a production > environment". I'd go beyond that. It includes putting the people and procedures in place for keeping the production system operating, upgrading it as needed, customer support, the whole bit. It's all the stuff that happens on the other side of the line separating "development" from "operations". From dustin at v.igoro.us Tue May 1 16:58:20 2007 From: dustin at v.igoro.us (dustin at v.igoro.us) Date: Tue, 1 May 2007 15:58:20 -0500 Subject: pre-PEP: Standard Microthreading Pattern Message-ID: <20070501205820.GE11383@v.igoro.us> I've been hacking away on this PEP for a while, and there has been some related discussion on python-dev that went into the PEP: http://mail.python.org/pipermail/python-dev/2007-February/070921.html http://mail.python.org/pipermail/python-dev/2007-February/071155.html http://mail.python.org/pipermail/python-dev/2007-February/071181.html I'd love to have feedback on this PEP: - from a user's perspective (would you want to write microthreaded code?) - from an implementer's perspective (and note that I have a reference implementation that's just getting packaged up right now). - from a technical perspective (efficiency, compatibility, etc.) - regarding the two unresolved issues in the text And now, without further ado: PEP: XXX Title: Standard Microthreading Pattern Version: $Revision$ Last-Modified: $Date$ Author: Dustin J. Mitchell Status: Draft Type: Informational Content-Type: text/x-rst Created: 17-Feb-2007 Post-History: Abstract ======== The extended support for generators introduced in PEP 342 [2]_ facilitated a natural way of writing generators that cooperatively yield control to other functions, allowing multitasking within a single OS thread. Such multitasking requires a supporting environment (usually in the form of a scheduler), and several such implementations are in active use. Each has slightly different structural requirements for the task-implementing code. This PEP proposes a single, consistent pattern for such code. This consistency will enable microthreaded code to run in a variety of environments, just as threaded code can currently run atop a variety of OS-level threading libraries. Compliant libraries, e.g., a microthreaded urllib, could then be developed, providing batteries-included functionality for microthreaded software. Definitions =========== Within this PEP, "microthreading" is defined as interleaving the execution of multiple independent codepaths by cooperatively yielding control periodically in each codepath; a "microthread", then, is one such codepath. This technique and variations on it have also been referred to as "weightless threads", "tasklets", and "greenlets". It is a specilization of the more general event-based multitasking model. Microthreads are conceptually distinct from coroutines. A coroutine can schedule a specific coroutine to be executed when it yields control, even passing a value to that coroutine. Microthreads, however, simply yield to facilitate multitasking, with no knowledge or control of the next codepath to be executed. This PEP addresses two audiences: authors of microthreaded code (users) and designers of microthreaded environments (implementations). Motivation ========== Application developers usually adopt an event-based architecture in order to exploit asynchronous IO facilities. Asynchronous IO is ideal when the overhead of an OS-level thread for each concurrent IO operation is too high. An event-based architecture is also useful when an application must perform lightweight multitasking -- for example, an email client must both wait for user input and monitor mailboxes for new mail. Implementing this sort of multitasking using threads requires careful use of synchronization primitives throughout the application to ensure correctness. Using common event-based techniques requires storing state on the heap and implementing callbacks for all state transitions, which can quickly become complex. A microthreaded architecture brings the best of both worlds: it allows users to store state in local varables, just as they would in a threaded implementation, while avoiding the need for complex synchronization primitives. An email client, for example, can implement the complex state of an IMAP client in a natural fashion, and reflect that state using natural Python data structures with no need for locking. Several well-developed implementations of cooperative multitasking are currently available, some of which implement microthreading. However, each implementation approaches the subject differently, and it is virtually impossible to share code between implementations. This PEP is intended to bring some measure of consistency to microthreaded code, to facilitate development of libraries and implementation-agnostic code repositories to support microthreaded development. Rationale ========= Since the introduction of generators in PEP 255 [3]_ and their extension to support coroutines in PEP 342 [2]_, generators have been used to implement various forms of microthreading [1]_: - Example 3 in PEP 342 implements a simple trampoline scheduler. - `Kiwi tasklets`_ (formerly GTasklets) use pre-PEP 342 generators along with an explicit post-yield function call to retrieve any incoming value or exception. - `Twisted Python`_ includes an ``inlineCallbacks`` decorator [#inlineCallbacks]_ which allows a generator to yield ``Deferred`` objects; callback results are then re-injected with ``send()``, while errbacks result in a ``throw()``. - `Kamaelia`_ includes Axon, a library supporting microprocesses which multitask by yielding frequently, and interact through a well-developed IPC mechanism. - David Mertz's "Charming Python: Implementing "weightless threads" with Python generators" [#Mertz]_ includes a basic microthreading scheduler and suggests directions for improvement. - An ASPN recipe by Maciej Obarski [#Obarski]_ gives a simple scheduler for task objects represnted by generators. Each of these implementations have specific requirements of the microthreaded code. The requirements differ enough that code written for one environment will generally not function properly in another. A common pattern for all microthreaded code will allow users to write microthreaded code that will be portable to multiple microthreading implementations. This will include libraries, which can then be shared more broadly. The specification in this PEP specifically avoids reference to any symbols not included in the built-in namespace, so environment-agnostic microthreaded code need not import any environment-specific modules. Implementation Specification ============================ An implementation is responsible for executing a body of code written by its users according to the microthreading pattern. Like a standard python thread, execution of a microthread begins with a call to a single function, and ends when that function completes. The function may call other functions, and so on; the entire control flow constitutes a microthread. Completely unrelated control flows may be occurring simultaneously in other microthreads. Within a microthreading implementation, all microthreads operate within a single OS-level thread, so at most one microthread is executing at any point. The implementation must not switch between microthreads except at times specified by the user. A microthreaded function is written as a generator function, with the points at which other microthreads may be executed indicated by ``yield``. Normal (non-generator) functions thus cannot be interrupted. While a microthreaded function is executing, its execution is represented by a generator. The implementation is responsible for ensuring that this generator has its ``next``, ``send``, and ``throw`` methods called appropriately. Specifically, it must call ``next`` to initiate processing, and ``step`` to execute each subsequent segment. At the completion of each segment, if the return value of ``next``, ``send``, or ``throw`` is not one of the special values described below, then that value must be supplied to the generator via ``send`` when it is next scheduled. When the generator is complete, it will raise a ``StopIteration`` exception, which the implementation must catch and handle by either resuming execution of the calling function (see `Nested Function Calls`, below) or terminating the microthread. Other exceptions must be handled as described in the `Exceptions` section, below. Nested Function Calls --------------------- When a microthreaded function yields a generator, then it is invoking another microthreaded function, the execution of which is represented by the yielded generator. Execution of the current function must be suspended until the new function has been executed to completion. Any return value from the new function must be supplied to the calling function via its generator's ``send`` method. Although the underlying implementation may vary, the effect is of a stack of generators within each microthread, with the topmost generator representing the state of the currently executing microthreaded function, and the remaining generators suspended awaiting its completion. Return Values ------------- Microthreaded functions return values to their callers by raising a ``StopIteration`` exception containing the return value in ``args[0]``. Implementations must catch this exception and handle it appropriately by supplying the return value to the next generator on the stack via ``send``, or if there is no next generator, terminating the microthread. Exceptions ---------- When a generator raises an exception, that exception must be propagated to the next generator on the stack via ``throw``. If there is no next generator, then the implementation may display a traceback to the user or take other appropriate action. Implementations may adjust tracebacks to remove implementation-related frames, but must not alter the exception itself. Special Values -------------- Implementations may attach special significance to other yielded values or raised exceptions, but these values and exceptions must be unique objects which could not be produced by code written with no knowledge of the implementation. Specifically, no special significance may be attached to any of the built-in Python types or types used in the standard library. Rather, an implementation should attach meaning to classes and objects local to the implementation's namespace. Thread Manipulation ------------------- Implementations are responsible for providing any appropriate functionality for manipulating microthreads. This PEP does not place any restrictions on such functionality. Pattern Specification ===================== This section specifies the microthreading pattern from the perspective of a user. In general, microthreaded code should closely resemble ordinary threaded code, with the addition of ``yield`` keywords at strategic locations. - Microthreaded functions are written as generator functions. Their execution will not be interrupted except at statements including the ``yield`` keyword. The value of a ``yield`` expression is the value of its argument, unless the argument is one of the special values discussed in this section. - A microthreaded function can call another microthreaded function by yielding the generator resulting from calling the microthreaded function. The value of the ``yield`` expression is the return value of the called function. - A microthreaded function can "return" a value by raising ``StopIteration`` with that value as an argument:: raise StopIteration(42) - An exception raised in a microthreaded function will propagate to its callers just as in a standard function. Uncaught exceptions will be handled in an implementation-dependent fashion. - Functions for thread manipulation are not specified in this PEP, and are implementation-dependent. Example ------- This trivial example highlights each of the aspects of the multithreaded pattern:: def fibonacci(n): latest, i = (1, 1), 2 if n < 1: raise ValueError # raise exception while i < n: latest = (latest[1], latest[0] + latest[1]) yield # cooperative yield raise StopIteration(latest[1]) # return value def fibsquared(n): try: fibn = (yield fibonacci(n)) ** 2 # function call except ValueError: # catch exception print "Sorry, cannot calculate fibsquared of", n else: print "fibsquared of", n, "is", fibn Backwards Compatibility ======================= As this is an informational PEP, no backward compatibility problems will arise from its adoption. In most cases, this PEP specifies a superset of the functionality of existing microthreading enviroments, so existing microthreaded code will continue to run without modification. One exception to this rule is Kamaelia's Axon, which specifies that generators which yield a false value will be terminated. That situation is not compatible with this PEP, which directs that such a value should be returned from the yield at the next execution of the microthread. The specification of Kiwi tasklets requires that generators implementing tasklets call ``tasklet.get_event()`` after most yields. This is not necessary under the specification in this PEP, and the ``get_event()`` function can simply be stubbed out to ensure backward compatibility. Unresolved Issues ================= Return Values ------------- Currently, a ``return`` statement with a value in a generator is a syntax error. The Python community should consider supporting the behavior described above in the Python compiler. Specifically, the compiler would treat:: return foo in a generator as equivalent to:: raise StopIteration(foo) This change raises no backward-compatibility issues (as the former expression is not currently legal), but may introduce some surprising behavior as a function could then continue executing after a return statement:: try: return 10 except StopIteration: print "I'm still here!" Non-Microthreaded Generators ---------------------------- Functions which return "normal" generators may confuse a microthreading implementation if those generators are accidentally yielded. Consider:: def get_constants(dict): return ( k for k in dict.iterkeys() if k[0] in string.uppercase ) def examine_module(mod): d = mod.__dict__ constants = yield get_constants(d) this example will fail, because the implementation will treat the generator expresion in ``get_constants`` as a microthreaded function, calling its ``send`` method until it is exhaustd, then assigning ``None`` to ``constants`` in ``examine_module``. The problem only occurs when such a generator is yielded: the snippet above will operate correctly if ``yield`` is removed from the last line. Thus users can avoid the problem by exercising caution in selecting the values that are yielded. References ========== .. [1] Stackless is not included in this list because, while it does implement a microthreaded environment, it does so without the use of generators and (as of this writing) requires a modified Python binary. .. [2] PEP 342, "Coroutines via Enhanced Generators", van Rossum, Eby (http://www.python.org/peps/pep-0342) .. [3] PEP 355, "Simple Generators", Schemenauer, Peters, Hetland (http://www.python.org/peps/pep-0342) .. _Kiwi tasklets: http://www.async.com.br/projects/kiwi/api/kiwi.tasklet.html .. _Twisted Python: http://twistedmatrix.com/ .. [#inlineCallbacks] http://twistedmatrix.com/documents/current/api/twisted.internet.defer.html .. _Kamaelia: http://kamaelia.sourceforge.net/ .. [#Mertz] "Charming Python: Implementing 'weightless threads' with Python generators," Mertz, (http://www-128.ibm.com/developerworks/library/l-pythrd.html) .. [#Obarski] "simple, cooperative multitasking using generators," Obarski, http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/466008 Copyright ========= This document has been placed in the public domain. .. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 coding: utf-8 End: From *firstname*nlsnews at georgea*lastname*.com Fri May 4 17:05:46 2007 From: *firstname*nlsnews at georgea*lastname*.com (Tony Nelson) Date: Fri, 04 May 2007 21:05:46 GMT Subject: Microsoft's Dynamic Languages Runtime (DLR) References: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> <1178151313.421106.43130@o5g2000hsb.googlegroups.com> <1178151574.302703.205560@l77g2000hsb.googlegroups.com> <1178296035.993859.183720@n59g2000hsh.googlegroups.com> Message-ID: <*firstname*nlsnews-337A6C.17060204052007@news.verizon.net> In article <1178296035.993859.183720 at n59g2000hsh.googlegroups.com>, Kaz Kylheku wrote: > On May 2, 5:19 pm, sturlamolden wrote: > > On May 3, 2:15 am, Kaz Kylheku wrote: > > > > > Kindly refrain from creating any more off-topic, cross-posted threads. > > > Thanks. > > > > The only off-topic posting in this thread is your own (and now this > > one). > > You are making a very clumsy entrance into these newsgroups. ... Go away. ________________________________________________________________________ TonyN.:' *firstname*nlsnews at georgea*lastname*.com ' From seyensubs at yahoo.com Tue May 15 00:45:26 2007 From: seyensubs at yahoo.com (seyensubs at yahoo.com) Date: 14 May 2007 21:45:26 -0700 Subject: Sorting troubles In-Reply-To: References: <1179158708.433792.127150@h2g2000hsg.googlegroups.com> <1179161396.220858.86150@q75g2000hsh.googlegroups.com> Message-ID: <1179204326.945346.38590@q75g2000hsh.googlegroups.com> On May 15, 5:35 am, Steven D'Aprano wrote: > On Mon, 14 May 2007 09:49:56 -0700, Thomas Nelson wrote: > > The thing is that [x for x in List[1:]...] is a brand new list created > > by iterating over the old one. > > How about: > > qSortHelp(List): > > newlist = qSort(List) > > for i, val in enumerate(newlist): > > List[i] = val > > You have to iterate over one more time, but this sorts the list in > > place. > > A better way of spelling that would be: > > def qSortHelp(List): > List[:] = qSort(List) > return List > > but the helper function is redundant, as it is easy enough to make the > qSort function behave the same way. We can also make the code a smidgen > more concise by reversing the sense of the test at the start of the code: > > def qSort(List): > if List: > List[:] = qSort([x for x in List[1:] if x< List[0]]) \ > + List[0:1] + qSort([x for x in List[1:] if x>=List[0]]) > return List > > -- > Steven. Ah, I see, just slicing it like that.. nice! But after doing some timing tests, the version that's in place and using partitions is about twice faster than the non hybrid qSort. The hybrid one, with insertionsSort used for smaller lists works faster, but in a weird way. When given lists of 2000, the best bet to is to set the threshold to 14, but when given a list of 40000, 14 is slow, but a threshold of 200(less or more is slower, again) makes it about 8 times faster than a normal qSort, and 4 times faster than an in-place qSort, using a self -defined partitioning alg. Making a hybrid out of the in-place partitioned qSort makes it a bit faster, but not by much compared to the other hybrid which uses list comprehensions. Teach said that the optimal threshold in hybrids is 14-16, but guess he wasn't so right after all =\\ The overhead of using insertion sort on a longer list turns out to be faster than just piling on recursions, when confronted with bigger lists. I should probably try and make it iterative now, see how it goes. Gonna need a stack though, I think. Thanks for all the answers up to now! :) From john at datavoiceint.com Tue May 15 14:40:59 2007 From: john at datavoiceint.com (HMS Surprise) Date: 15 May 2007 11:40:59 -0700 Subject: File record separators. In-Reply-To: References: <1179241525.667682.112220@y80g2000hsf.googlegroups.com> <1179249866.369812.167590@u30g2000hsc.googlegroups.com> Message-ID: <1179254458.906555.125240@e51g2000hsg.googlegroups.com> > > > Would like to use pickle but it is apparently unavailable in the > > package I am using, Jython 2.2. > > I am pretty sure some version of pickle or cPickle is available in Jython 2.1, > though. I'd take a second look, to be sure. Many thanks Boris! import cPickle caused no errors! From gagsl-py2 at yahoo.com.ar Fri May 4 00:27:16 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 04 May 2007 01:27:16 -0300 Subject: My Python annoyances References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> Message-ID: En Thu, 03 May 2007 10:49:26 -0300, Ben Collver escribi?: > I tried to write portable Python code. The zlib CRC function returned > different results on architectures between 32 bit and 64 bit > architectures. I filed a bug report. It was closed, without a comment > from the person who closed it. I get the unspoken message: bug reports > are not welcome. You got a comment from me, that you never disputed nor commented further. I would have changed the status to "invalid" myself, if I were able to do so. > I installed Cygwin on a Windows machine. I try to quit from an > interactive Python session. It tells me that on my platform, I must > press Control-Z to exit. I press Control-Z and it makes Python a > background process. Maybe because you were running Windows Python from inside a bash prompt? The Cygwin version tells you to use the right key combination to exit. > In short, there is plenty of room for improvement. Admittedly these are > not problems with the language definition. But I downloaded a Python > distribution, and the problems are Python specific. Yes, some documentation is a bit outdated as Python is evolving continuously. I prefer that, to a frozen language. -- Gabriel Genellina From tim at tdw.net Sat May 12 10:04:09 2007 From: tim at tdw.net (Tim Williams) Date: Sat, 12 May 2007 15:04:09 +0100 Subject: find out all threads? In-Reply-To: References: Message-ID: <9afea2ac0705120704t457cd8deufb4cbff806852c94@mail.gmail.com> On 11/05/07, Sven Rech wrote: > Hi, > > I have a written a C program which makes use of python embedding. > I want to find out all threads that a loaded module has started. > But I can't find anything about this in the docs. Is it possible? > Without details of your module, its dificult to say, maybe t_count = threading.activeCount() or t_count = threading.enumerate() will do what you need From chris.cavalaria at free.fr Wed May 16 05:48:49 2007 From: chris.cavalaria at free.fr (Christophe) Date: Wed, 16 May 2007 11:48:49 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179307776.953405.207680@l77g2000hsb.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179289167.723990.223890@u30g2000hsc.googlegroups.com> <464abd12$0$23364$426a34cc@news.free.fr> <1179307776.953405.207680@l77g2000hsb.googlegroups.com> Message-ID: <464ad388$0$28786$426a34cc@news.free.fr> sjdevnull at yahoo.com a ?crit : > Christophe wrote: >> sjdevnull at yahoo.com a ecrit : >>> Steven D'Aprano wrote: >>>> I would find it useful to be able to use non-ASCII characters for heavily >>>> mathematical programs. There would be a closer correspondence between the >>>> code and the mathematical equations if one could write D(u*p) instead of >>>> delta(mu*pi). >>> Just as one risk here: >>> When reading the above on Google groups, it showed up as "if one could >>> write ?(u*p)..." >>> When quoting it for response, it showed up as "could write D(u*p)". >>> >>> I'm sure that the symbol you used was neither a capital letter d nor a >>> question mark. >>> >>> Using identifiers that are so prone to corruption when posting in a >>> rather popular forum seems dangerous to me--and I'd guess that a lot >>> of source code highlighters, email lists, etc have similar problems. >>> I'd even be surprised if some programming tools didn't have similar >>> problems. >> So, it was google groups that continuously corrupted the good UTF-8 >> posts by force converting them to ISO-8859-1? >> >> Of course, there's also the possibility that it is a problem on *your* >> side > > Well, that's part of the point isn't it? It seems incredibly naive to > me to think that you could use whatever symbol was intended and have > it show up, and the "well fix your machine!" argument doesn't fly. A > lot of the time programmers have to look at stack traces on end-user's > machines (whatever they may be) to help debug. They have to look at > code on the (GUI-less) production servers over a terminal link. They > have to use all kinds of environments where they can't install the > latest and greatest fonts. Promoting code that becomes very hard to > read and debug in real situations seems like a sound negative to me. Who displays stack frames? Your code. Whose code includes unicode identifiers? Your code. Whose fault is it to create a stack trace display procedure that cannot handle unicode? You. Even if you don't make use of them, you still have to fix the stack trace display procedure because the exception error message can include unicode text *today* You should know that displaying and editing UTF-8 text as if it was latin-1 works very very well. Also, Terminals have support for UTF-8 encodings already. Or you could always use kate+fish to edit your script on the distant server without such problems (fish is a KDE protocol used to access a computer with ssh as if it was a hard disk and kate is the standard text/code editor) It's a matter of tools. From kerny404 at gmail.com Tue May 8 07:11:40 2007 From: kerny404 at gmail.com (andrea) Date: 8 May 2007 04:11:40 -0700 Subject: Designing a graph study program In-Reply-To: <5ab3mgF2o5bfbU1@mid.uni-berlin.de> References: <1178619753.077639.112510@q75g2000hsh.googlegroups.com> <5ab3mgF2o5bfbU1@mid.uni-berlin.de> Message-ID: <1178622700.228390.237310@n59g2000hsh.googlegroups.com> On 8 Mag, 13:02, "Diez B. Roggisch" wrote: > > Well then I wanted to draw graphs and I found that pydot is working > > really nicely. > > BUT I'd like to do this, an interactive program to see ho the > > algorithms works... > > For example in the breath search first, every time the algorithm > > colors a node, the program should redraw the graphs. Which modules > > should I use for graphics (I use macosX and I'd like something cross > > platforms). > > Use the bundled Tkinter. I've implemented a similar thing back in my under > graduation days using TCL/Tk, and Tk is perfectly suited for that task. > > Diez Ok thank you very much I'll try with that. But I have some design doubts, I'd like to keep the algorithm (for example bfs) as clean as possible, being independent from the drawing methods. And how could I make it step through algorithms without having a more complicated code? Maybe using threads? Thanks From martin at v.loewis.de Wed May 2 16:46:07 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 02 May 2007 22:46:07 +0200 Subject: Why are functions atomic? In-Reply-To: References: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> <1178044821.864741.235260@o5g2000hsb.googlegroups.com> <1178063341.779617.289690@o5g2000hsb.googlegroups.com> <1178065685.161372.81790@y80g2000hsf.googlegroups.com> <463816a9$0$9276$9b622d9e@news.freenet.de> Message-ID: <4638F88F.5010309@v.loewis.de> >> The answer is really really simple. The implementation of copy predates >> mutability. When the copy code was written, functions *were* immutable. >> When functions became mutable, the copy code was not changed, and >> nobody noticed or complained. > > That's probably an indication that mutable functions don't > get used all that much. Are there any instances of them in the > standard Python libraries? All user-defined functions are mutable. To me, this issue is rather that copying of functions isn't used all that much. In addition, it is certainly true that functions are rarely modified, even though all of them are mutable. See this for an example py> def foo():pass ... py> foo py> foo.__name__='bar' py> foo py> foo.value Traceback (most recent call last): File "", line 1, in ? AttributeError: 'function' object has no attribute 'value' py> foo.value=100 py> foo.value 100 Regards, Martin From showell30 at yahoo.com Sun May 27 21:12:15 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 27 May 2007 18:12:15 -0700 (PDT) Subject: itertools.groupby In-Reply-To: <1180312288.3155.19.camel@localhost.localdomain> Message-ID: <702263.11522.qm@web33504.mail.mud.yahoo.com> --- Carsten Haese wrote: > [...] It's an abstract code pattern for an abstract use > case. I question the use of abstract code patterns in documentation, as they just lead to confusion. I really think concrete examples are better in any circumstance. Also, to the OP's original contention, there is no way that "uniquekeys" is a sensible variable in the overly abstract example that is provided as an example in the, er, non-examples portion of the documentation. With the abstract non-example that's posted as an example, the assertion of uniqueness implicit in the name of the variable doesn't make any sense. > There is an > example on the following page, called Examples! > The example is useful. Thank you. > > These docs need work. Please do not defend them; > > [...] > To name just one, there's an example of > itertools.groupby in the last > code snippet at > http://informixdb.blogspot.com/2007/04/power-of-generators-part-two.html > Do we now, or could we, link to this example from the docs? > [...] that shouldn't stop you from suggesting improvements. > I already did in a previous reply. To repeat myself, I think a concrete example is beneficial even on the main page: import itertools syslog_messages = [ 'out of file descriptors', 'out of file descriptors', 'unexpected access', 'out of file descriptors', ] for message, messages in itertools.groupby(syslog_messages): print message, len(list(messages)) ...produces this... out of file descriptors 2 unexpected access 1 out of file descriptors 1 ____________________________________________________________________________________ Expecting? Get great news right away with email Auto-Check. Try the Yahoo! Mail Beta. http://advision.webevents.yahoo.com/mailbeta/newmail_tools.html From nomail at gmail.com Tue May 1 03:44:57 2007 From: nomail at gmail.com (Olivier Oost) Date: Tue, 01 May 2007 09:44:57 +0200 Subject: Log-in to forums (using cookielib)? Message-ID: <4636f011$0$329$e4fe514c@news.xs4all.nl> Hi, I need to login to a online forum, like a phpbb forum, and leave a message there. I figured I need to use cookielib, but the documentation of cookielib is not very clear to me. I tried to just copy/paste all the cookies from FireFox into my Python-program, like this: import cookielib, urllib2, urllib cookiejar=cookielib.CookieJar() urlOpener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar)) values={'__utmb':'1234', 'mybbuser':'1234_1234', '__utmz':'1234', 'sid':'1234', '__utma':'1234'} data=urllib.urlencode(values) request=urllib2.Request("http://ep2.nl",data) url=urlOpener.open(request) page=url.read(1024000) Can someone please tell me how I should log-in and leave a message on the board? From rurpy at yahoo.com Tue May 15 15:51:32 2007 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 15 May 2007 12:51:32 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179160242.787344.48060@h2g2000hsg.googlegroups.com> Message-ID: <1179258692.237438.110860@p77g2000hsh.googlegroups.com> "Hendrik van Rooyen" wrote in message news:mailman.7700.1179242569.32031.python-list at python.org... > wrote: [I fixed the broken attribution in your quote] > >(2) Several posters have claimed non-native english speaker > >status to bolster their position, but since they are clearly at > >or near native-speaker levels of fluency, that english is not > >their native language is really irrelevant. > > I dispute the irrelevance strongly - I am one of the group referred > to, and I am here on this group because it works for me - I am not > aware of an Afrikaans python group - but even if one were to > exist - who, aside from myself, would frequent it? - would I have > access to the likes of the effbot, Steve Holden, Alex Martelli, > Irmen de Jongh, Eric Brunel, Tim Golden, John Machin, Martin > v Loewis, the timbot and the Nicks, the Pauls and other Stevens? I didn't say that your (as a fluent but non-native English speaker) views are irrelevant, only that when you say, "I am a native speaker of Afrikaans and I don't want non- ascii identifiers" it shouldn't carry any more weight that if I (as a native English speaker) say the same thing. (But I wouldn't of course :-). My point was that this entire discussion is by English speakers and that a consesious by such a group, that non-english identfiers are bad, is neither surprising nor legitimate. > - I somehow doubt it. > > Fragmenting this resource into little national groups based > on language would be silly, if not downright stupid, and it seems > to me just as silly to allow native identifiers without also > allowing native reserved words, because you are just creating > a mess that is neither fish nor flesh if you do. It already is fragmented. There is a Japanese Python users group, complete with discussion forums, all in Japanese, not English. Another poster said he was going to bring up this issue on a French language discussion group. How can you possibly propose that some authority should decide what language a group of people should use to discuss a common interest?! > And the downside to going the whole hog would be as follows: > > Nobody would even want to look at my code if I write > "terwyl" instead of 'while', and "werknemer" instead of > "employee" - so where am I going to get help, and how, > once I am fully Python fit, can I contribute if I insist on > writing in a splinter language? First "while" is a keyword and will remain "while" so that has nothing to do with anything. If nobody want to look at your code, it is not the use of "werknemer" that is the cause. If you used that as an identifier that I assume you decided your code was exclusively of interest to Afrikaans speakers. Otherwise use you would have used English for for that indentifier. The point is that *you* are in the best position to decide that, not the designers of the language. > And while the Mandarin language group could be big enough > to be self sustaining, is that true of for example Finnish? > > So I don't think my opinion on this is irrelevant just because > I miss spent my youth reading books by Pelham Grenfell > Wodehouse, amongst others. > > And I also don't regard my own position as particularly unique > amongst python programmers that don't speak English as > their native language Like I said, that English is not your native language is irrelevant -- what matters is that you now speak English fluently. Thus you are an English speaker argueing that excluding non-english identifiers is not a problem. From sjmachin at lexicon.net Sat May 5 19:58:04 2007 From: sjmachin at lexicon.net (John Machin) Date: 5 May 2007 16:58:04 -0700 Subject: Init style output with python? In-Reply-To: References: Message-ID: <1178409484.562441.178370@n59g2000hsh.googlegroups.com> On May 6, 9:27 am, "Maxim Veksler" wrote: > Hi list, > > I'm working on writing sanity check script, and for aesthetic reasons > I would like the output be in the formatted like the gentoo init > script output, that is: > """ > Check for something .................................. [OK] > Check for something else ..........................[FAIL] > """ > > Is there are frame work or something in python that would allow me to > do this (quickly) ? > If not, ideas how I should I be getting this boring task of: > 1. get screen width Is it not (a) safe (b) sensible to assume a minimum width (say 79) and avoid the whole question of determining the terminal width? > 2. get output string length > 3. get out status length > 4. calculate space > 5. print string, print space, print status, print newline Surely you don't need assistance with steps 2 - 5 ... > what happens if user changes textual terminal "resolution" ? Something rather unaesthetic, I imagine. From antroy at gmail.com Thu May 3 08:39:52 2007 From: antroy at gmail.com (Ant) Date: 3 May 2007 05:39:52 -0700 Subject: How to check if a string is empty in python? In-Reply-To: <1hxia6q.18rflwk1mez8vhN%aleax@mac.com> References: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> <1178154290.811928.208900@h2g2000hsg.googlegroups.com> <1hxia6q.18rflwk1mez8vhN%aleax@mac.com> Message-ID: <1178195992.473679.137560@n59g2000hsh.googlegroups.com> On May 3, 5:59 am, a... at mac.com (Alex Martelli) wrote: > Steven D'Aprano wrote: > > On Wed, 02 May 2007 21:19:54 -0400, Roy Smith wrote: > > > > for c in s: > > > raise "it's not empty" > > > String exceptions are depreciated and shouldn't be used. > > >http://docs.python.org/api/node16.html > > They're actually deprecated, not depreciated. In Steven's defence, string exceptions *are* probably worth less, as there's no longer such a demand for them. -- Ant... From apatheticagnostic at gmail.com Tue May 22 23:16:51 2007 From: apatheticagnostic at gmail.com (kaens) Date: Tue, 22 May 2007 23:16:51 -0400 Subject: questions about programming styles In-Reply-To: <46529969.5000407@gmail.com> References: <46501710.6090904@gmail.com> <46515E7D.5010103@gmail.com> <4651AB2E.20509@freakmail.de> <46529969.5000407@gmail.com> Message-ID: <163f0ce20705222016n541a8861y2ad77b665d8acbe7@mail.gmail.com> > Thanks. I think what I actually want to learn is design pattern in a > looser sense, not in the computer-science-vocabulary-sense. > > I'm a graduate student in science, and python is my favourite programming > language in daily work. I can solve most of the problems with python, but > my programming efficienct is really low. Somethimes I have to stop to think > about when to use what idiom, such as when to use functions and when to > use methods. > > I want to learn how to write better programs more effectively and more > efficiently. I will try to have a look at the wikipedia. > > Thanks again for your kind suggestion :) > > Regards, > That stuff mainly just comes with time. Familiarize yourself with the docs, and code, and it will become like second nature after a bit. And you'll always have to stop and think about things - it tends to be best to do so before you start coding though. From dave.dean at xilinx.com Wed May 2 18:28:09 2007 From: dave.dean at xilinx.com (Dave Dean) Date: Wed, 2 May 2007 15:28:09 -0700 Subject: Basic question about sockets and security Message-ID: Hi all, I'm just starting out in sockets/network programming, and I have a very basic question...what are the 'security' implications of opening up a socket? For example, suppose I've written a simple chat server and chat client. The server opens a socket, listens on a port, and accepts incoming connections. The clients open a socket and connect to the server. If the server receives a message from a client, it sends that message out to every client. When a client receives a message, it places it in a text widget. So...are there inherent dangers in doing this? I have no real security concern in the actual application, but can an open socket somehow allow someone access to the rest of the computer? Is the 'security' of the socket handled at the OS level (or within the socket module)? I realize this isn't necessarily a Python question, but I wrote my application in Python and I'm not sure where to start. I'll repost this elsewhere if someone points me towards a more relevant group. Thanks, Dave From basilisk96 at gmail.com Wed May 23 18:09:54 2007 From: basilisk96 at gmail.com (Basilisk96) Date: 23 May 2007 15:09:54 -0700 Subject: NOOOOB In-Reply-To: <1179870264.586288.253550@m36g2000hse.googlegroups.com> References: <1179829763.464614.123920@a26g2000pre.googlegroups.com> <1179870264.586288.253550@m36g2000hse.googlegroups.com> Message-ID: <1179958194.813120.152650@u30g2000hsc.googlegroups.com> On May 22, 5:44 pm, sbrosci... at gmail.com wrote: > On May 22, 6:29 am, jolly wrote: > > > Hey guys, > > > I want to begin python. Does anyone know where a good starting point > > is? > > > Thanks, > > Jem > > I really liked How to Think Like a Computer Scientist learning with > python foound athttp://www.ibiblio.org/obp/thinkCSpy/. Unlike most > paper books you'd be hard pressed to find typos (that at this level of > programming you wouldn't notice) there. Also if you want another > source of info trywww.diveintopython.org. You can find the book on > the store shelves, but why pay when you can get it for free of the > net. You can view it as HTML or download the .pdf. I agree with the previous post on the "Think Like a CS" book. It is excellent text for getting your feet wet in Python, whether you have had previous programming experience or not. From __peter__ at web.de Mon May 28 06:10:42 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 28 May 2007 12:10:42 +0200 Subject: Issue of redirecting the stdout to both file and screen References: <1180343858.903251.182490@x35g2000prf.googlegroups.com> Message-ID: ??????????????? wrote: > I wanna print the log to both the screen and file, so I simulatered a > 'tee' > > class Tee(file): > > def __init__(self, name, mode): > file.__init__(self, name, mode) > self.stdout = sys.stdout > sys.stdout = self > > def __del__(self): > sys.stdout = self.stdout > self.close() > > def write(self, data): > file.write(self, data) > self.stdout.write(data) > > Tee('logfile', 'w') > print >>sys.stdout, 'abcdefg' > > I found that it only output to the file, nothing to screen. Why? > It seems the 'write' function was not called when I *print* something. There are places in the C code of Python that do the equivalent of if isinstance(file_like_object, file): file.write(file_like_object, text) else: file_like_object.write(text) Therefore you can't safely inherit from file. The workaround is to make your own file-like object; yours would become class Tee(object): def __init__(self, name, mode): self.file = open(name, mode) self.stdout = sys.stdout sys.stdout = self def __del__(self): sys.stdout = self.stdout self.file.close() def write(self, data): self.file.write(data) self.stdout.write(data) Peter From apatheticagnostic at gmail.com Wed May 23 01:53:29 2007 From: apatheticagnostic at gmail.com (kaens) Date: Wed, 23 May 2007 01:53:29 -0400 Subject: xml.parsers.expat loading xml into a dict and whitespace Message-ID: <163f0ce20705222253h2d171b1fs61efa448ad86dc8e@mail.gmail.com> Hey everyone, this may be a stupid question, but I noticed the following and as I'm pretty new to using xml and python, I was wondering if I could get an explanation. Let's say I write a simple xml parser, for an xml file that just loads the content of each tag into a dict (the xml file doesn't have multiple hierarchies in it, it's flat other than the parent node) so we have foo bar . . . (I'm using xml.parsers.expat) the parser sets a flag that says it's in the parent, and sets the value of the current tag it's processing in the start tag handler. The character data handler sets a dictionary value like so: dictName[curTag] = data after I'm done processing the file, I print out the dict, and the first value is : There are comments in the xml file - is this what is causing this? There are also blank lines. . .but I don't see how a blank line would be interpreted as a tag. Comments though, I could see that happening. Actually, I just did a test on an xml file that had no comments or whitespace and got the same behaviour. If I feed it the following xml file: hey bee eff it prints out: " : three : eff two : bee one : hey" wtf. For reference, here's the handler functions: def handleCharacterData(self, data): if self.inOptions and self.curTag != "options": self.options[self.curTag] = data def handleStartElement(self, name, attributes): if name == "options": self.inOptions = True if self.inOptions: self.curTag = name def handleEndElement(self, name): if name == "options": self.inOptions = False self.curTag = "" Sorry if the whitespace in the code got mangled (fingers crossed...) From duncan-news at grisby.org Tue May 22 12:53:09 2007 From: duncan-news at grisby.org (Duncan Grisby) Date: Tue, 22 May 2007 16:53:09 GMT Subject: Simple omniORBpy example throws exception with error 0x41540002 References: <1179833680.255391.198490@x18g2000prd.googlegroups.com> <5bg40hF2moliaU1@mid.uni-berlin.de> <1179839519.216407.124960@z24g2000prd.googlegroups.com> Message-ID: In article <1179839519.216407.124960 at z24g2000prd.googlegroups.com>, Samuel wrote: [...] >Ah, I see now how this works. I happen to run Ubuntu here, so I tried >the following: > >- sudo apt-get install orbit-name-server-2 >- orbit-name-server-2 & >- Add to /etc/omniORB4.cfg: >InitRef = NameService=IOR:010000002b000000... >(where everything starting from "IOR:" is the output given by orbit- >name-server-2. > >However, this does not seem to change the behavior. Any hints? I think ORBit is configured to only listen on its proprietary Unix domain socket protocol by default, not TCP, so omniORB doesn't know how to talk to it. You should either tell ORBit to listen on TCP (Google for how), or use omniORB's naming service, which listens on TCP by default. Alternatively, you don't particularly need to use a naming service if you don't want to. You can modify the example to output an IOR string for the object reference rather than trying to register it in the naming service. Print the result of orb.object_to_string(adderObjref) rather than the naming service stuff. The example you are looking at was given as a tutorial with me speaking, so it's a bit light on details of what's going on. You might find the introduction in the omniORBpy manual more useful: http://omniorb.sourceforge.net/omnipy3/omniORBpy/omniORBpy002.html or chapter 2 in the PDF version: http://omniorb.sourceforge.net/omnipy3/omniORBpy.pdf Cheers, Duncan. -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- From laurent.pointal at wanadoo.fr Mon May 28 09:19:36 2007 From: laurent.pointal at wanadoo.fr (Laurent Pointal) Date: Mon, 28 May 2007 15:19:36 +0200 Subject: What's the best way to iniatilize a function References: <7NmdncRrFaG3WMTbnZ2dnUVZ_gWdnZ2d@comcast.com> Message-ID: <465ad6e4$0$5104$ba4acef3@news.orange.fr> Jack wrote: >>> 2. what's the right way to call mylib_exit()? I put it in __del__(self) >>> but it is not being called in my simple test. >> >> instance.__del__ is only called when there are no references to the >> instance. > > I didn't call del explicitly. I'm expecting Python to call it when > the program exits. I put a logging line in __del__() but I never > see that line printed. It seems that __del__() is not being called > even when the program exits. Any idea why? If you make your extension available as a module (Python or C), you can use atexit: http://docs.python.org/lib/module-atexit.html Note: your exit handler will only be called at normal termination. From thomas.guest at gmail.com Tue May 22 03:21:06 2007 From: thomas.guest at gmail.com (tag) Date: 22 May 2007 00:21:06 -0700 Subject: doctest environment question In-Reply-To: References: <1179762737.153434.143030@b40g2000prd.googlegroups.com> <1179775483.685881.236940@x18g2000prd.googlegroups.com> Message-ID: <1179818466.394663.222390@k79g2000hse.googlegroups.com> On 21 May, 22:17, Peter Otten <__pete... at web.de> wrote: > If these don't work you'll have to give a bit more context. > > Peter Thanks again Peter. Here's something much closer to what I really want to do. You should be able to cut and paste this post into a file "post.txt". Running the command `python -c "import doctest; doctest.testfile('post.txt')"` gives a test failure even though everything works fine in an interpreted Python session. I'd like to find a way to make the doctest pass. >>> def announce(f): ... " Return a function which announces calls to the input function. " ... def wrapper(*v, **k): ... print "Calling %s" % f.__name__ ... return f(*v, **k) ... return wrapper We can rebind a function to announce calls to it: >>> def g(): pass ... >>> g = announce(g) >>> g() Calling g Or we can use decorator syntax: >>> @announce ... def f(): pass ... >>> f() Calling f Here's a function which rebinds a function at the top level of a module (it won't work for nested functions). >>> def announce_function(f): ... " Rebind f within a module so that calls to f are announced. " ... import inspect ... setattr(inspect.getmodule(f), f.__name__, announce(f)) Let's give it a try. This next works fine in an interactive Python session but fails when doctested. >>> def h(): pass ... >>> announce_function(h) >>> h() Calling h Here's the doctest failure: python -c "import doctest; doctest.testfile('post.txt')" ********************************************************************** File "post.txt", line 37, in post.txt Failed example: announce_function(h) Exception raised: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/doctest.py", line 1212, in __run compileflags, 1) in test.globs File "", line 1, in announce_function(h) File "", line 4, in announce_function setattr(inspect.getmodule(f), f.__name__, announce(f)) AttributeError: 'NoneType' object has no attribute 'h' ********************************************************************** File "post.txt", line 38, in post.txt Failed example: h() Expected: Calling h Got nothing ********************************************************************** 1 items had failures: 2 of 10 in post.txt ***Test Failed*** 2 failures. From stefan.behnel-n05pAM at web.de Tue May 15 02:23:54 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 15 May 2007 08:23:54 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <7xd512onsx.fsf@ruckus.brouhaha.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1hy2qg3.iqfvwnrvr9kjN%aleax@mac.com> <46482624.6050507@web.de> <7xd512onsx.fsf@ruckus.brouhaha.com> Message-ID: <464951fa$0$23135$9b4e6d93@newsspool1.arcor-online.net> Paul Rubin wrote: > Stefan Behnel writes: >> But then, where's the problem? Just stick to accepting only patches that are >> plain ASCII *for your particular project*. > > There is no feature that has ever been proposed for Python, that cannot > be supported with this argument. If you don't like having a "go to" > statement added to Python, where's the problem? Just don't use it in > your particular project. "go to" is not meant for clarity, nor does it encourage code readability. But that's what this PEP is about. Stefan From sjmachin at lexicon.net Tue May 15 20:45:36 2007 From: sjmachin at lexicon.net (John Machin) Date: 15 May 2007 17:45:36 -0700 Subject: Newbie Question: Getting a list of files In-Reply-To: References: Message-ID: <1179276336.298327.238350@h2g2000hsg.googlegroups.com> On May 16, 10:12 am, Brian wrote: > Hello, > > I am currently working on putting together a free, open source, > anti-spyware program for the Mac (and eventually for other OS's too.) > However, there's one thing that I am currently trying to figure out: > > How do I, in Python, obtain a recursive list of files in a specified > directory, including the subdirectories, etc? For example, in the old > MS-DOS days, we could specify at the command prompt "DIR /S" and this > would provide a listing of all files, including those in subdirectories, > no matter how far down the branch they were. How can this be done with > Python? > > P.S. I have been searching Google, but haven't found the answer yet. > Try reading the Python docs instead :-) In general, anyone doing anything much with files and directories should know what's in the os and os.path modules. In particular, os.walk is probably what you are looking for. HTH, John From nagle at animats.com Sat May 19 20:01:04 2007 From: nagle at animats.com (John Nagle) Date: Sun, 20 May 2007 00:01:04 GMT Subject: mod_python performs several magnitudes slower than PHP? In-Reply-To: <1179616996.948606.319670@q75g2000hsh.googlegroups.com> References: <1179616996.948606.319670@q75g2000hsh.googlegroups.com> Message-ID: <4dM3i.3287$y_7.725@newssvr27.news.prodigy.net> That's puzzling, because with mod_python, you're only invoking the compiler once per Apache restart. With CGI programs, you pay the loading penalty on every request. John Nagle chris.monsanto at gmail.com wrote: > Recently I've had to move my site to a new dedicated server running > FreeBSD 6.1. After installing apache 2.0.59, python 2.4.4 and > mod_python 3.3.1, I decided to bench a script in PHP vs one in Python. > I found out that for some reason, my mod_python was performing > extremely slow - magnitudes slower than it should. I scowered the > internet for hours and asked a few friends and still haven't been able > to find a solution to the problem. > > from mod_python import apache > > def handler(req): > for i in xrange(1000): > print >> req, "Yeah" > return apache.OK > > and... > > for ($i = 0; $i < 1000; $i++) > echo "Yeah\n" ; > ?> > > when I ran ab on both using 1000 requests and a concurrency of 10, i > got these results: > > python- Requests per second: 21.37 [#/sec] (mean) > php- Requests per second: 1008.37 [#/sec] (mean) > > Any ideas would really be appreciated... I'm on my last leg. > From google at mrabarnett.plus.com Wed May 2 21:07:53 2007 From: google at mrabarnett.plus.com (MRAB) Date: 2 May 2007 18:07:53 -0700 Subject: Handling Infinite Loops on Server Applications In-Reply-To: References: Message-ID: <1178154473.929262.15170@y80g2000hsf.googlegroups.com> On May 3, 1:38 am, "Paul Kozik" wrote: > I'm working with a small server program I'm writing for a small video > game. The main class constructor starts a thread that handles socket > connections, which itself starts new threads for each user connection. > > The actual server program itself however needs to wait in the > background, but continue looping as not to close the running threads. > The problem is, simply running a [while True: pass] main loop in this > style eats precious CPU cycles (and for nothing). If it waits for > input, such as a socket.accept() or raw_input(), this problem does not > occur (obviously because it's not constantly looping). > > What would be the best way to handle this, perhaps in a fashion > similar to how most server programs are handled (with arguments such > as [apache start], [apache stop])? Any guides towards this type of > application development? > You could put a sleep in the loop: import time while True: # Sleep for 1 minute, or whatever... time.sleep(60) From gene.tani at gmail.com Sun May 6 13:55:01 2007 From: gene.tani at gmail.com (gene tani) Date: 6 May 2007 10:55:01 -0700 Subject: Did you read about that? In-Reply-To: <463dd72e$0$331$e4fe514c@news.xs4all.nl> References: <1178446711.502374.286790@l77g2000hsb.googlegroups.com> <1178452403.114975.249050@u30g2000hsc.googlegroups.com> <1178457498.639373.157350@y80g2000hsf.googlegroups.com> <463dd72e$0$331$e4fe514c@news.xs4all.nl> Message-ID: <1178474101.930602.77770@n59g2000hsh.googlegroups.com> On May 6, 6:26 am, "Martin P. Hellwig" wrote: > Dustan wrote: > > On May 6, 8:20 am, Steven D'Aprano > > wrote: > >> On Sun, 06 May 2007 04:53:23 -0700, Dustan wrote: > >>> SPAM! > >>> SPAM! > >>> SPAM! > >>> SPAM! > >>> SPAM! > >>> SPAM! > >>> SPAM! > >>> SPAM! > >> Gosh, you think so? I'm glad we had you around to tell us, otherwise we > >> might have thought it was about Python programming. > > >> Actually, many of us wouldn't even have seen it in the first place, > >> because our ISPs do a good job of filtering out obvious spam before we > >> even see it. And then people like you come along, and reply to it, and we > >> see the reply -- complete with the original spam. > > > Well, sorry. I didn't realize I'd get whacked around for making a > > joke. > > >> -- > >> Steven. > > Aren't jokes supposed to be funny? > > > -- > mph > > http://martinphellwig.blogspot.com/ What you can do: complain to Google adsense about the site's "advertising" complain to Google groups about the post it would be #complete unethical# for me to suggest that OP posted an apparently unrelated topic because he wanted the site's performance "ab" tested, like, y'know ab -n 100000 -kc 200 http://yourspamsitehere.com From josiah.carlson at sbcglobal.net Thu May 17 01:31:00 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Wed, 16 May 2007 22:31:00 -0700 Subject: Asyncore Help? In-Reply-To: References: Message-ID: <464BE894.5060208@sbcglobal.net> Paul Kozik wrote: > I am working on the networking code for a small Multiplayer RPG I'm > working on. I currently have some basic code using threads, but it > seems like asyncore would be far better suited for my needs. However, > I have trouble finding a solid example for what I need. Python.org and > other sites provide simple examples, but they appear more intended for > servers that simply send one peice of data to the client. Here is a sample that combines asyncore/asynchat, wxPython, and optional threads: http://thread.gmane.org/gmane.comp.python.wxpython/46915/focus=47326 You can pull out the async subclasses and use them as a general Python object transfer mechanism. If you have specific asyncore/asynchat questions, email me directly and I will try to help you. - Josiah From michiel at thingmajig.org Sat May 19 12:50:49 2007 From: michiel at thingmajig.org (Michiel Sikma) Date: Sat, 19 May 2007 18:50:49 +0200 Subject: Structuring the code of a wiki parsing engine Message-ID: <1E855F6A-3EF9-45BD-A050-903F517F5CD6@thingmajig.org> Hello everybody. I'm kind of new to Python. I'm working on a simple text parser that will allow me to transform a certain syntax into a certain output. I find wikis interesting, so wiki to HTML parsing is one of the things that I want to accomplish (I'm not actually writing a whole wiki, that's complex, but I'm only trying to get basic text conversion going on). Presently, I'm thinking of putting the (simple, regexp-driven) filters in a module called "parsers", and then make a "handlers" module that allows for the actual transformation. So, for example, one parser would be a separate class (WikiParser) which would have an attribute called "emph" (emphasis) which is a string '\*\*(.+?)\*\*'. Then a handler class (HTMLHandler) would have an attribute called "emph" which is a string '\\1'. Then the regular expressions would be generated via a chosen parser/handler combination. This to make it easy to change things around later. My question to you: is this the right way to go about it? My parser doesn't really need to do all that much, but I would like for it to be easily changeable by editing a single file. Thanks for any help! Greets, Michiel From gagsl-py2 at yahoo.com.ar Sat May 19 04:31:29 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 19 May 2007 05:31:29 -0300 Subject: Python compared to other language References: <1179540061.598417.13870@y80g2000hsf.googlegroups.com> <1179555855.410877.51390@k79g2000hse.googlegroups.com> Message-ID: En Sat, 19 May 2007 03:24:15 -0300, walterbyrd escribi?: > My guess is that some of the C code used to develop Python is the same > between the different Python distros, but much of the code is unique > to the particular platform. If that is the case, then the C code may > not be very portable. Well, your guess was wrong. The core CPython code is the same on all platforms; of course it uses #define/#ifdef/etc. where appropiate, but it's not a mess, and not so much code is conditionally compiled. The Python developers take special care on portability - the C language itself (C89 is currently used) is pretty standard, but you have to be careful on how you write your code. > But, I can often take the same python code, and run it on MacOS, > Linux, FreeBSD, and Windows. Often I can do this even if the app has a > gui interface. Because someone has taken out all the differences, so you don't have to struggle with them yourself. GUI toolkits: some libraries "draw" the whole thing and manage all the user interaction themselves so they're basically portable but never have the native "look&feel" (tcl/tk); other rely on the native buttons and controls for each platform, but providing a homogeneous view for the programmer (wxWidgets). Anyway, they work across platforms because "someone" has already worked on the differences for you - using C. Both menctioned libraries are written in C (wx in C++), and Python provides a convenient wrapper for them. Even on the Python side, some libraries do one thing or another depending on the platform (cf: subprocess). The good thing is that *you* as a developer, don't have to worry about the differences; many are managed by Python itself internally, and many are worked on by other people on top of this. webbrowser.open('your favourite url') "just works" and does "the right thing" because of these efforts. -- Gabriel Genellina From steven at REMOVE.THIS.cybersource.com.au Mon May 7 03:22:58 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 07 May 2007 07:22:58 -0000 Subject: N00b question on Py modules References: <1178521238.333095.111370@h2g2000hsg.googlegroups.com> Message-ID: On Mon, 07 May 2007 00:00:38 -0700, lokesh.jagasia wrote: > I expected to see an output of 0 followed by 1. But it turns out that > the _exitcode variable is not changed at all. It seems that > setExitCode() might be editing a local copy of the _exitcode variable. Yes, that's exactly what is happening. > But then, how do I tell it to change the value of the module variable > and not its local variable. (1) Don't do that. (2) If you think you really need to do it, you don't. (3) If you REALLY need to do it, use the statement: global in your function. Over-use of global variables is one of the sins of programming. Some people might even say that using ANY global variables is a sin. I'm not that strict, but I encourage you to avoid global variables if you can. See here for more details: http://en.wikipedia.org/wiki/Global_variable -- Steven. From steve at holdenweb.com Sun May 20 16:58:52 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 20 May 2007 16:58:52 -0400 Subject: python shell In-Reply-To: <7HNE7MEP1$TGFwtY@woodrowhorsfall.plus.com> References: <1179337107.842668.112690@k79g2000hse.googlegroups.com> <1179552984.466321.137550@u30g2000hsc.googlegroups.com> <7HNE7MEP1$TGFwtY@woodrowhorsfall.plus.com> Message-ID: Douglas Woodrow wrote: > On Sat, 19 May 2007 21:42:27, Steve Holden wrote > >> http://en.wikipedia.org/wiki/Doctest > >> Since you claim to be exercising your pedantry, I wonder why I get the >> results I do. Since we *are* being pedantic, by the way, surely the >> name is actually "doctest", not "Doctest". > > Yes, as the page you are referring to mentions right at the top: > > ,---------------- > | Doctest > | From Wikipedia, the free encyclopedia > | > | The correct title of this article is doctest. The initial letter > is shown > | capitalized due to technical restrictions. > `---------------- > Whereas Cameron wrote > ... to explore Doctest more deeply ... 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From michael at jedimindworks.com Tue May 1 22:26:26 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Tue, 1 May 2007 21:26:26 -0500 Subject: os.path.join In-Reply-To: <1178069795.3201.1.camel@localhost.localdomain> References: <1178069795.3201.1.camel@localhost.localdomain> Message-ID: <5FC95F49-2E5E-40A8-B688-375E8BD77DBB@jedimindworks.com> On May 1, 2007, at 8:36 PM, Elliot Peele wrote: > Why does os.path.join('/foo', '/bar') return '/bar' rather than > '/foo/bar'? That just seems rather counter intuitive. It's the leading slash in '/bar'. os.path.join('/foo', 'bar') returns '/foo/bar'. From mail at timgolden.me.uk Wed May 2 11:48:57 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 02 May 2007 16:48:57 +0100 Subject: Active Directory: how to delete a user from a group? In-Reply-To: <4638B143.9040805@timgolden.me.uk> References: <1178119465.469546.275440@e65g2000hsc.googlegroups.com> <4638B143.9040805@timgolden.me.uk> Message-ID: <4638B2E9.90101@timgolden.me.uk> Tim Golden wrote: > Dirk Hagemann wrote: >> Hi! >> >> Does anyone has experience with manipulating MS Active Directory >> objects? I'd like to delete some users from a group, but so far I >> couldn't find anything about this. >> There is some good stuff about retrieving data out of the AD (thanks >> to Tim Golden!), but how can I manipulate or change AD objects like >> users, computers and groups with Python? Is there somewhere a >> documentation or some code? > > I freely admit I don't do too much changing of AD objects, > but my module should at least support the methods for doing > things. Some examples in Active Directory Cookbook: > > http://techtasks.com/code/viewbook/2 Sorry, you wanted to remove a user *from a group*. Misread. Translated from http://techtasks.com/code/viewbookcode/1626 import active_directory group = active_directory.find_group ("name-of-group") # or group = active_directory.AD_object ("group-moniker") user = active_directory.find_user ("name-of-user") # or user = active_directory.AD_object ("user-moniker") group.Remove (user.path ()) Obviously, for something this simple using an extra module is overkill. You might as well: import win32com.client group = win32com.client.GetObject ("group-moniker") group.Remove ("user-moniker") NB I haven't tried these, I've just translated them from the Cookbook site! TJG From kyosohma at gmail.com Mon May 21 11:23:50 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 21 May 2007 08:23:50 -0700 Subject: full screen graphics In-Reply-To: <1179754739.658332.122200@b40g2000prd.googlegroups.com> References: <1179754739.658332.122200@b40g2000prd.googlegroups.com> Message-ID: <1179761030.485993.269500@u36g2000prd.googlegroups.com> On May 21, 8:39 am, myheartinamerica wrote: > Hello, > > I need to run a particular graphics application over and over again > with a different command line to get benchmarks on the applications > performance (frame rates and similar data). I am running the following > within a while loop that parses out a different command line from a > configuration file. > > ############ > def runCommand(command): > """runCommand(command) > > Parameters: > command -- the full string of the command to execute > > """ > print command > try: > childProcess = subprocess.Popen(command) > > done = False > while not done: > returnCode = childProcess.poll() > if (returnCode != None): > done = True > else: > # sleep for 10 seconds before checking again > time.sleep(10) > except KeyboardInterrupt: > print 'KeyboardInterrupt received. Trying to kill Wolf2.exe' > print '>TASKKILL /F /T /PID ', childProcess.pid > killCommand = ''.join(('TASKKILL /F /T /PID ', > str(childProcess.pid))) > killSubProcess = subprocess.Popen(killCommand) > killSubProcess.wait() > sys.exit(0) > except OSError, (errno, strerror): > print 'OS Error (%s): %s' % (errno, strerror) > print 'Above error occurred while executing the following:' > print command > except WindowsError, (errno, strerror): > print 'MS Windows Error (%s): %s' % (errno, strerror) > print 'Above error occurred while executing the following:' > print command > ########## > > The problem lies in that the second time the application is run, it > doesn't grab focus and go full screen, but sits paused. It will not > continue running until I click on the minimized application in the > taskbar. Is there any way to force it to grab focus? > > I am running on Win32 with Python 2.5.1. > > Your help in this matter is greatly appreciated, > Mick Charles Beaver If your graphics program uses COM you may be able to do something like what's done in the following post: http://mail.python.org/pipermail/python-list/2005-June/327261.html I found this too, but I haven't tested it myself: http://downgra.de/articles/python-wmii/ You may be able to use Tim Golden's WMI module too. I would think you could use his "enumerate all running processes" and combine it with the "run a process minimized", except you'd change the flag so that it maximized instead. See link below: http://tgolden.sc.sabren.com/python/wmi_cookbook.html Hopefully that'll help you some. Mike From showell30 at yahoo.com Tue May 29 23:53:00 2007 From: showell30 at yahoo.com (Steve Howell) Date: Tue, 29 May 2007 20:53:00 -0700 (PDT) Subject: itertools.groupby In-Reply-To: <1180495814.669018.93410@h2g2000hsg.googlegroups.com> Message-ID: <705684.42894.qm@web33503.mail.mud.yahoo.com> On May 29, 2:34 am, Raymond Hettinger wrote: > The gauntlet has been thrown down. Any creative > thinkers > up to the challenge? Give me cool recipes. > I don't make any claims to coolness, but I can say that I myself would have written the code below with significantly more complexity before groupby(), and I can see the utility for this code in dealing with certain mail programs. The code is phrased verbosely, even if you remove the tests, but the meat of it could be boiled down to a one-liner. import itertools lines = ''' This is the first paragraph. This is the second. '''.splitlines() # Use itertools.groupby and bool to return groups of # consecutive lines that either have content or don't. for has_chars, frags in itertools.groupby(lines, bool): if has_chars: print ' '.join(frags) # PRINTS: # This is the first paragraph. # This is the second. ____________________________________________________________________________________Need a vacation? Get great deals to amazing places on Yahoo! Travel. http://travel.yahoo.com/ From showell30 at yahoo.com Sun May 27 13:28:41 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 27 May 2007 10:28:41 -0700 (PDT) Subject: itertools.groupby In-Reply-To: <1180286272.100790.131670@q75g2000hsh.googlegroups.com> Message-ID: <321222.39225.qm@web33508.mail.mud.yahoo.com> --- 7stud wrote: > Bejeezus. The description of groupby in the docs is > a poster child > for why the docs need user comments. Can someone > explain to me in > what sense the name 'uniquekeys' is used this > example: [...] > The groupby method has its uses, but it's behavior is going to be very surprising to anybody that has used the "group by" syntax of SQL, because Python's groupby method will repeat groups if your data is not sorted, whereas SQL has the luxury of (knowing that it's) working with a finite data set, so it can provide the more convenient semantics. ____________________________________________________________________________________You snooze, you lose. Get messages ASAP with AutoCheck in the all-new Yahoo! Mail Beta. http://advision.webevents.yahoo.com/mailbeta/newmail_html.html From rohitsethidce at gmail.com Wed May 23 19:16:43 2007 From: rohitsethidce at gmail.com (rohit) Date: 23 May 2007 16:16:43 -0700 Subject: read file to a dictionary Message-ID: <1179962203.201472.104500@q19g2000prn.googlegroups.com> i want to implement a dictionary in python the query is : without explicitly doing the following steps 1. reading from file to list 2. processing list to dictionary is there a module or a built in function that helps me "read" a file directly into a dictionary or any module that implements the above 2 steps thanks rohit From bruno.desthuilliers at gmail.com Wed May 30 03:30:59 2007 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: 30 May 2007 00:30:59 -0700 Subject: Key Listeners In-Reply-To: <1180491273.446164.281990@q75g2000hsh.googlegroups.com> References: <1180491273.446164.281990@q75g2000hsh.googlegroups.com> Message-ID: <1180510259.914953.225420@h2g2000hsg.googlegroups.com> On 30 mai, 04:14, Mike wrote: > Are there key listeners for Python? Either built in or third party? What is a "key listener" ? From gigs at hi.t-com.hr Tue May 22 06:53:44 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Tue, 22 May 2007 12:53:44 +0200 Subject: pipe tutorial Message-ID: does anyone know some good tutorial on pipes in python? thx From sjmachin at lexicon.net Mon May 7 18:48:41 2007 From: sjmachin at lexicon.net (John Machin) Date: 7 May 2007 15:48:41 -0700 Subject: is for reliable? In-Reply-To: References: Message-ID: <1178578121.386841.245080@e51g2000hsg.googlegroups.com> On May 8, 5:46 am, "pablo... at giochinternet.com" wrote: > Hi to all I have a question about the for statement of python. I have the > following piece of code where cachefilesSet is a set that contains the > names of 1398 html files cached on my hard disk > > for fn in cachefilesSet: > > fObj = codecs.open( baseDir + fn + '-header.html', 'r', 'iso-8859-1' ) > u = fObj.read() > > v = u.lower() > rows = v.split('\x0a') > > contentType = '' > > for r in rows: > if r.find('content-type') != -1: > y = r.find(':') > if y != -1: > z = r.find(';', y) > if z != -1: u, v, r, y, z .... are you serious? > contentType = r[y+1:z].strip() > cE = r[z+1:].strip() > characterEncoding = cE.strip('charset = ') Read the manual ... strip('charset = ') is NOT doing what you think it is. > else: > contenType = r[y+1:].strip() Do you mean contentType ? Consider using pychecker and/or pylint. > characterEncoding = '' > break > > if contentType == 'text/html': > processHTMLfile( baseDir + fn + '-body.html', characterEncoding, cardinalita ) We don't have crystal balls -- what does processHTMLfile() do? Where is "cardinalita" bound to a value? > > fileCnt += 1 > if fileCnt % 100 == 0: print fileCnt > > this code stops at the 473th file instead of reaching 1398 Sets are not ordered. There is no such thing as the 473rd element. I presume you mean that you believe that your code processes only 473 elements > > however I changed the for and substituted it with a while in this way > > while cachefilesSet: > fn = cachefilesSet.pop() > ....... > ....... > > the while loop reaches the 1398th file and is some 3-4 times faster than > the for loop > > How is this possible? Given that you open each file and read it, the notion that processing 3 times as many files is 3-4 times faster is very hard to swallow (even if you mean 3-4 times faster *per file*). Show us *all* of your code (with appropriate counting and timing) and its output. Something daft is happening in the part of the code that you haven't shown us. E.g. you are deleting elements from cachefilesSet, or perhaps even adding new entries. As a general rule, don't fiddle with a container over which you are iterating. Using the while container: item = container.pop() trick is not "iterating over". Interestingly, 1398 is rather close to 3 times 473. Coincidence? Have you tried your code on subsets of your 1398 element set? [This concept is called "testing"] A subset of size 10 plus copious relevant print statements in your code might show you what is happening. HTH, John From steven.bethard at gmail.com Sun May 27 12:23:30 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 27 May 2007 10:23:30 -0600 Subject: PyPI bdist_wininst upload failing In-Reply-To: References: <1180249872.007145.48030@a26g2000pre.googlegroups.com> Message-ID: Steven Bethard wrote: > Gabriel Genellina wrote: >> En Sun, 27 May 2007 12:19:03 -0300, Steven Bethard >> escribi?: >> >>> Also, I couldn't get the StringIO code from there to work: >>> >>> >>> import StringIO >>> >>> content = open('argparse-0.8.0.win32.exe').read() >> >> Use open("...","rb").read() - the "b" is important on Windows. > > Ahh, great. Thanks. > > So any ideas why distutils is generating a bdist_wininst installer with > file names like: > > lib/argparse-0.8.0-py2.5.egg-info > lib/argparse.py > > instead of what John Machin had: > > PURELIB/xlrd-0.6.1a4-py2.5.egg-info > PURELIB/xlrd/biffh.py > > The ones with 'lib' instead of 'PURELIB' will get rejected by the > safe_zipnames regular expression in verify_filetype.py: > > re.compile(r'(purelib|platlib|headers|scripts|data).+', re.I) > > Is there something I need to do when running 'setup.py bdist_wininst' to > get 'PURELIB' instead of 'lib'? I figured it out. As suggested here: http://peak.telecommunity.com/DevCenter/EasyInstall#administrator-installation I had created a distutils.cfg to redirect my installs from the regular site-packages directory. Since the distutils.cfg settings are read in for all distutils uses at the command line, they were also being read in when I tried to run "setup.py bdist_wininst", and so all my filenames were getting the altered paths instead of the regular PURELIB ones. Thanks everyone for the help! STeVe From paul at subsignal.org Sat May 5 07:29:53 2007 From: paul at subsignal.org (paul) Date: Sat, 05 May 2007 13:29:53 +0200 Subject: Problems Drawing Over Network In-Reply-To: <133nd279g7ob8a2@corp.supernews.com> References: <133nd279g7ob8a2@corp.supernews.com> Message-ID: Andrew schrieb: > Hello Everyone [snipped stuff] Sorry not being helpful, but I suggest you post a minimal sample of your code demonstrating your program. cheers Paul From etienne.hilson at gmail.com Tue May 29 02:27:16 2007 From: etienne.hilson at gmail.com (Etienne Hilson) Date: Tue, 29 May 2007 08:27:16 +0200 Subject: gui application on cross platform In-Reply-To: References: Message-ID: <194d520c0705282327n1d63e414rcfe4dc72b66eaf11@mail.gmail.com> > > james_027 wrote: > > > Hi, > > > > > > I am using delphi to develop gui application, and wish to make a shift > > > to python. here are some of my question/concern... > > > > > > 1. is python develop gui application a cross platform? just like java > > > swing? My first programming language was Delphi, and (after having to work several years with java), I had to restart programming, but only for my little home purpose (educatives for my children). I dive into python and I love it ! In a couple of days, I did a little program to manage and launch the roms of some console emulators with screenshots. I develop it and use it on my laptop on Gentoo linux, and run it on the windows desktop of my children. NO line has to be modified between the os, it is fantastic ! I use simple python for console text apps, wxPython for management graphical applications, and pygame for some little full of sprites games :-) -- (\__/) (='.'=) Ceci est un petit lapin. Copiez/collez-le dans (")_(") votre signature pour l'aider ? dominer le monde From zykhou at gmail.com Mon May 14 00:51:51 2007 From: zykhou at gmail.com (Paul Kozik) Date: Sun, 13 May 2007 21:51:51 -0700 Subject: Asyncore Help? Message-ID: <60e9f3330705132151q75f2bc2bt25aa04cff93f5b82@mail.gmail.com> I am working on the networking code for a small Multiplayer RPG I'm working on. I currently have some basic code using threads, but it seems like asyncore would be far better suited for my needs. However, I have trouble finding a solid example for what I need. Python.org and other sites provide simple examples, but they appear more intended for servers that simply send one peice of data to the client. I want to have a server program that is willing to accept commands sent from the client, and repeatedly wait for data and respond. Maintaining a long term connection until the client is done playing. Besides this I am also stuck with dealing with TCP data streams. I can receive and send the data (using threads, not yet with asynocore), but I am unsure how to deal with the streamlike nature of TCP (and would prefer to use TCP over UDP). I would like to have it so that the client sends the server a command (such as update position), and then the data, and have the server update that information on its side accordingly. While basic socket work was rather easy to deal with, this has proved significantly more difficult. Are there any good free sources for information on Asyncore, and dealing with TCP? From jeremiah.foster at gmail.com Thu May 3 11:09:46 2007 From: jeremiah.foster at gmail.com (miah_gbg) Date: 3 May 2007 08:09:46 -0700 Subject: Article on wxPython ToolKit for Mac OS X Message-ID: <1178204986.383057.264690@y80g2000hsf.googlegroups.com> Hi there! Just wanted to let people know in this group that I have recently (April 24th) published an introductory article on wxPython and Mac OS X. It is available here: http://www.macdevcenter.com/ Hope someone finds it useful. Regards, Jeremiah From vatamane at gmail.com Wed May 16 18:33:25 2007 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 16 May 2007 15:33:25 -0700 Subject: cPickle.dumps differs from Pickle.dumps; looks like a bug. In-Reply-To: <1179335622.006820.22460@q23g2000hsg.googlegroups.com> References: <1179335622.006820.22460@q23g2000hsg.googlegroups.com> Message-ID: <1179354805.165889.252010@o5g2000hsb.googlegroups.com> On May 16, 1:13 pm, Victor Kryukov wrote: > Hello list, > > I've found the following strange behavior of cPickle. Do you think > it's a bug, or is it by design? > > Best regards, > Victor. > > from pickle import dumps > from cPickle import dumps as cdumps > > print dumps('1001799')==dumps(str(1001799)) > print cdumps('1001799')==cdumps(str(1001799)) > > outputs > > True > False > > vicbook:~ victor$ 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.>>> quit() > > vicbook:~ victor$ uname -a > Darwin vicbook 8.9.1 Darwin Kernel Version 8.9.1: Thu Feb 22 20:55:00 > PST 2007; root:xnu-792.18.15~1/RELEASE_I386 i386 i386 I might have found the culprit: see http://svn.python.org/projects/python/trunk/Modules/cPickle.c Function static int put2(...) has the following code block in it : ---------cPickle.c----------- int p; ... if ((p = PyDict_Size(self->memo)) < 0) goto finally; /* Make sure memo keys are positive! */ /* XXX Why? * XXX And does "positive" really mean non-negative? * XXX pickle.py starts with PUT index 0, not 1. This makes for * XXX gratuitous differences between the pickling modules. */ p++; ------------------------------- p++ will cause the difference. It seems the developers are not quite sure why it's there or whether memo key sizes can be 0 or have to be 1. Here is corresponding section for the Python version (pickle.py) taken from Python 2.5 ---------pickle.py---------- def memoize(self, obj): """Store an object in the memo.""" # The Pickler memo is a dictionary mapping object ids to 2- tuples # that contain the Unpickler memo key and the object being memoized. # The memo key is written to the pickle and will become # the key in the Unpickler's memo. The object is stored in the # Pickler memo so that transient objects are kept alive during # pickling. # The use of the Unpickler memo length as the memo key is just a # convention. The only requirement is that the memo values be unique. # But there appears no advantage to any other scheme, and this # scheme allows the Unpickler memo to be implemented as a plain (but # growable) array, indexed by memo key. if self.fast: return assert id(obj) not in self.memo memo_len = len(self.memo) self.write(self.put(memo_len)) self.memo[id(obj)] = memo_len, obj # Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i. def put(self, i, pack=struct.pack): if self.bin: if i < 256: return BINPUT + chr(i) else: return LONG_BINPUT + pack(" References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> <1178917940.363627.216580@y5g2000hsa.googlegroups.com> <1178918526.243360.235280@y5g2000hsa.googlegroups.com> Message-ID: <1178918832.881022.70950@l77g2000hsb.googlegroups.com> Just an update of my output after Carsten and company's advice: C:\Python25\rg.py>help.py -h help.py Version 1.0 Copyright RDEG (c) 2007 Options : -h, --help -- display this message Progam Exit (0) C:\Python25\rg.py>help.py -i print arg ['-i'] type(arg): arg is True? False help.py version 1.0 Copyright RDEG (c) 2007 ['-i'] is an unrecognized option. Progam Exit (0) C:\Python25\rg.py>help.py -i help.py version 1.0 Copyright RDEG (c) 2007 ['-i'] is an unrecognized option. Progam Exit (0) C:\Python25\rg.py>help.py No Option provided help.py version 1.0 Copyright RDEG (c) 2007 No Option is an unrecognized option. Progam Exit (0) Thanks again. From adam at atlas.st Thu May 10 18:30:34 2007 From: adam at atlas.st (Adam Atlas) Date: 10 May 2007 15:30:34 -0700 Subject: Newbie question about string(passing by ref) In-Reply-To: <1178835593.771846.270750@u30g2000hsc.googlegroups.com> References: <1178833397.076720.279940@l77g2000hsb.googlegroups.com> <1178833659.400428.185630@u30g2000hsc.googlegroups.com> <1178834254.099555.306750@l77g2000hsb.googlegroups.com> <1178835593.771846.270750@u30g2000hsc.googlegroups.com> Message-ID: <1178836234.235624.65320@l77g2000hsb.googlegroups.com> On May 10, 6:19 pm, lazy wrote: > So, just to make sure even if I return a value, there is no copy done. > Is it correct? > For eg: > > def blah: > long_str="...." > return long_str > > my_str=blah() <=== So here there is no copy done but, my_str points to > the same memory where long_str was created. Exactly. As Bruno said, Python does not copy objects unless you specifically tell it to. From in.the.darkside at gmail.com Tue May 8 14:37:49 2007 From: in.the.darkside at gmail.com (darkside) Date: Tue, 8 May 2007 18:37:49 +0000 (UTC) Subject: fminbound Message-ID: Hello everyone: I'm new using scipy, so I'm sorry if any of my questions are silly. I'm trying to find the maxima, absolut and local, of a function, in order to fit an exponencial curve and get de exponecial argument. My function if the soluction of a couple equations system: def derivs3(x,t,gamma,omega,dl): d1 = omega*x[2] - gamma *x[0] d2 = dl*x[2] - (gamma/2.)* x[1] d3 = -omega *x[0] - dl*x[1] - (gamma/2.)* x[2] + (omega/2.) return d1,d2,d3 def solucion(a,t,gamma, omega, dl): sol=odeint(derivs3,a,t,(gamma,omega,dl)) return sol The case I'm interesting in, the soluction have the form of a sin*exp, so I want to find the function that envolves it, a exponencial function. To do this, I can find the maximas, and fit them, so I use: def g4(t1): sol2=odes.solucion((0.5,0,0),t1,0.5,5,0) return sol2[:,0] x_max = optimize.fminbound(g4,0,2) To use fminbound, I need a function that returns only a single array, so I use de g4 function. I use (0,2) as bounds. The problem I have is that the return is: x_max 1.9999959949686341 That aren't the maximas in the interval. If I change the interval: x_max = optimize.fminbound(g4,0.1,4) x_max 3.9999945129622403 And so on. I don't know what I'm doing wrong, so if everyone can help, I'm going to be really happy. From anton.vredegoor at gmail.com Tue May 15 08:44:44 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Tue, 15 May 2007 14:44:44 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179226183.215907.140450@q75g2000hsh.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179226183.215907.140450@q75g2000hsh.googlegroups.com> Message-ID: HYRY wrote: >> - should non-ASCII identifiers be supported? why? > Yes. I want this for years. I am Chinese, and teaching some 12 years > old children learning programming. The biggest problem is we cannot > use Chinese words for the identifiers. As the program source becomes > longer, they always lost their thought about the program logic. That is probably because they are just entering the developmental phase of being able to use formal operational reasoning. I can understand that they are looking for something to put the blame on but it is an error to give in to the idea that it is hard for 12 year olds to learn a foreign language. You realize that children learn new languages a lot faster than adults? > English keywords and libraries is not the problem, because we only use > about 30 - 50 of these words for teaching programming idea. They can > remember these words in one week. But for the name of variable or > function, it is difficult to remember all the English word. For > example, when we are doing numbers, maybe these words: [odd, even, > prime, minus ...], when we are programming for drawing: [line, circle, > pixel, ...], when it's for GUI: [ button, event, menu...]. There are > so many words that they cannot just remeber and use these words to > explain there idea. Again, it's probably not the language but the formal logic they have problems with. Please do *not* conclude that some child is not very good at math or logic or programming when they are slow at first. It doesn't tell one very much how good they might become later on and some premature idea the teacher might have formed about a pupil in that phase can even be harmful for their later perspectives. > Eventlly, when these children go to high school and study enough > English, I think they can use English words for programming. But as > the beginning step, it is difficult to learn both programming and > English. The older they get the harder it is for them to learn language. By withholding them English language experience at an early age you are doing them a disservice because later on they will have more trouble. The other thing is trying to teach them formal operational logic when they are not yet ready for it. In that case it would be better to wait until they are ready, but unfortunately there are large variations in the age at which children become ready. Please do not confuse the two very different matters of language acquisition and formal operational logic. Language is learned at an early age while formal logic starts at about the age of eleven (but with very large variation among children). > So, I made a little program, just replace all the Chinese words in the > program to some sequency identifiers such as [a1, a2, a3, ...], So we > can do programming in Chinese, and Python can still run it. Why not use IronPython? But anyway you are actually making things worse by *not* teaching them the language now that they will need later on and by *teaching* them formal operational logic at an age when they just get disappointed and frustrated by not yet being able to understand it. Better go easy on them and teach them lots of English computing terms and only introduce logic when they show they are ready. A. From steven at REMOVE.THIS.cybersource.com.au Tue May 15 21:02:17 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 16 May 2007 01:02:17 GMT Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179226183.215907.140450@q75g2000hsh.googlegroups.com> Message-ID: On Tue, 15 May 2007 14:44:44 +0200, Anton Vredegoor wrote: > HYRY wrote: >>> - should non-ASCII identifiers be supported? why? >> Yes. I want this for years. I am Chinese, and teaching some 12 years >> old children learning programming. The biggest problem is we cannot use >> Chinese words for the identifiers. As the program source becomes >> longer, they always lost their thought about the program logic. > > That is probably because they are just entering the developmental phase > of being able to use formal operational reasoning. I can understand that > they are looking for something to put the blame on but it is an error to > give in to the idea that it is hard for 12 year olds to learn a foreign > language. You realize that children learn new languages a lot faster > than adults? Children soak up new languages between the ages of about one and four. By 12, they're virtually adults as far as learning new languages. > Again, it's probably not the language but the formal logic they have > problems with. You have zero evidence for that, you're just applying your own preconceptions and ignoring what HYRY has told you. > Please do *not* conclude that some child is not very good > at math or logic or programming when they are slow at first. You're the one saying they're having problems with logic, not HYRY. He's saying they are having problems with English. -- Steven. From codewarrior at mail.com Wed May 30 13:08:37 2007 From: codewarrior at mail.com (kc) Date: Wed, 30 May 2007 12:08:37 -0500 Subject: Is PEP-8 a Code or More of a Guideline? References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <5c1jpkF2tl0ilU1@mid.individual.net> <1180539790.654176.26900@q75g2000hsh.googlegroups.com> Message-ID: <646aw86i.fsf@mail.com> "Joe Riopel" writes: > Using camel case instead of the under_score means less typing. I am lazy. > > fooBar > foo_bar Each requires exactly the same number of key strokes when I do the math. (Too lazy to explain further...) From kelvin.you at gmail.com Tue May 29 03:24:15 2007 From: kelvin.you at gmail.com (=?gb2312?B?yMvR1MLkyNXKx8zs0cSjrM37vKvM7NHEsru8+7zS?=) Date: 29 May 2007 00:24:15 -0700 Subject: how to print the GREEK CAPITAL LETTER delta under utf-8 encoding In-Reply-To: <465BD0AA.9080805@v.loewis.de> References: <1180414659.066482.236370@i38g2000prf.googlegroups.com> <465BBB49.6000803@v.loewis.de> <1180421212.151587.118020@r19g2000prf.googlegroups.com> <465BD0AA.9080805@v.loewis.de> Message-ID: <1180423455.639315.155990@a26g2000pre.googlegroups.com> On 5?29?, ??3?05?, "Martin v. Lo"wis" wrote: > > yes, it could print to the terminal(cmd.exe), but when I write these > > string to file. I got the follow error: > > > File "E:\Tools\filegen\filegen.py", line 212, in write > > self.file.write(data) > > UnicodeEncodeError: 'ascii' codec can't encode character u'\u0394' in > > position 0 > > : ordinal not in range(128) > > Yes, when writing to a file, you need to define an encoding, e.g. > > self.file.write(data.encode("utf-8")) > > You can use codecs.open() instead of open(), > so that you can just use self.file.write(data) > > Alternatively, you can find out what sys.stdout.encoding is, > and use that when encoding data for the terminal (falling back > to "utf-8" when .encoding is not available on the file). > > > but other text, in which include "chinese characters" got from > > os.listdir(...), are written to the file OK. why? > > Your version of Windows uses a code page that supports Chinese > characters in the byte-oriented character set. These are normally > encoded using the "mbcs" encoding (except that the terminal likely > uses a different encoding). So if you use "mbcs" instead of "utf-8", > you might be able to read the text as well. > > Regards, > Martin Thanks a lot! I want to just use the utf-8. how could I convert my 'mbcs' encoding to the utf-8 and write it to the file? I have replaced the open() to codecs.open() but it still can not decode the 'mbcs', the error is as follow: File "E:\Tools\filegen\filegen.py", line 213, in write self.file.write(data) File "C:\Python25\lib\codecs.py", line 638, in write return self.writer.write(data) File "C:\Python25\lib\codecs.py", line 303, in write data, consumed = self.encode(object, self.errors) UnicodeDecodeError: 'ascii' codec can't decode byte 0xcc in position 32: ordinal not in range(128) From mikeminer53 at hotmail.com Wed May 23 12:43:22 2007 From: mikeminer53 at hotmail.com (mkPyVS) Date: 23 May 2007 09:43:22 -0700 Subject: Resizing listbook's listview pane In-Reply-To: <1179932659.180278.72990@w5g2000hsg.googlegroups.com> Message-ID: <1179938602.688569.275400@o5g2000hsb.googlegroups.com> Sorry, copied from wxpython submit as well.. I'm using wxpython 2.8... Primariy I want the resize to happen programatically during object creation/post creation... I can worry about app size changes later. Thanks, From francois.schnell at gmail.com Sat May 5 19:13:04 2007 From: francois.schnell at gmail.com (francois.schnell at gmail.com) Date: 5 May 2007 16:13:04 -0700 Subject: problem with py2exe and microsoft speech SDK 5.1 In-Reply-To: References: Message-ID: <1178406784.240461.275930@q75g2000hsh.googlegroups.com> Hi Dave, I can't help you but maybe you'll have more luck if you try also the dedicated py2exe mailing list: https://lists.sourceforge.net/lists/listinfo/py2exe-users francois On May 4, 7:36 am, Dave Lim wrote: > >On May 3, 1:29 pm, Dave Lim > wrote: > >> Hello, this is my first time in the mailing list so > >> bear with me. > > >> Basically what I did was I followed this > > site:http://surguy.net/articles/speechrecognition.xml > > > > >> So I installed microsoft speech SDK 5.1 and then > used > >> pythonwin COM MakePy utility for it and it worked > out > >> fine. However, I need to compile my program into a > >> .exe and I have no idea how to make this work. I > tried > >> using py2exe but I get the error: > > >> Traceback (most recent call last): > >> File "simple-speech-recognition.py", line 57, in > ? > >> TypeError: Error when calling the metaclass bases > >> cannot create 'NoneType' instances > > >> If anybody knows a good solution to this problem I > >> would very much appreciate it if you can guide me > to > >> the right path / solution. > > >> Thank you very much! > >> -Dave Lim > > >> __________________________________________________ > >> Do You Yahoo!? > >> Tired of spam? Yahoo! Mail has the best spam > > protection aroundhttp://mail.yahoo.com > > >I've never done this, but I want to at some point, so > I went and > >grabbed some good links on packaging up Python apps: > > >http://davidf.sjsoft.com/mirrors/mcmillan-inc/install1.html > >http://www.pharscape.org/content/view/33/51/ > >http://wiki.python.org/moin/Py2Exe > >http://www.py2exe.org/index.cgi/Tutorial > > >There's also growth in using Python Eggs: > > http://peak.telecommunity.com/DevCenter/PythonEggs > > > > >Mike > > Thanks for the links. But I already have compiled it > successfully into an executable my only problem is i > still have that error. I still have the same error: > > Traceback (most recent call last): > File "simple-speech-recognition.py", line 57, in ? > TypeError: Error when calling the metaclass bases > cannot create 'NoneType' instances > > I used py2exe and I also added typelibs in the options > however that didn't seem to fix my problem. Below is > my setup.py, can anyone tell me what I'm lacking or > doing wrong here? > > setup.py > > from distutils.core import setup > import py2exe > > setup(options = {"py2exe": {"typelibs": > [('{C866CA3A-32F7-11D2-9602-00C04F8EE628}',0,5,0)]}}, > console = ["simple.py"]) > > Dave > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection aroundhttp://mail.yahoo.com From rschroev_nospam_ml at fastmail.fm Sat May 26 07:47:58 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 26 May 2007 11:47:58 GMT Subject: Newbie: Struggling again 'map' In-Reply-To: <1180173252.906992.262570@q75g2000hsh.googlegroups.com> References: <1180173252.906992.262570@q75g2000hsh.googlegroups.com> Message-ID: mosscliffe schreef: > for x,y in map("N/A", lista, listb): ########## Fails - Can not call a > 'str' > print "MAP:", x, "<>", y > > def fillwith(fillchars): > return fillchars > > for x,y in map(fillwith("N/A"), lista, listb): ########## Fails also - > Can not call a 'str' > print "MAP:", x, "<>", y The first argument to map is a function, which is called with the items of the argument sequences. If the first argument is None, a default function is used which returns a tuple of the items. In the case that two input sequences are provided: map(None, lista, listb) is equivalent to: def maketuple(a, b): return a, b map(maketuple, lista, listb) So what you want to do can be done with map like this: def make_fill_missing(fillchars): def fill_missing(a, b): if a is None: a = fillchars if b is None: b = fillchars return a, b return fill_missing map(make_fill_missing("N/A"), lista, listb)) -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From martin at v.loewis.de Wed May 2 00:42:17 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 02 May 2007 06:42:17 +0200 Subject: Why are functions atomic? In-Reply-To: <1178065685.161372.81790@y80g2000hsf.googlegroups.com> References: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> <1178044821.864741.235260@o5g2000hsb.googlegroups.com> <1178063341.779617.289690@o5g2000hsb.googlegroups.com> <1178065685.161372.81790@y80g2000hsf.googlegroups.com> Message-ID: <463816a9$0$9276$9b622d9e@news.freenet.de> Michael schrieb: > A bit more info, but still no clear picture about why functions are > mutable but have immutable copy symantics. There are arguments why > functions should be immutable, but the decision was to make user- > defined functions mutable. My question is still: why the present > ummutable copy symantics? The answer is really really simple. The implementation of copy predates mutability. When the copy code was written, functions *were* immutable. When functions became mutable, the copy code was not changed, and nobody noticed or complained. Regards, Martin From see_below_no_spam at yahoo.es Sat May 19 02:54:31 2007 From: see_below_no_spam at yahoo.es (Javier Bezos) Date: Sat, 19 May 2007 08:54:31 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <464C5382.6080403@v.loewis.de> <1179423799.254286.294930@w5g2000hsg.googlegroups.com> <1179503525.018943.95740@u30g2000hsc.googlegroups.com> <1179508599.868680.177960@e65g2000hsc.googlegroups.com> <1179523111.401781.125660@k79g2000hse.googlegroups.com> Message-ID: <@yahoo.com> escribi?: >> > Perhaps, but the treatment by your mail/news software plus the >> > delightful Google Groups of the original text (which seemed intact in >> > the original, although I don't have the fonts for the content) would >> > suggest that not just social or cultural issues would be involved. >> >> The fact my Outlook changed the text is irrelevant >> for something related to Python. > > On the contrary, it cuts to the heart of the problem. There are > hundreds of tools out there that programmers use, and mailing lists > are certainly an incredibly valuable tool--introducing a change that > makes code more likely to be silently mangled seems like a negative. In such a case, the Python indentation should be rejected (quite interesting you removed from my post the part mentioning it). I can promise there are Korean groups and there are no problems at all in using Hangul (the Korean writing). Javier ----------------------------- http://www.texytipografia.com From nyamatongwe+thunder at gmail.com Mon May 14 06:26:58 2007 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Mon, 14 May 2007 10:26:58 GMT Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: Anton Vredegoor: > Ouch! Now I seem to be disagreeing with the one who writes my editor. > What will become of me now? It should be OK. I try to keep my anger under control and not cut off the pixel supply at the first stirrings of dissent. It may be an idea to provide some more help for multilingual text such as allowing ranges of characters to be represented as hex escapes or character names automatically. Then someone who only normally uses ASCII can more easily audit patches that could contain non-ASCII characters. Neil From fidtz at clara.co.uk Wed May 2 12:19:25 2007 From: fidtz at clara.co.uk (fidtz at clara.co.uk) Date: 2 May 2007 09:19:25 -0700 Subject: ascii to unicode line endings Message-ID: <1178122765.162546.59680@l77g2000hsb.googlegroups.com> The code: import codecs udlASCII = file("c:\\temp\\CSVDB.udl",'r') udlUNI = codecs.open("c:\\temp\\CSVDB2.udl",'w',"utf_16") udlUNI.write(udlASCII.read()) udlUNI.close() udlASCII.close() This doesn't seem to generate the correct line endings. Instead of converting 0x0D/0x0A to 0x0D/0x00/0x0A/0x00, it leaves it as 0x0D/ 0x0A I have tried various 2 byte unicode encoding but it doesn't seem to make a difference. I have also tried modifying the code to read and convert a line at a time, but that didn't make any difference either. I have tried to understand the unicode docs but nothing seems to indicate why an seemingly incorrect conversion is being done. Obviously I am missing something blindingly obvious here, any help much appreciated. Dom From castironpi at gmail.com Tue May 8 00:46:07 2007 From: castironpi at gmail.com (castironpi at gmail.com) Date: 7 May 2007 21:46:07 -0700 Subject: interesting exercise In-Reply-To: <1178599363.051648.235280@w5g2000hsg.googlegroups.com> References: <1178595952.641173.76540@y80g2000hsf.googlegroups.com> <1178598876.913274.184850@p77g2000hsh.googlegroups.com> <1178599363.051648.235280@w5g2000hsg.googlegroups.com> Message-ID: <1178599567.894918.288450@l77g2000hsb.googlegroups.com> On May 7, 11:42 pm, castiro... at gmail.com wrote: > On May 7, 11:34 pm, castiro... at gmail.com wrote: > > > > > On May 7, 10:45 pm, Michael Tobis wrote: > > > > I want a list of all ordered permutations of a given length of a set > > > of tokens. Each token is a single character, and for convenience, they > > > are passed as a string in ascending ASCII order. > > > > For example > > > > permute("abc",2) > > > > should return ["aa","ab","ac","ba","bb","bc","ca","cb","cc"] > > > > and permute("13579",3) should return a list of 125 elements > > > ["111","113", ... ,"997","999"] > > > > permute("axc",N) or permute("2446",N) should raise ValueError as the > > > alphabet is not strictly sorted. > > > > I have a reasonably elegant solution but it's a bit verbose (a couple > > > dozen lines which I'll post later if there is interest). Is there some > > > clever Pythonism I didn't spot? > > > > thanks > > > mt > > > Post yours. > > Oh well, as I'm not the first. > [working solution snip] Or even, def p(a,b): if list( a ) != sorted( list( a ) ): raise ValueError, "String not ordered." if not b: return [''] return [i+j for i in list(a) for j in p(a,b-1)] p('abc',3) #fb: ['aaa', 'aab', 'aac', 'aba', 'abb', 'abc', 'aca', 'acb', 'acc', 'baa', 'bab', 'bac', 'bba', 'bbb', 'bbc', 'bca', 'bcb', 'bcc', 'caa', 'cab', 'cac', 'cba', 'cbb', 'cbc', 'cca', 'ccb', 'ccc'] p('abc',2) #fb: ['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc'] len(p("13579",3)) #fb: 125 edit() From kyosohma at gmail.com Thu May 3 11:04:21 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 3 May 2007 08:04:21 -0700 Subject: My Python annoyances In-Reply-To: <1178202431.147195.249790@u30g2000hsc.googlegroups.com> References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> <1178202431.147195.249790@u30g2000hsc.googlegroups.com> Message-ID: <1178204661.242750.100120@e65g2000hsc.googlegroups.com> On May 3, 9:27 am, Paul Boddie wrote: > On 3 Mai, 15:49, Ben Collver wrote: > > > I rewrote my code in Python and I found myself running into many of the > > same hassles that I run into with other languages: inaccurate and > > incomplete documentation, a maze of little platform-specific quirks to > > work around in the base classes, and a macho community of users. > > I'm sorry to hear about that. If by "macho" you mean people who insist > that things are good enough as they are, and that newcomers should > themselves adapt to whatever they may discover, instead of things > being improved so that they are more intuitive and reliable for > newcomers and experienced developers alike, then I'd certainly be > interested in undermining that culture. > > > The python web site recommended Dive Into Python, so I learned by > > reading that. It has several examples that don't work because the > > Python base classes have changed behavior. I should have taken that as > > lesson. > > Really Dive Into Python should be a sufficient guide, and it was > perhaps the best introduction to the language when it was written. It > is very unfortunate that the language has changed in a number of ways > (and exhibits continued change) whilst effort into documenting what is > already there remains neglected amongst the people making all the > changes. > > > I tried to write portable Python code. The zlib CRC function returned > > different results on architectures between 32 bit and 64 bit > > architectures. I filed a bug report. It was closed, without a comment > > from the person who closed it. I get the unspoken message: bug reports > > are not welcome. > > Can you provide the bug identifier? Bug reports are generally welcome, > and despite complaints about patch reviews, I've found people > reviewing things I've submitted. > > > I installed Cygwin on a Windows machine. I try to quit from an > > interactive Python session. It tells me that on my platform, I must > > press Control-Z to exit. I press Control-Z and it makes Python a > > background process. > > Yes, Ctrl-Z exits Python in the standard Windows edition. Since Cygwin > provides a POSIX-like environment, Ctrl-D should be used instead. If > the documentation is wrong, a bug report or patch should be filed > against the software. > > > I tried to use the XML.minidom. The documentation here is minimal as > > well. So I read up on other web sites. It turns out that the interface > > has changed quite a bit from the documentation I found on other web > > sites. Where are the much loved docstrings? In 2.3 minidom, they are > > sparse and cryptic. > > I really don't know what to say about the PyXML/xmlcore situation. I > don't use ElementTree and hardly use PyXML or minidom, but something > really should have been done about the maintenance of the established > libraries rather than declaring them as legacy items and pretending > that they don't exist. > > > Between 2.4 and 2.5, tempfile returns a different type of object. My > > code cannot have a single test, it has check for type(obj) == file or > > obj.__class__ == tempfile._TemporaryFileWrapper. > > Try using isinstance or relying on "deeper" knowledge of how the > object will be used. > > > I decided to make a tkinter front-end for a Python program. I decided > > to go with tkinter because it is included with many Python > > installations, so it maximizes the chance for my program to run out of > > the box. > > > The tkinter documentation on the Python site mainly consists of loose > > notes and links to other sites. The documentation on other sites is > > great, if you already know how to use tkinter. I ran into bugs in > > TkAqua which make the grid layout unusable for me. So I will need to > > ask potential users to install Xcode, X11, and mac ports, if they want > > to run my program. > > Take a look at the python.org Wiki for links to other resources on > Tkinter: > > http://wiki.python.org/moin/TkInter > > Or consider other graphical frameworks: > > http://wiki.python.org/moin/GuiProgramming > > > In short, there is plenty of room for improvement. Admittedly these are > > not problems with the language definition. But I downloaded a Python > > distribution, and the problems are Python specific. > > My opinions, already expressed, include the observation that the core > development community is more interested in extending the language > than in strengthening the standard library (and its documentation). It > should be noted that the proposed standard library reorganisation, > which is a very conservative affair, has actually been postponed until > after the release of Python 3.0a1 according to a message I read > recently. And yet, if you read people's lists about what they "hate" > about Python (amongst actual users of Python), guess which thing > almost always comes up? > > http://www.google.com/search?q=%22things+I+hate+about+Python%22 > > Paul I agree with Paul and Ben. The Docs need some help. Some are excellent and others are hosed because of changes to the language. I started with Tkinter, but quickly got frustrated with the lack of documentation or screwy out-dated docs. What really annoys me is that some very good authors state that Tkinter has excellent docs and multiple published books. I found one book by Grayson that is 7 years old. So I switched to wxPython. wxPython has a better user group and better docs. Unfortunately, they also have quite a few man pages, as do other external modules and man pages typically make my eyes swim. The closest thing to real docs by a real person for Python is Lundh's site: http://effbot.org/librarybook/ Fortunately, since Python is so easy, some of this can be overcome. Mike From chris.cavalaria at free.fr Wed May 16 06:44:01 2007 From: chris.cavalaria at free.fr (Christophe) Date: Wed, 16 May 2007 12:44:01 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464adea8$0$23132$9b4e6d93@newsspool1.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179289167.723990.223890@u30g2000hsc.googlegroups.com> <464abd12$0$23364$426a34cc@news.free.fr> <1179307776.953405.207680@l77g2000hsb.googlegroups.com> <464ad388$0$28786$426a34cc@news.free.fr> <464adea8$0$23132$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <464ae078$0$12296$426a34cc@news.free.fr> Ren? Fleschenberg a ?crit : > Christophe schrieb: >> You should know that displaying and editing UTF-8 text as if it was >> latin-1 works very very well.s > > No, this only works for those characters that are in the ASCII range. > For all the other characters it does not work well at all. This alone shows you don't know enouth about UTF-8 to talk about it. UTF-8 will NEVER use < 128 chars to describe multibyte chars. When you parse a UTF-8 file, each space is a space, each \n is an end of line and each 'Z' is a 'Z'. >> Also, Terminals have support for UTF-8 encodings already. > > Some have, some have not. And you not only need a terminal that can > handle UTF-8 data, you also need a font that has a glyph for all the > characters you need to handle, and you may also need a way to actualy > enter those characters with your keyboard. Ever heard of the famous "cut/paste"? I use it all the time, even when handling standard ASCII english code. It greatly cuts down my ability to make some typo while writing code. From brad at allendev.com Sat May 19 01:21:41 2007 From: brad at allendev.com (Brad Allen) Date: Sat, 19 May 2007 00:21:41 -0500 Subject: [dfwPython] A Few More Forrester Survey Questions In-Reply-To: <464DC49F.1090608@taupro.com> References: <464DC49F.1090608@taupro.com> Message-ID: At 10:22 AM -0500 5/18/07, Jeff Rush wrote: >I'm down to the wire here on answering the Forrester survey but am stumped on >a few questions I hope someone can help me out with. > >1) What -existing- examples of the use of Python to create social > web applications are there? These include chat, collaboration, > forum boards, and editable content pages, RSS feeds. > > I know I use a lot of these, but under pressure I'm not coming > up with a lot of names. Can you throw a few my way? I believe youtube.com is written in Python... Trac is a form of social collaboration for technical people working on projects. Obviously Plone is used for a multitude of social collaboration apps... >2) How easy is it to install an application written in the language? > How is the application deployed? > > I'm having some trouble understanding the difference between > "deployment" and "installation". I suspect those words may > have a special meaning to Java developers (who designed the survey) > or to Big Corporate IT developers. Ideas? > > I can tell the story of distutils, python eggs and PyPI, and py2exe > and py2mumble for the Mac -- is there more to the story than that? py2app for Mac There is also the drag & drop approach; many Python apps don't require an installer but can run standalone, especially since many operating systems already include a Python install by default. >3) What is the value of the language to developers? > > Yeah, a very common, slippery question. Toss me some good > explanations of why -you- value Python. Readable, free, > cross-platform, powerful. What else? I'll synthesize > something out of everyone's answers. Learn once, use everywhere: web apps, GUI apps, command line scripts, systems integration glue, wrapping libraries from other languages, Wide range of scale: from quick and dirty tasks to large complex systems. Wide range of skill: accessible to beginners, but supports advanced concepts experienced developers require. Practical syntax which emphasizes elegance and clarity through minimalism Dynamic language features allow high level and flexible design approach, boosting productivity. Robustness - bugs in Python itself are rare due to maturity from long widespread use. No IDE required: you go far with simple text editors, but good IDEs are available. Good community support due to widespread use and open source nature. Great as glue language, due to flexible options for calling external binary apps Mature ecosystem of libraries, both cross platform and platform native, and good options for accessing libraries in other languages. Professional opportunities: Python is in production use in a lot of companies, who realize it costs less than static languages and is more generally useful than PHP or Ruby. The only real competitor is Perl, which can be difficult to manage due to readability problems. Downsides: Poor multithreading support for the multiprocessor age (Kill GIL!) None of the Python web frameworks receive widespread use ala RoR or PHP From phd at phd.pp.ru Thu May 10 11:25:33 2007 From: phd at phd.pp.ru (Oleg Broytmann) Date: Thu, 10 May 2007 19:25:33 +0400 Subject: SQLObject 0.9.0 Message-ID: <20070510152533.GJ18313@phd.pp.ru> Hello! I'm pleased to announce the 0.9.0 release of SQLObject, the first stable release of the 0.9 branch. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.9.0 News and changes: http://sqlobject.org/News.html What's New ========== Features & Interface -------------------- * Support for Python 2.2 has been declared obsolete. * Removed actively deprecated attributes; lowered deprecation level for other attributes to be removed after 0.9. * SQLite connection got columnsFromSchema(). Now all connections fully support fromDatabase. There are two version of columnsFromSchema() for SQLite - one parses the result of "SELECT sql FROM sqlite_master" and the other uses "PRAGMA table_info"; the user can choose one over the other by using "use_table_info" parameter in DB URI; default is False as the pragma is available only in the later versions of SQLite. * Changed connection.delColumn(): the first argument is sqlmeta, not tableName (required for SQLite). * SQLite connection got delColumn(). Now all connections fully support delColumn(). As SQLite backend doesn't implement "ALTER TABLE DROP COLUMN" delColumn() is implemented by creating a new table without the column, copying all data, dropping the original table and renaming the new table. * Versioning - see http://sqlobject.org/Versioning.html * MySQLConnection got new keyword "conv" - a list of custom converters. * Use logging if it's available and is configured via DB URI. * New columns: TimestampCol to support MySQL TIMESTAMP type; SetCol to support MySQL SET type; TinyIntCol for TINYINT; SmallIntCol for SMALLINT; MediumIntCol for MEDIUMINT; BigIntCol for BIGINT. Small Features -------------- * Support for MySQL INT type attributes: UNSIGNED, ZEROFILL. * Support for DEFAULT SQL attribute via defaultSQL keyword argument. * cls.tableExists() as a shortcut for conn.tableExists(cls.sqlmeta.table). * cls.deleteMany(), cls.deleteBy(). Bug Fixes --------- * idName can be inherited from the parent sqlmeta class. * Fixed a longstanding bug with .select() ignoring 'limit' parameter. * Fixed a bug with absent comma in JOINs. * Fixed sqlbuilder - .startswith(), .endswith() and .contains() assumed their parameter must be a string; now you can pass an SQLExpression: Table.q.name.contains(func.upper('a')), for example. * Fixed a longstanding bug in sqlbuilder.Select() with groupBy being a sequence. * Fixed a bug with Aliases in JOINs. * Yet another patch to properly initialize MySQL connection encoding. * Fixed a minor comparison problem in test_decimal.py. * Fixed a bug in SQLRelatedJoin that ignored per-instance connection. Docs ---- * Added documentation about 'validator' Col constructor option. * Added an answer and examples to the FAQ on how to use sqlmeta.createSQL. * Added an example on how to configure logging. * More documentation about orderBy. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From mwilliams at mgreg.com Sun May 13 19:28:59 2007 From: mwilliams at mgreg.com (Michael Williams) Date: Sun, 13 May 2007 19:28:59 -0400 Subject: Using "subprocess" without lists. . .? In-Reply-To: <4647563E.6010702@gmail.com> References: <4647563E.6010702@gmail.com> Message-ID: I'm not sure you replied entirely to the correct post. Basically I'm interested in encoding video with FFMPEG, but there will be variable length commands so I'd rather be able to type a single string for the "command" as opposed to having to enter it in the form of a list. And there is really no way to properly parse because some options have values and others are simply flags. Thanks, Michael On May 13, 2007, at 2:17 PM, Steven Howe wrote: > Michael Williams wrote: >> Hi All, >> >> I've recently seen the "subprocess" module and am rather confused by >> it's requirements. Is it not possible to execute an entire string >> without having to break them up into a list of arguments? For >> instance, I'd much rather do the following: >> >> >> subprocess.call("ls -al | grep -i test") >> >> >> . . .than to have to: >> >> >> list = ["ls", "-a", "-l" ] . . . . . . and so on and so forth. >> subprocess.call(list. . .) >> >> >> What is the best way to go about executing a massively complex single >> line command? >> >> >> Thanks, >> Michael >> > How about a hybrid solution?: > from subprocess import Popen, PIPE > from string import strip > (stdout, stderr) = Popen(['ls','-al'], stdout=PIPE, > stderr=PIPE).communicate() > # process spins off. Ideally, you should wait for it to complete, > or assign the resulting object of Popen > # to a variable and inquire if it's completed via the 'poll()' > operator or wait on it via the 'wait()' > # operator. > # then query the stderr via communicate()[1]; if good, i.e. len > (stderr) == 0, inspect the resulting > # stdout string (via communicate()[0]) for your 'test' result. But > I'm being lazy. I assume the call to > # ls -al will be faster then my next statement. > res = [] > for line in stdout.strip(): > if 'test' in line: > res.append( line ) > > Do the work you need done at the shell prompt, do the rest in > Python. Also I wonder if, you were looking for the word 'test' in > the filename, glob.glob wouldn't have been a bit more efficient? > But if you were looking for a 'test' owner or group then using: > glob.glob(): get the list of files, with directory. Example: > glob.glob('/bin/*') > os.stat(): get an object of stats on a file. Example: os.stat('/bin/ > ls') > stat.ST_UID: get just the group id, as an integer from the object > returned by os.stat. Example: os.stat('/bin/ls')[stat.ST_UID] > pwd.getpwgid(): get the string translation of a UID. Example: > pwd.getpwgid( os.stat('/bin/ls')[stat.ST_UID] ) > stat.ST_GID: get the group id, as an integer from the object > returned os.stat. Example: > os.stat('/bin/ls')[stat.ST_GID] > grp.getgrgid(): get the string translation of a UID. Example: > grp.getgrgid( os.stat('/bin/ls')[stat.ST_UID] ) > Now I have a list, which I iterate over, getting the UID and GID, > as strings, that I can compare to. I never had to use a subprocess > and having to build up a 'wait on done loop'. Note, grp and pwd, I > think, are Python/Unix functions. What one does on Windows I don't > know, but I'll bet there are similar functions under Python/ > Windows. Don't get me wrong, Subprocess is a fast and damn useful > tool. I often use it to verify a program is in my path, before > creating a subprocess to run some task python isn't built for (like > mencoder functionality). > > You see, the issue is: shell, python & shell or python alone. When > transitioning from one language to another, say C/C++/Java to > Python, it is often easier to use your knowledge of the shell > command (bash/Bourne for example) to get things done. But it's only > a transitional issue. The need to use the shell is a good > demonstrator that either the Interpretor is weak, or that you > haven't fully explored it's abilities. With the Python Interpretor > at v2.4 going onto v2.5, it's very likely that the desired feature > exists; you have but to do some clever research to find it. As to > clever research ... I find Google a good place to start. > > I had some familiarity with os.stat and glob. But the grp and pwd > functions were things I discovered from http://docs.python.org/ > modindex.html and about two minutes of searching for 'python uid to > name' @ Google. > > Also, os.listdir and os.path.join would have worked just as well as > glob.glob('dirname/*'). But glob.glob was faster to write. Even a > better choice would have been to use the 'os.walk' to iterate over > the directory tree. > > sph. > > -- > HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -------------- next part -------------- An HTML attachment was scrubbed... URL: From revuesbio at gmail.com Tue May 8 06:15:41 2007 From: revuesbio at gmail.com (revuesbio) Date: 8 May 2007 03:15:41 -0700 Subject: msbin to ieee In-Reply-To: <1178573895.164509.82270@u30g2000hsc.googlegroups.com> References: <1178487847.671199.108140@h2g2000hsg.googlegroups.com> <1178502738.104124.3840@h2g2000hsg.googlegroups.com> <1178525916.145819.264070@n59g2000hsh.googlegroups.com> <1178536910.566119.6650@o5g2000hsb.googlegroups.com> <1178539202.316506.199940@p77g2000hsh.googlegroups.com> <1178542593.668743.71500@u30g2000hsc.googlegroups.com> <1178545075.530201.180120@u30g2000hsc.googlegroups.com> <1178573895.164509.82270@u30g2000hsc.googlegroups.com> Message-ID: <1178619341.882665.245470@e51g2000hsg.googlegroups.com> On 7 mai, 23:38, John Machin wrote: > On May 7, 11:37 pm, revuesbio wrote: > > > > > On 7 mai, 14:56, John Machin wrote: > > > > On May 7, 10:00 pm, revuesbio wrote: > > > > > On 7 mai, 13:21, John Machin wrote: > > > > > > On May 7, 6:18 pm, revuesbio wrote: > > > > > > > On 7 mai, 03:52, John Machin wrote: > > > > > > > > On May 7, 7:44 am, revuesbio wrote: > > > > > > > > > Hi > > > > > > > > Does anyone have the python version of the conversion from msbin to > > > > > > > > ieee? > > > > > > > > Thank u > > > > > > > > Yes, Google has it. Google is your friend. Ask Google. It will lead > > > > > > > you to such as: > > > > > > > >http://mail.python.org/pipermail/python-list/2005-August/337817.html > > > > > > > > HTH, > > > > > > > John > > > > > > > Thank you, > > > > > > > I've already read it but the problem is always present. this script is > > > > > > for double precision MBF format ( 8 bytes). > > > > > > It would have been somewhat more helpful had you said what you had > > > > > done so far, even posted your code ... > > > > > > > I try to adapt this script for single precision MBF format ( 4 bytes) > > > > > > but i don't find the right float value. > > > > > > > for example : 'P\xad\x02\x95' will return '0.00024924660101532936' > > > > > > If you know what the *correct* value is, you might like to consider > > > > > shifting left by log2(correct_value/erroneous_value) :-) > > > > > > Do you have any known correct pairs of (mbf4 string, decimal_float > > > > > value)? My attempt is below -- this is based on a couple of > > > > > descriptive sources that my friend Google found, with no test data. I > > > > > believe the correct answer for the above input is 1070506.0 i.e. you > > > > > are out by a factor of 2 ** 32 > > > > > > def mbf4_as_float(s): > > > > > m0, m1, m2, m3 = [ord(c) for c in s] > > > > > exponent = m3 > > > > > if not exponent: > > > > > return 0.0 > > > > > sign = m2 & 0x80 > > > > > m2 |= 0x80 > > > > > mant = (((m2 << 8) | m1) << 8) | m0 > > > > > adj = 24 + 128 > > > > > num = mant * 2.0 ** (exponent - adj) > > > > > if sign: > > > > > return -num > > > > > return num > > > > > > HTH, > > > > > John > > > > > well done ! it's exactly what i'm waiting for !! > > > > > my code was:>>> from struct import * > > > > >>> x = list(unpack('BBBB','P\xad\x02\x95')) > > > > >>> x > > > > [80, 173, 2, 149] > > > > >>> def conversion1(bytes): > > > > > b=bytes[:] > > > > sign = bytes[-2] & 0x80 > > > > b[-2] |= 0x80 > > > > exp = bytes[-1] - 0x80 - 56 > > > > acc = 0L > > > > for i,byte in enumerate(b[:-1]): > > > > acc |= (long(byte)<<(i*8)) > > > > return (float(acc)*2.0**exp)*((1.,-1.)[sign!=0]) > > > > Apart from the 2**32 problem, the above doesn't handle *any* of the > > > 2**24 different representations of zero. Try feeding \0\0\0\0' to it > > > and see what you get. > > > > > >>> conversion1(x) > > > > > 0.00024924660101532936 > > > > > this script come from google groups but i don't understand bit-string > > > > manipulation (I'm a newbie). informations about bit-string > > > > manipulation with python is too poor on the net. > > > > The basic operations (and, or, exclusive-or, shift) are not specific > > > to any language. Several languages share the same notation (& | ^ << > > > > >>), having inherited it from C. > > > > > thank you very much for your script. > > > > Don't thank me, publish some known correct pairs of values so that we > > > can verify that it's not just accidentally correct for 1 pair of > > > values. > > > pairs of values : > > (bytes string, mbf4_as_float(s) result) right > > float value > > ('P\xad\x02\x95', 1070506.0) > > 1070506.0 > > ('\x00\x00\x00\x02', 5.8774717541114375e-039) 0.0 > > There is no way that \x00\x00\x00\x02' could represent exactly zero. > What makes you think it does? Rounding? > > > ('\x00\x00\x00\x81', 1.0) > > 1.0 > > ('\x00\x00\x00\x82', 2.0) > > 2.0 > > ('\x00\x00@\x82', 3.0) > > 3.0 > > ('\x00\x00\x00\x83', 4.0) > > 4.0 > > ('\x00\x00 \x83', 5.0) > > 5.0 > > ('\xcd\xcc\x0c\x81', 1.1000000238418579) 1.1 > > ('\xcd\xcc\x0c\x82', 2.2000000476837158) 2.2 > > ('33S\x82', 3.2999999523162842) 3.3 > > ('\xcd\xcc\x0c\x83', 4.4000000953674316) 4.4 > > It is not apparent whether you regard the output from the function as > correct or not. > > 4.4 "converted" to mbf4 format is '\xcd\xcc\x0c\x83' which is > 4.4000000953674316 which is the closest possible mbf4 representation > of 4.4 (difference is 9.5e-008). > > The next lower mbf4 value '\xcc\xcc\x0c\x83' is 4.3999996185302734 > (difference is -3.8e-007). > > Note that floating-point representation of many decimal fractions is > inherently inexact. print repr(4.4) produces 4.4000000000000004 > > Have you read this: > http://docs.python.org/tut/node16.html > ? > > If you need decimal-fraction output that matches what somebody typed > into the original software, or saw on the screen, you will need to > know/guess the precision that was involved, and round the numbers > accordingly -- just like the author of the original software would > have needed to do. > > >>> ['%.*f' % (decplaces, 4.4000000953674316) for decplaces in range(10)] > > ['4', '4.4', '4.40', '4.400', '4.4000', '4.40000', '4.400000', > '4.4000001', '4.40000010', '4.400000095'] > > HTH, > John another couples and round number corresponding to the right value ('\x00\x00\x00\x02', 5.8774717541114375e-039, '0.000') ('0\x8b\x01\x95', 1061222.0, '1061222.000') ('\xb8\x1e=\x83', 5.9099998474121094, '5.910') (')\\O\x83', 6.4800000190734863, '6.480') ('\x9a\x99A\x83', 6.0500001907348633, '6.050') ('\x00\x00P\x83', 6.5, '6.500') ('8BY\x95', 1779783.0, '1779783.000') ('\x00\x00\x00\x02', 5.8774717541114375e-039, '0.000') ('\xe0\xa0\x02\x95', 1070108.0, '1070108.000') ('33{\x83', 7.8499999046325684, '7.850') ('q=z\x83', 7.820000171661377, '7.820') ('33s\x83', 7.5999999046325684, '7.600') (')\\\x7f\x83', 7.9800000190734863, '7.980') ('\x00\x9aX\x92', 221800.0, '221800.000') ('\x00\x00\x00\x02', 5.8774717541114375e-039, '0.000') ('0\xa1\x02\x95', 1070118.0, '1070118.000') ('\x85\xebq\x83', 7.559999942779541, '7.560') ('\x14\xaeo\x83', 7.4899997711181641, '7.490') ('\xcd\xccT\x83', 6.6500000953674316, '6.650') ('\x00\x00p\x83', 7.5, '7.500') ('\x00\xa4N\x92', 211600.0, '211600.000') ('\x00\x00\x00\x02', 5.8774717541114375e-039, '0.000') ('\x90\xa1\x02\x95', 1070130.0, '1070130.000') ('\xaeGa\x83', 7.0399999618530273, '7.040') ('\xc3\xf5p\x83', 7.5300002098083496, '7.530') ('\x8f\xc2e\x83', 7.179999828338623, '7.180') ('H\xe1b\x83', 7.0900001525878906, '7.090') ('\xc0\xe27\x93', 376598.0, '376598.000') ('\x00\x00\x00\x02', 5.8774717541114375e-039, '0.000') ('\x08\xa4\x02\x95', 1070209.0, '1070209.000') ('\x9a\x99a\x83', 7.0500001907348633, '7.050') ('\xd7\xa3x\x83', 7.7699999809265137, '7.770') ('H\xe1r\x83', 7.5900001525878906, '7.590') ('{\x14v\x83', 7.690000057220459, '7.690') ('\x80.W\x93', 440692.0, '440692.000') ('\x00\x00\x00\x02', 5.8774717541114375e-039, '0.000') ('h\xa4\x02\x95', 1070221.0, '1070221.000') ('\x8f\xc2\x01\x84', 8.1099996566772461, '8.110') ('=\n\x03\x84', 8.1899995803833008, '8.190') ('\xcd\xcc\x00\x84', 8.0500001907348633, '8.050') ('ffv\x83', 7.6999998092651367, '7.700') ('\x80X\x1a\x94', 632200.0, '632200.000') ('\x00\x00\x00\x02', 5.8774717541114375e-039, '0.000') ('\x08\xa7\x02\x95', 1070305.0, '1070305.000') ('33s\x83', 7.5999999046325684, '7.600') ('q=r\x83', 7.570000171661377, '7.570') ('\\\x8fj\x83', 7.3299999237060547, '7.330') ('33k\x83', 7.3499999046325684, '7.350') ('\xc0a\r\x94', 579100.0, '579100.000') ('\x00\x00\x00\x02', 5.8774717541114375e-039, '0.000') ('X\xa7\x02\x95', 1070315.0, '1070315.000') ('\xcd\xcc|\x83', 7.9000000953674316, '7.900') ('q=z\x83', 7.820000171661377, '7.820') ('\x00\x00p\x83', 7.5, '7.500') ('\x00\x00p\x83', 7.5, '7.500') ('\x00\x1b7\x92', 187500.0, '187500.000') ('\x00\x00\x00\x02', 5.8774717541114375e-039, '0.000') ('\xb8\xa7\x02\x95', 1070327.0, '1070327.000') ('{\x14~\x83', 7.940000057220459, '7.940') ('\xcd\xcc\x04\x84', 8.3000001907348633, '8.300') ('\xe1z\x00\x84', 8.0299997329711914, '8.030') ('\xcd\xcc\x10\x84', 9.0500001907348633, '9.050') ('\x00R\x00\x95', 1051200.0, '1051200.000') ('\x00\x00\x00\x02', 5.8774717541114375e-039, '0.000') ('P\xaa\x02\x95', 1070410.0, '1070410.000') ('R\xb8\x1e\x84', 9.9200000762939453, '9.920') ('\xd7\xa3\x1c\x84', 9.7899999618530273, '9.790') ('\x85\xeb\x19\x84', 9.619999885559082, '9.620') ('\x9a\x99\x19\x84', 9.6000003814697266, '9.600') ('\x98\x1c\x0c\x95', 1147795.0, '1147795.000') ('\x00\x00\x00\x02', 5.8774717541114375e-039, '0.000') ('\xa0\xaa\x02\x95', 1070420.0, '1070420.000') ('=\n\x0f\x84', 8.9399995803833008, '8.940') ('ff\x0e\x84', 8.8999996185302734, '8.900') ('\xe1z\x0c\x84', 8.7799997329711914, '8.780') ('\x1f\x85\x0f\x84', 8.9700002670288086, '8.970') ('\x00\x1d&\x92', 170100.0, '170100.000') ('\x00\x00\x00\x02', 5.8774717541114375e-039, '0.000') ('8\xad\x02\x95', 1070503.0, '1070503.000') ('\xf6(\x0c\x84', 8.7600002288818359, '8.760') ('\xe1z\x14\x84', 9.2799997329711914, '9.280') all is ok. thank u From mikeminer53 at hotmail.com Wed May 23 12:53:34 2007 From: mikeminer53 at hotmail.com (mkPyVS) Date: 23 May 2007 09:53:34 -0700 Subject: Resizing listbook's listview pane In-Reply-To: <1179932659.180278.72990@w5g2000hsg.googlegroups.com> Message-ID: <1179939214.679913.134670@q69g2000hsb.googlegroups.com> On May 23, 9:04 am, kyoso... at gmail.com wrote: > Which Python gui toolkit are you using? Tkinter, wxPython, pyQT? Are > you wanting the resize to happen programmatically, when the user > changes the app's size, both or what? > > More details would be helpful. > > Mike Sorry, copied from wxpython submit as well.. I'm using wxpython 2.8... Primariy I want the resize to happen programatically during object creation/post creation... I can worry about app size changes later. Thanks, From josh at laculine.com Fri May 25 12:33:56 2007 From: josh at laculine.com (Josh West) Date: Fri, 25 May 2007 17:33:56 +0100 Subject: Proxying every function in a module In-Reply-To: References: Message-ID: <46570FF4.9030409@laculine.com> Hello I've got a web application with the following structure: 1) module of 100 functions corresponding to user actions (e.g. "update_profile()", "organisations_list()") 2) a wsgi callable which maps urls to functions eg /organisations/list/?sort=date_created is mapped to organisations_list("dateCreated") 3) mapping is performed using inspect.getargspec() 4) a bunch of html generating templates In the templates I want to generate urls by referencing the function to which they map, rather than the url, e.g. Sort By Date Created In other words, I want to always refer to functions, rather than mixing up function calls and urls I would like a class that proxies all the 100 functions in the user actions module. When a proxied function is called via this class it should return the url to which it is mapped rather than executing the user action function. Sort By Date Created should produce: Sort By Date Created Obviously, I don't want to write and maintain copies of these 100 functions in another class. My question is therefore: what is the best way to proxy these 100 functions? Thanks Tim Arnold wrote: > Hi, I'm using ElementTree which is wonderful. I have a need now to write out > an XML file with these two headers: > > > > My elements have the root named tocbody and I'm using: > newtree = ET.ElementTree(tocbody) > newtree.write(fname) > > I assume if I add the encoding arg I'll get the xml header: > newtree = ET.ElementTree(tocbody) > newtree.write(fname,encoding='utf-8') > > but how can I get the into the tree? > > python2.4.1,hpux10,ElementTree1.2.6 > > thanks, > --Tim > > > From carl at personnelware.com Sat May 12 17:05:03 2007 From: carl at personnelware.com (Carl K) Date: Sat, 12 May 2007 16:05:03 -0500 Subject: ctree data Message-ID: A friend needs to convert c-tree plus data to MySql. I can to the "to MySql part, but need some help with the "from c-tree." If I just wanted to get this done, I would hunt down the ODBC driver and use some MSy thing. But I am trying to hone my Python skills, but right now I am in over my head, thus this post. I think with a little boost I will be able to make it all come together. (well, little boost may be an understatement - I have no clue how close/far I am from what I need.) My searching around has come up with a few ways to use Python to read the data: 1. pull what I need from some other py code that uses c-tree: http://oltp-platform.cvs.sourceforge.net/oltp-platform/OLTPP/services/PythonScript/PythonTranslate.h?view=markup http://oltp-platform.cvs.sourceforge.net/oltp-platform/OLTPP/scripts/TestZipCodes.py?view=markup 12 a,b,c = ZipCode.Get() 13 print "Zip code is ", a 14 print "State is ", b 15 print "City is ", c I am sure this is what I want. I just haven't figured out where to start. 2. "Pyrex" to create Python bindings to C API with minimal C knowledge. I took C and did a few little utilities on my own in the 90's. plus I can make a tarball. today I am not sure I even qualify for "minimal." 3. the C API is present as a shared object (.so), use it from Python with ctypes. I have no idea what that means. 4. odbc - I am actually not thrilled about using the ctree odbc driver in any environment, because someone else who tried to use it on some other data a few years ago said it was flaky, and support was next to useless. 5, get someone who knows perl to do it using http://cpan.uwinnipeg.ca/htdocs/Db-Ctree/Db/Ctree.html - This just shows what lengths I am willing to go to. but I really don't want to start learning perl. TIA Carl K From g_teodorescu at yahoo.com Mon May 14 04:28:58 2007 From: g_teodorescu at yahoo.com (g_teodorescu at yahoo.com) Date: 14 May 2007 01:28:58 -0700 Subject: How to do basic CRUD apps with Python In-Reply-To: <1179098458.333666.307750@e65g2000hsc.googlegroups.com> References: <1179098458.333666.307750@e65g2000hsc.googlegroups.com> Message-ID: <1179131338.196969.218940@h2g2000hsg.googlegroups.com> walterbyrd a scris: > With PHP, libraries, apps, etc. to do basic CRUD are everywhere. Ajax > and non-Ajax solutions abound. > > With Python, finding such library, or apps. seems to be much more > difficult to find. > > I thought django might be a good way, but I can not seem to get an > answer on that board. > > I would like to put together a CRUD grid with editable/deletable/ > addable fields, click on the headers to sort. Something that would > sort-of looks like an online spreadsheet. It would be nice if the > fields could be edited in-line, but it's not entirely necessary. > > Are there any Python libraries to do that sort of thing? Can it be > done with django or cherrypy? > > Please, don't advertise your PHP/Ajax apps. Try SqlSoup from SqlAlchemy. I can send examples in PyQt4. From tjreedy at udel.edu Mon May 14 14:32:45 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 14 May 2007 14:32:45 -0400 Subject: Sorting troubles References: <1179158708.433792.127150@h2g2000hsg.googlegroups.com> Message-ID: wrote in message news:1179158708.433792.127150 at h2g2000hsg.googlegroups.com... |I have the following implementations of quicksort and insertion sort: | | def qSort(List): | if List == []: return [] | return qSort([x for x in List[1:] if x< List[0]]) + List[0:1] + \ | qSort([x for x in List[1:] if x>=List[0]]) | | def insertSort(List): | for i in range(1,len(List)): | value=List[i] | j=i | while List[j-1]>value and j>0: | List[j]=List[j-1] | j-=1 | List[j]=value | | Now, the quickSort does not modify the original list, mostly because | it works on products and concatenations, rather than alterations. | The insertion sort, however, does modify the list. Now, to give | results, they should be called in such a way( A is an unsorted list) | A=qSort(A) | # the insertion sort does not require this, | insertSort(A) | | I would like to know how can I modify the qSort function such that it | affects the list directly inside | I have tried doing it like this | | def qSort(List): | if List == []: return [] | List = qSort([x for x in List[1:] if x< List[0]]) + List[0:1] + \ | qSort([x for x in List[1:] if x>=List[0]]) | return List | | while processing, the list changes, but those changes remain inside | the function, so that once it's over, if nothis catches the return, | the original List remains unchanged. | | If not a solution, I would like to at least know why it does what it | does. I so understand that List(above) is only a reference to the | actual data(a list), but I'm not passing a copy of the data to the | function, but the actual reference(hence, insertSort does | modifications). But then how can I change, inside the function, the | object List is referencing to? If I can't modify the original list, | maybe I can make the variable List point to another list? But changes | inside the function are local. Sorry if this is a bit confusing. The traditional way to do qsort in place (ignoring possible variations): def qsort(List, start=0, stop=None): if start >= stop: return if stop == None: stop = len(List) p = partition(List, start, stop) # p = index of pivot/partition item qsort(List, start, p) qsort(List, p+1, stop) where partition puts elements less that pivot value before the pivot value and greater values after. You could instead call your function qSorted to indicate that it returns a sorted copy ;-) Terry Jan Reedy From yavannadil at yahoo.com Sat May 5 04:19:03 2007 From: yavannadil at yahoo.com (yavannadil at yahoo.com) Date: 5 May 2007 01:19:03 -0700 Subject: How do I get type methods? In-Reply-To: References: <1178220806.664557.245780@c35g2000hsg.googlegroups.com> <1178253260.075515.43810@q75g2000hsh.googlegroups.com> <1178283588.694886.204250@c35g2000hsg.googlegroups.com> <1178289484.265718.198060@c35g2000hsg.googlegroups.com> Message-ID: <1178353143.859683.200420@e65g2000hsc.googlegroups.com> On May 4, 7:13 pm, Marc 'BlackJack' Rintsch wrote: > The OPs problem is, there is no access to the class or type because > there is no name. Exactly :-( > You can get just instances from a factory function. Worse, if I call localContext.ServiceManage I'll get something with different set of methods, but of the same type - 'pyuno' :-( From editor at methodsandtools.com Thu May 24 05:14:11 2007 From: editor at methodsandtools.com (martinig) Date: 24 May 2007 02:14:11 -0700 Subject: The Relative Importance of Web Development Message-ID: <1179998051.616603.11530@p77g2000hsh.googlegroups.com> If you follow the evolution of software development on Internet, you may have the impression that every new development is Web based and that the main areas of concern are whether you should develop new application with Ruby on Rail or if you should choose Flash rather than Ajax for the interface. However, if you ask developers, you may find that the Web is not as ubiquitous in their work as you may think. Even if 66% of the participants develop the majority of their new applications with a browser as the interface, there is still a large portion of developers that are working today for operating contexts that are outside the Web world, like embedded software or Windows applications. Get the full results of this poll on http://www.methodsandtools.com/dynpoll/oldpoll.php?WebDev2 From _karlo_ at _mosor.net Sat May 12 12:46:15 2007 From: _karlo_ at _mosor.net (Karlo Lozovina) Date: Sat, 12 May 2007 18:46:15 +0200 Subject: Basic question In-Reply-To: <1178986686.510137.195490@p77g2000hsh.googlegroups.com> References: <1178986686.510137.195490@p77g2000hsh.googlegroups.com> Message-ID: Cesar G. Miguel wrote: > for j in range(10): > print j > if(True): > j=j+2 > print 'interno',j > > What happens is that "j=j+2" inside IF does not change the loop > counter ("j") as it would in C or Java, for example. > Am I missing something? If you want that kind of behaviour then use a `while` construct: j = 0 while j < 5: print j if True: j = j + 3 print '-- ', j If you use a for loop, for each pass through the foor loop Python assigns next item in sequence to the `j` variable. HTH, Karlo. From zzzeek at gmail.com Sun May 20 19:57:59 2007 From: zzzeek at gmail.com (Michael Bayer) Date: 20 May 2007 16:57:59 -0700 Subject: Python Web Programming - looking for examples of solid high-traffic sites In-Reply-To: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> Message-ID: <1179705479.338825.163380@z28g2000prd.googlegroups.com> On May 16, 5:04 pm, Victor Kryukov wrote: > > Our main requirement for tools we're going to use is rock-solid > stability. As one of our team-members puts it, "We want to use tools > that are stable, has many developer-years and thousands of user-years > behind them, and that we shouldn't worry about their _versions_." The > main reason for that is that we want to debug our own bugs, but not > the bugs in our tools. youre not going to find a web development platform in any language at all where you will not come across bugs. you will always have to "worry" about versions. I have a day job where we worry about bugs and versions in struts, hibernate, mysql, and spring all day long, and each of those products probably has more users than all python frameworks combined (feel free to whomever to bring out numbers, id be glad to be proven wrong). The web platform for Python which has the longest running time and the most thousands-of-whatever hours is Zope (and Plone). All the others which are popular today have only a tiny fraction of the in-production time that Zope has. so if thats your criterion, then zope is what you'd probably have to use. > TurboGears, Django and Pylons are all nice, and provides rich features > - probably too many for us - but, as far as we understand, they don't > satisfy the stability requirement - Pylons and Django hasn't even > reached 1.0 version yet. And their provide too thick layer - we want > something 'closer to metal', probably similar to web.py - > unfortunately, web.py doesn't satisfy the stability requirement > either, or so it seems. I would seriously reconsider the notion that Pylons is "too thick" of a layer. Pylons is quite open ended and non-opinionated. the approaches of Pylons and Django couldnt be more different, so I would suggest digging a little deeper into the various frameworks before dismissing them on based on shallow judgments. Also, I understand reddit is built on web.py, which is pretty high-traffic/proven/etc. > So the question is: what is a solid way to serve dynamic web pages in > python? Our initial though was something like python + mod_python + > Apache, but we're told that mod_python is 'scary and doesn't work very > well'. mod_python works fantastically in my experience. that would satisfy your requirement of stability as well as "close to the metal". but youre going to have to roll your own pretty much everything...theres only the most rudimdental controller layer, not much of an idea of url resolution, and of course youd still have to figure out database/ templating. if you built a whole lot of custom mod_python handlers, youd be tied to a very specific kind of process model and couldnt really branch out into something like fcgi/mod_proxy->WSGI etc. I think you guys have to either be less rigid about your requirements and be willing to get your hands a little dirtier...web.py does seem to be the kind of thing you guys would like, but if it has some issues then youd just have to ....*shudder*....*contribute!* to that project a little bit. its sort of par for the course in the field of open source that youre going to have to be willing to contribute, if not patches, then at least feedback and test cases to the developers for issues found. if youre not willing to do that, you might have to stick with J2EE for now. From half.italian at gmail.com Thu May 31 20:09:12 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 31 May 2007 17:09:12 -0700 Subject: Using PIL to find separator pages In-Reply-To: References: Message-ID: <1180644646.690229.54390@q19g2000prn.googlegroups.com> On May 31, 10:01 am, Larry Bates wrote: > I have a project that I wanted to solicit some advice > on from this group. I have millions of pages of scanned > documents with each page in and individual .JPG file. > When the documents were scanned the people that did > the scanning put a colored (hot pink) separator page > between the individual documents. I was wondering if > there was any way to utilize PIL to scan through the > individual files, look at some small section on the > page, and determine if it is a separator page by > somehow comparing the color to the separator page > color? I realize that this would be some sort of > percentage match where 100% would be a perfect match > and any number lower would indicate that it was less > likely that it was a coverpage. > > Thanks in advance for any thoughts or advice. > > Regards, > Larry Bates I used GraphicsMagick for a similar situation. Once installed you can run `gm identify' to return all sorts of usefull information about the images. In my case I had python call 'gm' to identify the number of colors in each image, then inspect the output and handle the image accordingly. I'll bet PIL could do a similar thing, but in my case I was examining DPX files which PIL can't handle. Either approach will most likely take a bit of time unless you spread the work over several machines. ~Sean From nogradi at gmail.com Tue May 1 07:20:52 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Tue, 1 May 2007 13:20:52 +0200 Subject: zipfile: grabbing whole directories In-Reply-To: <334582.90971.qm@web50808.mail.re2.yahoo.com> References: <334582.90971.qm@web50808.mail.re2.yahoo.com> Message-ID: <5f56302b0705010420l8439544w5aa047148c23c5f2@mail.gmail.com> > The built in zipfile.write doesn't seem to like taking a directory instead > of a filename. > > for example: > for each in listofdir: > archive.write(each) > > blows up when one of the items listed in listofdir is a subdirectory. > > File "/usr/local/lib/python2.4/zipfile.py", line 405, in write > fp = open(filename, "rb") > > is there a mode or a '-r' style param I am missing? I guess what you really want is recursively archive every file in a directory and its subdirectories. If that is the case you can use os.walk to iterate over all such files so you can archive all of them while the directory structure will be preserved. HTH, Daniel From rrr at ronadam.com Thu May 10 01:28:07 2007 From: rrr at ronadam.com (Ron Adam) Date: Thu, 10 May 2007 00:28:07 -0500 Subject: PYDOC replacement. (Was:Sorting attributes by catagory) In-Reply-To: <1178755860.993987.312700@e51g2000hsg.googlegroups.com> References: <1178755860.993987.312700@e51g2000hsg.googlegroups.com> Message-ID: Nick Vatamaniuc wrote: > Ron, > > Consider using epydoc if you can. Epydoc will sort the methods and it > will also let you use custom CSS style sheets for the final HTML > output. Check out the documentation of my PyDBTable module. > http://www.psipy.com/PyDBTable > > -Nick Vatamaniuc Hi Nick, I already have sorting and style sheets taken care of. I'm just trying to get the content of each sub section correct at this point. The overall frame work is finished. I don't think Epydoc can replace the console help() output. The site.py module imports help(), from pydoc.py. That serves as the consoles interactive help mode. When you type help() at the console, you are using pydoc. Some of the differences... Epydoc ------ Output formats: - html files - graphs (requires Graphviz) I like this! - pdf files (requires latex) * Requires explicitly generating files first. * Supports file parsing only instead of introspection. Epydoc is more of a complete application and has many nice features such as the graphs and completeness checks, that will make it better than pydoc for creating more complete pre-generated html documents with less work. Pydoc ===== Output formats: - live interactive console text - live interactive html with a local html server. * no files are generated. (just in the browser cache) * supports custom CSS stylesheets (API data output...) - text - html page - html section (for use in templates) - xml - reST (not yet, but will be easy to do) The reason for having additional output formats is it makes it much easier to use it as a tool to extract documentation from source code to be combined with existing more complete documentation. I am planning on writing output formatters to return docutils and docbook data structures as well. With those, you will be able to convert to latex, pdf, and other formats. The data formats for those are very close to what I'm using, so this should be easy to do. Other side benefits of doing this is that some of the modules in pydoc have been generalized so that they can be used without pydoc. The html server, and the document data and formatter classes, can be used independently of pydoc. The overall total size has not increased much, and it is more modular, maintainable, and extendable. Maintainability is a major concern for any library module or package. Of course it will need to be approved first. ;-) Cheers, Ron From aahz at pythoncraft.com Thu May 31 13:17:25 2007 From: aahz at pythoncraft.com (Aahz) Date: 31 May 2007 10:17:25 -0700 Subject: Off Topic: What is the good book to learn Python ? References: <1180549522.350380.276570@q66g2000hsg.googlegroups.com> Message-ID: In article , kaens wrote: >On 30 May 2007 17:28:39 -0700, Aahz wrote: >> In article , >> kaens wrote: >>> >>>I would also recommend to stay away from any "for dummies" or "in x >>>(hours/days)" books. They can be decent introductory material, but >>>unless you are really really new to programming, you probably wouldn't >>>be getting enough information to justify the cost of the book (and a >>>lot of times they have a lot of bad practices in them) >> >> Maybe you should try actually reading _Python for Dummies_. ;-) > >I haven't read it, maybe I will. I have just noticed that the "for >dummies" books tend to be a bit lacking. Some are; some aren't. Like any broad and rapid-to-market series, there are plenty of books that are pretty bad. But there are also plenty of good Dummies books -- for example, _Personal Finance for Dummies_. Speaking as the co-author of _Python for Dummies_, one of our goals was to write a book that was both different from the other introductory Python books and managed to match the quality of the best of them. I'm not sure we succeeded in the second part, but I do think we did better than the median, if only because between me and David Goodger (our tech editor), we probably made fewer technical mistakes. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From bj_666 at gmx.net Tue May 8 07:29:04 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 08 May 2007 13:29:04 +0200 Subject: Designing a graph study program References: <1178619753.077639.112510@q75g2000hsh.googlegroups.com> <5ab3mgF2o5bfbU1@mid.uni-berlin.de> <1178622700.228390.237310@n59g2000hsh.googlegroups.com> Message-ID: In <1178622700.228390.237310 at n59g2000hsh.googlegroups.com>, andrea wrote: > But I have some design doubts, I'd like to keep the algorithm (for > example bfs) as clean as possible, being independent from the drawing > methods. > And how could I make it step through algorithms without having a more > complicated code? Maybe using threads? Create an API that informs some "observer" about actions like visiting a node, traversing or adding an egde and so on. This way you can register callbacks that translate between the graph and the GUI. If you don't want to change the algorithm or graph and node classes this notification can be injected by wrapper classes to some degree. For very fine grained observation of an algorithm you might try to implement a step by step debugger. Ciao, Marc 'BlackJack' Rintsch From tjreedy at udel.edu Wed May 2 21:27:49 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 2 May 2007 21:27:49 -0400 Subject: Lazy evaluation: overloading the assignment operator? References: <1178133344.415521.118710@n76g2000hsh.googlegroups.com> Message-ID: "sturlamolden" wrote in message news:1178133344.415521.118710 at n76g2000hsh.googlegroups.com... | | Python allows the binding behaviour to be defined for descriptors, | using the __set__ and __get__ methods. I think it would be a major | advantage if this could be generalized to any object, by allowing the | assignment operator (=) to be overloaded. Conceptually, assignment is *not* an operator. Binary operators take two values (of the same type) and produce a third (usually of either the input type or a boolean) that usually depends on both inputs. Assignment does nothing of the sort. In Python, the equal sign is *not* an operator: it is a grammatical symbol. One use of the operator fiction in C is to enable simple chained assignment: a=b=2. Python does this directly without the fiction. C's store-and-test usage can be implemented in Python with a 'purse' class. | One particular use for this would be to implement "lazy evaluation". Since (in Python, at least) operands are evaluated *before* the operator/function is called, I do not see how. | Should there be a PEP to overload the assignment operator? You mean a PEP to make assignment an (pseudo)operation and hence overloadable (as all operators are). That has been proposed and rejected before, more than once, but I don't have a reference handy. Terry Jan Reedy From kyosohma at gmail.com Wed May 9 11:09:57 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 9 May 2007 08:09:57 -0700 Subject: Specification for win32com.client package In-Reply-To: References: <23617.87850.qm@web63415.mail.re1.yahoo.com> <1178715787.220103.245060@e65g2000hsc.googlegroups.com> Message-ID: <1178723397.709258.50350@o5g2000hsb.googlegroups.com> On May 9, 8:25 am, Tim Golden wrote: > kyoso... at gmail.com wrote: > > The wiki idea sounds like a good one. I was thinking about doing some > > kind of Python site about the modules and I think the popular 3rd > > party ones would be a good place to start, maybe starting with win32. > > How much information do you think would need to be on a site like this > > to start out with? > > Someone did start a Python Win32 Wiki recently (check the > python-win32 archives for location etc.) I did mean to put > things on there myself, but real life has taken over. Often, > these things just need someone with a bit of oomph to at > least get the thing going. > > I think what's needed (if you're offering :) is for someone > to put a *framework* in place on such a site which would > make it easy for anyone to come along and fill in the gaps > with their particular 3rd-party app or brand of knowledge. > As I say, someone did start something, but I've not heard > anything from him since then and I haven't found the time > myself. If you were to kick something off and actually get > it going I wouldn't say no. > > TJG I think I found the thread you were talking about: http://mail.python.org/pipermail/python-win32/2007-March/005585.html I went to the site listed: www.wazoozle.com and I see nothing related to python there. In fact, James (the poster) doesn't appear to be listed anywhere either. Very weird. While I am not a wiki wizard, I will look into it. I might be able to bamboozle some free space on my friend's hosting service for such a project. If so, I'll let you know. Mike From Dave.Baum at motorola.com Thu May 10 10:56:03 2007 From: Dave.Baum at motorola.com (Dave Baum) Date: Thu, 10 May 2007 09:56:03 -0500 Subject: newb: Python Module and Class Scope References: <1178805769.658287.178240@q75g2000hsh.googlegroups.com> Message-ID: In article <1178805769.658287.178240 at q75g2000hsh.googlegroups.com>, johnny wrote: > Can a class inside a module, access a method, outside of class, but > inside of the module? > > Eg. Can instance of class a access main, if so how? What is the > scope of "def main()" interms of class A? > > myModule: > > class A: > main() > > def main(): > Yes, class A can access main. The name "main" will be defined at the top level of the module, and is considered a global for that module. Code within that module can access it simply as "main". Code in other modules would have to import the module in order to use symbols within it. For example... ### myModule.py #### class A: def m(): main() def main(): pass ### other.py ### import myModule def main(): pass class B: def o(): main() # calls main() in this module myModule.main() # calls main in myModule Dave From luc.saffre at gmail.com Mon May 7 01:12:01 2007 From: luc.saffre at gmail.com (luc.saffre at gmail.com) Date: 6 May 2007 22:12:01 -0700 Subject: invoke user's standard mail client In-Reply-To: References: <1178266064.922925.125760@y80g2000hsf.googlegroups.com> Message-ID: <1178514721.441025.293230@w5g2000hsg.googlegroups.com> On May 4, 11:42 am, Tim Golden wrote: > I'm going to stick my neck out and say: I doubt > if there's one recognised, approved method. That > would require every email client to have a way > of accepting a command which said "Open up a new > email and put this, this, and this into that field, > that space, and that attachment." Tim, I agree, but I hope that we are both wrong. > I would imagine that Acrobat must special case > known email clients and probably won't work for > some obscure client. Thunderbird, for example, > seems (haven't tried it) to allow for an attachment: > > http://www.mozilla.org/docs/command-line-args.html > > Doubtless Outlook has some equivalent mechanism. After > that, you're down to looking at docs for Eudora, Pine, > etc. That's what I plan to do if you are right. At least for Thunderbird and Outlook... Luc From rridge at caffeine.csclub.uwaterloo.ca Fri May 4 05:06:50 2007 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Fri, 04 May 2007 05:06:50 -0400 Subject: My Python annoyances References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> <1178202431.147195.249790@u30g2000hsc.googlegroups.com> Message-ID: Thorsten Kampe wrote: >He was using /Windows/ Python in Cygwin *chuckle*... Windows Python >says Ctrl-Z because it doesn't know that it's been run from bash where >Ctrl-Z is for job control. No, if you run Windows Python from Cygwin bash CTRL-Z works as the EOF character: ~$ /cygdrive/e/util/python24/python Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> quit 'Use Ctrl-Z plus Return to exit.' >>> ^Z ~$ jobs ~$ python Python 2.5 (r25:51908, Mar 13 2007, 08:13:14) [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> quit Use quit() or Ctrl-D (i.e. EOF) to exit >>> [1]+ Stopped python ~$ Apparently though the Cygwin version of Python now prints the correct message for quit. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From scanepa at gmail.com Mon May 28 03:06:18 2007 From: scanepa at gmail.com (Stefano Canepa) Date: 28 May 2007 00:06:18 -0700 Subject: gui application on cross platform In-Reply-To: <1180332092.551838.258440@z28g2000prd.googlegroups.com> References: <1180332092.551838.258440@z28g2000prd.googlegroups.com> Message-ID: <1180335978.008908.51990@q69g2000hsb.googlegroups.com> On 28 Mag, 08:01, james_027 wrote: > Hi, > > I am using delphi to develop gui application, and wish to make a shift > to python. here are some of my question/concern... > > 1. is python develop gui application a cross platform? just like java > swing? Yes. Qt, wxwidgets and pygtk run on Linux and Windows, don't know about Macs. > 2. delphi makes things easy for me like coding for a specific event on > a specific component, could it be the same for python? Not in the Delphi way but glade/gazpacho are good GUI designer for gtk. I have no experience with qtdesigner or the wx equivalent app. > 3. are there cool library of component like in delphi available for > python that will make database application more usesable? python has dbapi, all DBs look the same, python can also use ORM like SQLObjects and SQLALchemy > 4. where do I start the learning curve? I did some research and I > don't know which one to take among wxwdiget, pygtk, and etc. I tried wxwidgets and pygtk, then I decided to use pygtk but it could be I'll change my mind in the future. Bye sc From gagsl-py2 at yahoo.com.ar Wed May 16 00:45:10 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 16 May 2007 01:45:10 -0300 Subject: url question - extracting (2 types of) domains References: <1179281042.229172.246760@k79g2000hse.googlegroups.com> Message-ID: En Tue, 15 May 2007 23:04:02 -0300, lazy escribi?: > Im trying to extract the domain name from an url. lets say I call > it full_domain and significant_domain(which is the homepage domain) > Eg: url=http://en.wikipedia.org/wiki/IPod , > full_domain=en.wikipedia.org ,significant_domain=wikipedia.org You'll have to find a better definition of "significant_domain". A vaguely related concept would be SOA - Start of Authority. You could issue DNS queries for a SOA record, removing the heading parts until you get a matching answer. See http://www.dnspython.org/ -- Gabriel Genellina From cjlesh at gmail.com Sun May 20 19:55:07 2007 From: cjlesh at gmail.com (cjl) Date: 20 May 2007 16:55:07 -0700 Subject: Newbie Question: python mysqldb performance question Message-ID: <1179705306.956396.261700@a26g2000pre.googlegroups.com> Group: I'm new to python and new to mysql. I have a csv file that is about 200,000 rows that I want to add to a mysql database. Yes, I know that I can do this directly from the mysql command line, but I am doing it through a python script so that I can munge the data before adding it. I have the following example code: conn = MySQLdb.connect(db="database", host="localhost", user="root", passwd="password") c = conn.cursor() reader = csv.reader(open(sys.argv[1])) for row in reader: data1, data2, data3, data4 = row data = (data1,data2,data3,data4) c.execute("""insert into datatable values (%s, %s, %s, %s)""", data) conn.commit() This takes a really long time to execute, on the order of minutes. Directly importing the csv file into mysql using 'load infile' takes seconds. What am I doing wrong? What can I do to speed up the operation? Thanks in advance, cjl From grante at visi.com Wed May 16 00:22:32 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 16 May 2007 04:22:32 -0000 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <1hy2qg3.iqfvwnrvr9kjN%aleax@mac.com> <1hy69gm.eh6m866urk03N%aleax@mac.com> Message-ID: <134l1o8jn9rp24d@corp.supernews.com> On 2007-05-16, Alex Martelli wrote: > Aldo Cortesi wrote: > >> Thus spake Steven D'Aprano (steven at REMOVE.THIS.cybersource.com.au): >> >> > Perhaps you aren't aware that doing something "by eye" is idiomatic >> > English for doing it quickly, roughly, imprecisely. It is the opposite of >> > taking the time and effort to do the job carefully and accurately. If you >> > measure something "by eye", you just look at it and take a guess. >> >> Well, Steve, speaking as someone not entirely unfamiliar with idiomatic >> English, I can say with some confidence that that's complete and utter >> bollocks (idomatic usage for "nonsense", by the way). To do something "by >> eye" means nothing more nor less than doing it visually. Unless you can >> provide a citation to the contrary, please move on from this petty little >> point of yours, and try to make a substantial technical argument instead. > > I can't find any reference for Steven's alleged idiomatic use of "by > eye", either -- _however_, my wife Anna (an American from Minnesota) > came up with exactly the same meaning when I asked her if "by eye" had > any idiomatic connotations, so I suspect it is indeed there, at least in > the Midwest. That's what it means to me (I'm also from the upper midwest). One also hears the phrase "eyeball it" the the same context: "You don't need to measure that, just eyeball it." -- Grant Edwards grante Yow! BARBARA STANWYCK at makes me nervous!! visi.com From bill.simoni at gmail.com Sat May 5 01:23:24 2007 From: bill.simoni at gmail.com (bill.simoni at gmail.com) Date: 4 May 2007 22:23:24 -0700 Subject: mod_python not found properly by Apache (win32) Message-ID: <1178342604.759676.17520@p77g2000hsh.googlegroups.com> I'm unable to get mod_python to work properly on my Windows XP box. Any help would be appreciated. Here is what is installed: Apache 2.2.4 Python 2.5.1 mod_python 3.3.1 for python 2.5 and apache 2.2 Here is the error I get when trying to start apache: Event Type: Error Event Source: Apache Service Description: The Apache service named reported the following error: >>> httpd.exe: Syntax error on line 116 of C:/wamp/Apache2/conf/httpd.conf: Cannot load C:/wamp/Apache2/modules/mod_python.so into server: The specified module could not be found. . The module does exist at that location. My path environment variable does have C:\python25 included, which is where the dll is located. Any ideas? Thanks. From brenNOSPAMbarn at NObrenSPAMbarn.net Sun May 27 14:19:17 2007 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: Sun, 27 May 2007 18:19:17 GMT Subject: Is PEP-8 a Code or More of a Guideline? References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> Message-ID: Carsten Haese wrote: > On Sun, 2007-05-27 at 07:30 +0000, OKB (not okblacke) wrote: >> Underscores are harder to type than any alphanumeric >> character. > > This is a discussion about underscores versus capital letters > denoting the word boundaries in identifiers. How is an underscore > harder to type than a capital letter? It is harder in that the key that has the underscore on it is quite out of the way compared to any letter key. -- --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 newsuser at stacom-software.de Thu May 31 04:52:14 2007 From: newsuser at stacom-software.de (Alexander Eisenhuth) Date: Thu, 31 May 2007 10:52:14 +0200 Subject: Anyone else has seen "forrtl: error (200) ..." In-Reply-To: <1180541778.029551.17350@p77g2000hsh.googlegroups.com> References: <1180541778.029551.17350@p77g2000hsh.googlegroups.com> Message-ID: <465E8CBE.8040409@stacom-software.de> Jason schrieb: > Forrtl indicates that your script is running a Fortran library or > program. Remember that Python exceptions only apply during Python. > If a Fortran DLL performs a divide-by-zero error, or accesses invalid > memory, it will kill the interpreter instead of throwing a Python > exception. With Compaq Visual Fortran, the Fortran library calls can > kill your entire program if a function receives an invalid value. > (Try raising a negative real number to a fractional exponent, for > example.) > > I'd guess that the Fortran code is intercepting the CTRL-C signal and > killing the running script. > > Without knowing anything about your script and the library calls it > makes, I can't give you much advice. There may be little that you can > do, especially if you don't have the Fortran source code in question > and/or can't recompile it. Maybe someone with some Fortran/Python > experience can assist you. > > --Jason > Thanks for that hint. Indeed a extension I'm using in my script uses matlab, and matlab uses (I'm quite sure) fortran. But does that mean, if a fortran dll is loaded, a underlying software layer passes Ctrl+C to the fortran dll instead to python? (I can reproduce that in doing a ctrl+c while my script is currently at time.sleep(10) Thanks, Alexander From tal.no.no.spam at gmail.com Tue May 1 17:50:30 2007 From: tal.no.no.spam at gmail.com (Tal Einat) Date: 1 May 2007 14:50:30 -0700 Subject: Python for Windows other way to getting it? In-Reply-To: <1178055837.723546.228980@n59g2000hsh.googlegroups.com> References: <1178051916.033367.205320@h2g2000hsg.googlegroups.com> <59pp42F2jtk6gU2@mid.uni-berlin.de> <1178055837.723546.228980@n59g2000hsh.googlegroups.com> Message-ID: <1178056230.282600.199660@l77g2000hsb.googlegroups.com> On May 2, 12:43 am, noagbodjivic... at gmail.com wrote: > On May 1, 5:17 pm, "Diez B. Roggisch" wrote: > > > noagbodjivic... at gmail.com schrieb: > > > > Hello > > > I don't have permission to install new application on the PC I'm > > > using, I need a zipped version of python that I can copy on my > > > external drive. Where can I get a zip version? > > >http://www.voidspace.org.uk/python/movpy/ > > > Diez > > Thank you Diez, as a student I was hoping for an open source version. > There are none [good project for an experienced programmer]. But I > have however found an old stand alone version here :http://arctrix.com/nas/python/standalone.html Check out Portable Python: http://www.portablepython.com/ Still in beta status, but quite up-to-date, and free. - Tal Einat From bj_666 at gmx.net Mon May 14 03:45:22 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 14 May 2007 09:45:22 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <7x4pmg716p.fsf@ruckus.brouhaha.com> Message-ID: In <7x4pmg716p.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > Alexander Schmolck writes: >> Plenty of programming languages already support unicode identifiers, > > Could you name a few? Thanks. Haskell. AFAIK the Haskell Report says so but the compilers don't supported it last time I tried. :-) Ciao, Marc 'BlackJack' Rintsch From dborne at gmail.com Thu May 3 16:30:09 2007 From: dborne at gmail.com (Dave Borne) Date: Thu, 3 May 2007 15:30:09 -0500 Subject: How to replace the last (and only last) character in a string? In-Reply-To: <1178202464.201578.211150@c35g2000hsg.googlegroups.com> References: <1178202464.201578.211150@c35g2000hsg.googlegroups.com> Message-ID: <6e42ec490705031330v3c9fa0b7xf145b333befb2568@mail.gmail.com> > Let's suppose > s='12345 4343 454' > How can I replace the last '4' character? If the last '4' will not always be the last character in the string, you could do: 'X'.join(s.rsplit('4',1)) -Dave From sjdevnull at yahoo.com Wed May 16 13:41:17 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 16 May 2007 10:41:17 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464ad388$0$28786$426a34cc@news.free.fr> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179289167.723990.223890@u30g2000hsc.googlegroups.com> <464abd12$0$23364$426a34cc@news.free.fr> <1179307776.953405.207680@l77g2000hsb.googlegroups.com> <464ad388$0$28786$426a34cc@news.free.fr> Message-ID: <1179337277.347833.237450@n59g2000hsh.googlegroups.com> Christophe wrote: > sjdevnull at yahoo.com a ecrit : > > Christophe wrote: > >> sjdevnull at yahoo.com a ecrit : > >>> Steven D'Aprano wrote: > >>>> I would find it useful to be able to use non-ASCII characters for heavily > >>>> mathematical programs. There would be a closer correspondence between the > >>>> code and the mathematical equations if one could write D(u*p) instead of > >>>> delta(mu*pi). > >>> Just as one risk here: > >>> When reading the above on Google groups, it showed up as "if one could > >>> write ?(u*p)..." > >>> When quoting it for response, it showed up as "could write D(u*p)". > >>> > >>> I'm sure that the symbol you used was neither a capital letter d nor a > >>> question mark. > >>> > >>> Using identifiers that are so prone to corruption when posting in a > >>> rather popular forum seems dangerous to me--and I'd guess that a lot > >>> of source code highlighters, email lists, etc have similar problems. > >>> I'd even be surprised if some programming tools didn't have similar > >>> problems. > >> So, it was google groups that continuously corrupted the good UTF-8 > >> posts by force converting them to ISO-8859-1? > >> > >> Of course, there's also the possibility that it is a problem on *your* > >> side > > > > Well, that's part of the point isn't it? It seems incredibly naive to > > me to think that you could use whatever symbol was intended and have > > it show up, and the "well fix your machine!" argument doesn't fly. A > > lot of the time programmers have to look at stack traces on end-user's > > machines (whatever they may be) to help debug. They have to look at > > code on the (GUI-less) production servers over a terminal link. They > > have to use all kinds of environments where they can't install the > > latest and greatest fonts. Promoting code that becomes very hard to > > read and debug in real situations seems like a sound negative to me. > > Who displays stack frames? Your code. Whose code includes unicode > identifiers? Your code. Whose fault is it to create a stack trace > display procedure that cannot handle unicode? You. Thanks but no--I work with a _lot_ of code I didn't write, and looking through stack traces from 3rd party packages is not uncommon. And I'm often not creating a stack trace procedure, I'm using the built-in python procedure. And I'm often dealing with mailing lists, Usenet, etc where I don't know ahead of time what the other end's display capabilities are, how to fix them if they don't display what I'm trying to send, whether intervening systems will mangle things, etc. > Even if you don't > make use of them, you still have to fix the stack trace display > procedure because the exception error message can include unicode text > *today* It can, but having identifiers in portable characters at least allows some ability to navigate the code. Display of strings is safe by default anyway, as they can contain all sorts of data. > You should know that displaying and editing UTF-8 text as if it was > latin-1 works very very well. Given that we've already seen one (fairly simple) character posted in this thread that displayed differently in the HTML view than in the edit--and neither place as the symbol originally intended--I'm going to reserve judgement on this statement. I don't know whether the problem was with Google, my browser, or something else, but I do know that it made interchange of information difficult and that I'm using a fairly recent (within the last 3 years) out-of-the-box setup. > Also, Terminals have support for UTF-8 encodings already. Or you could > always use kate+fish to edit your script on the distant server without > such problems (fish is a KDE protocol used to access a computer with ssh > as if it was a hard disk and kate is the standard text/code editor) It's > a matter of tools. You don't always get to pick your tools. It's very nice to have things work with standard setups, be they brand new Windows boxes or the c. 1993 mail server in the office or your wife's handheld that you've grabbed to help do emergency troubleshooting from your vacation or whatever. From paddy3118 at googlemail.com Sat May 19 02:03:32 2007 From: paddy3118 at googlemail.com (Paddy) Date: 18 May 2007 23:03:32 -0700 Subject: Trying to choose between python and java In-Reply-To: References: Message-ID: <1179554612.273764.106050@q75g2000hsh.googlegroups.com> On May 16, 2:21 am, Anthony Irwin wrote: > Hi All, > > Thanks to all that replied. > > I saw on the python site a slide from 1999 that said that python was > slower then java but faster to develop with is python still slower > then java? Short answer: It might be. Long answer: There are a lot of active libraries and frameworks out their that attack common speed problems. For example numpy allows C-type speeds of execution of some numerical applications. Note its not fast if it is wrong, and Python may allow you to tune your algorithm with more ease. - Paddy. From nagle at animats.com Tue May 15 13:44:37 2007 From: nagle at animats.com (John Nagle) Date: Tue, 15 May 2007 10:44:37 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers - ambiguity issues In-Reply-To: <4649E730.9000609@web.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649BC4C.10200@web.de> <1179238847.407605.4620@w5g2000hsg.googlegroups.com> <4649C63C.1030508@web.de> <1179242328.800088.246620@h2g2000hsg.googlegroups.com> <4649D4A5.5060102@web.de> <1179247724.234869.47310@l77g2000hsb.googlegroups.com> <4649E730.9000609@web.de> Message-ID: There are really two issues here, and they're being confused. One is allowing non-English identifiers, which is a political issuer. The other is homoglyphs, two characters which look the same. The latter is a real problem in a language like Python with implicit declarations. If a maintenance programmer sees a variable name and retypes it, they may silently create a new variable. If Unicode characters are allowed, they must be done under some profile restrictive enough to prohibit homoglyphs. I'm not sure if UTS-39, profile 2, "Highly Restrictive", solves this problem, but it's a step in the right direction. This limits mixing of scripts in a single identifier; you can't mix Hebrew and ASCII, for example, which prevents problems with mixing right to left and left to right scripts. Domain names have similar restrictions. We have to have visually unique identifiers. There's also an issue with implementations that interface with other languages. Some Python implementations generate C, Java, or LISP code. Even CPython will call C code. The representation of external symbols needs to be standardized across those interfaces. John Nagle From maxwell at umiacs.umd.edu Wed May 2 14:11:11 2007 From: maxwell at umiacs.umd.edu (maxwell@ldc.upenn.edu) Date: 2 May 2007 11:11:11 -0700 Subject: gpp (conditional compilation) In-Reply-To: <1178127460.046945.254100@y80g2000hsf.googlegroups.com> References: <1178127460.046945.254100@y80g2000hsf.googlegroups.com> Message-ID: <1178129471.169223.17850@y80g2000hsf.googlegroups.com> (replying to myself because I got four good replies) Wow! That was fast! OK, I'll try out these ideas, and many thanks! Mike Maxwell From jjl at pobox.com Fri May 25 14:28:51 2007 From: jjl at pobox.com (John J. Lee) Date: Fri, 25 May 2007 18:28:51 GMT Subject: email modul with writing to mboxes (and locking) for python 2.4.*? References: Message-ID: <87veeg4v0q.fsf@pobox.com> Matej Cepl writes: > Is there somewhere support for the extension of email module, > which would support writing to (and creating new) mbox folders > (with all bells and whistles, like locking)? It seems to me that > current (Python 2.4.*, I even tried email package > 4.0.2 from python.org email SIG) implementation is read-only, am > I right? > > Thanks for any reply, > > Matej Cepl Not sure whether you know this already, but module mailbox in Python 2.5 supports writing mbox folders. If it's not 2.4 compatible, it's fairly likely to be an easy backport. John From john at datavoiceint.com Tue May 15 14:28:12 2007 From: john at datavoiceint.com (HMS Surprise) Date: 15 May 2007 11:28:12 -0700 Subject: Splitting a string Message-ID: <1179253692.110024.96330@w5g2000hsg.googlegroups.com> The string s below has single and double qoutes in it. For testing I surrounded it with triple single quotes. I want to split off the portion before the first \, but my split that works with shorter strings does not seem to work with this one. Ideas? Thanks, jvh s = ''''D132258\',\'\', \'status=no,location=no,width=630,height=550,left=200,top=100\')" target="_blank" class="dvLink" title="Send an Email to selected employee">''' t = s.split('\\') From eugene.vandenbulke at gmail.com Thu May 31 05:39:25 2007 From: eugene.vandenbulke at gmail.com (EuGeNe Van den Bulke) Date: Thu, 31 May 2007 11:39:25 +0200 Subject: file / module / package - import problem References: <1180558195.130303.310160@k79g2000hse.googlegroups.com> Message-ID: aspineux wrote: > import os.path > > file=open(os.path.join(os.path.dirname(__file__), 'hauteur.yaml')) Thanks that worked ;) From gerdusvanzyl at gmail.com Sat May 12 16:52:03 2007 From: gerdusvanzyl at gmail.com (Gerdus van Zyl) Date: 12 May 2007 13:52:03 -0700 Subject: Optimizing numpy Message-ID: <1179003123.707683.37360@y80g2000hsf.googlegroups.com> I have the following, that is used to convert pixel data and thus should be as fast as possible: b = numpy.ndarray (shape=(w,h,4), dtype=numpy.uint8) a = numpy.frombuffer(buf, numpy.uint8) a.shape = (w, h, 3) b[:,:,0] = a[:,:,2] b[:,:,1] = a[:,:,1] b[:,:,2] = a[:,:,0] b[:,:,3] = 255 Can anyone tell me if there is a faster way? Will making use of weave.blitz or pyrex help? Thank You. From theller at ctypes.org Wed May 16 12:16:45 2007 From: theller at ctypes.org (Thomas Heller) Date: Wed, 16 May 2007 18:16:45 +0200 Subject: calldll for Python 2.5 In-Reply-To: References: Message-ID: Larry Bates schrieb: > I've implemented several libraries using calldll (originally on > Python 2.2) and posted recipe on ASPN for a general implementation > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146847. > If I were doing it over again today, I would use ctypes, but I > have thousands of lines of library code that are dependent on > calldll. Anyone out there have a version that works with Python > 2.5 so I don't have to a massive rewrite? Can't you write a calldll replacement with ctypes? Thomas From Dicky.Links5 at gmail.com Tue May 22 01:17:04 2007 From: Dicky.Links5 at gmail.com (Dicky.Links5 at gmail.com) Date: 21 May 2007 22:17:04 -0700 Subject: ^? Ron Jeremeys Dick Gets Longer! Message-ID: <1179811024.413786.177400@b40g2000prd.googlegroups.com> http://stentorinternet.info - Animated Flash on Ron jeremies dick stuffin a young 19yr old chick. From miles.chris at gmail.com Tue May 15 09:15:54 2007 From: miles.chris at gmail.com (Chris Miles) Date: 15 May 2007 06:15:54 -0700 Subject: PyObject_Print in gdb Message-ID: <1179234954.101397.247260@o5g2000hsb.googlegroups.com> I've been using gdb to debug some Python extension modules lately, which has been very handy, but cannot get PyObject_Print() to work from within gdb, as recommended by http://wingware.com/doc/howtos/debugging-extension-modules-on-linux It recommends using "p PyObject_Print (obj, stderr, 0)" but stderr (and stdout) symbols are never available for me. (gdb) p args $2 = (PyObject *) 0x405030 (gdb) p PyObject_Print (args, stderr, 0) No symbol "stderr" in current context. (gdb) p PyObject_Print (args, stdout, 0) No symbol "stdout" in current context. Any tips on how to reference the stdout/stderr file pointers within gdb? Cheers, Chris From bj_666 at gmx.net Mon May 7 08:55:27 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 07 May 2007 14:55:27 +0200 Subject: long lists References: <1178522894.357829.28250@u30g2000hsc.googlegroups.com> <1178540073.988964.196860@w5g2000hsg.googlegroups.com> Message-ID: In <1178540073.988964.196860 at w5g2000hsg.googlegroups.com>, Merrigan wrote: > The Script it available at this url : http://www.lewendewoord.co.za/theScript.py > > P.S. I know it looks like crap, but I'm a n00b, and not yet through > the OOP part of the tutorial. One spot of really horrible runtime is the `comp_are()` function, it has quadratic runtime. Why the funny spelling BTW? Why are you binding the objects to new names all the time and calling `str()` repeatedly on string objects? The names `a`, `b` and `fn2up` are unnecessary, you can use `file1`, `file2` and `filename` instead. And ``str(str(b))`` on a string object is a no-operation. It's the same as simply writing ``b``. Those two nested ``for``-loops can be replaced by converting both lists into `set()` objects, calculating the difference and convert back to a sorted list: def compare(remote, local): return sorted(set(local) - set(remote)) Ciao, Marc 'BlackJack' Rintsch From jzgoda at o2.usun.pl Fri May 25 10:54:22 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 25 May 2007 16:54:22 +0200 Subject: just a bug In-Reply-To: References: <1179841504.782279.86490@u36g2000prd.googlegroups.com> <1180082137.329142.45350@p77g2000hsh.googlegroups.com> <1180090985.066935.218250@h2g2000hsg.googlegroups.com> Message-ID: Maksim Kasimov napisa?(a): >> 'utf8' codec can't decode bytes in position 176-177: invalid data >>>>> iMessage[176:178] >> '\xd1]' >> >> And that's your problem. In general you can't just truncate a utf-8 >> encoded string anywhere and expect the result to be valid utf-8. The >> \xd1 at the very end of your CDATA section is the first byte of a >> two-byte sequence that represents some unicode code-point between \u0440 >> and \u047f, but it's missing the second byte that says which one. > > > in previous message i've explain already that the situation widely > appears with > memory limited devices, such as mobile terminals of Nokia, SonyEriccson, > Siemens and so on. > > and i've notice you that it is a part of a splited string. No, it is not a part of string. It's a part of byte stream, split in a middle of multibyte-encoded character. You cann't get only dot from small letter "i" and ask the parser to treat it as a complete "i". -- Jarek Zgoda http://jpa.berlios.de/ From walterbyrd at iname.com Sat May 12 19:12:10 2007 From: walterbyrd at iname.com (walterbyrd) Date: 12 May 2007 16:12:10 -0700 Subject: Newbie look at Python and OO In-Reply-To: References: <1178812734.860473.236370@y80g2000hsf.googlegroups.com> <1346hrvgve90nea@corp.supernews.com> <1178939255.996029.263520@p77g2000hsh.googlegroups.com> Message-ID: <1179011530.325161.317380@l77g2000hsb.googlegroups.com> > > You started this thread with a list of conceptual problems you were > having. Are they now cleared up? > Yes. Thank you, and everybody else. I'm still learning, and still getting used to Python. But, I understand the concepts that I was having trouble with before. From kyosohma at gmail.com Wed May 23 15:47:41 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 23 May 2007 12:47:41 -0700 Subject: Resizing listbook's listview pane In-Reply-To: <1179939217.550237.300830@o5g2000hsb.googlegroups.com> Message-ID: <1179949661.695477.167450@m36g2000hse.googlegroups.com> On May 23, 11:53 am, mkPyVS wrote: > On May 23, 9:04 am, kyoso... at gmail.com wrote: > > > Which Python gui toolkit are you using? Tkinter, wxPython, pyQT? Are > > you wanting the resize to happen programmatically, when the user > > changes the app's size, both or what? > > > More details would be helpful. > > > Mike > > Sorry, copied from wxpython submit as well.. I'm using wxpython 2.8... > Primariy I want the resize to happen programatically during object > creation/post creation... I can worry about app size changes later. > > Thanks, Wow! You sure like to post a lot! Sheesh! I subscribe to the wxPython user's group and I don't see your post anywhere. I can't find much documentation for this control either. The demo seems to have a way to change the size of one of the panels using the method "SetSize" though. I recommend trying the wxPython group again though. Mike From admin at loial.co.uk Tue May 1 08:43:37 2007 From: admin at loial.co.uk (loial) Date: 1 May 2007 05:43:37 -0700 Subject: Store variable name in another variable In-Reply-To: <4631120a$0$27375$ba4acef3@news.orange.fr> References: <1177592072.498517.139260@b40g2000prd.googlegroups.com> <4631120a$0$27375$ba4acef3@news.orange.fr> Message-ID: <1178023417.680239.156910@n59g2000hsh.googlegroups.com> OK, I have it working with dictionaries. However I have another scenerio : I am reading a file containing records like the following : .. .. I need to substitute MYVARIABLE with the current value of MYVARIABLE in my python script and write the file out again. The file may contain many more lines and many substitution values on any line Assuming that MYVARIABLE is currently set to JOHN then the output would be Can this be done in Python? Amending the way the variable names are distinguished in the incoming file is possible if that would help. On 26 Apr, 22:02, Laurent Pointal wrote: > Cameron Laird wrote: > > In article , > > Laurent Pointal wrote: > >>loial a ?it : > >>> I need to store a list ofvariablenames in a dictionary or list. I > >>> then later need to retrieve the names of the variables and get the > >>> values from the named variables. The named variables will already have > >>> been created and given a value. > > >>"Named variables will already have been created"... in what namespace ? > > >>Store a list of names -> dict/list (see tutorial) > > >>Then, > >>use namespace.name > >>or getattr(namespace,"name") > >>or locals()["name"] > >>or globals()["name"] > > > admin, I want to be sure you understand the advice you've been given. > > Yes, it is possible to "double dereference" through named variables; > > HOWEVER, it is essentially *never* advantageous to do so in application > > programming with Python (nor is it in Perl and PHP, despite what many > > senior people there teach). Use a dictionary, perhaps one with > > multi-dimensional keys. > > Yes, I understand. I just reply to OP question not searching the reason why > he wants to manage *variables* this way (he talk about dict, so I hope he > know that they can be used to map names to values). > So, this is not an advice, just technical ways related to the question as it > was written. > > And yes, personnally i use dictionnaries for such purpose. > > A+ > > Laurent.- Hide quoted text - > > - Show quoted text - From mr_gees100_peas at yahoo.com Sun May 6 16:12:14 2007 From: mr_gees100_peas at yahoo.com (mr_gees100_peas) Date: Sun, 06 May 2007 20:12:14 -0000 Subject: using boost to extend python with c++ Message-ID: Hi, I've been trying for days to make either boost.python or swig to work for me. The one I have gotten the closest to is boost. Note that this is for windows XP. I'm not much of an unix person besides doing simple ls and copy paste. What I have done is to download the boost library: C:\boost_1_34_0 I downloaded the bjam library: C:\boost-jam-3.1.14-1-ntx86 I then set up the path so that I could do bjam from anywhere suing the coomand prompt. Did the same for python and g++. I'm using the g++ that came with bloodshed DevC++ compiler. So, I navigated myself to the tutorial example in the boost library. C:\boost_1_34_0\libs\python\example\tutorial In the command prompt I typed bjam and I got the following error message. C:\boost_1_34_0\libs\python\example\tutorial>bjam Jamroot:17: in modules.load rule python-extension unknown in module Jamfile. C:/boost_1_34_0/tools/build/v2/build\project.jam:312: in load-jamfile C:/boost_1_34_0/tools/build/v2/build\project.jam:68: in load C:/boost_1_34_0/tools/build/v2/build\project.jam:170: in project.find C:/boost_1_34_0/tools/build/v2\build-system.jam:237: in load C:\boost_1_34_0\libs\python\example\..\..\..\tools\build\v2/kernel\modules.jam:261: in import C:\boost_1_34_0\libs\python\example\..\..\..\tools\build\v2/kernel/bootstrap.jam:132: in boost-build C:\boost_1_34_0\libs\python\example\boost-build.jam:7: in module scope I've have been trying desperately for 3 days. I also tried swig with similar results but I feel I'm closer to solving the issue with boost than with swig. I'm at a total lost here. I have tried the tutorials in the boost web page but I just don't get anywhere. http://www.boost.org/libs/python/doc/tutorial/doc/html/python/hello.html From krw at att.bizzzz Mon May 7 17:00:01 2007 From: krw at att.bizzzz (krw) Date: Mon, 7 May 2007 17:00:01 -0400 Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> <08qk33t594ih0ulmjmev90d22lkfnotgoe@4ax.com> <463C2A3A.8332D211@hotmail.com> <0k8p33h90bp5tfajedb4bmd2eik8gfi2ho@4ax.com> Message-ID: In article , quasi at null.set says... > On Mon, 7 May 2007 10:55:55 -0400, James Beck > wrote: > > >In article <0k8p33h90bp5tfajedb4bmd2eik8gfi2ho at 4ax.com>, quasi at null.set > >says... > >> On Sat, 05 May 2007 07:54:50 +0100, Eeyore > >> wrote: > >> > >> > > >> > > >> >quasi wrote: > >> > > >> >> Gib Bogle wrote: > >> >> > >> >> >Ah, so the firefighters were in on the conspiracy! > >> >> > >> >> No, but the firefighters are very much aware that there is more to > >> >> 9/11 than has been officially revealed. > >> >> > >> >> This is even more true at Pentagon. The firefighters there brought > >> >> dogs trained to search for survivors and/or remains > >> > > >> >Sounds like good practice. > >> > > >> > > >> >> and found nothing. > >> > > >> >And the significance of this is ? > >> > >> The plane was supposed to have passengers. > >> > >> quasi > >> > >Yep, and they found them all, therefore, there were none for the dogs to > >find. > > You pretty much made that up. > > They found nothing -- no bodies, no body parts, no blood, no bones, no > luggage, no rings (do gold rings melt at jet fuel temperatures?), no > jewelry (do diamonds melt at jet fuel temperatures?), no plane seats, > no silverware (ok, maybe they only had plastic). In other words, an > immediate mystery to the firefighters was the lack of any indication > that the plane had passengers. Even if you believe that most of the > passengers were essentially incinerated, it's not believable that all > of them were. Some of the bodies should have been recoverable right at > the scene. If none of the passenger's remains were ever found, why all the fuss last year when they found more. IOW, you're a liar. > > Weeks later, parts of the wreckage were supposedly "analyzed" at a > government lab, and the official report claims they were able to > isolate DNA for many of the passengers. It doesn't ring true. > ...and a fool. -- Keith From Thomas.Lenarz at netcologne.de Mon May 21 12:28:36 2007 From: Thomas.Lenarz at netcologne.de (Thomas Lenarz) Date: Mon, 21 May 2007 16:28:36 GMT Subject: Python and GUI References: <1179761984.704369.116310@b40g2000prd.googlegroups.com> Message-ID: <4651c308.2576916@news.netcologne.de> On 21 May 2007 08:39:44 -0700, sdoty044 at gmail.com wrote: >All I am doing is prompting users for some data (listbox, radio >buttons, text box, ect...). Then I will have some text output, maybe >a scrolling text message as things are happening. > >I have some minor things I need to do, for example, if Checkbutton X >is clicked, I need to disable TextBox Y, and I would like to display >the scrolling text (output) > You should be able to do all those things with TKInter (though I am not sure about the automatted scrolling text.). >Ultimately, is it worth downloading and learning some of the packages >avaiable for Python, or should I just stick to the Tkinter stuff that >is included. Like Brad, I would recommend trying wxPyhton (http://www.wxpython.org/). There is an installer for Windows. Best is to look at the wxPython-Demo first thing. It contains a lot of example-code to borrow from. You can both read and try the code within the Demo-Application. However, the documentation of the class-library is for C++ only. You have to apply it to the python-version yourself. I prefer wxPython to TKInter because it offers more complex widgets namely Grids and Tabular-Lists right out of the box. Best wishes, Thomas From Graham.Dumpleton at gmail.com Thu May 17 18:46:49 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: 17 May 2007 15:46:49 -0700 Subject: Is wsgi ready for prime time? In-Reply-To: References: <1179426728.846565.51390@h2g2000hsg.googlegroups.com> Message-ID: <1179442008.580735.10870@k79g2000hse.googlegroups.com> On May 18, 5:31 am, Stefan Sonnenberg-Carstens wrote: > IMHO WSGI is _only_ a new way of talking to webservers, like apache. > It is as low-level as (f)cgi, so don't expect too much support at this > stage - > indeed a module like the cgi one in the std lib would be nice. > As google uses it (mod_wsgi), I would suspect you can use it. So people don't get the wrong impression, mod_wsgi is merely hosted on the Google code site. This does not mean that Google uses it, nor does Google have anything to do with its development. Graham From rridge at caffeine.csclub.uwaterloo.ca Sat May 5 04:14:40 2007 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Sat, 05 May 2007 04:14:40 -0400 Subject: My Python annoyances References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> <1178202431.147195.249790@u30g2000hsc.googlegroups.com> Message-ID: Ben Collver wrote: >It is problem report #1678102. I understand the problem: that a 32 bit >number looks different in a 32 bit signed int than in a 64 bit signed >int. However, the workaround of dropping a bit seems to defeat the >purpose of using a CRC. The workaround doesn't drop any bits, it converts the value to a Python long and extracts the lower 32 bits. There's really no good reason for Python to give two different results here. It should either return a signed 32-bit CRC value in a Python int, or return a unsigned 32-bit CRC value in either Python long or a Python int, if it's big enough. What it's doing now, returning unsigned value in a Python int, even when it's not big enough to hold the result, is wrong. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From lanwrangler at gmail.com Wed May 2 05:36:06 2007 From: lanwrangler at gmail.com (lanwrangler at gmail.com) Date: 2 May 2007 02:36:06 -0700 Subject: Comparing bitmap images for differences? In-Reply-To: <59p1unF2lje91U1@mid.uni-berlin.de> References: <1178024505.768505.262270@h2g2000hsg.googlegroups.com> <59p1unF2lje91U1@mid.uni-berlin.de> Message-ID: <1178098566.836135.193430@o5g2000hsb.googlegroups.com> On May 1, 3:42 pm, "Diez B. Roggisch" wrote: > With that, you can approach your problem. What is usually done is that a > sequence of background images is sampled & an average is built. Then the > actual image is subtracted from that image, with an epsilon to account > for noise. Thanks for the tip for an algorithm - I can see how that could work really nicely (and it gives me some ideas for other things, too!) Thanks also for the link to the OpenCV bindings. I'll give 'em a try and see what happens. Regards, Matthew. From martin at v.loewis.de Sun May 20 13:48:45 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 20 May 2007 19:48:45 +0200 Subject: Python compared to other language In-Reply-To: References: <1179540061.598417.13870@y80g2000hsf.googlegroups.com> <1179555855.410877.51390@k79g2000hse.googlegroups.com> <1179590470.964307.105720@l77g2000hsb.googlegroups.com> Message-ID: <465089FD.8040606@v.loewis.de> >> But that is my point. With Python, the language itself takes care of >> the platform differences, so the same Python code will run on >> different platforms. I realize that, at a lower level, everything is >> done is C. But, from the developers point of view: developing code in >> C requires more attention to platform specifics, than does developing >> code in Python. >> > That I can agree with, but it isn't the same as "not portable". It > would have been better to say "more difficult to port". Indeed, there are significant chunks (several hundred lines of code) that are specific to Microsoft Windows; also, there are some modules (e.g. nis, passwd) which solely run on Unix systems. This code is inherently unportable. In some cases, there is alternative code for other platforms, in some cases, there isn't. In Python itself, the fraction of platform-specific code is still small (I think - one would have to count to be sure). This is partly due to Python only using file and network IO from the system, and these two system-dependent aspects have fairly standard APIs even on the C level (POSIX in particular). GUI is much harder - in Tk, the amount of system-specific code is significant (ca. 80 kLOC specific to either Unix, Windows, or Mac, compared to 240 kLOC total, for Tk 8.4.7). Fortunately, Python abstains from implementing its own cross-platform GUI library, and offloads that burden to third-party libraries. Regards, Martin From devicerandom at gmail.com Thu May 24 12:53:09 2007 From: devicerandom at gmail.com (massimo s.) Date: 24 May 2007 09:53:09 -0700 Subject: of destructors, open files and garbage collection In-Reply-To: References: <1180021256.619953.80500@q66g2000hsg.googlegroups.com> Message-ID: <1180025589.199194.246410@g4g2000hsf.googlegroups.com> > Relying on the `__del__()` method isn't a good idea because there are no > really hard guaranties by the language if and when it will be called. Ok, I read the __del__() docs and I understand using it is not a good idea. I can easily add a close_files() method that forces all dangling files to be closed. It would be useful in a number of other possible situations. However, as rightly pointed out by the exhaustive answer of Paul Moore, tracking references of my objects would be very useful. How can I do that? From steven at REMOVE.THIS.cybersource.com.au Mon May 14 22:35:04 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 15 May 2007 02:35:04 GMT Subject: Sorting troubles References: <1179158708.433792.127150@h2g2000hsg.googlegroups.com> <1179161396.220858.86150@q75g2000hsh.googlegroups.com> Message-ID: On Mon, 14 May 2007 09:49:56 -0700, Thomas Nelson wrote: > The thing is that [x for x in List[1:]...] is a brand new list created > by iterating over the old one. > How about: > qSortHelp(List): > newlist = qSort(List) > for i, val in enumerate(newlist): > List[i] = val > You have to iterate over one more time, but this sorts the list in > place. A better way of spelling that would be: def qSortHelp(List): List[:] = qSort(List) return List but the helper function is redundant, as it is easy enough to make the qSort function behave the same way. We can also make the code a smidgen more concise by reversing the sense of the test at the start of the code: def qSort(List): if List: List[:] = qSort([x for x in List[1:] if x< List[0]]) \ + List[0:1] + qSort([x for x in List[1:] if x>=List[0]]) return List -- Steven. From deepns7 at gmail.com Fri May 4 03:03:44 2007 From: deepns7 at gmail.com (pradeep nair) Date: 4 May 2007 00:03:44 -0700 Subject: How to find the present working directory using python. Message-ID: <1178262224.269446.69410@c35g2000hsg.googlegroups.com> how to find out the present working directory using python. os.system('pwd') works good. But i need some specific one in python rather than embedding shell command into python. From pydecker at gmail.com Sun May 13 19:51:55 2007 From: pydecker at gmail.com (Peter Decker) Date: Sun, 13 May 2007 19:51:55 -0400 Subject: GUI tutorial In-Reply-To: <20070513175141.GD4044@spookie1.spookiegate> References: <20070513175141.GD4044@spookie1.spookiegate> Message-ID: On 5/13/07, John K Masters wrote: > Can someone point me in the direction of a good tutorial on programming > python with a GUI? I'm just starting out with python and have written a > few scripts successfully but would like to add a graphical front end to > them to make it easier for my work colleagues, most of whom have never > used a command line, to use. Take a look at the Dabo screencasts. They illustrate very well how easy it is to create GUIs using visual tools instead of in code. Of course, you can still create them in code if you like, but where's the fun in that? :) http://dabodev.com/documentation -- # p.d. From openopt at ukr.net Mon May 21 09:14:18 2007 From: openopt at ukr.net (dmitrey) Date: 21 May 2007 06:14:18 -0700 Subject: howto get function from module, known by string names? In-Reply-To: References: <1179228596.349933.168610@l77g2000hsb.googlegroups.com> Message-ID: <1179753257.882631.185150@z24g2000prd.googlegroups.com> And howto check does module 'asdf' exist (is available for import) or no? (without try/cache of course) Thx, D. Carsten Haese wrote: > On 15 May 2007 04:29:56 -0700, dmitrey wrote > > hi all, > > can anyone explain howto get function from module, known by string > > names? > > I.e. something like > > > > def myfunc(module_string1, func_string2, *args): > > eval('from ' + module_string1 + 'import ' + func_string2') > > return func_string2(*args) > > To find a module by its name in a string, use __import__. To find an object's > attribute by its name in a string, use getattr. > > Together, that becomes something like this: > > >>> def myfunc(module_string1, func_string2, *args): > ... func = getattr(__import__(module_string1), func_string2) > ... return func(*args) > ... > >>> myfunc("math", "sin", 0) > 0.0 > >>> myfunc("operator", "add", 2, 3) > 5 > > Hope this helps, > > -- > Carsten Haese > http://informixdb.sourceforge.net From jeff at jmcneil.net Sat May 19 22:40:53 2007 From: jeff at jmcneil.net (Jeff McNeil) Date: Sat, 19 May 2007 22:40:53 -0400 Subject: interesting dict bug In-Reply-To: <2adc542f0705191927u799da2ak9e884cef53f15979@mail.gmail.com> References: <2adc542f0705191927u799da2ak9e884cef53f15979@mail.gmail.com> Message-ID: <82d28c40705191940m261a12f5n9e118f871ad21971@mail.gmail.com> Filename is a unicode string. See http://www.diveintopython.org/xml_processing/unicode.html or http://docs.python.org/tut/node5.html#SECTION005130000000000000000. 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. >>> s = "string" >>> unicode(s) u'string' >>> You're not seeing the 'u' in the 'print filename' line as it isn't actually part of the data. You will see it in the 'print params2' output, though, as I believe it relies on the string object's __repr__ function, which will include the unicode specifier. -Jeff On 5/19/07, Sick Monkey wrote: > Here is a segment of some code that I have. > CODE: > -------------- > print filename > params2 = > {'filename':filename,'id3title':title,'id3artist':artist,'id3album':album,'id3year':year,'id3track':track,'id3genre':genre,'uname':username,'password':password,'filesToUpload':open(file, > 'rb')} > print params2 > ---------------- > OUTPUT: > 01.mp3 > {'password': u'XXX', 'id3year': '2002', 'id3album': 'album, 'id3title': > 'Lose Yourself', 'filename': u'01.mp3', 'uname': u'', 'id3genre': > 'Soundtrack', 'id3artist': 'Eminem', 'filesToUpload': u'/Users/ozdon/Music/test2/01- eminemhhh.mp3', mode 'rb' at 0x106a5c0>, > 'id3track': 'Unknown'} > -------------- > Does anyone know how the random " u' " is getting into the params2 or know > how to around this? > > I am using Python 2.5 on MacOSX. > > > -- > http://mail.python.org/mailman/listinfo/python-list > From jaysherby at gmail.com Wed May 30 01:59:33 2007 From: jaysherby at gmail.com (BlueJ774) Date: 29 May 2007 22:59:33 -0700 Subject: "is" and == In-Reply-To: References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> Message-ID: <1180504773.374529.161740@q66g2000hsg.googlegroups.com> On May 30, 12:57 am, Erik Max Francis wrote: > BlueJ774 wrote: > > Can someone please explain to me the difference between the "is" > > keyword and the == boolean operator. I can't figure it out on my own > > and I can't find any documentation on it. > > > I can't understand why this works: > > > if text is None: > > > and why this always returns false: > > > if message is 'PING': > > > even when message = 'PING'. > > > What's the deal with that? > > `x is y` means the same thing as: > > id(x) == id(y) > > You use the `is` operator for when you're testing for _object identity_, > not value. `None` is a special object sentinel that is not only a value > but a special _object_, and so if you're testing whether or not an > object is `None`, you do so with the `is` operator. > > If you're testing whether an object is equal to the string "PING" then > you do not want to do so by identity, but rather value, so you use the > `==` operator, not `is`. > > -- > Erik Max Francis && m... at alcyone.com &&http://www.alcyone.com/max/ > San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis > You could have another fate / You could be in another place > -- Anggun Thanks. That's exactly what I was looking for. From lyoshaM at gmail.com Wed May 23 15:24:21 2007 From: lyoshaM at gmail.com (Lyosha) Date: 23 May 2007 12:24:21 -0700 Subject: Inheriting from Python list object(type?) In-Reply-To: <1179947949.769537.91920@r3g2000prh.googlegroups.com> Message-ID: <1179948261.685010.40300@a26g2000pre.googlegroups.com> On May 23, 12:19 pm, Lyosha wrote: > On May 23, 12:07 pm, Mangabasi wrote: > > > On May 23, 1:43 pm, "Jerry Hill" wrote: > > > > On 23 May 2007 11:31:56 -0700, Mangabasi wrote: > > > > > When I modified this to: > > > > > class Point(list): > > > > def __init__(self,x,y): > > > > super(Point, self).__init__([x, y]) > > > > self.x = x > > > > self.y = y > > > > > It worked. > > > > Are you sure? > > > > >>> p = Point(10, 20) > > > >>> p > > > [10, 20] > > > >>> p.x > > > 10 > > > >>> p.x = 15 > > > >>> p > > > [10, 20] > > > >>> p[0] > > > 10 > > > >>> p.x > > > 15 > > > > That doesn't look like what you were asking for in the original post. > > > I'm afraid I don't know anything about numpy arrays or what special > > > attributes an object may need to be put into a numpy array though. > > > > -- > > > Jerry > > > This is the winner: > > > class Point(list): > > def __init__(self, x, y, z = 1): > > super(Point, self).__init__([x, y, z]) > > self.x = x > > self.y = y > > self.z = z > > [...] > > http://docs.python.org/dev/whatsnew/node3.htmlannounces named tuples > in python2.6. This is not what you want since tuples are immutable, > but you might get some inspiration from their implementation. Or > maybe not. Dude, google groups suck! They say "an error has occurred" and the message is happily posted. From jstroud at mbi.ucla.edu Sat May 5 08:45:39 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 05 May 2007 05:45:39 -0700 Subject: Firefighters at the site of WTC7 "Move away the building is going to blow up, get back the building is going to blow up." In-Reply-To: References: <1178161820.731367.264500@y80g2000hsf.googlegroups.com> <1hlj33p6aq838o2urk1dv6h75b5is4i2vd@4ax.com> <3TD_h.219$mR2.195@newssvr22.news.prodigy.net> <1178329932.455122.161530@u30g2000hsc.googlegroups.com> <1178346041.557106.129670@y80g2000hsf.googlegroups.com> Message-ID: jmfbahciv at aol.com wrote: > In article <1178346041.557106.129670 at y80g2000hsf.googlegroups.com>, > MooseFET wrote: >> On May 4, 8:19 pm, James Stroud wrote: >>> MooseFET wrote: >> Groucho Marx. > > Give that man a cigar. > > /BAH > Please take note aspiring humorists, we have here an actual example of humor. From mattnuzum at gmail.com Mon May 21 16:42:14 2007 From: mattnuzum at gmail.com (Matthew Nuzum) Date: 21 May 2007 13:42:14 -0700 Subject: Python Web Programming - looking for examples of solid high-traffic sites In-Reply-To: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> Message-ID: <1179780134.444059.147650@r3g2000prh.googlegroups.com> On May 16, 4:04 pm, Victor Kryukov wrote: > Hello list, > > our team is going to rewrite our existing web-site, which has a lot of > dynamic content and was quickly prototyped some time ago. See #3 below > Our main requirement for tools we're going to use is rock-solid > stability. As one of our team-members puts it, "We want to use tools > that are stable, has many developer-years and thousands of user-years > behind them, and that we shouldn't worry about their _versions_." > TurboGears, Django and Pylons are all nice, and provides rich features > - probably too many for us - but, as far as we understand, they don't > satisfy the stability requirement - Pylons and Django hasn't even > reached 1.0 version yet. See #3 below > And their provide too thick layer - we want > something 'closer to metal', probably similar to web.py - See #1 below > Your suggestions and comments are highly welcome! Victor et al, I would propose that you ask some different questions. I propose these out of personal experience, much of it from making poor decisions and learning the hard way. Sorry if these sound gruff, I think its hard to avoid when using bullet points; in my mind, these are all being phrased as kindly and gently as I can. #1 Seek flexibility over being "closer to metal." I say this because whenever I've thought I wanted to be closer to metal, its because I didn't want to be constrained by a framework's assumptions. I guess another reason would be the need for raw performance with computations, but I think you would have said that if that was your goal. Still, "more flexible" is not always better. "flexible and well integrated" is slightly better than "flexible to the Nth degree." #2 Look for projects that deal with updates and security fixes in a way that is sensitive to users of critical applications. This is better than programs that change little. For example, does the "vendor" provide patches containing just critical updates? Do they have good, clear communication about changes that may break compatibility? How long are older versions maintained? Asking these questions will help you find a thriving project that is actively maintained and supported. (contrast to abandonware, which hasn't changed in ages) #3 Why haven't you mentioned maintainability or scalability? It sounds like you're coming from a platform that you have outgrown, either because your app can't keep up with it's load, or because you can't enhance it with the features you want. You're not simply refactoring it, you're starting over from the beginning. How often do you want to start from scratch? If the answer is, "this is the last time," then I'd worry *way* more about this and point #2 than anything else you mentioned. #4 (optional) Has your dev team built many python web-apps? I'm guessing no, or you'd already have picked a platform because of experience. If they have not, I'd personally also ask for a platform that is easy to learn, works well with the dev tools (IDE, debugger, version control) you're familiar with, and has good documentation (dead tree or online). The unfortunate news, I'm afraid to say, is that because of the python culture, you're still going to face tough decisions as there are several mature products who score high marks in the areas I've listed above. It seems the python community at large is insanely bent on doing things the "right" way, so there may just be too many good options to choose from. But its better to ask the right questions. -- Matthew Nuzum newz2000 on freenode From ptmcg at austin.rr.com Thu May 17 08:43:38 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 17 May 2007 05:43:38 -0700 Subject: how do I count spaces at the beginning of a string? In-Reply-To: <1179367338.906430.97420@k79g2000hse.googlegroups.com> References: <1179367338.906430.97420@k79g2000hse.googlegroups.com> Message-ID: <1179405818.432742.146600@k79g2000hse.googlegroups.com> On May 16, 9:02 pm, walterbyrd wrote: > The strings start with whitespace, and have a '*' or an alphanumeric > character. I need to know how many whitespace characters exist at the > beginning of the string. ....aaaaaaand what have you tried so far? This really is a pretty basic question - to most folks on this list, it's about the same as "how do I count the fingers on my hand?". Is this your first Python program? Homework assignment? First program ever written in any language? Try reading one of the online tutorials or pick up a Python book or browse the archive from this list or the python-tutor mailing list - you shouldn't have to read too far to start getting an idea on how to approach this problem. www.python.org has links to all of these and more. Take a stab at this problem, and if you don't have any luck, come back (or try the python-tutor list) and post what you've tried. -- Paul From rene at korteklippe.de Tue May 15 07:05:12 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 15 May 2007 13:05:12 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464977D3.6010703@web.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> <4648294F.2000704@web.de> <46487a6c$0$2400$426a74cc@news.free.fr> <464977D3.6010703@web.de> Message-ID: <464993e7$0$23148$9b4e6d93@newsspool1.arcor-online.net> Stefan Behnel schrieb: > My personal take on this is: search-and-replace is easier if you used well > chosen identifiers. Which is easier if you used your native language for them, > which in turn is easier if you can use the proper spellings. I strongly disagree with this. My native language is German, and I do *not* find it easier to find well chosen identifiers using German. Not at all. Quite the opposite. Programming is such an English-dominated culture that I even "think" in English about it. When I want to explain something related to Computers to German "non-techies", I often have to think about an appropriate German word for what I have in mind first. Using the familiar English term would be alot easier. My experience is: If you know so little "technical" English that you cannot come up with well chosen English identifiers, you need to learn it. If you don't, you will not be able to write decent programs anyway. All the keywords are in English, all of the standard library is in English, most of the documentation is only available in English, almost all third party modules' interfaces are in English. Any program that uses non-English identifiers in Python is bound to become gibberish, since it *will* be cluttered with English identifiers all over the place anyway, wether you like it or not. The point is: Supporting non-ASCII identifiers does *not* allow people to write programs "using their native natural language". For that, you would also have to translate the standard library and so on. meincsv = csv.reader(open("meinedatei.csv")) for zeile in meincsv: for eintrag in zeile: print eintrag.upper() Even in that little trivial code snippet, you need to understand stuff like "reader", "open", "for", "in", "print" and "upper". Mixing in the German identifiers is both ugly and unnecessary. > For example, how many German names for a counter variable could you come up > with? Or english names for a function that does domain specific stuff and that > was specified in your native language using natively named concepts? Are you > sure you always know the correct english translations? I don't need to know the perfect English translation, just one that is understood by anyone who knows enough "Programming English", which is just about any programmer in the world. -- Ren? From sjmachin at lexicon.net Wed May 9 08:24:34 2007 From: sjmachin at lexicon.net (John Machin) Date: 9 May 2007 05:24:34 -0700 Subject: Using the CSV module In-Reply-To: References: Message-ID: <1178713474.473116.146320@e65g2000hsc.googlegroups.com> On May 9, 6:40 pm, "Nathan Harmston" wrote: > Hi, > > I ve been playing with the CSV module for parsing a few files. A row > in a file looks like this: > > some_id\t|\tsome_data\t|t\some_more_data\t|\tlast_data\t\n > > so the lineterminator is \t\n and the delimiter is \t|\t, however when > I subclass Dialect and try to set delimiter is "\t|\t" it says > delimiter can only be a character. > > I know its an easy fix to just do .strip("\t") on the output I get, > but I was wondering > a) if theres a better way of doing this when the file is actually > being parsed by the csv module No; usually one would want at least to do .strip() on each field anyway to remove *all* leading and trailing whitespace. Replacing multiple whitespace characters with one space is often a good idea. One may want to get fancier and ensure that NO-BREAK SPACE aka   (\xA0 in many encodings) is treated as whitespace. So your gloriously redundant tabs vanish, for free. > b) Why are delimiters only allowed to be one character in length. Speed. The reader is a hand-crafted finite-state machine designed to operate on a byte at a time. Allowing for variable-length delimiters would increase the complexity and lower the speed -- for what gain? How often does one see 2-byte or 3-byte delimiters? From transfire at gmail.com Thu May 3 13:46:23 2007 From: transfire at gmail.com (Trans) Date: 3 May 2007 10:46:23 -0700 Subject: Library Naming In-Reply-To: <1178213478.128373.190420@e65g2000hsc.googlegroups.com> References: <1178203288.888165.169130@y80g2000hsf.googlegroups.com> <1178213478.128373.190420@e65g2000hsc.googlegroups.com> Message-ID: <1178214383.145339.232280@e65g2000hsc.googlegroups.com> On May 3, 1:31 pm, "mensana... at aol.com" wrote: > On May 3, 9:41 am, Trans wrote: > > > I'm taking a pole on how best to name programming library packages. > > Well, the Poles have been wrong before. I don't know what's worse, my misspelling or your joke ;-) T. From michael.forbes at gmail.com Tue May 1 19:49:01 2007 From: michael.forbes at gmail.com (Michael) Date: 1 May 2007 16:49:01 -0700 Subject: Why are functions atomic? In-Reply-To: <1178044821.864741.235260@o5g2000hsb.googlegroups.com> References: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> <1178044821.864741.235260@o5g2000hsb.googlegroups.com> Message-ID: <1178063341.779617.289690@o5g2000hsb.googlegroups.com> >From TFM "Function objects also support getting and setting arbitrary attributes, which can be used, for example, to attach metadata to functions. Regular attribute dot-notation is used to get and set such attributes. Note that the current implementation only supports function attributes on user-defined functions. Function attributes on built-in functions may be supported in the future." http://docs.python.org/ref/types.html Again, rather inconsitent with the copy sematics. > On May 1, 9:34 am, John Nagle wrote: > > Because Python has objects for when you need to associate > > state with a function. > > > John Nagle From gagsl-py2 at yahoo.com.ar Tue May 1 18:18:16 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 01 May 2007 19:18:16 -0300 Subject: Python for Windows other way to getting it? References: <1178051916.033367.205320@h2g2000hsg.googlegroups.com> Message-ID: En Tue, 01 May 2007 17:38:36 -0300, escribi?: > I don't have permission to install new application on the PC I'm > using, I need a zipped version of python that I can copy on my > external drive. Where can I get a zip version? It's enough to copy the Python folder + pythonNN.dll from Windows\System32 If you don't set a custom PYTHONPATH (using .pth files instead) you should be fine, at least for usual cases. -- Gabriel Genellina From tiarno at sas.com Fri May 25 09:55:04 2007 From: tiarno at sas.com (Tim Arnold) Date: Fri, 25 May 2007 09:55:04 -0400 Subject: extra xml header with ElementTree? Message-ID: Hi, I'm using ElementTree which is wonderful. I have a need now to write out an XML file with these two headers: My elements have the root named tocbody and I'm using: newtree = ET.ElementTree(tocbody) newtree.write(fname) I assume if I add the encoding arg I'll get the xml header: newtree = ET.ElementTree(tocbody) newtree.write(fname,encoding='utf-8') but how can I get the into the tree? python2.4.1,hpux10,ElementTree1.2.6 thanks, --Tim From luc.saffre at gmail.com Fri May 4 04:07:44 2007 From: luc.saffre at gmail.com (luc.saffre at gmail.com) Date: 4 May 2007 01:07:44 -0700 Subject: invoke user's standard mail client Message-ID: <1178266064.922925.125760@y80g2000hsf.googlegroups.com> Hello, the simplest way to launch the user's standard mail client from a Python program is by creating a mailto: URL and launching the webbrowser: def mailto_url(to=None,subject=None,body=None,cc=None): """ encodes the content as a mailto link as described on http://www.faqs.org/rfcs/rfc2368.html Examples partly taken from http://selfhtml.teamone.de/html/verweise/email.htm """ url = "mailto:" + urllib.quote(to.strip(),"@,") sep = "?" if cc: url+= sep + "cc=" + urllib.quote(cc,"@,") sep = "&" if subject: url+= sep + "subject=" + urllib.quote(subject,"") sep = "&" if body: # Also note that line breaks in the body of a message MUST be # encoded with "%0D%0A". (RFC 2368) body="\r\n".join(body.splitlines()) url+= sep + "body=" + urllib.quote(body,"") sep = "&" return url import webbrowser url = mailto_url(...) webbrowser.open(url,new=1) (Excerpt from http://svn.berlios.de/wsvn/lino/trunk/src/lino/tools/mail.py?op=file&rev=0&sc=0) But this method is limited: you cannot specify a file to be attached to the mail. And I guess that there would be problems if the body text is too complex. Does somebody know about a better method? It should be possible at least on Windows, since Acrobat Reader is able to do it. Thanks in advance for any hints! Luc Saffre From gagsl-py2 at yahoo.com.ar Thu May 24 17:27:21 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 24 May 2007 18:27:21 -0300 Subject: What is an instance and what isn't? References: Message-ID: En Thu, 24 May 2007 12:18:36 -0300, Gre7g Luterman escribi?: > I'm writing a C program which handles Python objects in different ways > based > on their type. I do a PyInstance_Check(PyObj) to determine if the PyObj > is > an instance, but it is returning 0 on a lot of stuff that I thought > would be > an instance. So I did the following simple test on three things that look > like instances: PyInstance refers to instances of old style classes, now used much less than before. >>>> class b(dict): pass > ... >>>> type(b()) > > > I was relieved that a() returns an instance, but I was surprised that > Exceptions aren't really instances at all. And what's the deal with > derving > a class from a standard type like a dictionary? I thought for sure, that > would be an instance, but this shows it is a class?!? The "instance" type refers to said instances of old-style classes. For new style classes, when you call type(somenewstyleclass) you usually get `type`, and for its instances, you get somenewstyleclass. > Can anyone explain the last one and/or give me a simple test I can do in > C > to determine whether a Python object is "instance-like"? What do you mean by "instance-like"? All new objects are instances of its class, and all new classes are instances of type (or a custom metaclass). -- Gabriel Genellina From steve at holdenweb.com Sat May 19 21:50:58 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 19 May 2007 21:50:58 -0400 Subject: docs patch: dicts and sets In-Reply-To: <1179612045.678939.260650@p47g2000hsd.googlegroups.com> References: <_5-dnU7aIN73j9LbnZ2dnUVZ_uCinZ2d@comcast.com> <1179593927.503393.127350@u30g2000hsc.googlegroups.com> <1179596822.923443.67500@k79g2000hse.googlegroups.com> <1179601094.940650.276120@w5g2000hsg.googlegroups.com> <1179612045.678939.260650@p47g2000hsd.googlegroups.com> Message-ID: 7stud wrote: >> Actually, it would just move the "endless, petty discussions about what >> minutiae are more important" into the docs. I don't see how that's an >> improvement. > > Because it highlights the issues you will be faced with when using the > described functions. People will post about an issue they had with a > function, and then they will post their solution. Instead of having > to search all over google for an answer, the most relevant discussions > will be right in the docs. As you read the user comments, you would > be able to quickly tell whether a comment pertains to the issue you > are having trouble with, and if the comment isn't relevant, you can > skip the comment and look at the next comment. If you wanted, you > could limit yourself to reading just the official python description > of the function and be no worse off. > >> And most will simply be confused. > > Then it's likely someone will post something to clear up the confusion. > But the real point is that it won't actually do much good to turn the documentation into a miniature version of c.l.py itself. You and other readers might be interested in a recent experiment by Georg Brandl, one of the Python core developers. As Georg says, "For the impatient: the result can be seen at ". This is based on a translation of the existing Latex source into ReStructured Text format. I understand Georg is considering enabling user comments, among other enhancements. Yo should also understand that this is a work in progress which may never come to full fruition. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From showell30 at yahoo.com Sun May 27 11:23:26 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 27 May 2007 08:23:26 -0700 (PDT) Subject: ten small Python programs In-Reply-To: <1180269944.944150.135930@q66g2000hsg.googlegroups.com> Message-ID: <409218.34160.qm@web33506.mail.mud.yahoo.com> --- BartlebyScrivener wrote: > On May 26, 1:43 pm, Steve Howell > wrote: > > ------ > > # def defines a method in Python > > def tax(itemCharge, taxRate = 0.05): > > return itemCharge * taxRate > > print '%.2f' % tax(11.35) > > print '%.2f' % tax(40.00, 0.08) > > > I decided to go with a simpler example up front. ------ # def defines a method in Python def say_hello(name): print 'hello', name say_hello('Jack') say_hello('Jill') More here: http://wiki.python.org/moin/SimplePrograms Somebody also fixed a few style things in my other examples, changing a tuple to a list, catching a more specific exception. Whoever you are, thanks, I agree. ____________________________________________________________________________________Sick sense of humor? Visit Yahoo! TV's Comedy with an Edge to see what's on, when. http://tv.yahoo.com/collections/222 From nogradi at gmail.com Fri May 18 11:00:51 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Fri, 18 May 2007 17:00:51 +0200 Subject: Python Web Programming - looking for examples of solid high-traffic sites In-Reply-To: <1hyarxo.iqtdo1v9qpivN%aleax@mac.com> References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> <1hy9yf9.1nnsttj139za6bN%aleax@mac.com> <1hyarxo.iqtdo1v9qpivN%aleax@mac.com> Message-ID: <5f56302b0705180800r772fccc7u3f93b62c33005c60@mail.gmail.com> > > >> For example, it HAS been published elsewhere that YouTube uses lighttpd, > > >> not Apache: . > > > > > > How do you explain these, then: > > > > > > http://www.youtube.com/results.xxx > > > http://www.youtube.com/results.php > > > http://www.youtube.com/results.py > > > > Server signature is usually configurable. > > Yeah, but I don't know why it's configured it that way. A good example > of a question that looks perfectly appropriate for YouTube's OSCON > session. Let us know what they say! :) From timr at probo.com Fri May 4 01:56:07 2007 From: timr at probo.com (Tim Roberts) Date: Fri, 04 May 2007 05:56:07 GMT Subject: os.path.join References: <1178072869.844914.59010@u30g2000hsc.googlegroups.com> Message-ID: Elliot Peele wrote: >On Tue, 2007-05-01 at 19:27 -0700, 7stud wrote: >> On May 1, 7:36 pm, Elliot Peele wrote: >> > Why does os.path.join('/foo', '/bar') return '/bar' rather than >> > '/foo/bar'? That just seems rather counter intuitive. >> > >> > Elliot >> >> join( path1[, path2[, ...]]) >> Join one or more path components intelligently. If any component is an >> absolute path, all previous components (on Windows, including the >> previous drive letter, if there was one) are thrown away... > >Yes, but that still doesn't answer my question as to why os.path.join >works that way. I understand that that is how it is written, but why? It's behavior is exactly the same as if you did a series of "cd" commands at the shell with the same parameters. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From martin at v.loewis.de Sat May 12 05:40:01 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 12 May 2007 11:40:01 +0200 Subject: Thread-safe dictionary In-Reply-To: <1178821512.229872.98120@n59g2000hsh.googlegroups.com> References: <1178821512.229872.98120@n59g2000hsh.googlegroups.com> Message-ID: <46458b72$0$7654$9b622d9e@news.freenet.de> > - in __getitem__, does it release the lock after returning the item? Yes, it does. > - wouldn't it be better to use threading.RLock, mutex, ... instead? Better in what sense? Performance-wise? Semantically? Performance-wise, the best thing would be to do safe_dict = dict because the builtin dict is already thread-safe unless user-defined __hash__ or __eq__ methods get invoked (in which case the dictionary still works correctly - it's only that it may get modified while __hash__ or __eq__ is running). Semantically, it would be better to use a threading.RLock, if you expect that __hash__ or __eq__ may access the dictionary recursively. Regards, Martin From steveo at syslang.net Wed May 2 09:28:00 2007 From: steveo at syslang.net (Steven W. Orr) Date: Wed, 2 May 2007 09:28:00 -0400 (EDT) Subject: What do people use for code analysis. In-Reply-To: <5f56302b0705020348w1898b1faxa4aa59223f8b6ef1@mail.gmail.com> References: <5f56302b0705020348w1898b1faxa4aa59223f8b6ef1@mail.gmail.com> Message-ID: On Wednesday, May 2nd 2007 at 12:48 +0200, quoth Daniel Nogradi: =>> Lots of code, calls to, calls by, inheritance, multiple tasks, etc. =>> =>> What do people use to figure out what's happening? => =>This is a pretty cool project just for that: => =>http://codeinvestigator.googlepages.com/codeinvestigator I looked at codeinvestigator but it looks like it doesn't do what I want. I saw something about source navigator having python support. Have people used it? Does that work well? -- 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 mail at microcorp.co.za Wed May 23 06:13:34 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 23 May 2007 12:13:34 +0200 Subject: Lists vs tuples (newbie) References: Message-ID: <000201c79dda$eae8b8a0$03000080@hendrik> "Duncan Booth" wrote: > "Hendrik van Rooyen" wrote: > > > Aside from the hashing issue, there is nothing that a tuple can do > > that can't be done as well or better by a list. > > There are a few other cases where you have to use a tuple, for example in a > try..except statement the exception specification must be an exception to > be caught or a tuple of exception specifications: a list won't work to > catch multiple exceptions. Esoteric - But I stand corrected... any other "must use a tuple's " ? Seems they all fall into a class that can be described as required by the language - I was thinking data. - Hendrik From steven.bethard at gmail.com Sat May 26 15:38:44 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 26 May 2007 13:38:44 -0600 Subject: ten small Python programs In-Reply-To: References: Message-ID: Steve Howell wrote: > I've always thought that the best way to introduce new > programmers to Python is to show them small code > examples. > > When you go to the tutorial, though, you have to wade > through quite a bit of English before seeing any > Python examples. > > Below is my attempt at generating ten fairly simple, > representative Python programs that expose new users > to most basic concepts, as well as the overall syntax. Very cool! Do you mind putting this up on the Wiki somewhere so that we can link to it more easily? Maybe something like: http://wiki.python.org/moin/SimplePrograms Though the code should probably follow PEP 8 guidelines, e.g. under_scores instead of camelCase for object and method names: http://www.python.org/dev/peps/pep-0008/ > class ShoppingCart: > def __init__(self): self.items = [] > def buy(self, item): self.items.append(item) > def boughtItems(self): return self.items > myCart = ShoppingCart() > myCart.buy('apple') > myCart.buy('banana') > print myCart.boughtItems() I think boughtItems() is probably not a good example of Python code since in this case, you should probably just write ``my_cart.items``. Maybe it should define ``__len__`` instead? Or maybe something like:: def select_items(self, prefix): return [item for item in self.items if item.startswith(prefix)] STeVe From rohitsethidce at gmail.com Thu May 24 19:26:26 2007 From: rohitsethidce at gmail.com (rohit) Date: 24 May 2007 16:26:26 -0700 Subject: File monitoring for all drive Message-ID: <1180049186.804822.5060@a26g2000pre.googlegroups.com> hi i want to detect all file change operations(rename,delete,create....) on ALL THE DRIVES of the hard disk using the method ReadDirectoryChanges API , i.e program no. 3 in the webpage http://tgolden.sc.sabren.com/python/win32_how_do_i/watch_directory_for_changes.html . Please suggest some modification to the program so that i can detect changes to ALL the drives (to detect changes on c:\ set path_to_watch = "." to "c:\\" but this works for only one drive thanks rohit From steven.bethard at gmail.com Wed May 23 02:05:54 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 23 May 2007 00:05:54 -0600 Subject: xml.parsers.expat loading xml into a dict and whitespace In-Reply-To: References: Message-ID: kaens wrote: > Let's say I write a simple xml parser, for an xml file that just loads > the content of each tag into a dict (the xml file doesn't have > multiple hierarchies in it, it's flat other than the parent node) [snip] > > hey > bee > eff > > > it prints out: > " : > > three : eff > two : bee > one : hey" I don't have a good answer for your expat code, but if you're not married to that, I strongly suggest you look into ElementTree[1]:: >>> xml = '''\ ... ... hey ... bee ... eff ... ... ''' >>> import xml.etree.cElementTree as etree >>> tree = etree.fromstring(xml) >>> d = {} >>> for child in tree: ... d[child.tag] = child.text ... >>> d {'three': 'eff', 'two': 'bee', 'one': 'hey'} [1] ElementTree is in the 2.5 standard library, but if you're stuck with an earlier python, just Google for it -- there are standalone versions STeVe From rene at korteklippe.de Tue May 15 09:41:00 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 15 May 2007 15:41:00 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476081.7080609@web.de> <46498514$0$6402$9b4e6d93@newsspool2.arcor-online.net> <4649882E.3060005@web.de> <46499940$0$10199$9b4e6d93@newsspool4.arcor-online.net> <46499BF9.30209@web.de> <4649a2c1$0$10193$9b4e6d93@newsspool4.arcor-online.net> <4649A429.3010406@web.de> <4649ae4a$0$20289$9b4e6d93@newsspool3.arcor-online.net> <4649AF84.7010208@web.de> <4649b22c$0$20289$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <4649b86b$0$10197$9b4e6d93@newsspool4.arcor-online.net> Thorsten Kampe schrieb: > You are right, except that using the correct characters for words is > not a "funny thing". Using Polish diacritics (for example) for > identifier names just makes sense for a project that already uses > polish comments and polish names for their code. You will never get in > touch with that. Using the right charset for these polish words > doesn't change a bit in your ability to debug or understand this code. I will get in touch with it. I currently have applications installed on my computer that come with my Linux distribution and that use code with identifiers and comments written in a non-English language which I would like to understand. This is tough enough as it is, the same code with non-ASCII characters that maybe do not even display on my screen would be even tougher to understand, let alone modify. It does make a difference wether I can at least recognize and type in the characters or not. The expectation that such code will only be used for "very closed" projects that noone else will ever want to get in touch with is unrealistic. -- Ren? From tmp123 at menta.net Sun May 6 10:46:06 2007 From: tmp123 at menta.net (tmp123) Date: 6 May 2007 07:46:06 -0700 Subject: newbie: copy base class fields In-Reply-To: References: <1178201644.920048.205400@y5g2000hsa.googlegroups.com> Message-ID: <1178462766.900763.292710@u30g2000hsc.googlegroups.com> On May 3, 4:57 pm, "Jerry Hill" wrote: > Is it okay to copy them all at once? Like this: > > class B(A): > def __init__(self, a): > self.__dict__.update(a.__dict__) > self.v2 = 2 > Thanks a lot for the answers, they seem to agree with the requested funcitionality. Kind regards. From bj_666 at gmx.net Mon May 7 03:11:56 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 07 May 2007 09:11:56 +0200 Subject: N00b question on Py modules References: <1178521238.333095.111370@h2g2000hsg.googlegroups.com> Message-ID: In <1178521238.333095.111370 at h2g2000hsg.googlegroups.com>, lokesh.jagasia wrote: > My python module: > > _exitcode = 0 > > def setExitCode(): > _exitcode = 1 > > if __name__ == '__main__': > print _exitcode > setExitCode() > print _exitcode > > Actual O/P: > 0 > 0 > > I expected to see an output of 0 followed by 1. But it turns out that > the _exitcode variable is not changed at all. It seems that > setExitCode() might be editing a local copy of the _exitcode variable. > But then, how do I tell it to change the value of the module variable > and not its local variable. Any name that gets bound to an object within a function is local to that function unless you declare it as ``global``. But using lots of global variables is considered bad style so you may think about rewriting functions with ``global`` names to return the value(s) instead: _exitcode = 0 def set_exitcode(): return 1 if __name__ == '__main__': print _exitcode _exitcode = set_exitcode() print _exitcode Ciao, Marc 'BlackJack' Rintsch From kyosohma at gmail.com Thu May 31 09:17:57 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 31 May 2007 06:17:57 -0700 Subject: wxpython demo error on debian etch In-Reply-To: <1180588894.587378.276170@u30g2000hsc.googlegroups.com> References: <1180445918.523446.133300@g4g2000hsf.googlegroups.com> <1180446704.521350.72450@k79g2000hse.googlegroups.com> <1180459989.799593.243960@u30g2000hsc.googlegroups.com> <1180462154.551455.83010@k79g2000hse.googlegroups.com> <1180588894.587378.276170@u30g2000hsc.googlegroups.com> Message-ID: <1180617477.116990.71810@q66g2000hsg.googlegroups.com> On May 31, 12:21 am, BartlebyScrivener wrote: > On May 29, 1:09 pm, kyoso... at gmail.com wrote: > > > The newer versions of wxPython won't make your Debian crash or > > anything. We run Debian at work and I've upgraded the Python to 2.4 > > and the wxPython to its newest version. This has not affected the > > server's stability in any way. > > Install like this? > > Debian stable is way behind the times, so you may find something > appropriate in testing. Alternatively, the instructions below should > work. > > apt-get install alien > apt-get install libgtk2.0-dev freeglut3-dev python2.3-dev > wgethttp://easynews.dl.sourceforge.net/wxpython/wxPython2.8-2.8.3.0-1.src... > rpmbuild --rebuild --define 'pyver 2.3' > wxPython2.8-2.8.3.0-1.src.rpm > cd rpmdir > alien packagenames.rpm > dpkg -i whatever alien called them > > > > > This link explains the process the Debian team takes to implement new > > versions of packages (like wxPython):http://en.wikipedia.org/wiki/Debian > > > Basically, they test it for months before finally putting it in to the > > "stable" category. However, since they have to do this for lots of > > packages, one by one the packages get marked stable. So you could have > > something like wxPython marked stable in March and 6 months later, the > > rest of the packages are done so they're marked stable. And then after > > additional testing, they release the new version. > > > Hopefully that wasn't too confusing. > > > Mike I would assume that would work. If you run into any problems, it would be a good idea to post them to the wxPython user's group. They know a LOT more about that sort of stuff if things go wrong. Mike From frederic.pica at gmail.com Thu May 31 11:06:18 2007 From: frederic.pica at gmail.com (frederic.pica at gmail.com) Date: 31 May 2007 08:06:18 -0700 Subject: Python memory handling In-Reply-To: References: <1180611604.247696.149060@h2g2000hsg.googlegroups.com> Message-ID: <1180623978.372352.194860@q69g2000hsb.googlegroups.com> On 31 mai, 16:22, Paul Melis wrote: > Hello, > > frederic.p... at gmail.com wrote: > > I've some troubles getting my memory freed by python, how can I force > > it to release the memory ? > > I've tried del and gc.collect() with no success. > > [...] > > > > > The same problem here with a simple file.readlines() > > #Python interpreter memory usage : 1.1 Mb private, 1.4 Mb shared > > import gc #no memory change > > f=open('primary.xml') #no memory change > > data=f.readlines() #meminfo: 12 Mb private, 1.4 Mb shared > > del data #meminfo: 11.5 Mb private, 1.4 Mb shared > > gc.collect() # no memory change > > > But works great with file.read() : > > #Python interpreter memory usage : 1.1 Mb private, 1.4 Mb shared > > import gc #no memory change > > f=open('primary.xml') #no memory change > > data=f.read() #meminfo: 7.3Mb private, 1.4 Mb shared > > del data #meminfo: 1.1 Mb private, 1.4 Mb shared > > gc.collect() # no memory change > > > So as I can see, python maintain a memory pool for lists. > > In my first example, if I reparse the xml file, the memory doesn't > > grow very much (0.1 Mb precisely) > > So I think I'm right with the memory pool. > > > But is there a way to force python to release this memory ?! > > This is from the 2.5 series release notes > (http://www.python.org/download/releases/2.5.1/NEWS.txt): > > "[...] > > - Patch #1123430: Python's small-object allocator now returns an arena to > the system ``free()`` when all memory within an arena becomes unused > again. Prior to Python 2.5, arenas (256KB chunks of memory) were never > freed. Some applications will see a drop in virtual memory size now, > especially long-running applications that, from time to time, temporarily > use a large number of small objects. Note that when Python returns an > arena to the platform C's ``free()``, there's no guarantee that the > platform C library will in turn return that memory to the operating > system. > The effect of the patch is to stop making that impossible, and in > tests it > appears to be effective at least on Microsoft C and gcc-based systems. > Thanks to Evan Jones for hard work and patience. > > [...]" > > So with 2.4 under linux (as you tested) you will indeed not always get > the used memory back, with respect to lots of small objects being > collected. > > The difference therefore (I think) you see between doing an f.read() and > an f.readlines() is that the former reads in the whole file as one large > string object (i.e. not a small object), while the latter returns a list > of lines where each line is a python object. > > I wonder how 2.5 would work out on linux in this situation for you. > > Paul Hello, I will try later with python 2.5 under linux, but as far as I can see, it's the same problem under my windows python 2.5 After reading this document : http://evanjones.ca/memoryallocator/python-memory.pdf I think it's because list or dictionnaries are used by the parser, and python use an internal memory pool (not pymalloc) for them... Regards, FP From eric.devolder at gmail.com Wed May 30 18:12:05 2007 From: eric.devolder at gmail.com (Eric) Date: 30 May 2007 15:12:05 -0700 Subject: with ctypes, how to parse a multi-string Message-ID: <1180563125.783144.34260@m36g2000hse.googlegroups.com> Hi, I am currently dealing with ctypes, interfacing with winscard libbrary (for smart card access). Several APIs (e.g. SCardListReaderGroupsW ) take a pointer to an unicode string as a parameter , which points at function return to a "sequence" of unicode strings, NULL terminated. The last string is double NULL terminated. (of course buffer length is also returned as another parameter). e.g. it could return something like 'group1\x00group2\x00group3\x00\x00' What should I use as argtypes to my function prototype in order to gain access to the full list? using c_wchar_p works, but it resolves the string until it reaches the first \x00, resulting in having access to the first entry of the list only. as reference, my current ctypes mapping for this API is: # extern WINSCARDAPI LONG WINAPI # SCardListReaderGroupsW( # IN SCARDCONTEXT hContext, # OUT LPWSTR mszGroups, # IN OUT LPDWORD pcchGroups); _ListReaderGroups = scardlib.SCardListReaderGroupsW _ListReaderGroups.argtypes = [ c_ulong, c_void_p, c_void_p ] _ListReaderGroups.restype = c_ulong Calling the API looks like: pcchreadergrp = c_long(SCARD_AUTOALLOCATE) groups = c_wchar_p() _ListReaderGroups( ctx, byref(groups), byref(pcchreadergrp)) Should I be using some array/ctypes.cast() combination to gain access to all returned characters? From p at ulmcnett.com Tue May 29 18:42:49 2007 From: p at ulmcnett.com (Paul McNett) Date: Tue, 29 May 2007 15:42:49 -0700 Subject: updates in sqlite3 do not work In-Reply-To: <723eb6930705291530w190a7818i71f49d976217f38@mail.gmail.com> References: <723eb6930705291530w190a7818i71f49d976217f38@mail.gmail.com> Message-ID: <465CAC69.8090101@ulmcnett.com> Chris Fonnesbeck wrote: > I have a script set up to perform UPDATE commands on an sqlite database > using the sqlite3 module. Everything appears to run fine (there are no > error messages), except that none of the UPDATE commands appear to have > actually updated the table. If I run each command on its own in a sqlite > session, the UPDATE command works fine, so it is not a SQL syntax issue. > UPDATE simply seems not to work. Any idea what the problem might be? You need to explicitly commit the transaction e.g.: import sqlite3.dbapi2 as sqlite con = sqlite.connect("temp.db") cur = con.cursor() cur.execute("create table test (id INTEGER, name CHAR)") cur.execute("insert into test values (1, 'bob')") con.commit() HTH Paul -- pkm ~ http://paulmcnett.com From stefan.behnel-n05pAM at web.de Tue May 15 08:14:33 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 15 May 2007 14:14:33 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <4649a2c1$0$10193$9b4e6d93@newsspool4.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476081.7080609@web.de> <46498514$0$6402$9b4e6d93@newsspool2.arcor-online.net> <4649882E.3060005@web.de> <46499940$0$10199$9b4e6d93@newsspool4.arcor-online.net> <46499BF9.30209@web.de> <4649a2c1$0$10193$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <4649A429.3010406@web.de> Ren? Fleschenberg wrote: > Please try to understand that the fact that certain bad practices are > possible today is no valid argument for introducing support for more of > them! You're not trying to suggest that writing code in a closed area project is a bad habit, are you? What would be bad about allowing a project to decide about the best and clearest way to name identifiers? And: if it's not a project you will ever get in touch with - what do you care? Stefan From J2TheoN at gmail.com Thu May 10 20:11:16 2007 From: J2TheoN at gmail.com (Jon Pentland) Date: 10 May 2007 17:11:16 -0700 Subject: File modes In-Reply-To: References: <1178830039.962239.245800@e51g2000hsg.googlegroups.com> Message-ID: <1178842276.692281.174370@e51g2000hsg.googlegroups.com> I don't really see the use for being able to do that. Have you tried doing it with the 'app' mode?, But I am guessing that it is just an advanced mode spawned from 'w'. So, no, I don't think you can do this. From grante at visi.com Thu May 31 11:54:41 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 31 May 2007 15:54:41 -0000 Subject: c[:]() References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> <135tobve86qj808@corp.supernews.com> Message-ID: <135tru124pie2b3@corp.supernews.com> On 2007-05-31, Warren Stringer wrote: >> > But that still isn't as simple or as direct as: >> > >> > c[:]() >> >> Why do you always use a _copy_ of c in your examples? As long >> as you're wishing, why not just >> >> c() > > Oh hey Grant, yes, I misunderstood your question for a bit. I > thought you meant the difference between List comprehension > [...] and generator expressions (...) where the first returns > the whole list and the second iterates the whole list. > > But, yes, good point if I was only using [:]. For more > expressiveness, How is it more expressive? In the context you're concerned with, c[:] is the exactly same thing as c. You seem to be worried about saving keystrokes, yet you use c[:] instead of c. It's like having an integer variable i and using ((i+0)*1) instead of i. -- Grant Edwards grante Yow! I want to read my new at poem about pork brains and visi.com outer space ... From horpner at yahoo.com Fri May 11 09:15:01 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Fri, 11 May 2007 13:15:01 GMT Subject: searching algorithm References: <7dydnfjNWbo9H97bnZ2dnUVZ_oupnZ2d@comcast.com> <1178861348.204066.293820@o5g2000hsb.googlegroups.com> Message-ID: On 2007-05-11, ciju wrote: > By the way, both data structures could be implemented as tuple > in python, for I suppose, if only lookup is needed tuple gives > better performance than list. I used a list instead of a tuple where I thought a list would be convenient while building the data structure. But you could convert everything to tuples in the end, it's true. -- Neil Cerutti From kyosohma at gmail.com Tue May 22 15:44:00 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 22 May 2007 12:44:00 -0700 Subject: drag and drop with wxPython ? In-Reply-To: References: Message-ID: <1179863040.585516.155490@k79g2000hse.googlegroups.com> On May 22, 10:00 am, stef wrote: > hello, > > I'm trying to move from Delphi to Python > (move from MatLab to Python already succeeded, also thanks to this > discussion group). > From the discussions in this list about "the best" GUI for Python, > it now seems to me that wxPython is th? choice for my kind of applications. > > I've no experience with wxPython yet, > I just run a few examples and indeed it looks good (as expected from the > discussions in this list). > > What I really need at this moment for a new project, > (and I coulnd't find any example, lot of broken links ;-) > is how to implement some drag & drop facilities, > both to drag and drop normal button, > but also to drag and drop some dynamically created objects. > Just like a CAD program, but far more simpler. > > Does anyone has an example how to drag & drop components with wxPython ? > > thanks, > Stef Mientki Stef, wxPython's wiki has a couple examples: http://wiki.wxpython.org/DragAndDrop?highlight=%28drop%29%7C%28drag%29 http://wiki.wxpython.org/DragAndDropWithFolderMovingAndRearranging?highlight=%28drop%29%7C%28drag%29 I think Larry meant to say that the wxPython demo has an example. It's under the "Clipboard and DnD" category. For lots of help from people that create wxPython and its widgets, check out the wxPython user's group here: http://www.wxpython.org/maillist.php Mike From ragnar at lysator.liu.se Tue May 29 14:16:52 2007 From: ragnar at lysator.liu.se (Ragnar Ouchterlony) Date: Tue, 29 May 2007 18:16:52 GMT Subject: how to print the GREEK CAPITAL LETTER delta under utf-8 encoding In-Reply-To: <465BD0AA.9080805@v.loewis.de> References: <1180414659.066482.236370@i38g2000prf.googlegroups.com> <465BBB49.6000803@v.loewis.de> <1180421212.151587.118020@r19g2000prf.googlegroups.com> <465BD0AA.9080805@v.loewis.de> Message-ID: <1180462611.5376.13.camel@localhost> tis 2007-05-29 klockan 09:05 +0200 skrev "Martin v. Lo"wis": > Yes, when writing to a file, you need to define an encoding, e.g. > > self.file.write(data.encode("utf-8")) > > You can use codecs.open() instead of open(), > so that you can just use self.file.write(data) If I for some reason can't open the object myself or needs encoding on other file-like objects, I think the following wrapper function is of use (it essentially does what codecs.open() does but takes a file-object instead of a filename): def filewrapper(f, encoding=None, errors='strict'): if encoding is None: return f info = codecs.lookup(encoding) srw = codecs.StreamReaderWriter(f, info.streamreader, info.streamwriter, errors) # Add attributes to simplify introspection srw.encoding = encoding return srw I find this especially useful for changing how stdout and friends does it's encoding, e.g: >>> sys.stdout = filewrapper(sys.stdout, 'utf-8') >>> print u"??? \N{GREEK CAPITAL LETTER DELTA}" Useful if you don't want to append .encode() to everything you print out that potentially can contain non-ascii letters. /Ragnar From idaku2 at gmail.com Sat May 12 16:41:42 2007 From: idaku2 at gmail.com (idaku2 at gmail.com) Date: 12 May 2007 13:41:42 -0700 Subject: design question In-Reply-To: <5amj6gF2pbeeuU1@mid.individual.net> References: <1178992981.143066.279690@o5g2000hsb.googlegroups.com> <5amj6gF2pbeeuU1@mid.individual.net> Message-ID: <1179002502.146058.90860@n59g2000hsh.googlegroups.com> On May 12, 9:34 pm, Bjoern Schliessmann wrote: > In principle, this is legal. > > But OTOH, how could a ShoppingCart "buy" something? In my world, > Buyers "buy" when using ShoppingCarts. Yes, I don't know either. I got this assignment for my homework, and in UML diagram class ShoppingCart has method buy(), and the class Buyer doesn't have any methods, only attribute ShoppingCart, and I must simulate/implement online shopping. In my world buyers buy too, just wanna check with somebody with more experience. :) Thank you both. From carsten at uniqsys.com Tue May 15 09:00:43 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 15 May 2007 09:00:43 -0400 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179226183.215907.140450@q75g2000hsh.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179226183.215907.140450@q75g2000hsh.googlegroups.com> Message-ID: <1179234043.3385.9.camel@dot.uniqsys.com> On Tue, 2007-05-15 at 03:49 -0700, HYRY wrote: > > - should non-ASCII identifiers be supported? why? > Yes. I want this for years. I am Chinese, and teaching some 12 years > old children learning programming. The biggest problem is we cannot > use Chinese words for the identifiers. As the program source becomes > longer, they always lost their thought about the program logic. > > English keywords and libraries is not the problem, because we only use > about 30 - 50 of these words for teaching programming idea. They can > remember these words in one week. But for the name of variable or > function, it is difficult to remember all the English word. For > example, when we are doing numbers, maybe these words: [odd, even, > prime, minus ...], when we are programming for drawing: [line, circle, > pixel, ...], when it's for GUI: [ button, event, menu...]. There are > so many words that they cannot just remeber and use these words to > explain there idea. That is a good point, but I'd like to ask out of curiosity, at what age do children generally learn pinyin? (Assuming you speak Mandarin. If not, replace pinyin with the name of whatever phonetic transliteration is common in your region.) Granted, pinyin shoehorned into ASCII loses its tone marks, but the result would still be more mnemonic than an English word that the student has to learn. Regards, -- Carsten Haese http://informixdb.sourceforge.net From gtwatskixm at hotmail.cum Wed May 16 16:44:21 2007 From: gtwatskixm at hotmail.cum (gtski) Date: Wed, 16 May 2007 15:44:21 -0500 Subject: Jessica Simpson Sports new "Boob Job"!!!@ References: <1179126576.229946.109600@k79g2000hse.googlegroups.com> <1179165104.582094.200400@l77g2000hsb.googlegroups.com> Message-ID: "wb" wrote in message news:1179165104.582094.200400 at l77g2000hsb.googlegroups.com... > On May 14, 2:09 am, ready.or.speci... at gmail.com wrote: > > > If her boobs getting any bigger she won't be able to stand up. > Im afraid of boobs. they are not on men I suck. From fuzzyman at gmail.com Wed May 2 18:44:55 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 2 May 2007 15:44:55 -0700 Subject: Microsoft's Dynamic Languages Runtime (DLR) In-Reply-To: <59s6kbF2kq8uoU1@mid.individual.net> References: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> <59s6kbF2kq8uoU1@mid.individual.net> Message-ID: <1178145895.865828.18220@p77g2000hsh.googlegroups.com> On May 2, 8:20 pm, Pascal Costanza wrote: > sturlamolden wrote: > > On Monday Microsoft announced a new runtime for dynamic languages, > > which they call "DLR". It sits on top of the conventional .NET runtime > > (CLR) and provides services for dynamically typed languages like > > Python or Lisp (thus the cross-posting). Apparently is is distributed > > under a BSD-like open-source license. > > > I am curious to know how it performs in comparison to CPython and an > > efficient compiled Lisp like CMUCL. Speed is a major problem with > > CPython but not with .NET or CMUCL, so it will be interesting to see > > how the DLR performs in comparison. It would be great to finally see a > > Python that runs on steroids, but knowing M$ bloatware my expectations > > are not too high. > > > Has anyone looked at the DLR yet? What are your impression? > > So far, there is not a lot of information available. The only statement > about the technology I have read so far is that the DLR is a thin layer > on top of the CLR. This doesn't say a lot. > > So it's hard to tell whether this is a (good) marketing stunt or whether > there are actual substantial improvement to the infrastructure. Well, they're now implementing four dynamic languages on top of the DLR - not just IronPython. * IronPython * IronRuby * Java Script * VBx (a dynamic version of VB) The DLR provides a dynamic type system and hosting environment for dynamic languages. The nice part is that the DLR runs on top of the 'Core CLR' which ships with Silverlight. This means that apps. that run in Silverlight are secure - so you can run an IronPython console in the browser... Fuzzyman http://www.voidspace.org.uk/python/weblog/index.shtml > > Pascal > > -- > My website:http://p-cos.net > Common Lisp Document Repository:http://cdr.eurolisp.org > Closer to MOP & ContextL:http://common-lisp.net/project/closer/ From malaclypse2 at gmail.com Thu May 31 18:18:11 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Thu, 31 May 2007 18:18:11 -0400 Subject: c[:]() In-Reply-To: <001801c7a3cc$e9f0b270$240110ac@Muse> References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <135tobve86qj808@corp.supernews.com> <135tru124pie2b3@corp.supernews.com> <135tv1bjqgbmsc9@corp.supernews.com> <003301c7a3ab$f2bdf960$240110ac@Muse> <001801c7a3cc$e9f0b270$240110ac@Muse> Message-ID: <16651e80705311518g43066016x37f292e415f8c194@mail.gmail.com> On 5/31/07, Warren Stringer wrote: > In summation: > I started this thread asking why c[:]() wouldn't work Because it's not part of the language. Did you read something that made you think it would work? Or are you proposing a change to the language? I think you're better off providing the functionality yourself, for your own containers. Luckily, it's pretty easy to do. Mikael Olofsson showed you how to create a custom list that, when called, will call each of the items it contains. Then you can use the exact code you wrote in your first post, and it will do what you want. > I did not hijack another thread You really did. In the first message you sent, we see the following header: > In-Reply-To: <1180504773.374529.161740 at q66g2000hsg.googlegroups.com> What you probably did was click 'Reply' on a message in an existing thread, then change the Subject line and delete the quoted message. That doesn't start a new thread. That creates a new post in the old thread, with a new subject line and a completely unrelated message to the rest of the thread. If you're using a reader that groups everything by Subject line, it may even look like you started a new thread, but anyone who relies on the rest of the headers to build threads correctly will see differently. > I posted working examples (with one typo, not quoted here) I retyped the code you posted in the first post, and did not get the same results as you. Specifically: >>> def a: print 'a' SyntaxError: invalid syntax >>> def b: print 'b' SyntaxError: invalid syntax those obviously were not copied from working code. >>> c[:]() TypeError: 'tuple' object is not callable this has the correct spelling of 'tuple' in it. Your post misspelled it. and finally, >>> c[0]() a >>> c[:][0] I don't know how you could have gotten c[:][0] to print 'a', but it wasn't by running all of the code you presented to us. -- Jerry From pete.losangeles at gmail.com Tue May 15 23:08:39 2007 From: pete.losangeles at gmail.com (MisterPete) Date: 15 May 2007 20:08:39 -0700 Subject: inherit from file and create stdout instance? In-Reply-To: <1179280223.545538.81900@n59g2000hsh.googlegroups.com> References: <1179267498.154549.58370@h2g2000hsg.googlegroups.com> <1179270178.281061.34860@k79g2000hse.googlegroups.com> <1179272294.058634.140760@k79g2000hse.googlegroups.com> <1179280223.545538.81900@n59g2000hsh.googlegroups.com> Message-ID: <1179284919.465498.277290@w5g2000hsg.googlegroups.com> On May 16, 1:50 pm, 7stud wrote: > >but it is frustrating me that if I try to inherit from file it > >works fine for regular files > > I don't think that is correct characterization at all. What really > happens is that when you inherit from file, your class works when you > send the __init__ method a string, i.e. a filename. sys.stdout is not > a string. Presumably, when you have a file object like sys.stdout > already, you don't need to turn it into a file object, and therefore > file's init() method is not defined to accept a file object. > > >Is it just a bad idea to inherit from file to > >create a class to write to stdout or am I missing something? > > It seems to me that the very nature of a file object is to read and > write to itself. Yet, in some cases you want your file object to be > able to write to another file object. Why would you want your object > to be a file object if you can't use any of its methods? 7stud, I don't really want it to write to another file object, I'd like it to work just like a file object except for some extra options like verbosity. Similar to how sys provides stdout and stderr file objects I would like to provide Output objects for stdout and stderr... but without accepting a file object I'm not sure how I would instantiate an Output object that writes to anything like stdout or stderr without special casing them Gabriel, thanks for the suggestion! I think I'll go with an approach similar to that :) I guess I can't really get around using the stdout/stderr file objects for writing to those buffers. ============= oops, not that it really matters but I just realized that I cut and pasted the same code twice in my original post. I had meant to put this as the second chunk of code class Output(file): def __init__(self, name, mode='w', buffering=None, verbosity=1): super(Output, self).__init__(name, mode, buffering) self.verbosity = 1 def write(self, string, messageVerbosity=1): if messageVerbosity <= self.verbosity super(Output, self).write(string) From steven.bethard at gmail.com Sat May 12 14:49:35 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 12 May 2007 12:49:35 -0600 Subject: package rating system for the Cheese Shop In-Reply-To: <1178995430.511788.161150@e51g2000hsg.googlegroups.com> References: <1178995430.511788.161150@e51g2000hsg.googlegroups.com> Message-ID: cbtube03 at gmail.com wrote: > Is there a package rating system for the Cheese Shop, like how Perl > has cpanratings (http://cpanratings.perl.org/)? I don't know CPAN, but maybe this is what you're looking for: http://www.cheeserater.com/ ? STeVe From noagbodjivictor at gmail.com Thu May 3 20:28:44 2007 From: noagbodjivictor at gmail.com (noagbodjivictor at gmail.com) Date: 3 May 2007 17:28:44 -0700 Subject: How do I output a list like the interpreter do? In-Reply-To: <1178238251.343819.252370@h2g2000hsg.googlegroups.com> References: <1178236804.658955.204140@h2g2000hsg.googlegroups.com> <1178236866.035271.81460@c35g2000hsg.googlegroups.com> <1178238251.343819.252370@h2g2000hsg.googlegroups.com> Message-ID: <1178238524.374867.320190@p77g2000hsh.googlegroups.com> On May 3, 8:24 pm, noagbodjivic... at gmail.com wrote: > On May 3, 8:01 pm, noagbodjivic... at gmail.com wrote: > > > On May 3, 8:00 pm, noagbodjivic... at gmail.com wrote: > > > > >>> s = ['a','b'] > > > >>> s > > > ['a', 'b'] > > > > This is what I want so that I can put it in a module then import that > > > module to work with my variable. > > > Sorry for that typo in the title... > > I found a was using str(list). Do you know how to get rid of the > surrounding quotes? Nevermind... From michael at jedimindworks.com Wed May 23 17:36:11 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Wed, 23 May 2007 16:36:11 -0500 Subject: Creating Graphs for the Web In-Reply-To: <1179955032.556481.170260@g4g2000hsf.googlegroups.com> References: <1179955032.556481.170260@g4g2000hsf.googlegroups.com> Message-ID: <248D21A3-05EF-466C-86F2-C24E4363595E@jedimindworks.com> On May 23, 2007, at 4:17 PM, erikcw wrote: > I'm working on a django powered website, and need to dynamically > generate some graphs (bar, pie, and line) from users' data stored in > MySQL. > > Can anyone recommend a good library I can use for this? Matplotlib! From mcl.office at googlemail.com Sat May 26 08:15:43 2007 From: mcl.office at googlemail.com (mosscliffe) Date: 26 May 2007 05:15:43 -0700 Subject: Newbie: Struggling again 'map' In-Reply-To: References: <1180173252.906992.262570@q75g2000hsh.googlegroups.com> Message-ID: <1180181743.879140.304010@p47g2000hsd.googlegroups.com> Thank you all very much. I particularily found Roel's explanation and example most useful. At this stage I am getting my head around syntax, rather than language theory, although I know, I have to understand that as well. Thanks again. Richard On 26 May, 12:47, Roel Schroeven wrote: > mosscliffe schreef: > > > for x,y in map("N/A", lista, listb): ########## Fails - Can not call a > > 'str' > > print "MAP:", x, "<>", y > > > def fillwith(fillchars): > > return fillchars > > > for x,y in map(fillwith("N/A"), lista, listb): ########## Fails also - > > Can not call a 'str' > > print "MAP:", x, "<>", y > > The first argument to map is a function, which is called with the items > of the argument sequences. If the first argument is None, a default > function is used which returns a tuple of the items. In the case that > two input sequences are provided: > > map(None, lista, listb) > > is equivalent to: > > def maketuple(a, b): > return a, b > map(maketuple, lista, listb) > > So what you want to do can be done with map like this: > > def make_fill_missing(fillchars): > def fill_missing(a, b): > if a is None: > a = fillchars > if b is None: > b = fillchars > return a, b > return fill_missing > > map(make_fill_missing("N/A"), lista, listb)) > > -- > If I have been able to see further, it was only because I stood > on the shoulders of giants. -- Isaac Newton > > Roel Schroeven From gagsl-py2 at yahoo.com.ar Mon May 21 03:58:03 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 21 May 2007 04:58:03 -0300 Subject: Inverse of id()? References: <1179618173.280286.284120@n59g2000hsh.googlegroups.com> Message-ID: En Sun, 20 May 2007 22:19:01 -0300, Ian Clark escribi?: > On 5/20/07, Michael Hoffman wrote: >> [snip] >> That's not what I get: > > That's because you didn't have 'del a'. > > Now I tried this in the shell and got different id's for a and b, but > when I typed it into a file and ran from there the id's where always > the same. Must have something to do with other programs allocating > space faster than I can type everything out (I do have a few processes > going). Interesting. The point is, as id() is related to the object memory address, and memory may be reused, two objects (*NOT* simultaneously alive!!!) may return the same id(). Perhaps in some circunstances it's easier to show than in others, but it happens, so unless one is absolutely sure that the object is still alive, going back from its id to the original object is dangerous. -- Gabriel Genellina From laurent.pointal at wanadoo.fr Fri May 18 05:06:17 2007 From: laurent.pointal at wanadoo.fr (Laurent Pointal) Date: Fri, 18 May 2007 11:06:17 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <464d6b22$0$25929$ba4acef3@news.orange.fr> Long and interresting discussion with different point of view. Personnaly, even if the PEP goes (and its accepted), I'll continue to use identifiers as currently. But I understand those who wants to be able to use chars in their own language. * for people which are not expert developers (non-pros, or in learning context), to be able to use names having meaning, and for pro developers wanting to give a clear domain specific meaning - mainly for languages non based on latin characters where the problem must be exacerbated. They can already use unicode in strings (including documentation ones). * for exchanging with other programing languages having such identifiers... when they are really used (I include binding of table/column names in relational dataabses). * (not read, but I think present) this will allow developers to lock the code so that it could not be easily taken/delocalized anywhere by anybody. In the discussion I've seen that problem of mixing chars having different unicode number but same representation (ex. omega) is resolved (use of an unicode attribute linked to representation AFAIU). I've seen (on fclp) post about speed, it should be verified, I'm not sure we will loose speed with unicode identifiers. On the unicode editing, we have in 2007 enough correct editors supporting unicode (I configure my Windows/Linux editors to use utf-8 by default). I join concern in possibility to read code from a project which may use such identifiers (i dont read cyrillic, neither kanji or hindi) but, this will just give freedom to users. This can be a pain for me in some case, but is this a valuable argument so to forbid this for other people which feel the need ? IMHO what we should have if the PEP goes on: * reworking on traceback to have a general option (like -T) to ensure tracebacks prints only pure ascii, to avoid encoding problem when displaying errors on terminals. * a possibility to specify for modules that they must *define* only ascii-based names, like a from __futur__ import asciionly. To be able to enforce this policy in projects which request it. * and, as many wrote, enforce that standard Python libraries use only ascii identifiers. From steve at REMOVE.THIS.cybersource.com.au Fri May 11 23:43:03 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 12 May 2007 13:43:03 +1000 Subject: Newbie question about string(passing by ref) References: <1178833397.076720.279940@l77g2000hsb.googlegroups.com> Message-ID: On Thu, 10 May 2007 14:53:46 -0700, Gary Herron wrote: > Strings *are* passed by reference *always*. There is no copy and no > overhead. Efficiency is not based on length. Since the string is > immutable, nothing you do inside the function can change the string > outside the function. Python does NOT support pass by reference. Nor does it do pass by value. Both of those models might describe what other languages do, but they don't describe what Python does. Python's passing model is different from both pass by reference and pass by value, and there are circumstances where Python seems to be acting as if it were doing one or the other. But it isn't. The model Python uses is often (but not often enough...) called "pass by object" or "call by sharing". http://effbot.org/zone/call-by-object.htm Some people argue that because the underlying C implementation of C-Python uses pass-by-reference of pointers, it's okay to say Python does too. That's an invalid argument. Not all Python implementations are written in C. PyPy doesn't even have pointers, being written in Python. Even if it did, what the underlying engine does internally is irrelevant to what the Python language does. What Python does is pass _objects_, not values or references. -- Steven. From gagsl-py2 at yahoo.com.ar Thu May 17 19:49:18 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 17 May 2007 20:49:18 -0300 Subject: An expression that rebinds a variable? References: <1179411429.536764.5620@q75g2000hsh.googlegroups.com> <1179437375.505844.306510@e65g2000hsc.googlegroups.com> Message-ID: En Thu, 17 May 2007 18:29:35 -0300, GreenH escribi?: > Thanks, But, my interest is actually in finding the cases in which > eval(expr) would throw surprises at me by bringing changes in > namespace(s), just because I haven't given a namespace for that eval() > i.e., where would we see the perils of not passing namespace to the > 'eval'. As already said, it's hard to make changes to the local namespace, but the global namespace is directly accessible. py> z = {'a': 1} py> eval("z.setdefault('b',2)") 2 py> z {'a': 1, 'b': 2} eval is unsafe by definition, even if you provide your own namespaces. If you can't trust the expression to be evaluated, don't use eval if you are minimally concerned about security. -- Gabriel Genellina From ericcoetzee at gmail.com Tue May 1 04:22:49 2007 From: ericcoetzee at gmail.com (eC) Date: 1 May 2007 01:22:49 -0700 Subject: Qustion about struct.unpack In-Reply-To: References: Message-ID: <1178007769.831101.238210@u30g2000hsc.googlegroups.com> On Apr 30, 9:41 am, Steven D'Aprano wrote: > On Mon, 30 Apr 2007 00:45:22 -0700, OhKyu Yoon wrote: > > Hi! > > I have a really long binary file that I want to read. > > The way I am doing it now is: > > > for i in xrange(N): # N is about 10,000,000 > > time = struct.unpack('=HHHH', infile.read(8)) > > # do something > > tdc = struct.unpack('=LiLiLiLi',self.lmf.read(32)) > > I assume that is supposed to be infile.read() > > > # do something > > > Each loop takes about 0.2 ms in my computer, which means the whole for loop > > takes 2000 seconds. > > You're reading 400 million bytes, or 400MB, in about half an hour. Whether > that's fast or slow depends on what the "do something" lines are doing. > > > I would like it to run faster. > > Do you have any suggestions? > > Disk I/O is slow, so don't read from files in tiny little chunks. Read a > bunch of records into memory, then process them. > > # UNTESTED! > rsize = 8 + 32 # record size > for i in xrange(N//1000): > buffer = infile.read(rsize*1000) # read 1000 records at once > for j in xrange(1000): # process each record > offset = j*rsize > time = struct.unpack('=HHHH', buffer[offset:offset+8]) > # do something > tdc = struct.unpack('=LiLiLiLi', buffer[offset+8:offset+rsize]) > # do something > > (Now I'm just waiting for somebody to tell me that file.read() already > buffers reads...) > > -- > Steven D'Aprano I think the file.read() already buffers reads... :) From olsongt at verizon.net Wed May 23 11:10:05 2007 From: olsongt at verizon.net (olsongt at verizon.net) Date: 23 May 2007 08:10:05 -0700 Subject: Windows Debugging w/o MS In-Reply-To: References: Message-ID: <1179933005.903709.258250@q75g2000hsh.googlegroups.com> > > I've tried compiling python from source, and my extension module, > using MSVC8 (free express version), and I managed to get this to work. > The thing is, I don't want to have to recompile every single python > package I need (wxPython, SciPy, etc). > Debug builds are incompatible with release builds. You'll need to build every binary extension in debug mode (assuming the original authors don't provide debug builds). From warren at muse.com Thu May 31 17:44:49 2007 From: warren at muse.com (Warren Stringer) Date: Thu, 31 May 2007 14:44:49 -0700 Subject: c[:]() In-Reply-To: References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> <135tobve86qj808@corp.supernews.com> <135tru124pie2b3@corp.supernews.com> <135tv1bjqgbmsc9@corp.supernews.com> <003301c7a3ab$f2bdf960$240110ac@Muse> Message-ID: <001801c7a3cc$e9f0b270$240110ac@Muse> Quotes out of context with mistaken assumptions, now follow: > >>>> So c[:]() -- or the more recent go(c)() -- executes all those > >>>> behaviors. > > No it doesn't. See below. > > > > If c[:]() works, the so does this, using real world names > > > > orchestra[:].pickle() > > orchestra[conductor()].sequence() > > > > Though, I'm already starting to prefer: > > > > do(orchestra).pickle() > > do(orchestra(conductor)).sequence() > > > Yes, dammit, but c[:]() *DOESN'T WORK* unless you have made some pretty > crufty changes to the underlying object. I started this thread asking why c[:]() doesn't work. > This is what I'm having difficulty understanding. You said, in your > original post (which, by the way, hijacked another thread about > something completely different): What?!? I started this thread. > > I want to call every object in a tupple, like so: > > > [By the way, that's "tuple", not "tupple"] > > #------------------------------------------ > > def a: print 'a' > > def b: print 'b' > > c = (a,b) > > > >>>> >>>c[:]() # i wanna > > TypeError: 'tupple' object is not callable > > > >>>> >>>c[0]() # expected > > a > >>>> >>>c[:][0] # huh? > > a > This is what I just don't believe. And, of course, the use of "tupple" > above tells us that this *wasn't" just copied and pasted from an > interactive session. Try it. > >>>> >>> [i() for i in c] # too long and ...huh? > > a > > b > > [None,None] > > #------------------------------------------ > This is also clearly made up. I repeat: try it. > In a later email you say: > > > why does c[:][0]() work but c[:]() does not? > > The reason for this ... Stated elsewhere, but thanks > > Why does c[0]() has exactly the same results as c[:][0]() ? > > The reason for this is that c is exactly the same as c[:]. The slicing > notation "[:]" tells the interpreter to use a tuple consisting of > everything in the tuple to which it's applied. Since the interpreter > knows that tuples are immutable (can't be changed), it just uses the > same tuple -- since the immutability there's no way that a difference > could arise between the tuple and a copy of the tuple, Python doesn't > bother to make a copy. > > This behavior is *not* observed with lists, because lists are mutable. But neither tupples or lists work, so immutability isn't an issue. > I realise you are trying to find ways to make Python more productive for > you, and there's nothing wrong with that. But consider the following, > which IS copied and pasted: > > >>> def a(): > ... print "A" > ... > >>> def b(): > ... print "B" > ... > >>> c = (a, b) > >>> c > (, ) > >>> c[:] > (, ) > >>> c[0]() > A > >>> c[1]() > B > >>> c() > Traceback (most recent call last): > File "", line 1, in > TypeError: 'tuple' object is not callable > >>> c[:]() > Traceback (most recent call last): > File "", line 1, in > TypeError: 'tuple' object is not callable > >>> I never said that c() would execute a list nor did I ever say that c[:]() would execute a list. > I think the fundamental mistake you have made is to convince yourself that > > c[:]() > > is legal Python. It isn't, it never has been. In summation: I started this thread asking why c[:]() wouldn't work I did not hijack another thread I posted working examples (with one typo, not quoted here) I am extremely annoyed by this post Tis best not to assume what other people are thinking From tjreedy at udel.edu Wed May 9 17:49:14 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 9 May 2007 17:49:14 -0400 Subject: Behavior of mutable class variables References: <1178744257.369030.95310@w5g2000hsg.googlegroups.com> Message-ID: wrote in message news:1178744257.369030.95310 at w5g2000hsg.googlegroups.com... | Here's what I expect to happen each time simulation( ) is called: the | class variable NStocks for the class Stock is initialized to an empty | list, Why would you expect that ;-) A class statement is usually executed exactly once, as in your code. The body of a class statement usually consists of several name bindings: some are explicit, like your NStocks assignment statement; some are implicit, like you __init__ function definition. The resulting dictionary is used to create the class object, which is mostly a wrapper around the dict created by the class statement body. tjr From len-l at telus.net Thu May 24 16:04:03 2007 From: len-l at telus.net (Lenard Lindstrom) Date: Thu, 24 May 2007 20:04:03 GMT Subject: What is an instance and what isn't? In-Reply-To: References: Message-ID: Gre7g Luterman wrote: > I suppose I was lulled into complacency by how Python makes so many things > look like classes, but I'm starting to realize that they're not, are they? > > I'm writing a C program which handles Python objects in different ways based > on their type. I do a PyInstance_Check(PyObj) to determine if the PyObj is > an instance, but it is returning 0 on a lot of stuff that I thought would be > an instance. Python has two class systems: classic classes and new-style classes. New-style classes were introduced with Python 2.2. Classic classes remain for backwards compatibility. See section 3.3 "New-style and classic classes" in the Python 2.5 "Python Reference Manual" for an introduction. PyInstance_Check() returns true only if an object is a classic class instance. Built-in types like list and dict are new-style classes, so PyInstance_Check() will return false (0) for list and dictionary instances. It will also return false for instances of Python classes inheriting from a new-style class. > So I did the following simple test on three things that look > like instances: > > 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. >>>> class a: pass > .... >>>> type(a()) > >>>> type(Exception()) > >>>> class b(dict): pass > .... >>>> type(b()) > > > I was relieved that a() returns an instance, but I was surprised that > Exceptions aren't really instances at all. And what's the deal with derving > a class from a standard type like a dictionary? I thought for sure, that > would be an instance, but this shows it is a class?!? > Class "a" is a classic class. It does not inherit from a new-style class. In Python 2.5 Exception became a new-style class as well. dict is also a new-style class, as mentioned above. > Can anyone explain the last one and/or give me a simple test I can do in C > to determine whether a Python object is "instance-like"? > It all depends on what is meant by "instance-like". All Python classes are instances as well. In Python a class is defined by how it behaves rather than by some special interpreter level flag. So there is no definitive way to separate objects into "classes" and "instances". The best I can suggest is testing if an object is a "class-like" classic or new-style class. The inspect module defines an isclass function as follows: def isclass(object): """Return true if the object is a class. Class objects provide these attributes: __doc__ documentation string __module__ name of module in which this class was defined""" return isinstance(object, types.ClassType) or \ hasattr(object, '__bases__') --- Lenard Lindstrom From horpner at yahoo.com Thu May 10 14:32:46 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 10 May 2007 18:32:46 GMT Subject: append References: <1178816546.689849.255070@y5g2000hsa.googlegroups.com> Message-ID: On 2007-05-10, HMS Surprise wrote: > Trying not to be a whiner but I sure have trouble finding > syntax in the reference material. I want to know about list > operations such as append. Is there a pop type function? I > looked in tutorial, language reference, and lib for list, > append, sequence. Is there a place where us doofi ( who may not > have our heads out in the sunlight) may find all related syntax > grouped together? You need the material in the Python Manual in the astonishingly useful Library Reference section 1.2.3: Built-In Types. The only thing you'll look at nearly as much is 1.2.1: Built-In Functions. -- Neil Cerutti From colin.barnette at gmail.com Wed May 16 04:09:51 2007 From: colin.barnette at gmail.com (colin.barnette at gmail.com) Date: 16 May 2007 01:09:51 -0700 Subject: A new project. Message-ID: <1179302989.142733.257910@n59g2000hsh.googlegroups.com> I am interested in organizing and taking part in a project that would create a virtual world much like the one described in Neal Stephenson's 'Snow Crash'. I'm not necessarily talking about something 3d and I'm not talking about a game either. Like a MOO, only virtual. And each 'user' is allocated space with which they are free to edit in any way, within the confines of that space. I know Second Life and others come to mind when you think of this, but Frankly Second Life came off as sloppy to me. I want people to be able to code their own objects and environments with the ease of Python. I don't know forget the suggestions, anything is on the table, but there are just so many half-hearted and weak commercial attempts at this I feel that it's time to get Python involved in the game and do it right. If anyone has any interest, ideas, comments or otherwise, e-mail me. If some interest is shown we'll start a board, a site, an IRC channel or whatever we have to do to meet and get the ball rolling. :) Thanks. From john at datavoiceint.com Mon May 14 10:27:35 2007 From: john at datavoiceint.com (HMS Surprise) Date: 14 May 2007 07:27:35 -0700 Subject: Time In-Reply-To: <1179152573.315362.37040@u30g2000hsc.googlegroups.com> References: <1178916216.893542.257320@y80g2000hsf.googlegroups.com> <1178916422.065108.312920@l77g2000hsb.googlegroups.com> <1178920014.621031.301860@n59g2000hsh.googlegroups.com> <1178927105.482975.174760@y5g2000hsa.googlegroups.com> <1179151205.987222.54910@k79g2000hse.googlegroups.com> <1179152573.315362.37040@u30g2000hsc.googlegroups.com> Message-ID: <1179152855.424498.274820@p77g2000hsh.googlegroups.com> On May 14, 9:22 am, HMS Surprise wrote: > > if t[2] == 'PM': > > hrMn[0] = int(hrMn[0]) + 12 > > Oops, should be: > hrMn[0] = int(hrMn[0] > if t[2] == 'PM': > hrMn[0] += 12 Oops +=1, should be: hrMn[0] = int(hrMn[0] if t[2] == 'PM': hrMn[0] += 12 Need more starter fluid, coffee please!!! From phishboh at gmail.com Wed May 16 07:47:33 2007 From: phishboh at gmail.com (phishboh at gmail.com) Date: 16 May 2007 04:47:33 -0700 Subject: Automatic login to website (newbie) In-Reply-To: References: Message-ID: <1179316053.152612.312860@h2g2000hsg.googlegroups.com> On 15 Mai, 16:25, "Tim Williams" wrote: > The frame URL ishttp://www.expekt.com/contenttop.jsp, you could try > navigating directly to the frame to see if it helps > > website = "http://www.expekt.com/contenttop.jsp" > ie.navigate(website) > ie.textBoxSet('user', 'MyLogin') > ie.textBoxSet('pass', 'MyPassword') > ie.buttonClick('actn') Thanks a lot, it helped! (after also changing the last line to ie.buttonClick('login')) Next, I'd like to follow links within the website, but I ran into similar problems again. The following code navigates me to the desired website: # python.org ie = cPAMIE.PAMIE() website = "http://www.python.org" ie.navigate(website) ie.textBoxSet('q', 'pamie') ie.buttonClick('submit') ie.linkClick('Agile Testing with Python Test Frameworks') But nothing happens when using the any of the linkClick commands in the code below (I'd like to click the "odds" link in the upper menu): # expekt.com ie = cPAMIE.PAMIE() website = "http://www.expekt.com/eng" ie.navigate(website) ie.linkClick(' odds') #ie.linkClick('odds') #ie.linkClick('http://www.expekt.com/livebetting/index.jsp') #ie.linkClick('subMenusport1') I guess that I have to do something like "in the frame called 'menu', follow the link called 'odds'" (and similar for login; in the frame called 'contenttop', enter 'MyLogin' in the text box called 'user' and 'MyPassword' in the text box called 'pass'). Any ideas on how to accomplish this? Code samples (and/or documentation) to * launch IE (succeeded: IE = win32com.client.DispatchEx('InternetExplorer.Application.1')) * navigate to website (succeeded: IE.Navigate(website)) * fill in specific text box(es) in specific frame(s) and submit (need support) * follow specific link(s) in specific frame(s) (need support) using win32.client (or PAMIE or other) would be very welcome! Any help highly appreciated. Thanks! From deets at nospam.web.de Tue May 8 07:55:15 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 08 May 2007 13:55:15 +0200 Subject: Designing a graph study program References: <1178619753.077639.112510@q75g2000hsh.googlegroups.com> <5ab3mgF2o5bfbU1@mid.uni-berlin.de> <1178622700.228390.237310@n59g2000hsh.googlegroups.com> Message-ID: <5ab6p3F2ni551U1@mid.uni-berlin.de> > Ok thank you very much I'll try with that. > But I have some design doubts, I'd like to keep the algorithm (for > example bfs) as clean as possible, being independent from the drawing > methods. > And how could I make it step through algorithms without having a more > complicated code? Maybe using threads? Along the lines of what Marc said: Use two graph-implementations that share the same interface regarding the algorithms, but one will emit events to some observer for each operation on the graph - edge/node adding/removal, attribute changing and so forth. Thus the algorithm is kept clean, and all that you can visualize anyway is available to you. diez From mail at a-beyer.de Thu May 31 03:59:07 2007 From: mail at a-beyer.de (Andreas Beyer) Date: Thu, 31 May 2007 09:59:07 +0200 Subject: Good Python style? Message-ID: <465E804B.9060904@a-beyer.de> Hi, I found the following quite cryptic code, which basically reads the first column of some_file into a set. In Python I am used to seeing much more verbose/explicit code. However, the example below _may_ actually be faster than the usual "for line in ..." Do you consider this code good Python style? Or would you recommend to refrain from such complex single-line code?? Thanks! Andreas inp = resource(some_file) # read first entries of all non-empty lines into a set some_set = frozenset([line.split()[0] for line in \ filter(None, [ln.strip() for ln in inp])]) From robert.kern at gmail.com Wed May 16 17:22:51 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 16 May 2007 16:22:51 -0500 Subject: try In-Reply-To: <1179350291.106871.25640@e65g2000hsc.googlegroups.com> References: <1179350291.106871.25640@e65g2000hsc.googlegroups.com> Message-ID: HMS Surprise wrote: > I read in the ref man that try-except-finally did not work in earlier > versions, I am using jython 2.2. Does this imply that try-except > without finally does not work either? I get a syntax error on the else > below. Some of the functions embedded in the try section try to > convert strings to ints, etc and may fail on bad data, thus try seemed > like a good start for a workaround. > > Thanks, > > jh > > > #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > def restoreDevice(self, deviceId, closeTime = time()): > self.logon() > try: > lst = self.getLastUpdatedDevice(deviceId) > lastUpdated = lst[0] > incidentId = lst[1] > print 'L', lastUpdated, 'I', incidentId > self.restore(incidentId, lastUpdated) > except: > else: > print "couldn't find incident" The except: block still needs something in it, even if it is just "pass". -- 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 claird at lairds.us Wed May 2 18:13:37 2007 From: claird at lairds.us (Cameron Laird) Date: Wed, 2 May 2007 22:13:37 +0000 Subject: gpp (conditional compilation) References: <1178127460.046945.254100@y80g2000hsf.googlegroups.com> Message-ID: In article , Duncan Booth wrote: >"maxwell at ldc.upenn.edu" wrote: > >> I'm trying to use the gpp utility (Gnu points to >> http://en.nothingisreal.com/wiki/GPP) to do conditional compilation in >> Python, and I'm running into a problem: the same '#' character >> introduces Python comments and is used by default to introduce #ifdef >> etc. lines. >> >> Here's an example of what I'm trying to do: >> >> #ifdef DEBUG >> stderr.write("variable is...") #details of msg omitted >> #endif >> > >Why do you want conditional compilation. Is there anything wrong with: > > if __debug__: > stderr.write("variable is...") #details of msg omitted > >If you run Python with the -O command line option the code protected by the >if statement will be optimised out. > >For most other purposes where you might use conditional compilation just >adding 'if' statements to execute at runtime (or try/except) will do the >same purpose: > >if sys.platform=='win32': > def foo(): > ... something ... >else: > def foo(): > .... something different ... I want to reinforce this. Yes, it is possible to pre-process Python source, it's even been done before, and I'm sympathetic to the suggestion that m4's more appropriate than gpp. However, Duncan and others who've followed up are right: you can live without this stuff. In fact, those who think they need condi- tional compilation with Python are, with very few exceptions, simply mistaken. The urge to transform Python source this way almost always is a symptom of unfamiliarity with Python potential and good style. It's not just that Python can do without conditional compilation; Python offers *better* means to achieve the same goals. From gagsl-py2 at yahoo.com.ar Tue May 22 04:51:43 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 22 May 2007 05:51:43 -0300 Subject: converting text and spans to an ElementTree References: Message-ID: En Tue, 22 May 2007 03:02:34 -0300, Steven Bethard escribi?: > I have some text and a list of Element objects and their offsets, e.g.:: > > >>> text = 'aaa aaa aaabbb bbbaaa' > >>> spans = [ > ... (etree.Element('a'), 0, 21), > ... (etree.Element('b'), 11, 18), > ... (etree.Element('c'), 18, 18), > ... ] > > I'd like to produce the corresponding ElementTree. So I want to write a > get_tree() function that works like:: > > >>> tree = get_tree(text, spans) > >>> etree.tostring(tree) > 'aaa aaa aaabbb bbbaaa' > > Perhaps I just need some more sleep, but I can't see an obvious way to > do this. Any suggestions? I need *some* sleep, but the idea would be as follows: - For each span generate two tuples: (start_offset, 1, end_offset, element) and (end_offset, 0, -start_offset, element). If start==end use (start_offset, -1, start_offset, element). - Collect all tuples in a list, and sort them. The tuple is made so when at a given offset there is an element that ends and another that starts, the ending element comes first (because it has a 0). For all the elements that end at a given point, the shortest comes first. - Initialize an empty list (will be used as a stack of containers), and create a root Element as your "current container" (CC), the variable "last_used" will keep the last position used on the text. - For each tuple in the sorted list: - if the second item is a 1, an element is starting. Insert it into the CC element, push the CC onto the stack, and set the new element as the new CC. The element data is text[last_used:start_offset], and move last_used to start_offset. - if the second item is a 0, an element is ending. Discard the CC, pop an element from the stack as the new CC. The element data is text[last_used:end_offset], move last_used up to end_offset. - if the second item is a -1, it's an element with no content. Insert it into the CC element. You can play with the way the tuples are generated and sorted, to get 'aaa aaa aaabbb bbbaaa' instead. -- Gabriel Genellina From deets at nospam.web.de Wed May 30 15:10:42 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 30 May 2007 21:10:42 +0200 Subject: Appending a log file and see progress as program executes In-Reply-To: References: <5c5u8vF2v1pm3U2@mid.uni-berlin.de> Message-ID: <5c60hiF2uhe70U1@mid.uni-berlin.de> Steve Holden schrieb: > Diez B. Roggisch wrote: >> Karim Ali schrieb: > [...] >> >> install cygwin bash, and use >> >> tail out.log >> > I think Diez meant > > tail -f out.log I did. Thanks. diez From larry.bates at websafe.com Tue May 29 13:19:20 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 29 May 2007 12:19:20 -0500 Subject: SMTPAuthenticationError In-Reply-To: <1180457929.374281.168960@g37g2000prf.googlegroups.com> References: <1180457929.374281.168960@g37g2000prf.googlegroups.com> Message-ID: Ramashish Baranwal wrote: > Hi, > > I am trying to send a mail using smtplib. My server requires me to > authenticate, for this I'm using SMTP.login function. However it > fails- > >>>> server = smtplib.SMTP(host='mail.domain', port=25) >>>> server.login('username', 'password') > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.4/smtplib.py", line 587, in login > raise SMTPAuthenticationError(code, resp) > smtplib.SMTPAuthenticationError: (535, 'authorization failed > (#5.7.0)') > > I am sure that I am giving the correct credentials. The same works in > Thunderbird. Am I missing something here or am I supposed to use some > other library for this? > > Thanks in advance, > Ram > Are you sure that your SMTP server uses this type of authentication? Some SMTP servers use POP3 followed by SMTP to authenticate instead. use telnet to verify, this link might help. http://www.computerperformance.co.uk/exchange2003/exchange2003_SMTP_Auth_Login.htm#3)%20Auth%20Login -Larry From aleax at mac.com Wed May 9 01:05:12 2007 From: aleax at mac.com (Alex Martelli) Date: Tue, 8 May 2007 22:05:12 -0700 Subject: which is more pythonic/faster append or +=[] References: Message-ID: <1hxtelz.7f6rvnw4cyxmN%aleax@mac.com> alf wrote: > two ways of achieving the same effect > > > l+=[n] > > or > > l.append(n) > > > so which is more pythonic/faster? .append - easy to measure, too: brain:~ alex$ python -mtimeit 'L=range(3); n=23' 'x=L[:]; x.append(n)' 1000000 loops, best of 3: 1.31 usec per loop brain:~ alex$ python -mtimeit 'L=range(3); n=23' 'x=L[:]; x+=[n]' 1000000 loops, best of 3: 1.52 usec per loop Alex From rene at korteklippe.de Tue May 15 17:28:09 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 15 May 2007 23:28:09 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649dd55$0$23144$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <464a25e9$0$10188$9b4e6d93@newsspool4.arcor-online.net> Javier Bezos schrieb: >> But having, for example, things like open() from the stdlib in your code >> and then ?ffnen() as a name for functions/methods written by yourself is >> just plain silly. It makes the code inconsistent and ugly without >> significantly improving the readability for someone who speaks German >> but not English. > > Agreed. I always use English names (more or > less :-)), but this is not the PEP is about. We all know what the PEP is about (we can read). The point is: If we do not *need* non-English/ASCII identifiers, we do not need the PEP. If the PEP does not solve an actual *problem* and still introduces some potential for *new* problems, it should be rejected. So far, the "problem" seems to just not exist. The burden of proof is on those who support the PEP. -- Ren? From CRhode at LacusVeris.com Tue May 15 11:24:39 2007 From: CRhode at LacusVeris.com (Chuck Rhode) Date: Tue, 15 May 2007 10:24:39 -0500 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <134hdc9qpdjhbaa@corp.supernews.com> <134hdn8j41l3u16@corp.supernews.com> Message-ID: Grant Edwards wrote this on Mon, 14 May 2007 19:22:16 +0000. My reply is below. >> Of course. If they're any longer than that then you can't fit an >> entire identifier into a 36-bit CDC 6600 machine register so you >> can do a compare with a single machine instruction. While skimming this discussion, I, too, was suffering flashbacks to CDC's 6-bit Hollerith code. -- .. Chuck Rhode, Sheboygan, WI, USA .. Weather: http://LacusVeris.com/WX .. 69? ? Wind NNE 6 mph ? Sky partly cloudy. From __peter__ at web.de Fri May 18 05:05:21 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 May 2007 11:05:21 +0200 Subject: Random selection References: <20070518103926.65bb8ea7.tartifola@gmail.com> Message-ID: Tartifola wrote: > I have a list with probabilities as elements > > [p1,p2,p3] > > with of course p1+p2+p3=1. I'd like to draw a > random element from this list, based on the probabilities contained in > the list itself, and return its index. > > Any help on the best way to do that? import random import bisect def draw(probabilities): sigma = 0.0 ps = [] for p in probabilities: sigma += p ps.append(sigma) _bisect = bisect.bisect _random = random.random while 1: yield _bisect(ps, _random()) if __name__ == "__main__": from itertools import islice histo = [0]*4 for i in islice(draw([0.2, 0.3, 0.5]), 100000): histo[i] += 1 print histo From sjmachin at lexicon.net Fri May 11 21:02:09 2007 From: sjmachin at lexicon.net (John Machin) Date: 11 May 2007 18:02:09 -0700 Subject: module error for elementtree In-Reply-To: References: <1178867119.666923.204000@h2g2000hsg.googlegroups.com> Message-ID: <1178931729.844197.130770@l77g2000hsb.googlegroups.com> On May 11, 11:12 pm, "Jerry Hill" wrote: > On 11 May 2007 00:05:19 -0700, saif.shak... at gmail.com > > wrote: > > For the above code to work elementtree is > > imported in first line ,but when running it says : > > ImportError: No module named elementtree.ElementTree > > Does thie module exists as default or a patch is needed? > > That depends on which version of Python you are running. Starting > with 2.5, ElementTree was moved into the standard library, as part of > the xml package. If you're using an older version of python, I think > you'll need to download and install the elementtree package fromhttp://effbot.org/zone/element-index.htm > > Assuming you're using python 2.5, you probably want something like this: > > from xml.etree.ElementTree import ElementTree as et > 1. The OP appears to be confusing ElementTree and Element (objects of the first class are containers of objects of the second class). 2. For any serious work to be done efficiently, the cElementTree module should be used. 3. Here's some code that appears to work for supporting multiple versions of Python: 8< --- import_et.py --- import sys python_version = sys.version_info[:2] print >> sys.stderr, "Python version:", sys.version_info if python_version >= (2, 5): import xml.etree.cElementTree as ET else: try: import cElementTree as ET except ImportError: try: import ElementTree as ET except ImportError: msg = "\nYou need the [c]ElementTree package\n" \ "from http://effbot.org/downloads/\n\n" sys.stderr.write(msg) raise print >> sys.stderr, "ET imported from", ET.__file__ 8< --- end of import_et.py --- 4. and some (occasionally astonishing) results: C:\junk>for %v in (5,1,4) do \python2%v\python import_et.py C:\junk>\python25\python import_et.py Python version: (2, 5, 1, 'final', 0) ET imported from C:\python25\lib\xml\etree\cElementTree.pyc C:\junk>\python21\python import_et.py Python version: (2, 1, 3, 'final', 0) ET imported from C:\python21\cElementTree.pyd C:\junk>\python24\python import_et.py Python version: (2, 4, 3, 'final', 0) ET imported from C:\Documents and Settings\sjm\Application Data\Python- Eggs\celementtree-1.0.5_20051216-py2.4-win32.egg-tmp\cElementTree.pyd IIRC, I have TurboGears (a leading contender for the "All of your sys.path are belong to us" award) to thank for that little gem :-) HTH, John From bdesth.quelquechose at free.quelquepart.fr Wed May 2 19:19:14 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 03 May 2007 01:19:14 +0200 Subject: My Python annoyances In-Reply-To: References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> Message-ID: <463912a4$0$2415$426a74cc@news.free.fr> James Stroud a ?crit : (snip) > > I want to complain about the fact that I wrote 200 lines the other day > and it worked first time. Problem was, I spent 20 minutes before I > realized that the lack of errors was a result of the lack of bugs. +1 QOTW From chris at simplistix.co.uk Thu May 17 19:41:17 2007 From: chris at simplistix.co.uk (Chris Withers) Date: Fri, 18 May 2007 00:41:17 +0100 Subject: MailingLogger 3.1.0 Released! Message-ID: <464CE81D.8010706@simplistix.co.uk> Hot on the heals of the 3.0.0 release, this 3.1.0 release offers support for SMTP hosts that require authentication in order to send mail... Mailinglogger enables log entries to be emailed either as the entries are logged or as a summary at the end of the running process. This pair of enhanced emailing handlers for the python logging framework is now available as a standard python package and as an egg. The handlers have the following features: - customisable and dynamic subject lines for emails sent - emails sent with an X-Mailer header for easy filtering - flood protection to ensure the number of emails sent is not excessive - fully documented and tested In addition, extra support is provided for configuring the handlers when using ZConfig, Zope 2 or Zope 3. Installation is as easy as: easy_install mailinglogger For more information, please see: http://www.simplistix.co.uk/software/python/mailinglogger cheers, Chris -- Simplistix - Content Management, Zope & Python Consulting - http://www.simplistix.co.uk From arnodel at googlemail.com Sun May 20 16:27:20 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 20 May 2007 13:27:20 -0700 Subject: Getting the member of a singleton set Message-ID: <1179692840.158236.198150@z24g2000prd.googlegroups.com> Hi all, I often find myself needing to get (non-destructively) the value of the member of a singleton set. Is there a good way to do this (as an expression?) None of the ones I can think of satisfy me, eg: * list(myset)[0] * iter(myset).next() * set(myset).pop() What I would like is something like a 'peek()' function or method (would return the same as pop() but wouldn't pop anything). I would like to know of a better idiom if it exists. If not, isn't there a need for one? Note: it is comparatively easier to do this destructively: myset.pop() or to bind a name to the member: element, = myset PS: this problem is not restricted to sets but could occur with many 'container' types. -- Arnaud From nogradi at gmail.com Tue May 1 14:08:17 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Tue, 1 May 2007 20:08:17 +0200 Subject: sqlite for mac? In-Reply-To: <1178039558.882802.214030@n59g2000hsh.googlegroups.com> References: <1177993261.572563.70370@n76g2000hsh.googlegroups.com> <1178039558.882802.214030@n59g2000hsh.googlegroups.com> Message-ID: <5f56302b0705011108n26186167ocdbdf4ef163f5730@mail.gmail.com> > > > Does sqlite come in a mac version? > > > > The interface (pysqlite) is part of the python 2.5 standard library > > but you need to install sqlite itself separately (as far as I > > remember) fromwww.sqlite.org > > > > Daniel > > I'm using python 2.4.4 because the download said there were more mac > modules available for 2.4.4. than 2.5, and I can't seem to locate a > place to download sqlite for mac. If you use python 2.4.4 you can install the pysqlite module from http://www.initd.org/tracker/pysqlite/wiki/pysqlite (this is the interface that is included in python 2.5, you need to install sqlite itself, probably from source, with any python version). Daniel From gagsl-py2 at yahoo.com.ar Mon May 14 23:06:20 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 15 May 2007 00:06:20 -0300 Subject: Class name as argument References: <1179182092.643727.223740@u30g2000hsc.googlegroups.com> Message-ID: En Mon, 14 May 2007 19:34:52 -0300, HMS Surprise escribi?: > Snippet 1 below doesn't do much but works (more code is inserted by a > generator). In the next to last line the class name is also used as > argument. I have seen this construct before and have had error > messages tell me that the name is expected. Why is this so? In snippet > 2 that I concocted is not required. Is it related to __init__ perhaps? The arguments are those expected by the class constructor: __new__, and initializer: __init__. It's up to the class designer to define which arguments are required -if any- and which ones are optional -if any-. In your case, see the documentation for PyHttpTestCase. -- Gabriel Genellina From steve at REMOVE.THIS.cybersource.com.au Thu May 24 06:51:02 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 24 May 2007 20:51:02 +1000 Subject: 0 == False but [] != False? References: <1179982400.412340.178710@g4g2000hsf.googlegroups.com> <1rda53hphn117k5scvcqrc7c2e37utfhgu@4ax.com> Message-ID: On Thu, 24 May 2007 06:59:32 +0000, Tim Roberts wrote: > As a general rule, I've found code like "if x == False" to be a bad idea in > ANY language. Surely that should be written as "if (x == False) == True"? -- Steven. From mensanator at aol.com Sat May 12 20:55:40 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 12 May 2007 17:55:40 -0700 Subject: Interesting list Validity (True/False) In-Reply-To: References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> <1178914190.166662.285410@p77g2000hsh.googlegroups.com> <1178915791.584216.293130@l77g2000hsb.googlegroups.com> <1178918808.091358.233740@o5g2000hsb.googlegroups.com> Message-ID: <1179017740.656323.209590@e51g2000hsg.googlegroups.com> On May 12, 12:56?pm, Carsten Haese wrote: > On Fri, 2007-05-11 at 14:26 -0700, mensana... at aol.com wrote: > > if arg==True: > > > tests the type property (whether a list is a boolean). > > That sounds nonsensical and incorrect. Please explain what you mean. Sec 2.2.3: Objects of different types, except different numeric types and different string types, never compare equal; > > "if arg==True" tests whether the object known as arg is equal to the > object known as True. > > Regards, > > -- > Carsten Haesehttp://informixdb.sourceforge.net From sturlamolden at yahoo.no Tue May 1 12:10:25 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 1 May 2007 09:10:25 -0700 Subject: Lisp-like macros in Python? Message-ID: <1178035825.193334.184250@o5g2000hsb.googlegroups.com> Hello The Lisp crowd always brags about their magical macros. I was wondering if it is possible to emulate some of the functionality in Python using a function decorator that evals Python code in the stack frame of the caller. The macro would then return a Python expression as a string. Granted, I know more Python than Lisp, so it may not work exactly as you expect. Any comments and improvements are appreciated. Regards, Sturla Molden __codestore__ = {} def macro(func): """ Lisp-like macros in Python (C) 2007 Sturla Molden @macro decorates a function which must return a Python expression as a string. The expression will be evaluated in the context (stack frame) of the caller. """ def macro_decorator(*args,**kwargs): global __codestore__ import sys pycode = '(' + func(*args,**kwargs) + ')' try: ccode = __codestore__[pycode] except: ccode = compile(pycode,'macrostore','eval') __codestore__[pycode] = ccode frame = sys._getframe().f_back try: retval = eval(ccode,frame.f_globals,frame.f_locals) return retval except: raise macro_decorator.__doc__ = func.__doc__ return macro_decorator # Usage example def factorial(x): """ computes the factorial function using macro expansion """ @macro def fmacro(n): """ returns '1' or 'x*(x-1)*(x-2)*...*(x-(x-1))' """ if n == 0: code = '1' else: code = 'x' for x in xrange(1,n): code += '*(x-%d)' % (x) return code return fmacro(x) From conor.robinson at gmail.com Mon May 21 12:48:38 2007 From: conor.robinson at gmail.com (py_genetic) Date: 21 May 2007 09:48:38 -0700 Subject: converting strings to most their efficient types '1' --> 1, 'A' ---> 'A', '1.2'---> 1.2 In-Reply-To: References: <1179529661.555196.13070@k79g2000hse.googlegroups.com> <1179551680.283157.19000@y80g2000hsf.googlegroups.com> <464FA156.2070704@lexicon.net> Message-ID: <1179766118.332466.251870@r3g2000prh.googlegroups.com> This is excellect advise, thank you gentelman. Paddy: We can't really, in this arena make assumtions about the data source. I fully agree with your point, but if we had the luxury of really knowing the source we wouldn't be having this conversation. Files we can deal with could be consumer data files, log files, financial files... all from different users BCP-ed out or cvs excell etc. However, I agree that we can make one basic assumtion, for each coll there is a correct and furthermore optimal format. In many cases we may have a supplied "data dictionary" with the data in which case you are right and we can override much of this process, except we still need to find the optimal format like int8 vs int16. James: Using a baysian method were my inital thoughts as well. The key to this method, I feel is getting a solid random sample of the entire file without having to load the whole beast into memory. What are your thoughts on other techniques? For example training a neural net and feeding it a sample, this might be nice and very fast since after training (we would have to create a good global training set) we could just do a quick transform on a coll sample and ave the probabilities of the output units (one output unit for each type). The question here would encoding, any ideas? A bin rep of the vars? Furthermore, niave bayes decision trees etc? John: > The approach that I've adopted is to test the values in a column for all > types, and choose the non-text type that has the highest success rate > (provided the rate is greater than some threshold e.g. 90%, otherwise > it's text). > For large files, taking a 1/N sample can save a lot of time with little > chance of misdiagnosis. I like your approach, this could be simple. Intially, I was thinking a loop that did exactly this, just test the sample colls for "hits" and take the best. Thanks for the sample code. George: Thank you for offering to share your transform function. I'm very interested. From chris.arndt at web.de Mon May 7 09:56:22 2007 From: chris.arndt at web.de (Christopher Arndt) Date: 7 May 2007 06:56:22 -0700 Subject: Getting some element from sets.Set In-Reply-To: <1178267029.258868.219800@h2g2000hsg.googlegroups.com> References: <1178258913.095438.173020@h2g2000hsg.googlegroups.com> <1178267029.258868.219800@h2g2000hsg.googlegroups.com> Message-ID: <1178546182.056214.120580@y5g2000hsa.googlegroups.com> On 4 Mai, 10:23, "jm.sur... at no.spam.gmail.com" wrote: > > > It is not possible to index set objects. That is OK. > > > But, what if I want to find some element from the Set. > > In the particular case, I have to read an attribute from any one of > the elements, which one doesn't matter because this attribute value is > same across all elements in the set. Just to clarify: do you want to just get an *arbitrary* element from the set or do you want to find a *specific* element in the set? In the first case you have to convert it to a list (as pointed out earlier in this thread): >>> s = set(range(10)) >>> list(s)[0] 0 In the second case, just use th "in" operator: >>> 10 in s False >>> 5 in s True Since you have to have a reference to the object for whose membership you are testing, you can just use this object. Stupid example: >>> class Point: ... def __init__(self, x, y): ... self.x = x ... self.y = y ... >>> l = [Point(n,n+2) for n in range(10)] >>> s = set(l) >>> Point(0,2) in s False >>> l[0] in s True >>> >>> l[0].x,l[0].y (0, 2) Chris From carsten at uniqsys.com Sun May 13 09:57:26 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sun, 13 May 2007 09:57:26 -0400 Subject: Interesting list Validity (True/False) In-Reply-To: <1179020634.130689.171960@o5g2000hsb.googlegroups.com> References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> <1178914190.166662.285410@p77g2000hsh.googlegroups.com> <1178915791.584216.293130@l77g2000hsb.googlegroups.com> <1178918808.091358.233740@o5g2000hsb.googlegroups.com> <1179017740.656323.209590@e51g2000hsg.googlegroups.com> <1179020634.130689.171960@o5g2000hsb.googlegroups.com> Message-ID: <1179064646.3097.24.camel@localhost.localdomain> On Sat, 2007-05-12 at 18:43 -0700, mensanator at aol.com wrote: > > That doesn't explain what you mean. How does "if arg==True" test whether > > "a list is a boolean"? > > >>> type(sys.argv) > > >>> type(True) > All right, so what you meant was "Assuming that arg is a list, 'if arg==True' will always fail because lists never compare equal to any boolean." > Actually, it's this statement that's non-sensical. > > > "if arg==True" tests whether the object known as arg is equal to the > object known as True. > > > [snip examples of "surprising" equality tests...] The statement I made is simply the meaning of "if arg==True" by definition, so I don't see how it can be nonsensical. The problem is that you consider equality tests in Python to be nonsensical because they don't fit with your opinion of what equality should mean. Regards, -- Carsten Haese http://informixdb.sourceforge.net From python at rcn.com Thu May 10 02:46:31 2007 From: python at rcn.com (Raymond Hettinger) Date: 9 May 2007 23:46:31 -0700 Subject: change of random state when pyc created?? In-Reply-To: References: Message-ID: <1178779591.271735.95890@l77g2000hsb.googlegroups.com> On May 9, 6:42 am, "Alan Isaac" wrote: > Is there > a warning anywhere in the docs? Should > there be? I do not think additional documentation here would be helpful. One could note that the default hash value is the object id. Somewhere else you could write that the placement of objects in memory is arbitrary and can be affected by a number of factors not explicity under user control. With those notes scattered throughout the documentation, I'm not sure that you would have found them and recognized the implications with respect to your design and with respect to the deletion of pyc files (which is just one factor among many that could cause different placements in memory). Also, the existing docs describe behavior at a more granular level. How the parts interact is typically left to third-party documentation (i.e. the set docs say what the set methods do but do not give advice on when to use them instead of a dict or list). Out of this thread, the more important lesson is that the docs intentionally do not comment on implemation specific details. When the docs do not make specific guarantees and behavior is left undefined, it is not a good practice to make assumptions about invariants that may or may not be true (in your case, you assumed that objects would be located in the same memory locations between runs -- while that sometimes happens to be true, it is certainly not guaranteed behavior as you found out -- moreover, you've made non-guaranteed assumptions about the arbitrary ordering of an unordered collection -- a definite no-no). Raymond Hettinger From showell30 at yahoo.com Tue May 29 18:18:25 2007 From: showell30 at yahoo.com (Steve Howell) Date: Tue, 29 May 2007 15:18:25 -0700 (PDT) Subject: itertools.groupby In-Reply-To: <1180442369.3373.26.camel@dot.uniqsys.com> Message-ID: <295830.97547.qm@web33505.mail.mud.yahoo.com> --- Carsten Haese wrote: > As an aside, while groupby() will indeed often be > used in conjunction > with sorted(), there is a significant class of use > cases where that's > not the case: I use groupby to produce grouped > reports from the results > of an SQL query. In such cases, I use ORDER BY to > guarantee that the > results are supplied in the correct order rather > than using sorted(). > Although I'm not trying to preoptimize here, it seems a mistake to use sorted() and groupby() in conjunction, if you're dealing with a use case where you don't need the groups themselves to be sorted. Instead, you'd use something more straightforward (and faster, I think) like the cookbook "SQL-like Group By" example. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/259173 It seems to me that the classic use case for itertools.groupby() is the never-ending stream of data where you're just trying to pick out consecutive related elements. For example, if you're snooping on syslog, you could use groupby() to avoid repeating duplicate messages to some other output stream. ____________________________________________________________________________________Take the Internet to Go: Yahoo!Go puts the Internet in your pocket: mail, news, photos & more. http://mobile.yahoo.com/go?refer=1GNXIC From vmaslov at swsoft.com Mon May 7 01:54:42 2007 From: vmaslov at swsoft.com (Vyacheslav Maslov) Date: Mon, 07 May 2007 12:54:42 +0700 Subject: Help creating Tiger hash function in Python In-Reply-To: <133tf2ucg5dpd0f@corp.supernews.com> References: <133tf2ucg5dpd0f@corp.supernews.com> Message-ID: <463EBF22.7010201@swsoft.com> > I am a Uni student and for a project in Information Systems Security due > in just under two weeks, I have tried to make a Python version of the > Biham / Anderson Tiger Hash function. I have put the original C source > and my two files Tiger.py and doHash.py on my website: > > http://www.users.on.net/~mlivingstone/ > > My problems are doubtless basic since I have been teaching myself > Python. My best knowledge is Java :-( > > Firstly, in doHash.py, I cannot invoke tiger() without getting unbounded > errors and / or complaints about no such method. First of all you should create an instance of you Tiger class, you try to do this by line: x = Tiger.Tiger But this is wrong, because you should call constructor and pass all necessary parameters, in very simple case: x = Tiger.Tiger() (if there is no constructor parameters) -- Vyacheslav Maslov SWsoft, Inc. From steven.bethard at gmail.com Sun May 27 02:20:46 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 27 May 2007 00:20:46 -0600 Subject: PyPI bdist_wininst upload failing In-Reply-To: References: Message-ID: Steven Bethard wrote: > I just tried to upload new versions of the argparse module to PyPI, but > it seems like I can no longer upload Windows installers: > > $ setup.py sdist bdist_wininst upload > ... > running upload > Submitting dist\argparse-0.8.0.zip to http://www.python.org/pypi > Server response (200): OK > Submitting dist\argparse-0.8.0.win32.exe to http://www.python.org/pypi > Upload failed (400): Bad Request > > Anyone know what I'm doing wrong? (I've always been able to upload > bdist_wininst packages to PyPI in the past.) Still haven't figured this out yet, but I discovered that I get a slightly more informative message if I do the upload manually with the PyPI form. It then says: Error processing form invalid distribution file Looks like this originates from: https://svn.python.org/packages/trunk/pypi/webui.py down near the bottom in the file_upload() method. I can't figure out which "invalid distribution file" error is being triggered, but in looking around, I saw that is_distutils_file() in: https://svn.python.org/packages/trunk/pypi/verify_filetype.py says: if filename.endswith('.exe'): # check for valid exe if filetype != 'bdist_wininst': return False try: t = StringIO.StringIO(content) t.filename = filename z = zipfile.ZipFile(t) l = z.namelist() except zipfile.error: return False for zipname in l: if not safe_zipnames.match(zipname): return False That seems a little weird to me. Are the bdist_wininst exe files really zip files? Or did I just misunderstand what "content" is? STeVe From p at ulmcnett.com Fri May 25 20:09:39 2007 From: p at ulmcnett.com (Paul McNett) Date: Fri, 25 May 2007 17:09:39 -0700 Subject: How to get started as a xhtml python mysql freelancer ? In-Reply-To: <1180136893.220560.49340@q75g2000hsh.googlegroups.com> References: <1180136893.220560.49340@q75g2000hsh.googlegroups.com> Message-ID: <46577AC3.8060903@ulmcnett.com> gert wrote: > I made something that i was hoping it could make people happy enough > so i could make a living by providing support for commercial use of > http://sourceforge.net/projects/dfo/ > > But in reality i am a lousy sales men and was wondering how you people > sell stuff as a developer ? In my experience, you don't make money by selling support unless you are a large company selling support for a large project or a wide array of projects. The people that will use your library will mostly be developers and not end-users, after all. To make money from things you develop, I think you need to take your library and either build an application that has wide appeal and sell that, or sell yourself as a custom developer that can build the application the customer needs, using the tools you are comfortable with. You can then build in the cost of developing your library that you will reuse for the custom applications. -- pkm ~ http://paulmcnett.com From erikwickstrom at gmail.com Fri May 25 11:02:49 2007 From: erikwickstrom at gmail.com (erikcw) Date: 25 May 2007 08:02:49 -0700 Subject: Why isn't this query working in python? In-Reply-To: References: <1180103946.552760.239200@p47g2000hsd.googlegroups.com> Message-ID: <1180105369.754385.118910@k79g2000hse.googlegroups.com> On May 25, 10:51 am, "Dave Borne" wrote: > > I'm trying to run the following query: > ... > > member_id=%s AND expire_date > NOW() AND completed=1 AND (product_id > > Shouldn't you be using the bind variable '?' instead of '%s' ? > (I'm asking because I'm not entirely sure how the execute command is > doing the substitution) > > -Dave Hi Dave, I'm not sure. I've been using this format for all of my other queries without issue. What would the query look like with the bind variable instead? Erik From mail at timgolden.me.uk Fri May 4 04:42:51 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 04 May 2007 09:42:51 +0100 Subject: invoke user's standard mail client In-Reply-To: <1178266064.922925.125760@y80g2000hsf.googlegroups.com> References: <1178266064.922925.125760@y80g2000hsf.googlegroups.com> Message-ID: <463AF20B.7030002@timgolden.me.uk> luc.saffre at gmail.com wrote: > the simplest way to launch the user's standard mail client from a > Python program is by creating a mailto: URL and launching the > webbrowser: [... snip code ...] > But this method is limited: you cannot specify a file to be attached > to the mail. And I guess that there would be problems if the body text > is too complex. > Does somebody know about a better method? > It should be possible at least on Windows, since Acrobat Reader is > able to do it. I'm going to stick my neck out and say: I doubt if there's one recognised, approved method. That would require every email client to have a way of accepting a command which said "Open up a new email and put this, this, and this into that field, that space, and that attachment." The only thing I can think of which comes close is the mailto: protocol you refer to, but according to its RFC http://www.faqs.org/rfcs/rfc2368.html the only fields allowed are headers and the special case of "body" which, as you point out, is hardly intended for embedded attachments. I would imagine that Acrobat must special case known email clients and probably won't work for some obscure client. Thunderbird, for example, seems (haven't tried it) to allow for an attachment: http://www.mozilla.org/docs/command-line-args.html Doubtless Outlook has some equivalent mechanism. After that, you're down to looking at docs for Eudora, Pine, etc. TJG From steve at holdenweb.com Thu May 31 12:19:46 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 31 May 2007 12:19:46 -0400 Subject: HTML Form/Page and Navigation with multiple buttons In-Reply-To: <1180624671.896662.174390@m36g2000hse.googlegroups.com> References: <1180617750.709628.180070@p77g2000hsh.googlegroups.com> <465edbfa$0$784$426a34cc@news.free.fr> <1180624671.896662.174390@m36g2000hse.googlegroups.com> Message-ID: mosscliffe wrote: > Excellent - thanks for all your help. I now have a form created by a > python script executing an HTML page, doing everything I need, except > for Session Data (probably use hidden fields ?? future research) and > the actual paging logic !!! > In fact you should find you can name all of the buttons the same. Then when you click one the value associated with that name tells you which button the user pressed. Just don't call your button "submit", since that masks a JavaScript form method that you will probably end up using sooner or later. > If I use a link. I have to add all my hidden fields to the query > string, otherwise cgi.FieldStorage(), does not return the hidden > fields. This would also mean users see all the hidden field data. > > Is there another way, other than a cookie ? > > Why is a link better than a button ? > Beats me why you got that advice. Buttons are perfectly adequate for that purpose. However, you can if you want use links with "javascript: ..." href values to accomplish local scripting which can do funky stuff like setting form field values and submitting the form. This can get tricky though, and it sounds like you are maybe a little too new to the web to be messing with client-side scripting. Later ... > I have been using 'post' for my form, to eliminate the displaying of > field values. > That does make the location bar easier on the user's eye, and is the standard way to proceed. It doesn't add anything in the way of security, however. > I accept I am quite niave about FORM/HTML logic. > We all have to start somewhere! 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From steve at holdenweb.com Thu May 17 17:48:21 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 17 May 2007 17:48:21 -0400 Subject: FreeType In-Reply-To: <397DF4A1-A882-4B90-ADE1-8D3F3BC408F6@jedimindworks.com> References: <1179422948.600593.117310@p77g2000hsh.googlegroups.com> <1179431247.954420.219690@q75g2000hsh.googlegroups.com> <397DF4A1-A882-4B90-ADE1-8D3F3BC408F6@jedimindworks.com> Message-ID: <464CCDA5.4030505@holdenweb.com> Michael Bentley wrote: > On May 17, 2007, at 2:47 PM, Glich wrote: > >> I've been there. All the code is in C/C++, don't I need it in python? >> I will explore the software. I dismissed this because there was no >> python. I am knew to all of this. Thanks for your reply. > > The c stuff (freetype) is what you need (it gets installed as a > library that can be used by python or any other software entity that > needs its functionality). It may seem a little weird, but lots of > the stuff you call from python is written in c. More than likely, > your python interpreter is also written in c :-) > > Alternatively use the Python Imaging Library (PIL), which I believe includes freetype support. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From apatheticagnostic at gmail.com Wed May 30 22:14:21 2007 From: apatheticagnostic at gmail.com (kaens) Date: Wed, 30 May 2007 22:14:21 -0400 Subject: Off Topic: What is the good book to learn Python ? In-Reply-To: References: <1180549522.350380.276570@q66g2000hsg.googlegroups.com> Message-ID: <163f0ce20705301914y7dd31c32vfc406de88516a59@mail.gmail.com> On 30 May 2007 17:28:39 -0700, Aahz wrote: > In article , > kaens wrote: > > > >I would also recommend to stay away from any "for dummies" or "in x > >(hours/days)" books. They can be decent introductory material, but > >unless you are really really new to programming, you probably wouldn't > >be getting enough information to justify the cost of the book (and a > >lot of times they have a lot of bad practices in them) > > Maybe you should try actually reading _Python for Dummies_. ;-) > -- > Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ > > "as long as we like the same operating system, things are cool." --piranha > -- > http://mail.python.org/mailman/listinfo/python-list > I haven't read it, maybe I will. I have just noticed that the "for dummies" books tend to be a bit lacking. That's just my opinion, of course. From thorsten at thorstenkampe.de Thu May 31 14:00:55 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Thu, 31 May 2007 19:00:55 +0100 Subject: Python memory handling References: <1180611604.247696.149060@h2g2000hsg.googlegroups.com> <1180627331.756615.132650@k79g2000hse.googlegroups.com> Message-ID: * Chris Mellon (Thu, 31 May 2007 12:10:07 -0500) > > Like: > > import pool > > pool.free() > > pool.limit(size in megabytes) > > > > Why not letting the user choosing that, why not giving the user more > > flexibility ? > > I will try later under linux with the latest stable python > > > > Regards, > > FP > > > > The idea that memory allocated to a process but not being used is a > "cost" is really a fallacy, at least on modern virtual memory sytems. > It matters more for fully GCed languages, where the entire working set > needs to be scanned, but the Python GC is only for breaking refcounts > and doesn't need to scan the entire memory space. > > There are some corner cases where it matters, and thats why it was > addressed for 2.5, but in general it's not something that you need to > worry about. If it's swapped to disk than this is a big concern. If your Python app allocates 600 MB of RAM and does not use 550 MB after one minute and this unused memory gets into the page file then the Operating System has to allocate and write 550 MB onto your hard disk. Big deal. Thorsten From duprez at hinet.net.au Mon May 28 22:00:53 2007 From: duprez at hinet.net.au (Mick Duprez) Date: 28 May 2007 19:00:53 -0700 Subject: Python command line error In-Reply-To: References: <1180398300.682311.224210@i38g2000prf.googlegroups.com> Message-ID: <1180404052.995269.30590@i38g2000prf.googlegroups.com> On May 29, 11:33 am, Max Erickson wrote: > Mick Duprez wrote: > > Hi All, > > > I've installed Python 2.5 on a number of machines but on one I'm > > having problems with the CLI. > > If I fire up the 'cmd' dos box and type 'python' I get a line of > > gibberish and it locks up the cli, if I run the 'command' dos box > > I get a few lines of garbage and it crashes/closes the dos box. > > > I've tried a re-install, checked my system paths etc but I can't > > get it to work, it works ok for running scripts from a dbl click > > in explorer for instance and from Idle, I just can't run scripts > > from the command line. > > > I have installed - > > xp pro sp2 > > Python25 > > wxPython2.8 unicode > > PIL > > numpy > > > any clues to what's causing this behavior? > > tia, > > Mick. > > What kind of gibberish? Actual garbage characters and the like? > > Anyway, maybe try running which; this one should be easy to get > going: > > http://gnuwin32.sourceforge.net/packages/which.htm > > But I have never used it, I use the one in this package: > > http://unxutils.sourceforge.net/ > > It expects 'python.exe' or whatever, not just 'python', I would > expect the gnuwin32 version to behave similarly. > > max Thanks Max, I just worked it out just before I read your post...doh! I have cygwin on this machine also and the cygwin/bin path was before the Python25 path so it was playing up, I put the Python25 path before the cygwin stuff and it's fixed. It's always something simple! Cheers, Mick. From steve at REMOVE.THIS.cybersource.com.au Thu May 10 11:49:33 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 11 May 2007 01:49:33 +1000 Subject: keyword checker - keyword.kwlist References: Message-ID: On Thu, 10 May 2007 13:38:40 +0000, tom wrote: > Hi > > I try to check whether a given input is keyword or not. However this > script won't identify keyword input as a keyword. How should I modify it > to make it work? It works for me. Try printing keyword.__file__ to make sure you are importing the right file. Also try printing keyword.kwlist. -- Steven. From aotto1968 at onlinehome.de Thu May 10 02:59:10 2007 From: aotto1968 at onlinehome.de (Andreas Otto) Date: Thu, 10 May 2007 08:59:10 +0200 Subject: python module developer wanted for 'libmsgque' Message-ID: Hi, I'm a the maintainer for the new project 'libmsgque' hosted at SF (see below for details) and need a volunteer to develop the language bindings for python. Is somebody available to take over this job ? An example language binding for tcl is allready available. This is the initial announcement: ANNOUNCE: libmsgque2.3-beta2 The libmsgque project is an infrastructure for linking applications together to act like a single application. This is done using Unix or inet domain sockets. The framework handles all aspects of setting up and maintaining the link in addition to starting and stopping the different applications, starting and stopping the communication interface, sending and receiving packages, reading and writing data from or into packages, setting up and maintaining the event handling for asynchronous transfers, and propagating warnings or errors. WHERE TO GET ============ As usual, it is available from: http://libmsgque.sourceforge.net/ http://sourceforge.net/projects/libmsgque/ WHAT'S NEW ========== This is the initial announcement WHAT IS IT ========== First of all it is a framework to link commands together to avoid the traditional shell pipline using a similar approach as MS PowerShell. To get more information's please use the following links: 1. an overview about the basic concept: http://libmsgque.sourceforge.net/overview.htm 2. the man page of the tclmsgque extension: http://libmsgque.sourceforge.net/tclmsgque.htm Regards, Andreas Otto (aotto1968) From bj_666 at gmx.net Fri May 25 05:45:23 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 25 May 2007 11:45:23 +0200 Subject: just a bug (was: xml.dom.minidom: how to preserve CRLF's inside CDATA?) References: <1179841504.782279.86490@u36g2000prd.googlegroups.com> <1180082137.329142.45350@p77g2000hsh.googlegroups.com> Message-ID: In <1180082137.329142.45350 at p77g2000hsh.googlegroups.com>, sim.sim wrote: > Below the code that tryes to parse an well-formed xml, but it fails > with error message: > "not well-formed (invalid token): line 3, column 85" How did you verified that it is well formed? `xmllint` barf on it too. > The "problem" within CDATA-section: it consists a part of utf-8 > encoded string wich was splited (widely used for memory limited > devices). > > When minidom parses the xml-string, it fails becouse it tryes to convert > into unicode the data within CDATA-section, insted of just to return the > value of the section "as is". The convertion contradicts the > specification http://www.w3.org/TR/REC-xml/#sec-cdata-sect An XML document contains unicode characters, so does the CDTATA section. CDATA is not meant to put arbitrary bytes into a document. It must contain valid characters of this type http://www.w3.org/TR/REC-xml/#NT-Char (linked from the grammar of CDATA in your link above). Ciao, Marc 'BlackJack' Rintsch From broek at cc.umanitoba.ca Mon May 7 03:50:32 2007 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Mon, 07 May 2007 02:50:32 -0500 Subject: PChess 0.9 In-Reply-To: References: Message-ID: <463EDA48.2050308@cc.umanitoba.ca> majeed rana said unto the world upon 05/07/2007 01:13 AM: > I want pchess 0.9 > I want a mansion and a yacht. Unlike you, google can't help me. Brian vdB From vatamane at gmail.com Thu May 10 04:40:44 2007 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 10 May 2007 01:40:44 -0700 Subject: PYDOC replacement. (Was:Sorting attributes by catagory) In-Reply-To: References: <1178755860.993987.312700@e51g2000hsg.googlegroups.com> Message-ID: <1178786444.529360.195910@h2g2000hsg.googlegroups.com> On May 10, 1:28 am, Ron Adam wrote: > Nick Vatamaniuc wrote: > > Ron, > > > Consider using epydoc if you can. Epydoc will sort the methods and it > > will also let you use custom CSS style sheets for the final HTML > > output. Check out the documentation of my PyDBTable module. > >http://www.psipy.com/PyDBTable > > > -Nick Vatamaniuc > > Hi Nick, > > I already have sorting and style sheets taken care of. I'm just trying to > get the content of each sub section correct at this point. The overall > frame work is finished. > > I don't think Epydoc can replace the console help() output. The site.py > module imports help(), from pydoc.py. That serves as the consoles > interactive help mode. When you type help() at the console, you are using > pydoc. > > Some of the differences... > > Epydoc > ------ > Output formats: > - html files > - graphs (requires Graphviz) I like this! > - pdf files (requires latex) > > * Requires explicitly generating files first. > * Supports file parsing only instead of introspection. > > Epydoc is more of a complete application and has many nice features such as > the graphs and completeness checks, that will make it better than pydoc for > creating more complete pre-generated html documents with less work. > > Pydoc > ===== > Output formats: > - live interactive console text > - live interactive html with a local html server. > * no files are generated. (just in the browser cache) > * supports custom CSS stylesheets > > (API data output...) > - text > - html page > - html section (for use in templates) > - xml > - reST (not yet, but will be easy to do) > > The reason for having additional output formats is it makes it much easier > to use it as a tool to extract documentation from source code to be > combined with existing more complete documentation. > > I am planning on writing output formatters to return docutils and docbook > data structures as well. With those, you will be able to convert to latex, > pdf, and other formats. The data formats for those are very close to what > I'm using, so this should be easy to do. > > Other side benefits of doing this is that some of the modules in pydoc have > been generalized so that they can be used without pydoc. The html server, > and the document data and formatter classes, can be used independently of > pydoc. > > The overall total size has not increased much, and it is more modular, > maintainable, and extendable. Maintainability is a major concern for any > library module or package. > > Of course it will need to be approved first. ;-) > > Cheers, > Ron Thanks for the info, Ron. I had no idea pydoc was that powerful! -Nick From steven.bethard at gmail.com Sun May 27 02:25:21 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 27 May 2007 00:25:21 -0600 Subject: Is PEP-8 a Code or More of a Guideline? In-Reply-To: References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> Message-ID: Stefan Sonnenberg-Carstens wrote: > Paul McGuire schrieb: >> I'm starting a new thread for this topic, so as not to hijack the one >> started by Steve Howell's excellent post titled "ten small Python >> programs". >> >> In that thread, there was a suggestion that these examples should >> conform to PEP-8's style recommendations, including use of >> lower_case_with_underscores style for function names. I raised some >> questions about this suggestion, since I liked the names the way they >> were, but as a result, part of the discussion has drifted into a >> separate track about PEP-8, and naming styles. > > I prefer mixedCaseStyle, and I think that should be "standard", as this > style is commonly > used in all "major" languages , for example Java,C++,C#. > It shortens the identifiers but leaves the meaning intact. The argument for under_score_names is usually that non-native speakers can more easily find the word boundaries. Not being a non-native speaker ;-) I can't verify that one, but it's pretty plausible given the current amount of money spent on research on automatic word-segmentation for languages like Chinese. =) STeVe From joshusdog at gmail.com Fri May 25 15:52:56 2007 From: joshusdog at gmail.com (joshusdog at gmail.com) Date: 25 May 2007 12:52:56 -0700 Subject: unhandled exception question Message-ID: <1180122776.247680.151150@p77g2000hsh.googlegroups.com> I'm working on a test application that embeds the Python interpreter. I have the following problem... I've created my own interactive interpreter loop. Essentially, it reads the command from the prompt and calls the following C code: PyObject* pMainModule = PyImport_AddModule("__main__"); PyObject* pMainDictionary = PyModule_GetDict(pMainModule); PyObject* pObj = PyRun_String(pCommandText, Py_single_input, pMainDictionary, pMainDictionary); where pCommandText is the text entered by the user. I also have the following Python functions defined: def Boo(): raise Exception() def Foo(): try: MyModule.SomeFunction() except Exception: print "goodbye" MyModule.SomeFunction() is defined in C. All it does is call Boo() with the following code: PyObject* pMainModule = PyImport_AddModule("__main__"); PyObject* pMainDictionary = PyModule_GetDict(pMainModule); PyObject* pObj = PyRun_String("Boo()", Py_single_input, pMainDictionary, pMainDictionary); If it's at all relevent, I'm using Boost.Python to embed MyModule. Now here's the problem: when I type "Foo()" at the prompt, it calls Foo(), which calls MyModule.SomeFunction(), which calls Boo(), which raises the exception. However, the exception doesn't get handled, despite the try-except statement in Foo(). Even stranger, if I manually enter the entire multi-line try-except statement at the prompt (instead of simply calling Foo()), the exception is handled properly and "goodbye" is printed to the screen. What's going on here? Why is exception properly handled in the second case, but not the first? From tjreedy at udel.edu Thu May 3 16:18:03 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 3 May 2007 16:18:03 -0400 Subject: My Python annoyances References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> Message-ID: "Ben Collver" wrote in message news:FbadnQTrwMX6daTbnZ2dnUVZ_segnZ2d at scnresearch.com... |I rewrote my code in Python and I found myself running into many of the | same hassles that I run into with other languages: inaccurate and | incomplete documentation, a maze of little platform-specific quirks to | work around in the base classes, and a macho community of users. Including you. | I tried to write portable Python code. The zlib CRC function returned | different results on architectures between 32 bit and 64 bit | architectures. I filed a bug report. It was closed, without a comment | from the person who closed it. Misleading and untrue. Here is the link you omitted http://sourceforge.net/tracker/index.php?func=detail&aid=1678102&group_id=5470&atid=105470 www.python.org/sf/1678102 Three days after you posted, 'gagenellina' explained that he thought your complaint was invalid. "py> -531560245 & 0xffffffff 3763407051L It's the same number (actually, the same bit pattern). ..." A few weeks later, noticing that you had not challenged his explanation, I closed after changing the Resolution box to Invalid. THAT WAS MY COMMENT. A month later, I notice that you still have not directly challenged G's claim of invalidity. Instead, you ignored it and simply repeated your claim here. WHO IS IGNORING WHO? | I get the unspoken message: bug reports are not welcome. Giving the shortage of reviewer time, invalid bug reports on tracker are a nuisance and a diversion from attending to valid reports and reviewing patches. That is why I encourage people to post here for community review. Real bug reports are quite welcome, as any honest person could determine by looking thru the tracker. Terry Jan Reedy From dr.mtarver at ukonline.co.uk Fri May 4 05:07:06 2007 From: dr.mtarver at ukonline.co.uk (Mark Tarver) Date: 4 May 2007 02:07:06 -0700 Subject: Lisp for the C21 In-Reply-To: <1178219732.127815.3260@y80g2000hsf.googlegroups.com> References: <1178155239.007219.205020@y5g2000hsa.googlegroups.com> <1178219732.127815.3260@y80g2000hsf.googlegroups.com> Message-ID: <1178269626.886617.214390@u30g2000hsc.googlegroups.com> QUOTE Python has readable syntax, a huge library, and bindings for what seems like every major in linux. Perl has CPAN. It seems with those languages if you want to do something all you have to do is import functionality from a library someone had written and use that. In lisp you'd have to "roll your own". Why should I keep on learning lisp when there are python and perl? UNQUOTE I can see where this guy is coming from (though I can't find the original post any more (?)). See my remarks on the Lisp for the Twenty First Century http://www.lambdassociates.org/lC21.htm for our take on this one. Mark From bill.scherer at verizonwireless.com Thu May 24 10:25:49 2007 From: bill.scherer at verizonwireless.com (Bill Scherer) Date: Thu, 24 May 2007 10:25:49 -0400 Subject: installing cx_Oracle. In-Reply-To: References: Message-ID: <4655A06D.704@verizonwireless.com> Carl K wrote: > Getting closer, thanks Bill and Diez. > > $ export ORACLE_HOME > $ ORACLE_HOME=/usr/lib/oracle/xe/app/oracle/product/10.2.0/client > $ python setup.py build > $ sudo python setup.py install > > $ python -c "import cx_Oracle" > Traceback (most recent call last): > File "", line 1, in ? > ImportError: libclntsh.so.10.1: cannot open shared object file: No such file or > directory > > guessing I need to add > /usr/lib/oracle/xe/app/oracle/product/10.2.0/client/lib/ > to some path? > You can `export LD_LIBRARY_PATH=/usr/lib/oracle/xe/app/oracle/product/10.2.0/client/lib` or (assuming a recent RedHat linux (or similar) now), put that path in a file, /etc/ld.so.conf.d/oracle.conf and run /sbin/ldconfig You'll find the latter operation to be persistent, and the former is not. > btw - anyone know of a .deb that will install this? > > Carl K > From rowan at sylvester-bradley.org Fri May 11 08:13:46 2007 From: rowan at sylvester-bradley.org (rowan at sylvester-bradley.org) Date: 11 May 2007 05:13:46 -0700 Subject: How to tell whetehr Python script called as CGI or from command line? In-Reply-To: References: <1176725137.128549.131130@p77g2000hsh.googlegroups.com> Message-ID: <1178885626.420970.13250@l77g2000hsb.googlegroups.com> > import os > if "QUERY_STRING" in os.environ: > # CGI script > > might work. Thanks Steve for this suggestion. I did something similar: import os req = os.getenv('REQUEST_URI') if (not req is None) and len(req) > 0: web = True which seemed to work for me. Rowan From phil at riverbankcomputing.co.uk Wed May 9 11:19:49 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Wed, 9 May 2007 16:19:49 +0100 Subject: Gui thread and async jobs. In-Reply-To: <1343obt58trd8c0@corp.supernews.com> References: <1178627450.408287.139070@p77g2000hsh.googlegroups.com> <1343obt58trd8c0@corp.supernews.com> Message-ID: <200705091619.50043.phil@riverbankcomputing.co.uk> On Wednesday 09 May 2007 3:58 pm, Grant Edwards wrote: > On 2007-05-08, king kikapu wrote: > > Hi, i am reading the book "Python Cookbook, 2nd edition" and i > > encountered a very handy recipe, the one that is called > > "Combining GUIs and Asynchronous I/O with Threads" > > > > It is talking about retain a main GUI thread, doing async work > > with worker threads and have both talk through a Queue object > > to dispatch their messages, so the main (GUI) thread remain > > responsive. It has a very good example by using Tkinter and Qt > > that is indeed working. The only point that make me wonder is > > that the QUI thread has to use some polling to check for > > messages in the Queue. > > It sounds to me like Qt is missing some rather important > features and/or convenience functions. In other toolkits (e.g. > wxPython), invoking GUI methods/functions from non-GUI threads > is trivial and involves no polling by the GUI thread. > > For example, if in a wxPython application you wanted to call > someGUIobject.method(foo,bar) from a non-GUI thread you just do > this: > > wx.CallAfter(someGUIobject.method,foo,bar) > > If you look under the covers there is a queue involved, but > it's nothing the user has to poll or worry about. In Qt it's all part of the signal/slot mechanism which works across threads. Surprise, surprise, under the covers there is a queue involved. Phil From showell30 at yahoo.com Sun May 27 14:10:52 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 27 May 2007 11:10:52 -0700 (PDT) Subject: ten small Python programs In-Reply-To: Message-ID: <599105.83882.qm@web33506.mail.mud.yahoo.com> --- Steven Bethard wrote: > > I think I would rewrite the current unit-testing > example to use the > standard library unittest module:: > > # Let's write reusable code, and unit test it. > def add_money(amounts): > # do arithmetic in pennies so as not to > accumulate float errors > pennies = sum([round(int(amount * 100)) for > amount in amounts]) > return float(pennies / 100.0) > import unittest > class TestAddMoney(unittest.TestCase): > def test_float_errors(self): > self.failUnlessEqual(add_money([0.13, > 0.02]), 0.15) > self.failUnlessEqual(add_money([100.01, > 99.99]), 200) > self.failUnlessEqual(add_money([0, > -13.00, 13.00]), 0) > if __name__ == '__main__': > unittest.main() > Just a minor quibble, but wouldn't you want the import and test class to only get executed in the ___main__ context? ____________________________________________________________________________________Got a little couch potato? Check out fun summer activities for kids. http://search.yahoo.com/search?fr=oni_on_mail&p=summer+activities+for+kids&cs=bz From david at zettazebra.com Sun May 6 13:44:40 2007 From: david at zettazebra.com (David Clymer) Date: Sun, 06 May 2007 13:44:40 -0400 Subject: Crypto plaintext padding (SOLVED) In-Reply-To: <1178465973.4345.12.camel@zepto.home.zettazebra.com> References: <1178465973.4345.12.camel@zepto.home.zettazebra.com> Message-ID: <1178473480.4456.3.camel@zepto.home.zettazebra.com> On Sun, 2007-05-06 at 11:39 -0400, David Clymer wrote: > I'm using pycrypto's AES module, and am attempting to automate the > padding of the plaintext (the size of the text to be encrypted must be a > multiple of 16). However, my padding scheme sometimes fails to calculate > the necessary padding correctly, and I'm not sure why. > > Using the text 'foo bar', it fails, but if I do 'foo bars' it works. > Randomized testing fails sometimes and not others. > > Any pointers as to what I might be doing wrong (code attached)? Nevermind. After I walked away from it for a bit, the mistake was obvious. I was using the modulus of the text length by the block size directly, rather than the block size minus that number: --- /home/david/Desktop/test.py 2007-05-06 13:38:52.000000000 -0400 +++ test.py 2007-05-06 13:39:38.000000000 -0400 @@ -9,12 +9,12 @@ def __init__(self, text, key_phrase): key = SHA256.new(key_phrase) self.aes = AES.new(key.digest()) - #self.encrypted_text = self.aes.encrypt(self._pad(text)) + self.encrypted_text = self.aes.encrypt(self._pad(text)) def _unpad(self, txt): """Remove padding from the given text""" for x in xrange(len(txt) - self.aes.block_size,len(txt)): - if x == ord(txt[x]): + if len(txt[x:]) == ord(txt[x]): if txt[x-1:] + self._gen_pad(txt[x-1:]): return txt[:x] return txt @@ -25,7 +25,7 @@ def _gen_pad(self, txt): """Generate padding for the given plaintext""" - pad_len = (len(txt)) % self.aes.block_size + pad_len = self.aes.block_size - (len(txt) % self.aes.block_size) if pad_len > 0: return chr(pad_len) * pad_len return chr(self.aes.block_size) * self.aes.block_size -- gpg-key: http://www.zettazebra.com/files/key.gpg -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From bignose+hates-spam at benfinney.id.au Sun May 27 07:20:24 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 27 May 2007 21:20:24 +1000 Subject: Is PEP-8 a Code or More of a Guideline? References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> Message-ID: <87abvqpl6v.fsf@benfinney.id.au> Stefan Sonnenberg-Carstens writes: > I prefer mixedCaseStyle, and I think that should be "standard", I dislike it. It's inconsistent, and confusingly similar to TitleCaseStyle used for class names in Python. > as this style is commonly used in all "major" languages , for > example Java,C++,C#. Is C no longer a "major" language? The long-standing convention there is for lower_case_with_underscores. > It shortens the identifiers but leaves the meaning intact. The shortening is both minor, and irrelevant: clarity is worth more than shorter names merely for the sake of shorter names. -- \ "If you're a young Mafia gangster out on your first date, I bet | `\ it's real embarrassing if someone tries to kill you." -- Jack | _o__) Handey | Ben Finney From rene at korteklippe.de Tue May 15 07:59:09 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 15 May 2007 13:59:09 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46499B16.2070901@web.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <4648252D.5020704@web.de> <46483740.4050406@web.de> <46498cb1$0$6411$9b4e6d93@newsspool2.arcor-online.net> <46499273.6050806@web.de> <46499a54$0$10199$9b4e6d93@newsspool4.arcor-online.net> <46499B16.2070901@web.de> Message-ID: <4649a08c$0$23148$9b4e6d93@newsspool1.arcor-online.net> Stefan Behnel schrieb: >>> Admittedly, it's done in Java, but why should Python fail to support unicode >>> identifiers in the way Java does? >> Your example does not prove much. The fact that some people use >> non-ASCII identifiers when they can does not at all prove that it would >> be a serious problem for them if they could not. > > Are we trying to prove that? IMO, if you cannot prove it, the PEP should be rejected, since that would mean it introduces new problems without any proven substantial benefits. > And, would we have serious problems and people running from Python if Python > 2.5 did not integrate the "with" statement? 1) Which additional potential for bugs and which hindrances for code-sharing do you see with the with-statement? 2) The with-statement does have proven substantial benefits, IMO. -- Ren? From siona at chiark.greenend.org.uk Tue May 15 12:38:16 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 15 May 2007 17:38:16 +0100 (BST) Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <87E*+HNKr@news.chiark.greenend.org.uk> Nick Craig-Wood wrote: >b) Unicode characters would creep into the public interface of public >libraries. I think this would be a step back for the homogeneous >nature of the python community. One could decree that having a non-ASCII character in an identifier would have the same meaning as a leading underscore 9-) -- \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 shakil.ahmed at igib.res.in Mon May 7 01:27:59 2007 From: shakil.ahmed at igib.res.in (Shakil Ahmed) Date: Mon, 7 May 2007 10:57:59 +0530 Subject: Problem to Download ftp file Message-ID: <1D011717865DAE46B56AA1455F02CAC5C952DB@n1ex> hi Actually i need to know that how can i download a ftp file from ncbi by using python module ftputil. please help me. Thanks regards, Shakil import ftputil host = ftputil.FTPHost('ftp.ncbi.nih.gov/repository/OMIM/morbidmap', 'anonymous', 'password') The Error message is: raise FTPOSError(ftp_error) FTPOSError: (11001, 'getaddrinfo failed') Debugging info: ftputil 2.2.2, Python 2.4.3 (win32) -------------- next part -------------- An HTML attachment was scrubbed... URL: From p at ulmcnett.com Wed May 23 14:10:28 2007 From: p at ulmcnett.com (Paul McNett) Date: Wed, 23 May 2007 11:10:28 -0700 Subject: dabo framework dependancies In-Reply-To: References: <1179761984.704369.116310@b40g2000prd.googlegroups.com> <46532f57$0$32303$426a34cc@news.free.fr> Message-ID: <46548394.9070406@ulmcnett.com> Peter Decker wrote: > On 5/22/07, daniel gadenne wrote: > >> I'm considering moving over to dabo for wxpython development. >> However I do not write traditional database applications >> ? la foxpro (I'm a 20 years user of fox...) anymore. >> Only xml-fed applications. >> >> I'm a bit hesitant to jump onboard since dabo seemns to carry >> over its own lot of database connectivity dependancy. >> >> Can you reasonably use dabo for plain datafree application? > > That's exactly how I use it. I write apps that don't use database > servers, and don't have any database programs installed. I just want > the dabo.ui stuff, since it makes wxPython so easy to work with. Dabo has three main modules: db, biz, and ui, and an overarching application object. Every class descends from an abstract dObject. For database apps, you'd typically set some connection information in the db layer, put all your business code in the biz layer, and define your GUI in the (you guessed it) ui layer. You can certainly do what Peter has done and only use the ui layer and application object. I've done this myself and if I ever had to code a non-database UI that's probably what I'd do, too. Although I have to admit I can't really picture an application that doesn't need to save data. Here's a simple example that puts up a textbox: """ import dabo dabo.ui.loadUI("wx") app = dabo.dApp() app.setup() frm = app.MainForm tb = dabo.ui.dTextBox(frm, Value="Type in here", FontBold=True) app.start() """ You can easily define your own subclasses, too: """ import dabo dabo.ui.loadUI("wx") class MyRadioList(dabo.ui.dRadioList): def initProperties(self): self.Choices = ["Snakes", "Bees", "Fishes"] def onHit(self, evt): print "Radio choice '%s' selected." % self.Value app = dabo.dApp() app.setup() frm = app.MainForm rl = MyRadioList(frm) app.start() """ So, yes, you can reasonably use Dabo even if you have no traditional database in the mix. -- pkm ~ http://paulmcnett.com From DustanGroups at gmail.com Wed May 30 19:13:51 2007 From: DustanGroups at gmail.com (Dustan) Date: 30 May 2007 16:13:51 -0700 Subject: c[:]() In-Reply-To: References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> Message-ID: <1180566831.239580.199300@m36g2000hse.googlegroups.com> On May 30, 5:37 pm, "Warren Stringer" wrote: > Hey many thanks for the replies! > > Ah, so is seems that c[:][:][:][:][:][:][:][:][:][:][:][0]() > also work ... > > Ah well, can't have everything. Guess I was inspired by the alphabetically > adjacent message "Call for Ruby Champion". Would have been nice for it work > - a more elegant iterator would be hard to come by. A PEP, perhaps? Maybe > not; am still a bit new - am probably missing something obvious why this > isn't an easy fix. > > Pretty cool that I can override the list class. > > Cheers, Do a search on "python is not java" (words to live by). You can also plug in another language you know (like Ruby), but you won't get as many results. From jstroud at mbi.ucla.edu Wed May 16 18:06:32 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 16 May 2007 15:06:32 -0700 Subject: How do I count the number of spaces at the left end of a string? In-Reply-To: <1179351367.714864.47190@l77g2000hsb.googlegroups.com> References: <1179351367.714864.47190@l77g2000hsb.googlegroups.com> Message-ID: walterbyrd wrote: > I don't know exactly what the first non-space character is. I know the > first non-space character will be * or an alphanumeric character. > This is another of the hundreds of ways: py> for i,c in enumerate(astring): ... if c != ' ': break ... py> print i From sjmachin at lexicon.net Thu May 3 18:03:43 2007 From: sjmachin at lexicon.net (John Machin) Date: 3 May 2007 15:03:43 -0700 Subject: _csv.Error: string with NUL bytes In-Reply-To: References: <1178204593.280648.208040@c35g2000hsg.googlegroups.com> <1178209090.674787.202970@o5g2000hsb.googlegroups.com> <1178211458.634214.306500@o5g2000hsb.googlegroups.com> <1178213314.203450.167350@n76g2000hsh.googlegroups.com> Message-ID: <1178229823.425364.278500@n76g2000hsh.googlegroups.com> On May 4, 3:40 am, dus... at v.igoro.us wrote: > On Thu, May 03, 2007 at 10:28:34AM -0700, IAmStar... at gmail.com wrote: > > On May 3, 10:12 am, dus... at v.igoro.us wrote: > > > On Thu, May 03, 2007 at 09:57:38AM -0700, fscked wrote: > > > > > As Larry said, this most likely means there are null bytes in the CSV file. > > > > > > Ciao, > > > > > Marc 'BlackJack' Rintsch > > > > > How would I go about identifying where it is? > > > > A hex editor might be easiest. > > > > You could also use Python: > > > > print open("filewithnuls").read().replace("\0", ">>>NUL<<<") > > > > Dustin > > > Hmm, interesting if I run: > > > print open("test.csv").read().replace("\0", ">>>NUL<<<") > > > every single character gets a >>>NUL<<< between them... > > > What the heck does that mean? > > > Example, here is the first field in the csv > > > 89114608511, > > > the above code produces: > > >>>NUL<<<8>>>NUL<<<9>>>NUL<<<1>>>NUL<<<1>>>NUL<<<4>>>NUL<<<6>>>NUL<<<0>>>NUL<<<8>>>NUL<<<5>>>NUL<<<1>>>NUL<<<1>>>NUL<<<, > > I'm guessing that your file is in UTF-16, then -- Windows seems to do > that a lot. Do what a lot? Encode data in UTF-16xE without putting in a BOM or telling the world in some other fashion what x is? Humans seem to do that occasionally. When they use Windows software, the result is highly likely to be encoded in UTF-16LE -- unless of course the human deliberately chooses otherwise (e.g. the "Unicode bigendian" option in NotePad's "Save As" dialogue). Further, the data is likely to have a BOM prepended. The above is consistent with BOM-free UTF-16BE. From kyosohma at gmail.com Wed May 23 15:20:52 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 23 May 2007 12:20:52 -0700 Subject: Namespace issue In-Reply-To: Message-ID: <1179948052.267560.61640@p77g2000hsh.googlegroups.com> On May 23, 1:20 pm, Ritesh Raj Sarraf wrote: > Hi, > > I need a little help in understanding how Namespaces and scoping works with > Classes/Functions in Python. > > Here's my code: > class FetchData: > def __init__(self, dataTypes=["foo", "bar", "spam"], archive=False): > > self.List = [] > self.Types = dataTypes > > if archive: > self.Archiver = Archiver(True) > > def FetchData(self, PackageName, Filename=None): > > try: > import my_module > except ImportError: > return False > > if Filename != None: > try: > file_handle = open(Filename, 'a') > except IOError: > sys.exit(1) > > (amnt, header, self.List) = my_module.get_data(PackageName) > > This is the only way this code will work. > > As per my understanding, the bad part is that on every call of the method > FetchData(), an import would be done. > > To not let that happen, I can put the import into __init__(). But when I put > in there, I get a NameError saying that my_module is not available even > though it got imported. > All I noticed is that the import has to be part of the method else I end up > getting a NameError. But always importing my_module is also not good. > > What is the correct way of doing this ? > IMO, ideally it should be part of __init__() and be imported only when the > class is instantiated. > > Thanks, > Ritesh > -- > If possible, Please CC me when replying. I'm not subscribed to the list. The reason you can't put the import into the __init__ is that that is also a method, so the imported module is only available to that method's namespace. This is also true if you had put the import into any other method. The only way to make it global is to put your class into its own module and put the import before the class creation. Depending on how your instantiating the class, you may not need to worry about the whole importing thing. If you have all your code like this: class something(obj): def __init__(self): #do something def grabData(self): # do something import module x = something() y = something() Then the module gets imported only once. See http://www.python.org/search/hypermail/python-1993/0342.html I'm not sure what happens when you have one module calling another module that import a third module though. Mike From sinoodle at yahoo.com Wed May 9 16:01:42 2007 From: sinoodle at yahoo.com (sinoodle at yahoo.com) Date: 9 May 2007 13:01:42 -0700 Subject: Questions about bsddb In-Reply-To: <1178720648.233560.319570@p77g2000hsh.googlegroups.com> References: <1178713407.968873.260950@n59g2000hsh.googlegroups.com> <1178720648.233560.319570@p77g2000hsh.googlegroups.com> Message-ID: <1178740902.495700.60310@p77g2000hsh.googlegroups.com> Thanks for the info Nick. I plan on accessing the data in pretty much random order, and once the database is built, it will be read only. At this point Im not too concerned about access times, just getting something to work. I've been messing around with both bt and hash with limited success, which led me to think that maybe I was going beyond some internal limit for the data size.It works great on a limited set of data, but once I turn it loose on the full set, usually several hours later, it either causes a hard reset of my machine or the HD grinds on endlessly with no apparent progress. Is there a limit to the size of data you can place per key? Thanks for the MySQL suggestion, I'll take a look. -JM From shaharh at gmail.com Tue May 1 16:02:02 2007 From: shaharh at gmail.com (Shafik) Date: 1 May 2007 13:02:02 -0700 Subject: Using python with MySQL In-Reply-To: <1178048415.272711.261930@n59g2000hsh.googlegroups.com> References: <1178048415.272711.261930@n59g2000hsh.googlegroups.com> Message-ID: <1178049722.530888.269840@c35g2000hsg.googlegroups.com> On May 1, 10:40 pm, HMS Surprise wrote: > Greetings, > > I need to peform some simple queries via MySQL. Searching the list I > see that folks are accessing it with python. I am very new to python > and pretty new to MySQL too. Would appreciate it if you could point me > to some documentation for accessing MySQL via python. Something of the > "Python and MySQL for Dummies" caliber would be about my speed, but of > course I will be thankful for anything offered. > > Thanks, > > jvh hi, download this module: http://sourceforge.net/projects/mysql-python and look at the tutorial here: http://www.kitebird.com/articles/pydbapi.html From jstroud at mbi.ucla.edu Thu May 3 00:23:13 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 02 May 2007 21:23:13 -0700 Subject: ignorance and intolerance in computing communties In-Reply-To: <1178120019.271716.299590@e65g2000hsc.googlegroups.com> References: <1178120019.271716.299590@e65g2000hsc.googlegroups.com> Message-ID: Xah Lee wrote: > Today, a motherfucker Christophe Rhodes (aka Xof in irc://chat.freenode.net/lisp > ) kicked banned me. Are you aware that you are a troll? Have you considered that this has anything to do with your being kick-banned? Why do 99.999999 % of the people on the web not get treated like you? Answer: you are a troll and they are not. James From tim at tdw.net Tue May 22 10:55:42 2007 From: tim at tdw.net (Tim Williams) Date: Tue, 22 May 2007 15:55:42 +0100 Subject: Printing dots in sequence ('...') In-Reply-To: References: Message-ID: <9afea2ac0705220755i4584efbawf87f40951d95d880@mail.gmail.com> On 22 May 2007 01:02:31 -0700, beertje wrote: > This is a very newbie question for my first post, perhaps > appropriately. > > I want to print '....' gradually, as a progress indicator. I have a > for-loop that every 10 steps executes: > print '.', > > This results in something like 'Loading. . . .', whereas I want > 'Loading....' > > A pet peeve, I can't for the life of me figure out how to get this > desired output. How do I print dots - or anything for that matter - in > sequence without a space being inserted in between? > maybe this: (on Win32, don't know about *nix) for x in range(10): print '.\b', -- Tim Williams From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu May 24 04:02:35 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 24 May 2007 10:02:35 +0200 Subject: Can I reference 1 instance of an object by more names ? rephrase In-Reply-To: References: <4654289a$0$2326$426a74cc@news.free.fr> Message-ID: <46554679$0$19879$426a74cc@news.free.fr> Maric Michaud a ?crit : > Stef Mientki a ?crit : (snip) >> # I need to read and write the individual bits of the byte object >> # so I can create 8 blocks of code like this, one for each bit position >> # I use it, like this >> # name1 = cpu_ports() >> # name1.p5 = True >> # or >> # name1.p[5] = True >> >> @apply # read / write bit 5 >> def p5(): >> def fset(self, value): >> index = 5 >> value = ( value & 1L ) << index >> mask = ( 1L ) << index >> self._d = ( self._d & ~mask ) | value >> def fget(self): >> index = 5 >> return ( self._d >> index ) & 1 >> return property(**locals()) >> >> I can optimize the above code a little bit, >> but I've the feeling that I don't need to repeat this code 8 times. > > something like that should just work (untested) : > > def bit(): > def fset(self, value): > index = 5 > value = ( value & 1L ) << index > mask = ( 1L ) << index > self._d = ( self._d & ~mask ) | value > def fget(self): > index = 5 > return ( self._d >> index ) & 1 > return property(**locals()) > > > class cpu_ports(object) : > > p1 = bit() > p2 = bit() > p3 = bit() > p4 = bit() > p5 = bit() As a side note, properties are just an example of objects using the descriptor protocol. You can build your own descriptors for more advanced use (think : 'smart' attributes): http://users.rcn.com/python/download/Descriptor.htm http://docs.python.org/ref/descriptors.html From aahz at pythoncraft.com Tue May 15 16:32:29 2007 From: aahz at pythoncraft.com (Aahz) Date: 15 May 2007 13:32:29 -0700 Subject: Trying to choose between python and java References: Message-ID: In article , Anthony Irwin wrote: > >#5 someone said that they used to use python but stopped because the >language changed or made stuff depreciated (I can fully remember >which) and old code stopped working. Is code written today likely to >still work in 5+ years or do they depreciate stuff and you have to update? You're probably thinking of http://www.gbch.net/gjb/blog/software/discuss/python-sucks.html Thing is, while he has a point, I don't think it's a very good one. For example, just yesterday in upgrading from Java 1.4.2 to Java 5.0, I had to fix a bunch of instances of "package foo.bar.baz;" to "package baz;" because apparently the latter is now "correct". Bugfixes happen, and sometimes they break working code. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Look, it's your affair if you want to play with five people, but don't go calling it doubles." --John Cleese anticipates Usenet From paddy3118 at googlemail.com Sat May 19 01:32:43 2007 From: paddy3118 at googlemail.com (Paddy) Date: 18 May 2007 22:32:43 -0700 Subject: Typed named groups in regular expression In-Reply-To: References: Message-ID: <1179552763.278347.163300@e65g2000hsc.googlegroups.com> On May 16, 6:58 pm, "Hugo Ferreira" wrote: > Hi! > > Is it possible to "automagically" coerce the named groups to python types? e.g.: > > >>> type(re.match('(?P\d*)', '123').groupdict()['x']) > > > > But what I'm looking forward is for the type to be 'int'. > > Cheers! > > Hugo Ferreira If you do a ot of that sort of thing in many programs then it might be worth your while to set up a framework that does it. Something like adding an underscore then the name of a type conversion function to all group names, and creating a function to apply the type convertion function to all named groups of a match object. - Paddy. From ptmcg at austin.rr.com Sat May 26 22:13:46 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 26 May 2007 19:13:46 -0700 Subject: ten small Python programs In-Reply-To: References: <1180229019.873381.52800@m36g2000hse.googlegroups.com> Message-ID: <1180232026.357074.186770@o5g2000hsb.googlegroups.com> On May 26, 8:48 pm, Steve Howell wrote: > > I'm thinking you could actually have a progression > from a 1 line program up to a 50-line program. The > number 50 is kind of arbitrary, but my gut says that > by a 50-line program, you will have demonstrated > almost every useful concept. > If there is anything arbitrary here, I'd say it is your "increment each example by one source line" constraint. This can force you to use some bad coding practices to meet your target line count for a given example. Maybe try this approach: pick your top 10/20/50 language features and develop concise examples. Then order the examples by length as a first cut (longer examples probably *are* more complex), and then reorder a bit to handle pre-requisites (introduce a minimum of new features, preferably 1, per example). Overall, I'd have a tough time picking just 10 language features to illustrate, but there are probably 10-20 basic features that will get new people onto fairly productive ground. Pick 20 as your example count (50 sounds a bit long), and stick to it, and then later add "20 More Little Programs" for the next wave of examples in increasing complexity. One other nit to pick: have your example classes inherit from object, to get new people using new-style classes from the get-go. -- Paul From mailme.gurpreet at yahoo.com Fri May 11 02:42:55 2007 From: mailme.gurpreet at yahoo.com (Gurpreet Singh) Date: Thu, 10 May 2007 23:42:55 -0700 (PDT) Subject: Simple Tkinter Progress Bar Message-ID: <890234.75240.qm@web62008.mail.re1.yahoo.com> Hi I am a newbie in Python I am creating a simple Tkinter based application. I have written Tkinter GUI source code and the programme logic in the same .py file. I am searching for a way to implement a simple Progress bar for my application. Are there any simple ways of doin it. ____________________________________________________________________________________Yahoo! oneSearch: Finally, mobile search that gives answers, not web links. http://mobile.yahoo.com/mobileweb/onesearch?refer=1ONXIC From nogradi at gmail.com Fri May 18 06:14:40 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Fri, 18 May 2007 12:14:40 +0200 Subject: Python Web Programming - looking for examples of solid high-traffic sites In-Reply-To: <1hy9yf9.1nnsttj139za6bN%aleax@mac.com> References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> <1hy9yf9.1nnsttj139za6bN%aleax@mac.com> Message-ID: <5f56302b0705180314y66b33cd4y26cd9d57064c49fd@mail.gmail.com> > For example, it HAS been published elsewhere that YouTube uses lighttpd, > not Apache: . How do you explain these, then: http://www.youtube.com/results.xxx http://www.youtube.com/results.php http://www.youtube.com/results.py Just wondering, Daniel From steven.bethard at gmail.com Tue May 22 02:02:34 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 22 May 2007 00:02:34 -0600 Subject: converting text and spans to an ElementTree Message-ID: I have some text and a list of Element objects and their offsets, e.g.:: >>> text = 'aaa aaa aaabbb bbbaaa' >>> spans = [ ... (etree.Element('a'), 0, 21), ... (etree.Element('b'), 11, 18), ... (etree.Element('c'), 18, 18), ... ] I'd like to produce the corresponding ElementTree. So I want to write a get_tree() function that works like:: >>> tree = get_tree(text, spans) >>> etree.tostring(tree) 'aaa aaa aaabbb bbbaaa' Perhaps I just need some more sleep, but I can't see an obvious way to do this. Any suggestions? Thanks, STeVe From martin at v.loewis.de Mon May 14 01:45:07 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 14 May 2007 07:45:07 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179080185.225291.126420@w5g2000hsg.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179080185.225291.126420@w5g2000hsg.googlegroups.com> Message-ID: <4647F763.7020005@v.loewis.de> > It should be noted that the Python community may use other forums, in > other languages. They would likely be a lot more enthusiastic about > this PEP than the usual crowd here (comp.lang.python). Please spread the news. Martin From carsten at uniqsys.com Mon May 14 21:10:51 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 14 May 2007 21:10:51 -0400 Subject: Interesting list Validity (True/False) In-Reply-To: <1179168081.603409.39970@e51g2000hsg.googlegroups.com> References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> <1178914190.166662.285410@p77g2000hsh.googlegroups.com> <1178915791.584216.293130@l77g2000hsb.googlegroups.com> <1178918808.091358.233740@o5g2000hsb.googlegroups.com> <1179017740.656323.209590@e51g2000hsg.googlegroups.com> <1179020634.130689.171960@o5g2000hsb.googlegroups.com> <1179031812.090768.248750@l77g2000hsb.googlegroups.com> <1179168081.603409.39970@e51g2000hsg.googlegroups.com> Message-ID: <1179191451.3241.15.camel@localhost.localdomain> On Mon, 2007-05-14 at 11:41 -0700, mensanator at aol.com wrote: > On May 13, 8:24 am, Steven D'Aprano > wrote: > > On Sat, 12 May 2007 21:50:12 -0700, mensana... at aol.com wrote: > > >> > > > >> > "if arg==True" tests whether the object known as arg is equal to the > > >> > object known as True. > > >> > > > > > >> Not at all, it makes perfect sense. X == Y always tests whether the > > >> argument X is equal to the object Y regardless of what X and Y are. > > > > > Except for the exceptions, that's why the statement is wrong. > > > > But there are no exceptions. > > > Sec 2.2.3: > Objects of different types, *--->except<---* different numeric types > and different string types, never compare equal; > The exceptions you mean are not exceptions to "'X==Y' means 'X equals Y'". They are exceptions to "'X equals Y' means 'X is mathematically the same as Y'," but that is not how equality is actually defined. -- Carsten Haese http://informixdb.sourceforge.net From victor.kryukov at gmail.com Thu May 24 21:40:04 2007 From: victor.kryukov at gmail.com (Victor Kryukov) Date: 24 May 2007 18:40:04 -0700 Subject: Python Web Programming - looking for examples of solid high-traffic sites In-Reply-To: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> Message-ID: <1180057204.948575.73070@p77g2000hsh.googlegroups.com> Hello list, thanks a lot to everybody for their suggestions. We're yet to make our final decision, and the information you've provided is really helpful. Best, Victor. From Florian.Lindner at xgm.de Mon May 28 07:36:40 2007 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Mon, 28 May 2007 13:36:40 +0200 Subject: Formal interfaces with Python Message-ID: Hello, some time ago I've heard about proposals to introduce the concecpt of interfaces into Python. I found this old and rejected PEP about that: http://www.python.org/dev/peps/pep-0245/ What is the current status of that? Thanks, Florian From sjmachin at lexicon.net Sun May 20 17:58:26 2007 From: sjmachin at lexicon.net (John Machin) Date: Mon, 21 May 2007 07:58:26 +1000 Subject: pyExcelerator bug? In-Reply-To: <1179694886.941462.308560@b40g2000prd.googlegroups.com> References: <1179355368.793891.233240@u30g2000hsc.googlegroups.com> <1179694886.941462.308560@b40g2000prd.googlegroups.com> Message-ID: <4650C482.4090606@lexicon.net> On 21/05/2007 7:01 AM, Waldemar Osuch wrote: > On May 16, 4:42 pm, tkp... at hotmail.com wrote: >> My program creates three lists: the first has dates expressed as >> strings, the second has floats that are strictly positive, and the >> third has floats that are strictly negative. I have no trouble writing >> the data in these lists to a .csv file using the csv module using the >> following code. >> >> outfile = file(fn + '.csv','wb') >> writer = csv.writer(outfile) >> for i in range(len(dateList)): >> writer.writerow([dateList[i], posVals[i], negVals[i]]) >> outfile.close() >> >> However, when I try to write to an Excel file usingpyExcelerator(see >> code below), the third list is not always written correctly - my >> program sometimes writes positive numbers into the third column of the >> spreadsheet. Is this a known bug? [looks like my (earlier) reply to the original post didn't make it to c.l.py] This may well be a manifestation of the RK bug that is reported in two bug reports (1509223 and 1596642) on the pyExcelerator sourceforge site. However it is impossible to tell for sure, as the OP has supplied neither an executable demonstration script nor any actual-versus-expected numbers. >> if so, is there a workaround? Yes. In fact there are three: (1) An avoid-the-problem patch (doesn't create RK records), like Waldemar's. (2) A patch that corrects the pyExcelerator code -- see patch number 1618443 on the pyExcelerator sourceforge site. (3) A fix that creates RK records more efficiently than (2) -- see "xlwt" below. >> Is pyExcelerator being developed any longer? My attempts to reach the >> developer have gone nowhere. (1) There seems to be sporadic activity on the pyExcelerator sourceforge site. (2) I am maintaining xlwt (i.e. Excel write), a fork of pyExcelerator -- fixed known and unknown bugs, improved performance, and made it run under Python 2.3. Available from https://secure.simplistix.co.uk/svn/xlwt/trunk See also http://groups.google.com/group/python-excel >> >> w =pyExcelerator.Workbook() >> ws = w.add_sheet(fn + p) >> for i,d in enumerate(dateList): >> ws.write(i+1, 0, dateList[i]) >> ws.write(i+1, 1, posVals[i]) >> ws.write(i+1, 2, negVals[i]) >> w.save(fn+'.xls') >> > > Try using this patch on Cell.py and see if it fixes your problem: > > > > --- Cell.py (revision 4522) > +++ Cell.py (revision 4523) > > @@ -101,6 +101,14 @@ > > > def get_biff_data(self): > + return BIFFRecords.NumberRecord(self.__parent.get_index(), > self.__idx, self.__xf_idx, self.__number).get() > + # Skipping all the logic below. > + # From what I understand it tries to save space. > + # Unfortunately it gets it wrong and produces false results. > + # For example: > + # 814289000 gets written out as -259452824 > + > Cheers, John From whamil1 at entergy.com Mon May 21 09:13:29 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Mon, 21 May 2007 08:13:29 -0500 Subject: tkinter button state = DISABLED Message-ID: <588D53831C701746A2DF46E365C018CE01D2CAA2@LITEXETSP001.etrsouth.corp.entergy.com> > From: Eric Brunel On Thu, 17 May 2007 09:30:57 +0200, Hendrik van Rooyen > wrote: > > "Gabriel Genellina" wrote: > >> En Wed, 16 May 2007 03:22:17 -0300, Hendrik van Rooyen > >>> I have never seen this working in Tkinter, unless the button was > >>> pressed > >>> on the > >>> widget > >>> in question - and worse, once you have clicked down on a ButtonRelease > >>> binding > >>> you can move the mouse pointer anywhere you like, even out of the > >>> application > >>> and when you release it, the bound function is called... > >>> > >>> Its either a bug or a feature, I don't know. > >> > >> Uhmm... I'm not sure I understand you completely. I only said that the > >> "command" is fired only when the mouse button is pressed on the widget, > >> AND released inside the same widget. If both events don't happen in the > >> same widget, "command" won't fire. Maybe you are saying the same > >> thing... > >> anyway I'm not a Tk expert. > > > > No command is ok and you have described it right - its ButtonRelease > that > > seems broken to me > > Apparently, this behaviour is the intended one, at least for buttons; see: > http://www.tcl.tk/man/tcl8.4/TkCmd/bind.htm#M11 > > As for the question "why?", maybe you should ask it on the c.l.tcl > newsgroup? The difference between bind and the button's command parameter makes sense to me. You'd use bind to create something like a right-click menu, where you want the same thing to happen whether the button is disabled or not. You use the command parameter when you care about the state of the button. -- -Bill Hamilton From youshouldlistento at gmail.com Tue May 8 03:38:48 2007 From: youshouldlistento at gmail.com (=?ISO-8859-1?Q?Cesar_H=E4rdfeldt?=) Date: Tue, 8 May 2007 09:38:48 +0200 Subject: Getting a function name from string Message-ID: <390810050705080038p7f26d7b2maf9f6230178147ff@mail.gmail.com> " It has been my experience that, more often than not, any time you think you want to evaluate strings, you don't need to. For instance, instead of passing around the name of the function as a string: s = "someFunction" eval(s)() you can pass around the function as an object: s = someFunction # note the lack of brackets s() -- Steven. " I want to read a module name and a function in that module from a ini-file and then run the function with some arguments also read from the ini-file. Is there a way to do this, still avoiding the eval()-method? example: module = modelParser.getModule() function = modelParser.getFunc() parms = modelParser.getParms() (modelParser just extracts string from the ini-file) I now have 'module' and 'function' as strings and 'parms' normally as a list of strings. I can import the module by __import__(module) but is there another way to call: module.function(parms) than using eval()? Thanks for any suggestions, Best Cesar -------------- next part -------------- An HTML attachment was scrubbed... URL: From grante at visi.com Fri May 11 23:20:56 2007 From: grante at visi.com (Grant Edwards) Date: Sat, 12 May 2007 03:20:56 -0000 Subject: Newbie look at Python and OO References: <1178812734.860473.236370@y80g2000hsf.googlegroups.com> <1346hrvgve90nea@corp.supernews.com> Message-ID: <134ackoio9hu0ab@corp.supernews.com> On 2007-05-12, Steven D'Aprano wrote: > On Thu, 10 May 2007 16:25:35 +0000, Grant Edwards wrote: > >>> I know why, but this is not what I would ordinarilly expect, >> >> Stop thinking in "C". ;) > > Dude! Did you miss the Original Poster's VERY FIRST SENTENCE??? > > "I learned to program with Pascal, way back when." > > He's thinking in Pascal, not C. My bad. Though there's mot that much difference... -- From JoeSalmeri at hotmail.com Fri May 18 19:48:49 2007 From: JoeSalmeri at hotmail.com (Joe Salmeri) Date: Fri, 18 May 2007 19:48:49 -0400 Subject: pyodbc.Error Crash Message-ID: I believe this bug is also related to the other problem I just reported. OS = Windows XP SP2 DB = Microsoft Access XP PROBLEM: When you use + (or &) to concatenation columns together and the columns are of type text and the combined length exceed 255 this causes pyodbc to fail and python to crash. Basically select c2 + ' ' + c3 from test_concat where c1 = 1 will cause the problem if c2 and c3 are text columns and their combined length is > 255. I also encountered this problem years ago with mxODBC and I believe the problem may actually be an underlying bug in odbc. When I contacted Marc-Andr? Lemburg,the author of mxODBC he patched it to fix the problem and I believe the workaround was to allocate a larger buffer. If the columns that are concatenated are memo columns I also believe the problem occurs. # pyodbc.Error: ('HY090', '[HY090] [Microsoft][ODBC Driver Manager] Invalid string # or buffer length (0)') To recreate the problem create an Access db named test and create a DSN named test. Run the createtable.py script to create the table and then run the broke.py to demonstrate the problem. The broke.py script has 4 select statements but only one is executed. Change line number 34 to specify which one you want to test. # # createtable.py script # import pyodbc dbs = pyodbc.connect('dsn=test') c = dbs.cursor() try: sql = 'drop table test_concat' c.execute(sql) dbs.commit() except: # ignore drop table failure pass sql = 'create table test_concat (c1 int not null, c2 text not null, c3 text not null)' c.execute(sql) dbs.commit() sql = 'insert into test_concat values(1, ?, ?)' c2_value = '1' * 251 c2_value = '%sJOE1' % (c2_value) c3_value = '1' * 251 c3_value = '%sJOE2' % (c3_value) c.execute(sql, (c2_value, c3_value)) dbs.commit() c.close() dbs.close() # # broke.py script # import pyodbc dbs = pyodbc.connect('dsn=test') c = dbs.cursor() sql1 = "select c2 from test_concat where c1 = 1" sql2 = "select c2, c3 from test_concat where c1 = 1" sql3 = "select c2 + ' ' + c3 from test_concat where c1 = 1" sql4 = "select c2 + ' ' + c3 as a from test_concat where c1 = 1" # # 1: Works fine # # 2: Works fine # # 3: Errors and python crashes # # Traceback (most recent call last): # File "H:\1-pyodbc-bug\concat-bug\broke.py", line 36, in ? # row = c.fetchone() # pyodbc.Error: ('HY090', '[HY090] [Microsoft][ODBC Driver Manager] Invalid string # or buffer length (0)') # # 4: Errors and python crashes # # Traceback (most recent call last): # File "H:\1-pyodbc-bug\concat-bug\broke.py", line 36, in ? # row = c.fetchone() # pyodbc.Error: ('HY090', '[HY090] [Microsoft][ODBC Driver Manager] Invalid string # or buffer length (0)') # c.execute(sql4) row = c.fetchone() print row[0] if len(row) > 1: print row[1] c.close() dbs.close() From castironpi at gmail.com Tue May 8 22:36:06 2007 From: castironpi at gmail.com (castironpi at gmail.com) Date: 8 May 2007 19:36:06 -0700 Subject: tokenize generate_tokens token[0] Message-ID: <1178678166.463902.322730@e65g2000hsc.googlegroups.com> Is token[0] guaranteed to be OP for parentheses, commas, etc.? From deets at nospam.web.de Tue May 1 04:15:08 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 01 May 2007 10:15:08 +0200 Subject: playing sound in mac osx In-Reply-To: References: Message-ID: <59ob8dF2lbogtU1@mid.uni-berlin.de> tooru honda schrieb: > Hi, > > I am a newbie to mac and python. > > Is there an easy way to play wav or mp3 sound file ? I used to use > winsound module before switching to mac, but that only works for windows. pygame might help. Diez From aahz at pythoncraft.com Sat May 5 19:11:38 2007 From: aahz at pythoncraft.com (Aahz) Date: 5 May 2007 16:11:38 -0700 Subject: FIXED: webmaster@python.org References: Message-ID: In article , Aahz wrote: >In article , >Carsten Haese wrote: >> >>I just tried sending an email to webmaster at python.org to request a >>website change, and the email bounced back with this excerpt from the >>delivery failure report: > >Oops! I've informed the appropriate people. >For now, either hang on to your request or send it directly to me. >Thanks for letting us know! Okay, anyone who was trying to send e-mail to the webmasters should try again. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Look, it's your affair if you want to play with five people, but don't go calling it doubles." --John Cleese anticipates Usenet From larry.bates at websafe.com Wed May 16 11:35:10 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 16 May 2007 10:35:10 -0500 Subject: calldll for Python 2.5 Message-ID: I've implemented several libraries using calldll (originally on Python 2.2) and posted recipe on ASPN for a general implementation http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146847. If I were doing it over again today, I would use ctypes, but I have thousands of lines of library code that are dependent on calldll. Anyone out there have a version that works with Python 2.5 so I don't have to a massive rewrite? Thanks in advance, Larry From george.sakkis at gmail.com Wed May 23 17:09:28 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 23 May 2007 14:09:28 -0700 Subject: Parallel/distributed generator In-Reply-To: <1179948980.173325.262610@d30g2000prg.googlegroups.com> Message-ID: <1179954568.502985.157310@g4g2000hsf.googlegroups.com> On May 23, 3:35 pm, half.ital... at gmail.com wrote: > On May 23, 11:00 am, George Sakkis wrote: > > > > > I'm looking for any existing packages or ideas on how to implement the > > equivalent of a generator (in the Python sense, i.e.http://www.python.org/dev/peps/pep-0255/) in a parallel/distributed > > way. As a use case, imagine a function that generates a range of > > primes. I'd like to be able to do something along the following lines: > > > def iterprimes(start=1, end=None): > > # ... > > yield prime > > > # rpc-related initialization > > ... > > rpc_proxy = some_rpc_lib(iterprimes, start=1e6, end=1e12) > > for prime in proxy: > > print prime > > > Is there any module out there that does anything close to this ? > > > George > > Parellel Python? > > http://www.parallelpython.com/content/view/17/31/#SUM_PRIMES > > I've never used it, but looks like it does what you are looking for. Looked promising, until I saw that it requires you to pass explicitly the dependent functions and the modules to be imported for the callable to work. I guess this has to be done recursively for all the dependent functions/modules, which is impractical for anything but toy examples. George From showell30 at yahoo.com Mon May 28 18:03:42 2007 From: showell30 at yahoo.com (Steve Howell) Date: Mon, 28 May 2007 15:03:42 -0700 (PDT) Subject: itertools.groupby In-Reply-To: <1180382532.846606.265100@q19g2000prn.googlegroups.com> Message-ID: <43064.9791.qm@web33511.mail.mud.yahoo.com> --- Raymond Hettinger wrote: > > > That's not for everyone, so it isn't a loss if > > > someone sticks > > > with writing plain, clear everyday Python > instead of > > > an itertool. > > > > I know most of the module is fairly advanced, and > that > > average users can mostly avoid it, but this is a > very > > common-antipattern that groupby() solves: > > I think the OP would have been better-off with plain > vanilla Python such as: > > See > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/259173 > That recipe implements SQL-like Group By, but it's the uniq-like reimplementation of groupby() that I think is error prone. The OP was writing code that wanted the uniq-like semantics. ____________________________________________________________________________________Boardwalk for $500? In 2007? Ha! Play Monopoly Here and Now (it's updated for today's economy) at Yahoo! Games. http://get.games.yahoo.com/proddesc?gamekey=monopolyherenow From michael.forbes at gmail.com Fri May 4 15:55:03 2007 From: michael.forbes at gmail.com (Michael) Date: 4 May 2007 12:55:03 -0700 Subject: Why are functions atomic? In-Reply-To: References: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> <1178044821.864741.235260@o5g2000hsb.googlegroups.com> <1178063341.779617.289690@o5g2000hsb.googlegroups.com> <1178065685.161372.81790@y80g2000hsf.googlegroups.com> <1178083318.404304.76100@q75g2000hsh.googlegroups.com> <1178260571.160570.299160@p77g2000hsh.googlegroups.com> Message-ID: <1178308503.420603.158120@e65g2000hsc.googlegroups.com> On May 4, 5:49 am, "Chris Mellon" wrote: > You aren't getting "bit" by any problem with closures - this is a > syntax problem. I understand that it is not closures that are specifically biting me. However, I got bit, it was unplesant and I don't want to be bit again;-) Thus, whenever I need to pass information to a function, I use default arguments now. Is there any reason not to do this other than the fact that it is a bit more typing? Michael From stefan.behnel-n05pAM at web.de Tue May 15 08:29:54 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 15 May 2007 14:29:54 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <4649a561$0$10187$9b4e6d93@newsspool4.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1hy2qg3.iqfvwnrvr9kjN%aleax@mac.com> <46482624.6050507@web.de> <7xd512onsx.fsf@ruckus.brouhaha.com> <464951EF.7030900@web.de> <464997a5$0$10193$9b4e6d93@newsspool4.arcor-online.net> <4649a561$0$10187$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <4649A7C2.7060407@web.de> Ren? Fleschenberg wrote: > Thorsten Kampe schrieb: >>> Identifiers which my terminal cannot even display surely >>> are not very readable. >> This PEP is not about you. It's about people who write in their native >> language and who are forced to use a dodgy transcription from >> characters of their own language to ASCII. > > It is impossible to write Python in a native language other than English > even with the implementation of this PEP. All you get is a weird mixture > of English identifiers from various libraries and identifiers in your > native language. The difference is: keywords and the standard library are a) limited b) public c) domain specific in the Python world or the respective module domain d) chosen according to Python stdlib guidelines (more or less) Identifiers are a) unlimited b) domain specific to a project domain c) chosen according to project guidelines > And even if you consider that more clear and readable > than English-only Python code, the fact that it discourages code sharing > remains. So? Is that bad? Can't OpenSource and closed source happily live together? Stefan From ramakrishnadeepak at gmail.com Tue May 22 02:57:38 2007 From: ramakrishnadeepak at gmail.com (deepak) Date: 21 May 2007 23:57:38 -0700 Subject: httpd: Syntax error on line 54 Message-ID: <1179817058.576484.135570@y2g2000prf.googlegroups.com> I installed apache 2.2.4 and modPython 3.3.1 on Fc6 while starting the apache server the following error occurs: httpd: Syntax error on line 54 of /usr/local/apache2/conf/httpd.conf: Cannot load /usr/local/apache2/modules/mod_python.so into server: /usr/ local/apache2/modules/mod_python.so: cannot restore segment prot after reloc: Permission denied help plz From duncan.booth at invalid.invalid Mon May 21 07:56:53 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 21 May 2007 11:56:53 GMT Subject: Lists vs tuples (newbie) References: Message-ID: Szabolcs wrote: > > I was wondering about why are there both tuples and lists? Is there > anything I can do with a tuple that I cannot do with a list? > > In what circumstances is it advantageous to use tuples instead of lists? > Is there a difference in performance? > > I am still learning Python, so please be gentle ... > Have you found the Python FAQ yet? It answers this exact question and many others: http://www.python.org/doc/faq/general/#why-are-there-separate-tuple-and-list-data-types From bjornkri at gmail.com Tue May 22 04:49:03 2007 From: bjornkri at gmail.com (beertje) Date: 22 May 2007 01:49:03 -0700 Subject: Printing dots in sequence ('...') In-Reply-To: References: <1179820951.288587.142670@h2g2000hsg.googlegroups.com> Message-ID: <1179823743.150983.146290@q66g2000hsg.googlegroups.com> Perfect, thanks :) From bj_666 at gmx.net Thu May 3 12:29:51 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 03 May 2007 18:29:51 +0200 Subject: _csv.Error: string with NUL bytes References: <1178204593.280648.208040@c35g2000hsg.googlegroups.com> <1178209090.674787.202970@o5g2000hsb.googlegroups.com> Message-ID: In <1178209090.674787.202970 at o5g2000hsb.googlegroups.com>, fscked wrote: > The traceback is as follows: > > Traceback (most recent call last): > File "createXMLPackage.py", line 35, in ? > for boxid, mac, activated, hw_ver, sw_ver, heartbeat, name, > address, phone, country, city, in csvreader: > _csv.Error: string with NUL bytes > Exit code: 1 , 0001h As Larry said, this most likely means there are null bytes in the CSV file. Ciao, Marc 'BlackJack' Rintsch From nogradi at gmail.com Fri May 18 14:13:17 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Fri, 18 May 2007 20:13:17 +0200 Subject: Python Web Programming - looking for examples of solid high-traffic sites In-Reply-To: <1hyarxo.iqtdo1v9qpivN%aleax@mac.com> References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> <1hy9yf9.1nnsttj139za6bN%aleax@mac.com> <1hyarxo.iqtdo1v9qpivN%aleax@mac.com> Message-ID: <5f56302b0705181113s4e6632c7o4fed062499530f1b@mail.gmail.com> > > >> For example, it HAS been published elsewhere that YouTube uses lighttpd, > > >> not Apache: . > > > > > > How do you explain these, then: > > > > > > http://www.youtube.com/results.xxx > > > http://www.youtube.com/results.php > > > http://www.youtube.com/results.py > > > > Server signature is usually configurable. > > Yeah, but I don't know why it's configured it that way. A good example > of a question that looks perfectly appropriate for YouTube's OSCON > session. Actually, the fact that http://www.youtube.com/results.php returns legitimate content might be explainable by the fact that youtube was started as a PHP app so they might provide this URL for backward compatibility although today there is no PHP at all. See the abstract of Mike Solomon's OSCON talk: "YouTube began as a small PHP application. [...]" http://conferences.oreillynet.com/cs/os2007/view/e_sess/13435 From cesar.gomes at gmail.com Sat May 12 14:47:11 2007 From: cesar.gomes at gmail.com (Cesar G. Miguel) Date: 12 May 2007 11:47:11 -0700 Subject: Basic question In-Reply-To: References: <1178986686.510137.195490@p77g2000hsh.googlegroups.com> <1178991933.421386.58500@u30g2000hsc.googlegroups.com> <1178992910.318929.77790@e51g2000hsg.googlegroups.com> Message-ID: <1178995630.925969.207740@w5g2000hsg.googlegroups.com> On May 12, 3:40 pm, Dmitry Dzhus wrote: > > Actually I'm trying to convert a string to a list of float numbers: > > str = '53,20,4,2' to L = [53.0, 20.0, 4.0, 2.0] > > str="53,20,4,2" > map(lambda s: float(s), str.split(',')) > > Last expression returns: [53.0, 20.0, 4.0, 2.0] > -- > Happy Hacking. > > Dmitry "Sphinx" Dzhushttp://sphinx.net.ru Nice! The following also works using split and list comprehension (as suggested in a brazilian python forum): ------------------- L = [] file = ['5,1378,1,9', '2,1,4,5'] str='' for item in file: L.append([float(n) for n in item.split(',')]) ------------------- Thank you for all suggestions! From gherron at islandtraining.com Thu May 10 17:53:46 2007 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 10 May 2007 14:53:46 -0700 Subject: Newbie question about string(passing by ref) In-Reply-To: <1178833397.076720.279940@l77g2000hsb.googlegroups.com> References: <1178833397.076720.279940@l77g2000hsb.googlegroups.com> Message-ID: <4643946A.2070503@islandtraining.com> lazy wrote: > Hi, > > I want to pass a string by reference. I understand that strings are > immutable, but Im not > going to change the string in the function, You're confused here. "Immutable" means it *cannot* be changed, so your decision to not change the string is not really your decision at all, but a consequence of the language. > just to aviod the overhead > of copying(when pass-by-value) because the > strings are long and this function will be called over and over > again. > I initially thought of breaking the strings into list and passing the > list instead, but I think there should be an efficient way. > > So is there a way to pass a const reference to a string? > > Thanks > > Strings *are* passed by reference *always*. There is no copy and no overhead. Efficiency is not based on length. Since the string is immutable, nothing you do inside the function can change the string outside the function. Gary Herron From bdesth.quelquechose at free.quelquepart.fr Tue May 8 17:23:18 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 08 May 2007 23:23:18 +0200 Subject: changing a var by reference of a list In-Reply-To: References: <5abcj4F2nv0p0U1@mid.uni-berlin.de> Message-ID: <4640e048$0$19020$426a34cc@news.free.fr> Jorgen Bodde a ?crit : > Ok thanks, > > I will try this approach. The idea was that I could give a list to the > SQL execute command, so that the results coming back would > automatically be assigned to variables. > You may want to have a look at SQLAlchemy. From deets at nospam.web.de Thu May 31 11:21:08 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 31 May 2007 17:21:08 +0200 Subject: How to clean a module? In-Reply-To: <1180622824.836459.222090@q19g2000prn.googlegroups.com> References: <1180622824.836459.222090@q19g2000prn.googlegroups.com> Message-ID: <5c87f5F2mg4c1U1@mid.uni-berlin.de> ai schrieb: > It assumes that there is a module A which have two global variables X > and Y. If I run "import A" in the IDLE shell, then I can use A.X and > A.Y correctly. But if I want to change the module A and then delete > the variable Y, I find I can use A.Y just the same as before! > In fact, I have tried all the following methods but can't remove the > A.Y: > execute "import A" again > "reload(A)" > "del A; import A" > Yes, if you use "del A.Y", it works. But it is stupid since there are > probably many names. In my thought, if no one references objects in A, > "del A" will release all memory about A. But it seems that the fact is > not. So I can not refresh the namespace to follow changes of a module > easily and I will worry about the memory if I del a module. > I want to know if there is a way to clear a module entirely. There might be other answers - but the easiest and IMHO best is to simply restart the interpreter. Because whatever you type in there, you could or should even (if it reaches some complexity) put in a small test script - and execute that from the interpreter at a shell prompt. The advantage is that you don't suffer from any side-effects e.g. IDLE has (no Tk mainloop for example) and avoid the problems you describe entirely. Together with a bunch of others. If you want/have to, you can drop into interpreter mode after script execution with python -i myscript.py Diez From MMM at disney.com Mon May 14 14:28:08 2007 From: MMM at disney.com (MMM at disney.com) Date: Mon, 14 May 2007 13:28:08 -0500 Subject: =// Homeland Security on High Alert!! Fuck Blogs and Bloggers References: <1179166411.536148.186120@w5g2000hsg.googlegroups.com> Message-ID: On 14 May 2007 11:13:31 -0700, ready.or.special3 at gmail.com wrote: >http://freewindowsvista.blogspot.com/ - With a class action lawsuit >looming, three politicians question the head of the Department of >Homeland Security about the lost hard drive. The laptop was never >found... Links always lead to a fucking advertisement with no pics...fuck you asshole.. From ceball at gmail.com Fri May 4 11:02:13 2007 From: ceball at gmail.com (Chris) Date: 4 May 2007 08:02:13 -0700 Subject: Strange terminal behavior after quitting Tkinter application In-Reply-To: References: <1178257164.415485.155290@q75g2000hsh.googlegroups.com> Message-ID: <1178290933.793501.110130@c35g2000hsg.googlegroups.com> On May 4, 8:52 pm, "Hamilton, William " wrote: > > -----Original Message----- > > From: Chris > > Subject: Re: Strange terminal behavior after quittingTkinter > application > > Clicking 'Quit' or on the window's 'x' causes the application to quit > > without messing up the terminal. With root.mainloop() commented out, > > though, no combination of root.quit(), root.destroy(), and sys.exit() > > stops the terminal from getting messed up. > > > So, I should call mainloop() for my application...except that I want > > to use the commandline, too, and calling mainloop() freezes the > > commandline. I wonder if there is another way to use the commandline > > and have a GUI? I couldn't find any clear information about that. > > Can you run it in the background? IIRC, if you put an ampersand ('&') > at the end of the command line, it will run as a background process and > leave your command line available for other tasks. (The marker may be > something other than &, it's been a long, long time since I've used *nix > in a gui environment.) Ah, sorry, I wasn't being precise. I meant the python commandline python interpreter. So from a terminal I type (for example): python -i application.py This launches the interpreter in my terminal. Then I can start the GUI (by typing "Application()", for example). If I use mainloop(), I can't interact with the interpreter from the terminal until I quit the GUI. Without mainloop(), I can continue to enter python commands. From aleax at mac.com Wed May 9 21:24:59 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 9 May 2007 18:24:59 -0700 Subject: which is more pythonic/faster append or +=[] References: <1hxtelz.7f6rvnw4cyxmN%aleax@mac.com> <1178723595.516379.18180@u30g2000hsc.googlegroups.com> Message-ID: <1hxuz03.husyup2cjk81N%aleax@mac.com> 7stud wrote: ... > > .append - easy to measure, too: > > > > brain:~ alex$ python -mtimeit 'L=range(3); n=23' 'x=L[:]; x.append(n)' > > 1000000 loops, best of 3: 1.31 usec per loop > > > > brain:~ alex$ python -mtimeit 'L=range(3); n=23' 'x=L[:]; x+=[n]' > > 1000000 loops, best of 3: 1.52 usec per loop > > > > Alex > > Why is it necessary to copy L? If you don't, then L gets longer and longer -- to over a million elements by the end of the loop -- so we're measuring something that's potentially very different from the problem under study, "what's the best way to append one item to a 3-items list". That's important to consider for any microbenchmark of code that changes some existing state: make sure you're measuring a piece of code that _overall_ does NOT change said existing state in a cumulative way, otherwise you may be measuring something very different from the issue of interest. It's maybe the only important caveat about using "python -mtimeit". Alex From noagbodjivictor at gmail.com Thu May 3 21:27:12 2007 From: noagbodjivictor at gmail.com (noagbodjivictor at gmail.com) Date: 3 May 2007 18:27:12 -0700 Subject: How do I import a variable from another module? Message-ID: <1178242032.254096.316860@o5g2000hsb.googlegroups.com> I have a variable names actions in a module named qt_actions.py Well this is what I get: >>> import qt_actions >>> qt_actions.actions Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'actions' From sturlamolden at yahoo.no Wed May 30 10:53:46 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 30 May 2007 07:53:46 -0700 Subject: writing to a file In-Reply-To: <5c5681F2t82noU1@mid.uni-berlin.de> References: <1180515758.671628.43200@k79g2000hse.googlegroups.com> <5c5681F2t82noU1@mid.uni-berlin.de> Message-ID: <1180536826.630382.89610@u30g2000hsc.googlegroups.com> On May 30, 1:41 pm, "Diez B. Roggisch" wrote: > montyphy... at gmail.com schrieb: > > what i want to know is which one is faster (if there is any difference > > in speed) since i'm working with very large files. of course, if there > > is any other way to write data to a file, i'd love to hear about it > > You should look at the mmap-module. Yes, memory mappings can be more efficient than files accessed using file descriptors. But mmap does not take an offset parameter, and is therefore not suited for working with large files. For example you only have a virtual memory space of 4 GiB on a 32 bit system, so there is no way mmap can access the last 4 GiB of an 8 GiB file on a 32 bit system. If mmap took an offset parameter, this would not be a problem. However, numpy has a properly working memory mapped array class, numpy.memmap. It can be used for fast file access. Numpy also has a wide range of datatypes that are efficient for working with binary data (e.g. an uint8 type for bytes), and a record array for working with structured binary data. This makes numpy very attractive when working with binary data files. Get the latest numpy here: www.scipy.org. Let us say you want to memory map an 23 bit RGB image of 640 x 480 pixels, located at an offset of 4096 bytes into the file 'myfile.dat'. Here is how numpy could do it: import numpy byte = numpy.uint8 desc = numpy.dtype({'names':['r','g','b'],'formats':[byte,byte,byte]}) mm = numpy.memmap('myfile.dat', dtype=desc, offset=4096, shape=(480,640), order='C') red = mm['r'] green = mm['g'] blue = mm['b'] Now you can access the RGB values simply by slicing the arrays red, green, and blue. To set the R value of every other horizontal line to 0, you could simply write red[::2,:] = 0 As always when working with memory mapped files, the changes are not committed before the memory mapping is synchronized with the file system. Thus, call mm.sync() when you want the actual write process to start. The memory mapping will be closed when it is garbage collected (typically when the reference count falls to zero) or when you call mm.close(). From manishk at cybage.com Wed May 16 02:00:33 2007 From: manishk at cybage.com (Manish Kumar) Date: Wed, 16 May 2007 11:30:33 +0530 Subject: Needs help to install ZOracleDA Message-ID: Hi All, How can I install ZOracleDA on Red Hat Linux machine? Configuration of my system is as below: Zope-2.7 Python-2.3.5 Oracle-9i I have tried to install ZOracleDA but installable needed rh-7.1-python-1.5.2-dco2.so file which is not present in Binaries directory. Any help from you people is appreciable. Regards, Manish Kumar "Legal Disclaimer: This electronic message and all contents contain information from Cybage Software Private Limited which may be privileged, confidential, or otherwise protected from disclosure. The information is intended to be for the addressee(s) only. If you are not an addressee, any disclosure, copy, distribution, or use of the contents of this message is strictly prohibited. If you have received this electronic message in error please notify the sender by reply e-mail to and destroy the original message and all copies. Cybage has taken every reasonable precaution to minimize the risk of malicious content in the mail, but is not liable for any damage you may sustain as a result of any malicious content in this e-mail. You should carry out your own malicious content checks before opening the e-mail or attachment." www.cybage.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Wed May 2 17:08:38 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 02 May 2007 23:08:38 +0200 Subject: Lazy evaluation: overloading the assignment operator? In-Reply-To: <1178133344.415521.118710@n76g2000hsh.googlegroups.com> References: <1178133344.415521.118710@n76g2000hsh.googlegroups.com> Message-ID: <59scumF2lqg76U1@mid.uni-berlin.de> sturlamolden schrieb: > Python allows the binding behaviour to be defined for descriptors, > using the __set__ and __get__ methods. I think it would be a major > advantage if this could be generalized to any object, by allowing the > assignment operator (=) to be overloaded. > > One particular use for this would be to implement "lazy evaluation". > For example it would allow us to get rid of all the temporary arrays > produced by NumPy. > > For example, consider the expression: > > y = a * b + c * d > > If this expression is evaluated bya Fortran 90/95 compiler, it will > automatically generate code like > > do i = 1,n > y(i) = a(i) * b(i) + c(i) * d(i) > enddo > > On the other hand, conventional use of overloaded binary operators > would result in something like this: > > allocate(tmp1,n) > do i = 1,n > tmp1(i) = a(i) * b(i) > enddo > allocate(tmp2,n) > do i = 1,n > tmp2(i) = c(i) * d(i) > enddo > allocate(tmp3,n) > do i = 1,n > tmp3(i) = tmp1(i) + tmp2(i) > enddo > deallocate(tmp1) > deallocate(tmp2) > do i = 1,n > y(i) = tmp3(i) > enddo > deallocate(tmp3) > > Traversing memory is one of the most expensive thing a CPU can do. > This approach is therefore extremely inefficient compared with what a > Fortran compiler can do. I fail to see where laziness has anything to do with this. In C++, this problem can be remedied with the so called temporary base class idiom. But this has nothing to do with laziness, which does not reduce the amount of code to execute, but instead defers the point of execution of that code. And AFAIK the general overhead of laziness versus eager evaluation does not pay off - haskell is a tad slower than e.g. an ML dialect AFAIK. Diez From laurent.pointal at limsi.fr Wed May 2 09:59:29 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Wed, 02 May 2007 15:59:29 +0200 Subject: pack/unpack zero terminated string In-Reply-To: <1178114191.580368.59520@c35g2000hsg.googlegroups.com> References: <1178114191.580368.59520@c35g2000hsg.googlegroups.com> Message-ID: tmp123 a ?crit : > Hello, > > Thanks for your time. > > After review the "struct" documentation, it seems there are no option > to pack/unpack zero terminated strings. > > By example, if the packed data contains: byte + zero terminated string > + zero terminated string + byte, it seems no possible to unpack it > using "struct". > > Please, has someone any hint or pointer to another librarian to be > used? May look at ctypes and its c_char_p type Documentation says: http://python.net/crew/theller/ctypes/reference.html#fundamental-data-types c_char_p Represents the C char * datatype, which must be a pointer to a zero-terminated string. The constructor accepts an integer address, or a string. Note: its in standard libraries from Python 2.5. From torriem at chem.byu.edu Mon May 21 15:36:16 2007 From: torriem at chem.byu.edu (Michael L Torrie) Date: Mon, 21 May 2007 13:36:16 -0600 Subject: Python and GUI In-Reply-To: <4651C776.30105@redhat.com> References: <1179761984.704369.116310@b40g2000prd.googlegroups.com> <4651C776.30105@redhat.com> Message-ID: <1179776176.28714.21.camel@contra.chem.byu.edu> On Mon, 2007-05-21 at 18:23 +0200, Petr Muller wrote: > There's PyQt thingy, imho very good and easy to learn/use, but still > powerful. I've used it for a small gui-oriented project with almost no > problems and it worked like a charm. However, sometimes I had troubles > finding useful documentation for it. > I've also tried to play with PyGTK, it's quite nice and easy (and you > have the advantage of Glade), but I don't like GTK way of creating GUI. > I haven't used Tkinter a lot, only looked at it. And I didn't like it much. How does GTK's way of creating the GUI (I presume you're not talking look and feel) differ from Qt's? From what I can see (having developed large apps in both GTKmm and Qt (C++), they both function the same. In other words you create the widget first, then parent it in a container and add callbacks. Whereas wxPython's approach is somewhat different. It appears that most wxPython apps setup the GUI programmatically, whereas Most Qt and Gtk apps tend to use XML-based gui-building factories. In this latter case, Glade's method is quite different from Qt's. > > I would really suggest PyQt. (with a big IMHO :) > > Petr From jakub.stolarski at gmail.com Mon May 14 16:31:16 2007 From: jakub.stolarski at gmail.com (Jakub Stolarski) Date: 14 May 2007 13:31:16 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <4648bd67$0$5110$ba4acef3@news.orange.fr> References: <46473267$0$31532$9b622d9e@news.freenet.de> <4648bd67$0$5110$ba4acef3@news.orange.fr> Message-ID: <1179174676.691294.91090@n59g2000hsh.googlegroups.com> On May 14, 9:49 pm, M?ta-MCI wrote: > Hi! > > - should non-ASCII identifiers be supported? why? > - would you use them if it was possible to do so? in what cases? > > Yes. > > JScript can use letters with accents in identifiers > XML (1.1) can use letters with accents in tags > C# can use letters with accents in variables > SQL: MySQL/MS-Sql/Oralcle/etc. can use accents in fields or request > etc. > etc. > > Python MUST make up for its lost time. > > MCI And generally nobody use it. It sounds like "are for art's sake". But OK. Maybe it'll be some impulse to learn some new languages. +1 for this PEP From noagbodjivictor at gmail.com Thu May 3 20:00:04 2007 From: noagbodjivictor at gmail.com (noagbodjivictor at gmail.com) Date: 3 May 2007 17:00:04 -0700 Subject: How do I output a list like the interpreter do? Message-ID: <1178236804.658955.204140@h2g2000hsg.googlegroups.com> >>> s = ['a','b'] >>> s ['a', 'b'] >>> This is what I want so that I can put it in a module then import that module to work with my variable. From deets at nospam.web.de Wed May 9 09:54:55 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 09 May 2007 15:54:55 +0200 Subject: change of random state when pyc created?? References: Message-ID: <5ae25fF2oggbqU1@mid.uni-berlin.de> Alan Isaac wrote: > > "Peter Otten" <__peter__ at web.de> wrote in message > news:f1rt61$kfg$03$1 at news.t-online.com... >> Alan Isaac wrote: >> There is nothing wrong with the random module -- you get the same numbers > on >> every run. When there is no pyc-file Python uses some RAM to create it >> and therefore your GridPlayer instances are located in different memory >> locations and get different hash values. This in turn affects the order >> in which they occur when you iterate over the GridPlayer.players_played >> set. > > Thanks!! > This also explains Steven's results. > > If I sort the set before iterating over it, > the "anomaly" disappears. > > This means that currently the use of sets > (and, I assume, dictionaries) as iterators > compromises replicability. Is that a fair > statement? Yes. > For me (and apparently for a few others) > this was a very subtle problem. Is there > a warning anywhere in the docs? Should > there be? Not really, but that depends on what you know about the concept of sets and maps as collections of course. The contract for sets and dicts doesn't imply any order whatsoever. Which is essentially the reason why set(xrange(10))[0] doesn't exist, and quite a few times cries for an ordered dictionary as part of the standard libraries was made. Diez From larry.bates at websafe.com Fri May 25 18:41:47 2007 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 25 May 2007 17:41:47 -0500 Subject: csv.reader length? In-Reply-To: References: <1180118981.024036.163590@p47g2000hsd.googlegroups.com> <1180122583.282729.275840@p47g2000hsd.googlegroups.com> Message-ID: Peter Otten wrote: > 7stud wrote: > >> On May 25, 12:49 pm, cjl wrote: > >>> reader = csv.reader(open('somefile.csv')) >>> for row in reader: >>> do something >>> >>> Any way to determine the "length" of the reader (the number of rows) >>> before iterating through the rows? > > No. You have to read the records to know the length: > > rows = list(reader) > print len(rows) > for row in rows: > # ... > >> How about: >> >> f = open("somefile.csv") >> numlines = len(f.readlines()) > > No, a field in a csv file may contain newlines: > >>>> import csv >>>> csv.writer(open("tmp.csv", "w")).writerows([["a", "b\nc"], ["d", "e"]]) >>>> len(open("tmp.csv").readlines()) > 3 # number of lines >>>> len(list(csv.reader(open("tmp.csv")))) > 2 # number of records > > Peter > Did you try: import crystal_ball num_lines=crystal_ball(reader) Sorry I couldn't resist. -Larry From arjunajay_ajay at rediffmail.com Sat May 19 12:14:40 2007 From: arjunajay_ajay at rediffmail.com (Arjun Narayanan) Date: 19 May 2007 09:14:40 -0700 Subject: Can't embed python in C++(Mingw[3.*] compiler) Message-ID: <1179591280.469302.289010@p77g2000hsh.googlegroups.com> For thr program, #include "E:\Python25\include\Python.h" #include int main(int argc, char* argv[]){ Py_Initialise(); Py_Finalise(); return 0; } I get the errors, main.cpp:7: `Py_Initialise' undeclared (first use this function) main.cpp:7: (Each undeclared identifier is reported only once for each function it appears in.) main.cpp:8: `Py_Finalise' undeclared (first use this function) Process terminated with status 1 (0 minutes, 1 seconds) I included "E:\Python25\include\Python.h" Also I think that when I use C instead of c++ errors did'nt happen although I can't repeat that now Also do I need to link only 'libpython25.a' From ms at cerenity.org Fri May 11 04:58:18 2007 From: ms at cerenity.org (Michael) Date: Fri, 11 May 2007 09:58:18 +0100 Subject: Erlang style processes for Python References: <1178759792.268979.206630@p77g2000hsh.googlegroups.com> Message-ID: <46442fa9$0$8713$ed2619ec@ptn-nntp-reader02.plus.net> Jacob Lee wrote: > Funny enough, I'm working on a project right now that is designed for > exactly that: PARLEY, http://osl.cs.uiuc.edu/parley . Have you seen Kamaelia? Some people have noted that Kamaelia seems to have a number of similarities to Erlang's model, which seems to come from a common background knowledge. (Kamaelia's model is based on a blending of what I know from a very basic recasting of CSP, Occam, unix pipelines and async hardware verification). Home: http://kamaelia.sourceforge.net/Home Intros: http://kamaelia.sourceforge.net/Introduction http://kamaelia.sourceforge.net/t/TN-LinuxFormat-Kamaelia.pdf http://www.bbc.co.uk/rd/pubs/whp/whp113.shtml * http://kamaelia.sourceforge.net/t/TN-LightTechnicalIntroToKamaelia.pdf http://kamaelia.sourceforge.net/Docs/NotationForVisualisingAxon The one *'d is perhaps the best at the moment. Detail: http://kamaelia.sourceforge.net/Cookbook http://kamaelia.sourceforge.net/Components Michael. From rene at korteklippe.de Tue May 15 07:21:10 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 15 May 2007 13:21:10 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464951EF.7030900@web.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1hy2qg3.iqfvwnrvr9kjN%aleax@mac.com> <46482624.6050507@web.de> <7xd512onsx.fsf@ruckus.brouhaha.com> <464951EF.7030900@web.de> Message-ID: <464997a5$0$10193$9b4e6d93@newsspool4.arcor-online.net> Stefan Behnel schrieb: > "go to" is not meant for clarity, nor does it encourage code readability. Some people would argue that position. > But that's what this PEP is about. IMHO, this PEP does not encourage clarity and readability, it discourages it. Identifiers which my terminal cannot even display surely are not very readable. -- Ren? From danb_83 at yahoo.com Thu May 17 00:36:20 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: 16 May 2007 21:36:20 -0700 Subject: How do I tell the difference between the end of a text file, and an empty line in a text file? In-Reply-To: <1179352021.803070.200780@k79g2000hse.googlegroups.com> References: <1179352021.803070.200780@k79g2000hse.googlegroups.com> Message-ID: <1179376579.946761.40200@q75g2000hsh.googlegroups.com> On May 16, 4:47 pm, walterbyrd wrote: > Python's lack of an EOF character is giving me a hard time. > > I've tried: > > ----- > s = f.readline() > while s: > . > . > s = f.readline() > -------- > > and > > ------- > s = f.readline() > while s != '' > . > . > s = f.readline() > ------- > > In both cases, the loop ends as soon it encounters an empty line in > the file, i.e. > > xxxxxxxxxx > xxxxxxxxxxx > xxxxxxx > < - - - loop end here > xxxxxxxxxxxxxx > xxxxxxxxxx > x > < ---- loop should end here Use a "for s in f" loop instead. From gherron at islandtraining.com Sat May 12 12:49:02 2007 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 12 May 2007 09:49:02 -0700 Subject: Basic question In-Reply-To: <1178986686.510137.195490@p77g2000hsh.googlegroups.com> References: <1178986686.510137.195490@p77g2000hsh.googlegroups.com> Message-ID: <4645EFFE.3040709@islandtraining.com> Cesar G. Miguel wrote: > I've been studying python for 2 weeks now and got stucked in the > following problem: > > for j in range(10): > print j > if(True): > j=j+2 > print 'interno',j > > What happens is that "j=j+2" inside IF does not change the loop > counter ("j") as it would in C or Java, for example. > > Am I missing something? > > []'s > Cesar > > Nope. The loop counter will be assigned successively through the list of integers produced by range(10). Inside the loop, if you change j, then from that point on for that pass through the body, j will have that value. But such an action will not change the fact that next pass through the loop, j will be assigned the next value in the list. From tjreedy at udel.edu Sat May 12 00:54:08 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 12 May 2007 00:54:08 -0400 Subject: Recursion limit problems References: <1178921877.442519.165740@u30g2000hsc.googlegroups.com> Message-ID: "elventear" wrote in message news:1178921877.442519.165740 at u30g2000hsc.googlegroups.com... | Hello everyone, | | I am runing into recursion limit problems. I have found that the | culprit was related to the __hash__ function that I had assigned to | the objects that were added to a set. | | Basically my __hash__ function is the following: | | def __hash__(self): | out_int = 0 | for property,value in self: | out_int ^= hash( property )^hash( value ) | | return out_int | | And the iterator for this object is: | | def __iter__(self): | for property,value in self.__dict__.iteritems(): | yield property,value | | After commenting the __hash__ function and using the default provided | by Python (I suppose it is based on the position in memory of the | object), the recursion limit problems went away. (This problem was | happening even after increasing the recursion limit to the maximum of | my platform, MacOSX). | | I am not that versed in Python, so I don't know exactly I could do to | overcome this problem, any ideas are deeply appreciated. Without seeing the full code and the exception traceback, my guess is that your __hash__ somehow calls itself due to a refence loop in your object. A simple example of a loop: a = []; a.append(a) Now, list objects are not hashable, but if they were, and the hash were value based (like your), then hash(a) would call hash(a) would call hash(a).... Suggestion: put print id(self) in __hash__ and see if you get a repeat. And maybe reduce the recursion limit to reduce the traceback listing ;-) Terry Jan Reedy From bdesth.quelquechose at free.quelquepart.fr Sun May 13 10:40:16 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 13 May 2007 16:40:16 +0200 Subject: design question In-Reply-To: <1179002502.146058.90860@n59g2000hsh.googlegroups.com> References: <1178992981.143066.279690@o5g2000hsb.googlegroups.com> <5amj6gF2pbeeuU1@mid.individual.net> <1179002502.146058.90860@n59g2000hsh.googlegroups.com> Message-ID: <4647192c$0$2346$426a74cc@news.free.fr> idaku2 at gmail.com a ?crit : > On May 12, 9:34 pm, Bjoern Schliessmann mail-0306.20.chr0n... at spamgourmet.com> wrote: > > >>In principle, this is legal. >> >>But OTOH, how could a ShoppingCart "buy" something? In my world, >>Buyers "buy" when using ShoppingCarts. > > > Yes, I don't know either. I got this assignment for my homework, and > in UML diagram class ShoppingCart has method buy(), and the class > Buyer doesn't have any methods, only attribute ShoppingCart, and I > must simulate/implement online shopping. In my world buyers buy too, > just wanna check with somebody with more experience. :) It's alas pretty common to see OO taught by persons who'd rather do some other job - preferably not related to computers. > Thank you both. > From stephen04 at tiscali.co.uk Tue May 15 20:31:17 2007 From: stephen04 at tiscali.co.uk (Stephen Lewitowski) Date: Wed, 16 May 2007 01:31:17 +0100 Subject: Python Newbie Suggestions In-Reply-To: <1179264515.958714.72880@l77g2000hsb.googlegroups.com> References: <1179264515.958714.72880@l77g2000hsb.googlegroups.com> Message-ID: <464a50d7$1_4@mk-nntp-2.news.uk.tiscali.com> garcigal at gmail.com wrote: > I'm a mechanical engineer with little experience programming. I've > used C++ and machine language for getting micro-controllers to work > and thats about it. I work allot with software developers at my job > and can read C++ code pretty good (ie. I understand whats going on). > Does anyone have any good tips or resources for someone interested in > learning PYTHON. This is purely for hobby purposes and I'd like to > expose my kids to a programing language too. If any one has any > helpful books, tips or suggestions please let me know. I have > Windows, MAC and Linux box's at my house but I'm a primarily a MAC > user. > I was once a newbie too. I started with the Python Tutorial which is on the Python Website and found it to be a good starting point. http://docs.python.org/tut/tut.html Have a go with this and see how you get on. There are lots of resources at http://www.python.org, including distributions of the latest version of the python interpreter, which you should install (if you have not already) before attempting the tutorials. From bbxx789_05ss at yahoo.com Mon May 14 12:22:46 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 14 May 2007 09:22:46 -0700 Subject: which is more pythonic/faster append or +=[] In-Reply-To: References: <1hxtelz.7f6rvnw4cyxmN%aleax@mac.com> <1178726923.909537.209300@l77g2000hsb.googlegroups.com> <1178739061.919664.128260@y80g2000hsf.googlegroups.com> <1178825802.319573.113930@w5g2000hsg.googlegroups.com> Message-ID: <1179159766.373670.105720@e65g2000hsc.googlegroups.com> On May 10, 2:39 pm, Steven Bethard wrote: > 7studwrote: > >> Is there any documentation for the syntax you used with timeit? > > > This is the syntax the docs describe: > [snip > > python timeit.py [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement ...] > [snip] > > Then in the examples in section 10.10.2 > [snip] > > timeit.py 'try:' ' str.__nonzero__' 'except AttributeError:' ' pass' > [snip] > > and then there is Alex Martelli's syntax: > [snip] > > python -mtimeit 'L=range(3); n=23' 'x=L[:]; x.append(n)' > > The following three things are equivalent: > python /path/to/.py > /path/to/.py # assuming the OS knows how to exec it > python -m # assuming is on sys.path > > So that just leaves the differences between: > [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement ...] > 'try:' ' str.__nonzero__' 'except AttributeError:' ' pass' > 'L=range(3); n=23' 'x=L[:]; x.append(n)' > > Those look pretty similar to me (aside from the fact that they're > testing different things). Each argument in single quotes is a line of > the code you want timed. > Thanks. From steve at REMOVE.THIS.cybersource.com.au Wed May 2 18:55:19 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 03 May 2007 08:55:19 +1000 Subject: Slicing Arrays in this way References: <4638fe20$0$16403$88260bb3@free.teranews.com> Message-ID: On Wed, 02 May 2007 15:03:24 -0700, Tobiah wrote: > > >>> elegant_solution([1,2,3,4,5,6,7,8,9,10]) > [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] Wow! That's impressive. What version of Python are you using? When I try it, I get this: >>> elegant_solution([1,2,3,4,5,6,7,8,9,10]) Traceback (most recent call last): File "", line 1, in NameError: name 'elegant_solution' is not defined -- Steven. From gagsl-py2 at yahoo.com.ar Sat May 19 02:09:45 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 19 May 2007 03:09:45 -0300 Subject: which is the comprehencive module for postgresql? References: Message-ID: En Sat, 19 May 2007 02:25:11 -0300, krishnakant Mane escribi?: > some times having many choices often confuses the users. > can some one plese tell me which is the most comprehencive, well > documented and widely used and tested module to connect from python to > postgresql database? I looked around PYPgsql but there seams to be > very little documentation. I've never used Postgresql with Python so I can't recommend any, but see this wiki page: http://wiki.python.org/moin/PostgreSQL -- Gabriel Genellina From fabien.lyon at isismpp.fr Tue May 29 14:01:07 2007 From: fabien.lyon at isismpp.fr (fabien.lyon) Date: Tue, 29 May 2007 20:01:07 +0200 Subject: embeded python progam into visual C++ application crash Message-ID: <1DC9064A1EB94845987C198ADF4E11201594A9@messagix.ISISTHIBAUD.local> hello, The C++ application uses a python module which wraps commands set for CVS management: checkout, checkin and tag. We used python2.5.1 and Visual C++ 6.0 The problem we get is: After a good import and definition of python functions we have a random unhandled exception (from python25.dll) when calling python interface function several times. All the python module has been tested using the python IDLE. This the C++ sequence code we used: Py_initialize() Py_Import("moduleName") cvs_init() // cvs view initialisation handled by python script init() cvs_set_tag() // cvs commit and tag handled by python script settag() // the exception occured here This is the python script part: def init(pathBench=None): global CVSROOT global BENCH_DIR ret = 0 str = 'CVS initialization: init() OK' if os.path.isdir(pathBench): try : cvsapi.checkout(CVSROOT, 'bench', destination=pathBench, recursive=False) except cvsapi.CheckoutError, error: ret = -1 str = "CVS initialisation %s: %s, init() KO" % (pathBench,error) else: ret = -1 str = "CVS initialization: pathBench %s is not a directory, init() KO" % pathBench return ret,str def settag(tagName, pathBench): ret = 0 str = 'CVS commit and tag: Warning no bench, settag()' try: pathBench = pathBench.rstrip('\\') pathTest = pathTest.rstrip('\\') pathStorage = pathStorage.rstrip('\\') if not os.path.isdir(pathBench) : ret = -1 return ret, str ret, str = SettagView(tagName, pathBench) except cvsapi.PathError,error: ret = -1 str = "settag(): path error %s" % error except cvsapi.AddError,error: ret = -1 str = "settag(): cvs add error %s" % error except: ret = -1 str = "settag() unknown error" return ret,str Any information will be welcome as the scripts are running under IDLE and not in embeded C++ thanks for your help Fabien LYON Service Informatique ISIS * fabien.lyon at isismpp.fr * (+33) 05-61-43-59-04 * (poste interne) 5904 Fax (+33) 05-61-43-58-60 * 6 rue des Fr?res Boude ZI Thibaud, BP 70439 31104 Toulouse Cedex 1 From paddy3118 at googlemail.com Sat May 19 11:26:54 2007 From: paddy3118 at googlemail.com (Paddy) Date: 19 May 2007 08:26:54 -0700 Subject: Start In-Reply-To: References: Message-ID: <1179588413.987135.241210@e65g2000hsc.googlegroups.com> On May 19, 4:18 pm, Nautilus wrote: > Can anybody halp me start using Python. http://wiki.python.org/moin/BeginnersGuide And welcome :-) - Paddy. From rampeters at gmail.com Fri May 11 11:54:31 2007 From: rampeters at gmail.com (johnny) Date: 11 May 2007 08:54:31 -0700 Subject: Simple Python REGEX Question Message-ID: <1178898871.781501.135170@p77g2000hsh.googlegroups.com> I need to get the content inside the bracket. eg. some characters before bracket (3.12345). I need to get whatever inside the (), in this case 3.12345. How do you do this with python regular expression? From claird at lairds.us Sat May 19 20:56:24 2007 From: claird at lairds.us (Cameron Laird) Date: Sun, 20 May 2007 00:56:24 +0000 Subject: python shell References: <1179337107.842668.112690@k79g2000hse.googlegroups.com> <1179552984.466321.137550@u30g2000hsc.googlegroups.com> Message-ID: In article <1179552984.466321.137550 at u30g2000hsc.googlegroups.com>, Paddy wrote: >On May 16, 6:38 pm, Krypto wrote: >> I have been using python shell to test small parts of the big program. >> What other ways can I use the shell effectively. My mentor told me >> that you can virtually do anything from testing your program to >> anything in the shell. Any incite would be useful. > >Doctest! >http://en.wikipedia.org/wiki/Doctest . . . will probably prove more fruitful. While I don't like follow-ups which consist of trivial corrections, I *very* much want to encourage readers to explore Doctest more deeply; it deserves the attention, even at the cost of appearing pedantic. From mickel.gronroos at gmail.com Wed May 23 04:13:16 2007 From: mickel.gronroos at gmail.com (=?ISO-8859-1?Q?Mickel_Gr=F6nroos?=) Date: Wed, 23 May 2007 11:13:16 +0300 Subject: Writing a Web Service in Python for MS Office Research Task Pane Message-ID: <93ef803f0705230113p641ccfe7l4466a616f3a140a4@mail.gmail.com> Hi fellow pythoneers, I'm thinking about writing a simple web service for use in the "Research Task Pane" in Microsoft Office. There is a lot of C# and VB code samples out there and tutorials on how to do this in Visual Studio on Windows; however, I am interested in writing the web service in Python and keep it available on a web server running Linux. Does anybody have any experience on this? Code samples? Reasons for NOT attempting this in Python? Much obliged, Mickel Gr?nroos Helsinki From half.italian at gmail.com Mon May 7 12:45:44 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 7 May 2007 09:45:44 -0700 Subject: long lists In-Reply-To: <1178540073.988964.196860@w5g2000hsg.googlegroups.com> References: <1178522894.357829.28250@u30g2000hsc.googlegroups.com> <1178540073.988964.196860@w5g2000hsg.googlegroups.com> Message-ID: <1178556344.378245.249800@n59g2000hsh.googlegroups.com> On May 7, 5:14 am, Merrigan wrote: > On May 7, 10:18 am, Steven D'Aprano > > > > wrote: > > On Mon, 07 May 2007 00:28:14 -0700, Merrigan wrote: > > > 1. I have the script popping all the files that need to be checked into > > > a list, and have it parsing the list for everything...Now the problem is > > > this : The sever needs to check (at the moment) 375 files and eliminate > > > those that don't need reuploading. This number will obviously get bigger > > > and bigger as more files gets uploaded. Now, the problem that I'm having > > > is that the script is taking forever to parse the list and give the > > > final result. How can I speed this up? > > > By writing faster code??? > > > It's really hard to answer this without more information. In particular: > > > - what's the format of the list and how do you parse it? > > > - how does the script decide what files need uploading? > > > -- > > Steven. > > Hi, Thanx for the reply, > > The Script it available at this url :http://www.lewendewoord.co.za/theScript.py > > P.S. I know it looks like crap, but I'm a n00b, and not yet through > the OOP part of the tutorial. > > Thanx in advance! Do you have access to the machine via ssh? I would try to get away from FTP and use rsync for this kind of thing if possible. ~Sean From maric at aristote.info Thu May 17 12:03:29 2007 From: maric at aristote.info (Maric Michaud) Date: Thu, 17 May 2007 18:03:29 +0200 Subject: Execute commands from file In-Reply-To: References: <1179320782.594398.67980@u30g2000hsc.googlegroups.com> <464b370c$0$3808$5402220f@news.sunrise.ch> <1179387023.005808.60670@o5g2000hsb.googlegroups.com> Message-ID: <464C7CD1.8060706@aristote.info> Steve Holden a ?crit : > i3dmaster wrote: >> On May 16, 1:05 pm, Steve Holden wrote: >>> Martin Blume wrote: >>>> "tmp123" schrieb > >>>>> We have very big files with python commands >>>>> (more or less, 500000 commands each file). >>>>> It is possible to execute them command by command, >>>> inp = open(cmd_file) >>>> for line in inp: >>>> exec line >>> The problem with this approach is that each line executes without any >>> connection to the environment created by previous lies. >>> >>> Try it on a file that reads something like >>> >>> xxx = 42 >>> print xxx >>> >> cat file: >> >> x = 100 >> print x >> >> cat file.py: >> #!/usr/bin/python2.4 >> >> import os.path >> import sys >> >> file, ext = os.path.splitext(sys.argv[0]) >> f = open(file,'rb') >> for i in f: >> exec i >> >>> ./file.py >> 100 >> >> Don't see the problem though. >> > No, because there isn't one. Now try adding a function definition and > see how well it works. > > regards > Steve This is just a problem with indentation and blocks of code, the followong will do : commands = open("commands") namespace, block = {}, "" for line in commands : line=line[:-1] if not line : continue if line[0].isspace() : block += '\n' + line continue else : if block.strip() : exec block in namespace block = line exec block in namespace print dict((k, v) for k, v in namespace.items() if k != "__builtins__") with commands containing : """ x = 5 def toto(arg) : print arg def inner() : print arg*arg inner() toto(x) """ output : 5 25 {'x': 5, 'toto': } (sorry Steve for the private mail) -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 4 26 88 00 97 Mobile: +33 6 32 77 00 21 From sjmachin at lexicon.net Mon May 7 19:40:15 2007 From: sjmachin at lexicon.net (John Machin) Date: 7 May 2007 16:40:15 -0700 Subject: No module named urllib In-Reply-To: <1178579211.696681.212110@w5g2000hsg.googlegroups.com> References: <1178575589.059564.226060@q75g2000hsh.googlegroups.com> <1178578854.926104.184700@y5g2000hsa.googlegroups.com> <1178579211.696681.212110@w5g2000hsg.googlegroups.com> Message-ID: <1178581215.434894.223880@y80g2000hsf.googlegroups.com> On May 8, 9:06 am, HMS Surprise wrote: > On May 7, 6:00 pm, John Machin wrote: > > > > > On May 8, 8:06 am, HMS Surprise wrote: > > > > I edited environment varialbes and have added C:\Python25\Lib to > > > PYTHONPATH but get the no module message when the statement > > > That directory should already be in sys.path after a normal Python > > install. Likewise the PYTHONPATH environment variable should be > > undefined: > > > DOS_prompt> set PYTHONPATH > > Environment variable PYTHONPATH not defined > > > What was already in PYTHONPATH before you added something? > > Why did you think you needed to change things? > > Only what I added before: > .; c:\maxq\bin\testScripts; c:\maxq\bin;c:\maxq\jython You have somehow managed to *REPLACE* the whole of sys.path with those 4 directories. Have you fiddled with PYTHONHOME as well? [You shouldn't]. Go to a DOS-prompt and type set PYTHONPATH set PYTHONHOME and tell us what you see. From http Sun May 13 13:52:12 2007 From: http (Paul Rubin) Date: 13 May 2007 10:52:12 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <20070513160046.GC29172@v.igoro.us> Message-ID: <7x646wa9wz.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > This is a commonly-raised objection, but I don't understand why people > see it as a problem. The phishing issue surely won't apply, as you > normally don't "click" on identifiers, but rather type them. In a > phishing case, it is normally difficult to type the fake character > (because the phishing relies on you mistaking the character for another > one, so you would type the wrong identifier). It certainly does apply, if you're maintaining a program and someone submits a patch. In that case you neither click nor type the character. You'd normally just make sure the patched program passes the existing test suite, and examine the patch on the screen to make sure it looks reasonable. The phishing possibilities are obvious. From laurent.pointal at wanadoo.fr Wed May 2 15:43:53 2007 From: laurent.pointal at wanadoo.fr (Laurent Pointal) Date: Wed, 02 May 2007 21:43:53 +0200 Subject: [ANN] Update to Python Quick Reference Card (for Python 2.4) (v0.67) References: <4bnh33pb644j9qsvij3citqrpb2bmqlsu4@4ax.com> Message-ID: <4638e8a8$0$27396$ba4acef3@news.orange.fr> Casey Hawthorne wrote: > PC-cillin flagged this as a dangerous web site. Maybe PC-cillin tag as dangerous all sites about Python, the famous snake. PS. And why does it tag my laboratory work page as dangerous ? It's pure HTML, I worked to have even no javascript, readable with lynx. From kyosohma at gmail.com Wed May 9 15:36:15 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 9 May 2007 12:36:15 -0700 Subject: Specification for win32com.client package In-Reply-To: References: <23617.87850.qm@web63415.mail.re1.yahoo.com> <1178715787.220103.245060@e65g2000hsc.googlegroups.com> <1178723397.709258.50350@o5g2000hsb.googlegroups.com> Message-ID: <1178739375.611828.103320@o5g2000hsb.googlegroups.com> On May 9, 10:26 am, Tim Golden wrote: > kyoso... at gmail.com wrote: > > On May 9, 8:25 am, Tim Golden wrote: > >> kyoso... at gmail.com wrote: > >>> The wiki idea sounds like a good one. I was thinking about doing some > >>> kind of Python site about the modules and I think the popular 3rd > >>> party ones would be a good place to start, maybe starting with win32. > >>> How much information do you think would need to be on a site like this > >>> to start out with? > >> Someone did start a Python Win32 Wiki recently (check the > >> python-win32 archives for location etc.) I did mean to put > >> things on there myself, but real life has taken over. Often, > >> these things just need someone with a bit of oomph to at > >> least get the thing going. > > >> I think what's needed (if you're offering :) is for someone > >> to put a *framework* in place on such a site which would > >> make it easy for anyone to come along and fill in the gaps > >> with their particular 3rd-party app or brand of knowledge. > >> As I say, someone did start something, but I've not heard > >> anything from him since then and I haven't found the time > >> myself. If you were to kick something off and actually get > >> it going I wouldn't say no. > > >> TJG > > > I think I found the thread you were talking about: > >http://mail.python.org/pipermail/python-win32/2007-March/005585.html > > > I went to the site listed:www.wazoozle.comand I see nothing related > > to python there. In fact, James (the poster) doesn't appear to be > > listed anywhere either. Very weird. > > Strange. Maybe he gave up and hosted something > else instead. It's not as though the name was > related :) > > > While I am not a wiki wizard, I will look into it. I might be able to > > bamboozle some free space on my friend's hosting service for such a > > project. If so, I'll let you know. > > Personally, if only to save startup pain, I'd be inclined to > use the main Python wiki, at least to get going. I know I > said at the time that I was willing to kick something off, > but days led to weeks... and you can guess the rest. > > Why not corner an area onhttp://wiki.python.org/moin/ > and put headings in place? I'm not a great fan of MoinMoin, > but it's there and it carries a (certain) measure of > authority. That said, if you want to set up on your own > space, I'm not objecting. I'll do my best (this time) to > supply info and keep things going. > > TJG It looks like there's already a "Useful Modules" page on the wiki: http://wiki.python.org/moin/ I could put the win32 stuff in there under the Platform Specific --> Windows sub-header, I suppose. Or maybe the documentation page? I dunno. Whatever I end up doing, it'll have to be one of these evenings after work is done. I'll let you know somehow. Mike From chris.cavalaria at free.fr Wed May 16 04:12:59 2007 From: chris.cavalaria at free.fr (Christophe) Date: Wed, 16 May 2007 10:12:59 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179289167.723990.223890@u30g2000hsc.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179289167.723990.223890@u30g2000hsc.googlegroups.com> Message-ID: <464abd12$0$23364$426a34cc@news.free.fr> sjdevnull at yahoo.com a ?crit : > Steven D'Aprano wrote: >> I would find it useful to be able to use non-ASCII characters for heavily >> mathematical programs. There would be a closer correspondence between the >> code and the mathematical equations if one could write D(u*p) instead of >> delta(mu*pi). > > Just as one risk here: > When reading the above on Google groups, it showed up as "if one could > write ?(u*p)..." > When quoting it for response, it showed up as "could write D(u*p)". > > I'm sure that the symbol you used was neither a capital letter d nor a > question mark. > > Using identifiers that are so prone to corruption when posting in a > rather popular forum seems dangerous to me--and I'd guess that a lot > of source code highlighters, email lists, etc have similar problems. > I'd even be surprised if some programming tools didn't have similar > problems. So, it was google groups that continuously corrupted the good UTF-8 posts by force converting them to ISO-8859-1? Of course, there's also the possibility that it is a problem on *your* side so, to be fair I've launched google groups and looked for this thread. And of course the result was that Steven's post displayed perfectly. I didn't try to reply to it of course, no need to clutter that thread anymore than it is. -- ?(?*?) From grante at visi.com Thu May 31 13:23:04 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 31 May 2007 17:23:04 -0000 Subject: c[:]() References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> <135tobve86qj808@corp.supernews.com> <135tru124pie2b3@corp.supernews.com> <135tv1bjqgbmsc9@corp.supernews.com> Message-ID: <135u13od1801l04@corp.supernews.com> On 2007-05-31, Steve Holden wrote: >> I still don't see how c[:] is any different from c. > > It isn't. The OP is projecting a wish for a function call on a > list to be interpreted as a call on each member of the list > with the same arguments. Yea, I got that part. > The all-members slice notation is a complete red herring. That's what I thought, but the OP seems convinced that c[:] is somehow behaviorally different than c (something more than just being an exact copy of the list with a different id()). The only thing I could think of is that he has overridden the __getitem__ method of the class to which c belongs with something that has some sort of side-effects which he wishes to invoke. > It would require a pretty fundamental re-think to give such a > construct sensible and consistent semantics, I think. He could just define a container class that does what he wants... -- 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 ramashish.lists at gmail.com Tue May 29 13:41:53 2007 From: ramashish.lists at gmail.com (Ramashish Baranwal) Date: 29 May 2007 10:41:53 -0700 Subject: How to set a class inheritance at instance creation? In-Reply-To: <1180453971.556244.91370@q69g2000hsb.googlegroups.com> References: <1180453971.556244.91370@q69g2000hsb.googlegroups.com> Message-ID: <1180459016.408048.258600@r19g2000prf.googlegroups.com> On May 29, 8:52 pm, glomde wrote: > Hi I wonder if you can set what subclass a class should > have at instance creation. > > The problem is that I have something like: > > class CoreLang(): > def AssignVar(self, var, value): > pass > > class Lang1(CoreLang): > def AssignVar(self, var, value): > return var, "=", value > > class Lang2(CoreLang): > def AssignVar(self, var, value): > return var, "<=", value > > class WriteStruct(): > def Generate(self, vars): > for var in vars: > print self.AssignVar() > > The problem is that I want WriteStruct to sometimes be a subclass of > Lang1 and sometimes > of Lang2. > In the above example I could but the Generate Method in CoreLang. But > in my real > example I also want to able to subclass WriteStruct to be able to easy > customize WriteStruct. > Which I wouldnt be able to do if it was a method in CoreLang. > > So in code I would like to write something like: > > WriteStruct(Lang1).Generate(vars) class WriteStruct: def __init__(self, SubClass): self._sub = SubClass() def Generate(self, vars): for var in vars: print self._sub.AssignVar() > Even better would be that if I in the Lang1 class could > just do WriteStruct().Generate(vars) and Lang1 class would > magically make WriteStruct a subclass of itself. > I don't think I understood what you want here. Ram From martin at v.loewis.de Mon May 7 18:15:57 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 08 May 2007 00:15:57 +0200 Subject: getmtime differs between Py2.5 and Py2.4 In-Reply-To: References: Message-ID: <463FA51D.1060600@v.loewis.de> > Is this a bug? Why don't you read the responses posted earlier? John Machin replied (in <1178232636.415630.106320 at l77g2000hsb.googlegroups.com>) that you are mistaken: There is NO difference between the outcome of os.path.getmtime between Py2.5 and Py2.4. It always did return UTC, and always will. Regards, Martin From harvey.thomas at informa.com Fri May 25 08:57:51 2007 From: harvey.thomas at informa.com (harvey.thomas at informa.com) Date: 25 May 2007 05:57:51 -0700 Subject: just a bug (was: xml.dom.minidom: how to preserve CRLF's inside CDATA?) In-Reply-To: <1180090985.066935.218250@h2g2000hsg.googlegroups.com> References: <1179841504.782279.86490@u36g2000prd.googlegroups.com> <1180082137.329142.45350@p77g2000hsh.googlegroups.com> <1180090985.066935.218250@h2g2000hsg.googlegroups.com> Message-ID: <1180097871.265507.174720@p77g2000hsh.googlegroups.com> On May 25, 12:03 pm, "sim.sim" wrote: > On 25 ???, 12:45, Marc 'BlackJack' Rintsch wrote: > > > In <1180082137.329142.45... at p77g2000hsh.googlegroups.com>, sim.sim wrote: > > > Below the code that tryes to parse an well-formed xml, but it fails > > > with error message: > > > "not well-formed (invalid token): line 3, column 85" > > > How did you verified that it is well formed? `xmllint` barf on it too. > > you can try to write iMessage to file and open it using Mozilla > Firefox (web-browser) > > > > > > > > > > The "problem" within CDATA-section: it consists a part of utf-8 > > > encoded string wich was splited (widely used for memory limited > > > devices). > > > > When minidom parses the xml-string, it fails becouse it tryes to convert > > > into unicode the data within CDATA-section, insted of just to return the > > > value of the section "as is". The convertion contradicts the > > > specificationhttp://www.w3.org/TR/REC-xml/#sec-cdata-sect > > > An XML document contains unicode characters, so does the CDTATA section. > > CDATA is not meant to put arbitrary bytes into a document. It must > > contain valid characters of this typehttp://www.w3.org/TR/REC-xml/#NT-Char(linkedfrom the grammar of CDATA in > > your link above). > > > Ciao, > > Marc 'BlackJack' Rintsch > > my CDATA-section contains only symbols in the range specified for > Char: > Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | > [#x10000-#x10FFFF] > > filter(lambda x: ord(x) not in range(0x20, 0xD7FF), iMessage)- Hide quoted text - > > - Show quoted text - You need to explicitly convert the string of UTF8 encoded bytes to a Unicode string before parsing e.g. unicodestring = unicode(encodedbytes, 'utf8') Unless I messed up copying and pasting, your original string had an erroneous byte immediately before ]]>. With that corrected I was able to process the string correctly - the CDATA marked section consits entirely of spaces and Cyrillic characters. As I noted earlier you will lose \r characters as part of the basic XML processing. HTH Harvey From komar_wijaya at yahoo.com Fri May 4 04:03:27 2007 From: komar_wijaya at yahoo.com (Komar Wijaya) Date: Fri, 4 May 2007 09:03:27 +0100 (BST) Subject: Need Help Message-ID: <300418.75060.qm@web43141.mail.sp1.yahoo.com> Hello, I'm a new guy in Linux. My name is Komar from Indonesia. I am doing a project about GNU radio and i need to install wxPython. I'm using fedora core 5 and suse 10.0 as my operating systems and using python 2.4. In Suse 10.0, I have search the internet and I found file 'python-wxGTK-2..1.0-4.i586.rpm' and when I start to install the file there are so many errors like this: error: Failed depedencies: libwx_baseu-2.6.so is needed .. libwx_baseu_net-2.6.so is needed libwx_baseu_xml-2.6.so is needed libwx_gtk2u_adv-2.6.so is needed libwx_gtk2u_animate-2.6.so is needed libwx_gtk2u_core-2.6.so is needed libwx_gtk2u_gizmos-2.6.so is needed libwx_gtk2u_gl-2.6.so is needed libwx_gtk2u_html-2.6.so is needed libwx_gtk2u_stc-2.6.so is needed libwx_gtk2u_xrc-2.6.so is needed Am I downloading wrong file? What is the solution? In fedora core 5, I am downloading the file from wxPython.org and I downloaded file for fedora core 4. There are: - wxPython-common-gtk2-unicode-2.8.3.0-fc4_py2.4.i386.rpm - wxPython2.8-gtk2-unicode-2.8.3.0-fc4_py2.4.i386.rpm - wxPython2.8-devel-unicode-2.8.3.0-fc4_py2.4.i386.rpm The installation of wxPython-common-gtk2-unicode-2.8.3.0-fc4_py2.4.i386.rpm is succesfull but the installation of wxPython2.8-gtk2-unicode-2.8.3.0-fc4_py2.4.i386.rpm is failed and the error message appear like this: ' libgstgconf-0.8.so. is needed by wxPython2.8-gtk2-unicode-2.8.3.0 libgstinterfaces-0.8.so is needed by wxPython2.8-gtk2-unicode-2.8.3.0 libgstreamer-0.8.so is needed by wxPython2.8-gtk2-unicode-2.8.3.0 ' I don't understand about the error. Maybe you can help e solve the problem. Thank you. Send instant messages to your online friends http://uk.messenger.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From johnjsal at NOSPAMgmail.com Thu May 3 14:48:01 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 03 May 2007 14:48:01 -0400 Subject: My Python annoyances In-Reply-To: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> Message-ID: <463a2e22$0$11272$c3e8da3@news.astraweb.com> Andr? wrote: > Fortunately, Python has incorporated some newbie-unfriendly features, > like metaclasses and, to a lesser extent, decorators which, at last, > make use of a special character. There should be more of these, to > make Python something more challenging to learn. After reading the entire post about Python's ease of use, I find this particular paragraph especially pointed. :) I guess all the previous points about Python's features helps to show how these other things (decorators, etc.) really stand out as perhaps being un-Pythonic? At least, to me, it was an interesting way to make that argument. From arkanes at gmail.com Wed May 9 16:49:57 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 9 May 2007 15:49:57 -0500 Subject: change of random state when pyc created?? In-Reply-To: References: <5ae25fF2oggbqU1@mid.uni-berlin.de> Message-ID: <4866bea60705091349u1fa9f25q135f29055999694a@mail.gmail.com> On 5/9/07, Alan G Isaac wrote: > Robert Kern wrote: > > http://docs.python.org/lib/typesmapping.html > > """ > > Keys and values are listed in an arbitrary order which is non-random, varies > > across Python implementations, and depends on the dictionary's history of > > insertions and deletions. > > """ > > > Even this does not tell me that if I use a specified implementation > that my results can vary from run to run. That is, it still does > not communicate that rerunning an *unchanged* program with an > *unchanged* implementation can produce a change in results. > Well, now you know. I'm not sure why you expect any given program to be idempotent unless you take specific measures to ensure that anyway. From lumo2000 at gmail.com Wed May 23 05:54:50 2007 From: lumo2000 at gmail.com (lumo2000 at gmail.com) Date: 23 May 2007 02:54:50 -0700 Subject: Python 404 Problem Message-ID: <1179914090.179957.301040@h2g2000hsg.googlegroups.com> hello NG. i have to install a little python application and my problem is, that python does not find the proper include files, although they are, where the script searches for... any ideas how to solve this? i am out of ideas... python returns the following error message: --> --> --> IOError Python 2.3.4: C:\Python23\python.exe Wed May 23 11:47:01 2007 A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred. C:\BioCase21\www\testingtool\index.cgi 20 #----------------------------------------------------------------------------------------------------------- 21 # See fundamentals things being done -- this will, inter alia, put g.callCgi into the global namespace: 22 execfile( os.path.abspath(os.path.join(os.path.dirname( __file__ ), os.path.pardir, os.path.pardir, 'lib', 'biocase', 'fundamentals.py' ) ) ) 23 #------------------------------------------------------------- 24 import biocase.tools.templating builtin execfile = , os = , os.path = , os.path.abspath = , os.path.join = , os.path.dirname = , __file__ = r'C: \BioCase21\www\testingtool\index.cgi', os.path.pardir = '..' IOError: [Errno 2] No such file or directory: 'C:\\BioCase21\\lib\ \biocase\\fundamentals.py' args = (2, 'No such file or directory') errno = 2 filename = r'C:\BioCase21\lib\biocase\fundamentals.py' strerror = 'No such file or directory' From steven.klass at gmail.com Wed May 2 11:13:12 2007 From: steven.klass at gmail.com (rh0dium) Date: 2 May 2007 08:13:12 -0700 Subject: Is it possible to determine what a function needs for parameters - In-Reply-To: References: <1178115727.932794.100390@h2g2000hsg.googlegroups.com> Message-ID: <1178118792.289104.212670@l77g2000hsb.googlegroups.com> > This is far more work than you need. Push an (args, kwargs) tuple into > your arguments queue and call self.function(*args, **kwargs). No see I tried that and that won't work. I'm assuming what you are referring to is this (effectively) Q.put(((),{a:"foo", b:"bar})) input = Q.get() self.function( *input[0], **input[1]) This will obviously fail if several conditions aren't met - hence the kludge. Am I missing something here? From noagbodjivictor at gmail.com Wed May 2 10:24:22 2007 From: noagbodjivictor at gmail.com (noagbodjivictor at gmail.com) Date: 2 May 2007 07:24:22 -0700 Subject: Refreshing imported modules Message-ID: <1178115862.194846.126240@h2g2000hsg.googlegroups.com> I have the python interperter opened while editing a module. The problem is that when I make changes, the module is not refreshed whenever I import it again. I have to re-launch the interpreter, is there a way to shortcut this? From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed May 16 04:38:54 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 16 May 2007 10:38:54 +0200 Subject: Distributing programs depending on third party modules. In-Reply-To: <62bee$464a1c4a$4275d90a$14962@FUSE.NET> References: <53357$4649c4a6$4275d90a$20775@FUSE.NET> <464a1617$0$14328$426a74cc@news.free.fr> <62bee$464a1c4a$4275d90a$14962@FUSE.NET> Message-ID: <464ac306$0$802$426a74cc@news.free.fr> Kevin Walzer a ?crit : > Bruno Desthuilliers wrote: > >>> What platform are you doing this on? On the Linux platform, >>> "dependency hell" of this sort is pretty much unavoidable, >> >> Yes it is. EasyInstall works just fine. > > You can install a beast like PyQt with easy_install? Meaning, that it > will download and build/install not just the PyQt bits, but also Qt > itself, sip, and all the other foundational components? Are these components packaged in such a way to support easy_install ?-) No, of course, easy_install doesn't *actually* support this (while AFAICT, it technically *could* do the job). I was talking about dependencies between Python packages. If you want support for such external dependencies, emerge (Gentoo-Linux) is your friend - and believe me, it's really impressive. Note that if you go that way, neither Windows nor MacOS X are actually able to cleanly manage such dependencies (which is why the usual solution on these platforms - or at least on Windows - is to just bundle everything in a single big package). FWIW, I sure had much more trouble with "DLHell" on Windows than on Gentoo or Ubuntu. > If easy_install > handles all that, I'm impressed. I'm already impressed by the whole setuptools package. From gagsl-py2 at yahoo.com.ar Tue May 15 04:54:45 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 15 May 2007 05:54:45 -0300 Subject: Trying to choose between python and java References: <464972ad$0$23728$426a74cc@news.free.fr> Message-ID: En Tue, 15 May 2007 05:43:36 -0300, Bruno Desthuilliers escribi?: >> Is code written today likely to still work >> in 5+ years or do they depreciate stuff and you have to update? > > I still use code written more than five years ago. Just as an example, PIL (Python Imaging Library) works unchanged with any version from Python 1.5 (released 1999) till the latest 2.5 (released this year) -- Gabriel Genellina From byte8bits at gmail.com Mon May 21 10:09:57 2007 From: byte8bits at gmail.com (brad) Date: Mon, 21 May 2007 10:09:57 -0400 Subject: re.compile for names In-Reply-To: References: Message-ID: Marc 'BlackJack' Rintsch wrote: > What about names with letters not in the ASCII range? Like Asian names? The names we encounter are spelled out in English... like Xu, Zu, Li-Cheng, Matsumoto, Wantanabee, etc. So the ASCII approach would still work. I guess. My first thought was to spell out names entirely, but that quickly seemed a bad idea. Doing an re on smith with whitespace boundaries is more accurate than smi w/o, but the volume of names just makes it impossible. And the volume of false positives using only smi makes it somewhat worthless too. It's tough when a problem needs an accurate yet broad solution. Too broad and the results are irrelevant as they'll include so many false positives, too accurate and the results will be missing a few names. It's a no-win :( Thanks for the advice. Brad From howe.steven at gmail.com Sun May 13 14:17:34 2007 From: howe.steven at gmail.com (Steven Howe) Date: Sun, 13 May 2007 11:17:34 -0700 Subject: Using "subprocess" without lists. . .? In-Reply-To: References: Message-ID: <4647563E.6010702@gmail.com> Michael Williams wrote: > Hi All, > > I've recently seen the "subprocess" module and am rather confused by > it's requirements. Is it not possible to execute an entire string > without having to break them up into a list of arguments? For > instance, I'd much rather do the following: > > > subprocess.call("ls -al | grep -i test") > > > . . .than to have to: > > > list = ["ls", "-a", "-l" ] . . . . . . and so on and so forth. > subprocess.call(list. . .) > > > What is the best way to go about executing a massively complex single > line command? > > > Thanks, > Michael > How about a hybrid solution?: from subprocess import Popen, PIPE from string import strip (stdout, stderr) = Popen(['ls','-al'], stdout=PIPE, stderr=PIPE).communicate() /# process spins off. Ideally, you should wait for it to complete, or assign the resulting object of Popen # to a variable and inquire if it's completed via the 'poll()' operator or wait on it via the 'wait()' # operator. # then query the stderr via communicate()[1]; if good, i.e. len(stderr) == 0, inspect the resulting # stdout string (via communicate()[0]) for your 'test' result. But I'm being lazy. I assume the call to # ls -al will be faster then my next statement./ res = [] for line in stdout.strip(): if 'test' in line: res.append( line ) Do the work you need done at the shell prompt, do the rest in Python. Also I wonder if, you were looking for the word 'test' in the filename, glob.glob wouldn't have been a bit more efficient? But if you were looking for a 'test' owner or group then using: glob.glob(): get the _list_ of files, with directory. Example: *glob.glob('/bin/*') * os.stat(): get an _object_ of stats on a file. Example:* os.stat('/bin/ls')* stat.ST_UID: get just the group id, as an _integer_ from the object returned by os.stat. Example: *os.stat('/bin/ls')[stat.ST_UID] *pwd.getpwgid(): get the _string_ translation of a UID. Example: *pwd.getpwgid( os.stat('/bin/ls')[stat.ST_UID] )* stat.ST_GID: get the group id, as an _integer_ from the object returned os.stat. Example: *os.stat('/bin/ls')[stat.ST_GID]* grp.getgrgid(): get the _string_ translation of a UID. Example: *grp.getgrgid( os.stat('/bin/ls')[stat.ST_UID] )* Now I have a list, which I iterate over, getting the UID and GID, as strings, that I can compare to. I never had to use a subprocess and having to build up a 'wait on done loop'. Note, grp and pwd, I think, are Python/Unix functions. What one does on Windows I don't know, but I'll bet there are similar functions under Python/Windows. Don't get me wrong, Subprocess is a fast and damn useful tool. I often use it to verify a program is in my path, before creating a subprocess to run some task python isn't built for (like mencoder functionality). You see, the issue is: _shell,_ _python & shell_ or _python alone_. When transitioning from one language to another, say C/C++/Java to Python, it is often easier to use your knowledge of the shell command (bash/Bourne for example) to get things done. But it's only a transitional issue. The need to use the shell is a good demonstrator that either the Interpretor is weak, or that you haven't fully explored it's abilities. With the Python Interpretor at v2.4 going onto v2.5, it's very likely that the desired feature exists; you have but to do some clever research to find it. As to clever research ... I find Google a good place to start. I had some familiarity with os.stat and glob. But the grp and pwd functions were things I discovered from http://docs.python.org/modindex.html and about two minutes of searching for 'python uid to name' @ Google. Also, os.listdir and os.path.join would have worked just as well as glob.glob('dirname/*'). But glob.glob was faster to write. Even a better choice would have been to use the 'os.walk' to iterate over the directory tree. sph. -- HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul at boddie.org.uk Fri May 25 06:39:54 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 25 May 2007 03:39:54 -0700 Subject: psycopg2 & large result set In-Reply-To: <1180084593.130202.241550@q69g2000hsb.googlegroups.com> References: <1180084593.130202.241550@q69g2000hsb.googlegroups.com> Message-ID: <1180089593.985853.290860@q66g2000hsg.googlegroups.com> On 25 May, 11:16, Jon Clements wrote: > > I'm using psycopg2 to retrieve results from a rather large query (it > returns 22m records); unsurprisingly this doesn't fit in memory all at > once. What I'd like to achieve is something similar to a .NET data > provider I have which allows you to set a 'FetchSize' property; it > then retrieves 'n' many rows at a time, and fetches the next 'chunk' > after you read past the end of the current chunk. I suppose I could > use Python for .NET or IronPython but I'd rather stick with CPython > 2.5 if possible. > > I'm not 100% sure if it's an interface or a server thing. Any ideas > are most welcome. It's an interface thing. The DB-API has fetchone, fetchmany and (optionally) iteration methods on cursor objects; PostgreSQL supports what you have in mind; pyPgSQL supports it at the interface level, but psycopg2 only supports it if you use "named cursors", which is not part of the DB-API specification as far as I recall, and not particularly convenient if you're thinking of targeting more than one database system with the same code. See this bug filed against psycopg2 and the resulting discussion: http://www.initd.org/tracker/psycopg/ticket/158 I've been running a patched version of psycopg2, but haven't developed the patch further since it may be more convenient for me to switch back to pyPgSQL eventually. Paul From duncan.booth at invalid.invalid Thu May 17 03:50:53 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 May 2007 07:50:53 GMT Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179160242.787344.48060@h2g2000hsg.googlegroups.com> Message-ID: "Gabriel Genellina" wrote: > - Someone proposed using escape sequences of some kind, supported by > editor plugins, so there is no need to modify the parser. I'm not sure whether my suggestion below is the same as or a variation on this. > > - Refactoring tools should let you rename foreign identifiers into > ASCII only. A possible modification to the PEP would be to permit identifiers to also include \uxxxx and \Uxxxxxxxx escape sequences (as some other languages already do). Then you could have a script easily (and reversibly) convert all identifiers to ascii or indeed any other encoding or subset of unicode using escapes only for the unrepresentable characters. I think this would remove several of the objections: such as being unable to tell at a glance whether someone is trying to spoof your variable names, or being unable to do minor maintenance on code using character sets which your editor doesn't support: you just run the script which would be included with every copy of Python to restrict the character set of the source files to whatever character set you feel happy with. The script should also be able to convert unrepresentable characters in strings and comments (although that last operation wouldn't be guaranteed reversible). Of course it doesn't do anything for the objection about such identifiers being ugly, but you can't have everything. From steve at REMOVE.THIS.cybersource.com.au Mon May 28 10:46:06 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 29 May 2007 00:46:06 +1000 Subject: Can string be callable as a method ? References: <1180359947.660314.26320@n15g2000prd.googlegroups.com> Message-ID: On Mon, 28 May 2007 06:45:47 -0700, Jia Lu wrote: > Hi all > I tried to scan a directory and __import__ all modules , > > imported module: help > imported module: __init__ > imported module: hi > imported module: thanks > > and I scaned all methods in them, and put them to a list like: > > [['f_chelp', 'f_help'], [], ['f_exclaim', 'f_hi', 'random'], > ['f_thanks', 'random']] > > But how can I call them from that list?? >>> import math >>> dir(math) ['__doc__', '__file__', '__name__', 'acos', 'asin', ... ] >>> >>> math.__dict__['acos'](0) 1.5707963267948966 >>> getattr(math, 'asin')(0) 0.0 Instead of storing the names of the functions, better to store the functions themselves: >>> my_list = [math.acos, math.asin] >>> my_list[0](1) 0.0 Hope this helps, -- Steven. From mail at microcorp.co.za Wed May 16 05:16:09 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 16 May 2007 11:16:09 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de><1179160242.787344.48060@h2g2000hsg.googlegroups.com> <1179258692.237438.110860@p77g2000hsh.googlegroups.com> Message-ID: <03fa01c7979e$86381dc0$03000080@hendrik> wrote: > > "Hendrik van Rooyen" wrote in message > news:mailman.7700.1179242569.32031.python-list at python.org... > > > wrote: > > [I fixed the broken attribution in your quote] > Sorry about that - I deliberately fudge email addys... > First "while" is a keyword and will remain "while" so > that has nothing to do with anything. I think this cuts right down to why I oppose the PEP. It is not so much for technical reasons as for aesthetic ones - I find reading a mix of languages horrible, and I am kind of surprised by the strength of my own reaction. If I try to analyse my feelings, I think that really the PEP does not go far enough, in a sense, and from memory it seems to me that only E Brunel, R Fleschenberg and to a lesser extent the Martellibot seem to somehow think in a similar way as I do, but I seem to have an extreme case of the disease... And the summaries of reasons for and against have left out objections based on this feeling of ugliness of mixed language. Interestingly, the people who seem to think a bit like that all seem to be non native English speakers who are fluent in English. While the support seems to come from people whose English is perfectly adequate, but who are unsure to the extent that they apologise for their "bad" English. Is this a pattern that you have identified? - I don't know. I still don't like the thought of the horrible mix of "foreign" identifiers and English keywords, coupled with the English sentence construction. And that, in a nutshell, is the main reason for my rather vehement opposition to this PEP. The other stuff about sharing and my inability to even type the OP's name correctly with the umlaut is kind of secondary to this feeling of revulsion. "Beautiful is better than ugly" - Hendrik From sbassi at clubdelarazon.org Sat May 26 01:33:15 2007 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Sat, 26 May 2007 02:33:15 -0300 Subject: Removing NS in ElementTree Message-ID: <9e2f512b0705252233k5ddcd1d1ka46aaf330088a93@mail.gmail.com> I would like to remove the namespace information from my elements and have just the tag without this information. This "{http://uniprot.org/uniprot}" is preapended into all my output. I understand that the solution is related with "_namespace_map" but I don't know much more. >>> for x in eleroot[0]: print x.tag print x.text {http://uniprot.org/uniprot}accession Q9JJE1 {http://uniprot.org/uniprot}organism {http://uniprot.org/uniprot}dbReference None {http://uniprot.org/uniprot}sequence MPKKKPTPIQLNPAPDGSAVNGTSSAETNLEALQKKLEELELDEQQRKRL EAFLTQKQKVGELKDDDFEKISELGAGNGGVVFKVSHKPSGLVMARKLIH LEIKPAIRNQIIRELQVLHECNSPYIVGFYGAFYSDGEISICMEHMDGGS LDQVLKKAGRIPEQILGKVSIAVIKGLTYLREKHKIMHRDVKPSNILV -- Sebasti?n Bassi (???????) Diplomado en Ciencia y Tecnolog?a. GPG Fingerprint: 9470 0980 620D ABFC BE63 A4A4 A3DE C97D 8422 D43D Club de la raz?n (www.clubdelarazon.org) From bbxx789_05ss at yahoo.com Wed May 30 15:06:28 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 30 May 2007 12:06:28 -0700 Subject: Off Topic: What is the good book to learn Python ? In-Reply-To: <1180551255.649269.251000@u30g2000hsc.googlegroups.com> References: <1180549522.350380.276570@q66g2000hsg.googlegroups.com> <1180551255.649269.251000@u30g2000hsc.googlegroups.com> Message-ID: <1180551988.641579.27980@q66g2000hsg.googlegroups.com> In my opinion, "Beginning Python: From Novice to Professional" is a horrible book. I constantly have to consult "Learning Python(2nd ed.) to clear up all the blunders in Beginning Python. In addition, Learning Python(2nd ed) has exercises and Beginning Python doesn't. So I would recommend "Learning Python(2nd ed)". From wildemar at freakmail.de Wed May 23 18:22:52 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Thu, 24 May 2007 00:22:52 +0200 Subject: Properties/Decorators [WAS: Can I reference 1 instance of an object by more names ? rephrase] In-Reply-To: <5bj1ddF2sd0aoU1@mid.uni-berlin.de> References: <4654289a$0$2326$426a74cc@news.free.fr> <5bj1ddF2sd0aoU1@mid.uni-berlin.de> Message-ID: <4654BEBC.2060406@freakmail.de> Diez B. Roggisch wrote: > It is that very apply. > > And apply takes a function as argument + additional arguments, and executes > that function, returning the result of that function-call. It was used > before the > > f(*args, **kwargs) > > notation was introduced. > > Now what we have here is "value" as function, passed as single argument to > apply (because decorators are just callables), which will invoke "value" > with no arguments. The result of that operation is the property-object, > that thus is returned by apply. And in the end gets assigned to the name > value in the cpu_ports-class. > Sooo clever :). But apply is deprecated ... can I do the same thing some other way? W From kelvin.you at gmail.com Fri May 11 01:50:31 2007 From: kelvin.you at gmail.com (=?gb2312?B?yMvR1MLkyNXKx8zs0cSjrM37vKvM7NHEsru8+7zS?=) Date: 10 May 2007 22:50:31 -0700 Subject: how to refer to partial list, slice is too slow? Message-ID: <1178862631.470437.134180@h2g2000hsg.googlegroups.com> I'm a python newbie. It seems the slice operation will do copy. for example: >>> a = [1,2,3,4,5,6,7,8,9,0] >>> b = a[7:] >>> b [8, 9, 0] >>> a.remove(9) >>> a [1, 2, 3, 4, 5, 6, 7, 8, 0] >>> b [8, 9, 0] if the list have large members, the slice operations will consume many times. for instance, I have a long string named it as S, the size is more than 100K I want to parser it one part-to-part. first, I process the first 100 byte, and pass the remainder to the next parser function. I pass the S[100:] as an argument of the next parser function. but this operation will cause a large bytes copy. Is there any way to just make a reference to the remainder string not copy? From kyosohma at gmail.com Tue May 22 11:00:13 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 22 May 2007 08:00:13 -0700 Subject: Create an XML document Message-ID: <1179846012.972391.160800@z28g2000prd.googlegroups.com> Hi all, I am attempting to create an XML document dynamically with Python. It needs the following format: 1179775800 1800 I tried using minidom with the following code: from xml.dom.minidom import Document doc = Document() zappt = doc.createElement('zAppointments') zappt.setAttribute('reminder', '15') doc.appendChild(zappt) appt = doc.createElement('appointment') zappt.appendChild(appt) begin = doc.createElement('begin') appt.appendChild(begin) f = file(r'path\to\file.xml', 'w') f.write(doc.toprettyxml(indent=' ')) f.close() This gives me the following: How do I get Python to put values into the elements by tag name? I can parse my documents just fine, but now I need to edit them and write them out to a file for an application I am working on. I am sure I am missing something obvious. Thanks a lot! Mike From steve at holdenweb.com Fri May 25 12:41:28 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 25 May 2007 12:41:28 -0400 Subject: webbrowser module bug? In-Reply-To: References: <1180106384.198363.14120@p47g2000hsd.googlegroups.com> Message-ID: <465711B8.7070505@holdenweb.com> Ron Adam wrote: > kyosohma at gmail.com wrote: >> On May 24, 5:03 pm, Ron Adam wrote: >>> Is anyone else having problems with the webbrowser module? >>> >>> Python 2.5.1c1 (release25-maint, Apr 12 2007, 21:00:25) >>> [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 >>> Type "help", "copyright", "credits" or "license" for more information. >>> >>> import webbrowser >>> >>> webbrowser.open('http://www.python.org') >>> True >>> >>> >>> >>> It opens firefox as expected, but the url is ... >>> >>> file:///home/ron/%22http://www.python.org%22 >>> >>> Which of course doesn't do what is expected. >>> >>> Any ideas? >>> >>> Ron >> I don't know. This works for me with Python 2.4 on Windows XP SP2. The >> docs don't say much (http://docs.python.org/lib/module- >> webbrowser.html). Maybe it would be beneficial to read the module's >> code? Or use the "register" command manually? > > It works for me on python 2.4 also, but not on later versions. > > Looks like I'll need to try to test the url at the point where it calls the > browser from webbrowser.py. > > Can someone else test this on python 2.5? > On my Windows laptop it works on 2.4.1 and 2.5.1 native, but not on 2.5.1 for Cygwin. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From george.sakkis at gmail.com Wed May 23 18:43:08 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 23 May 2007 15:43:08 -0700 Subject: Properties/Decorators [WAS: Can I reference 1 instance of an object by more names ? rephrase] In-Reply-To: References: <4654289a$0$2326$426a74cc@news.free.fr> <5bj1ddF2sd0aoU1@mid.uni-berlin.de> Message-ID: <1179960188.673422.197410@w5g2000hsg.googlegroups.com> On May 23, 6:22 pm, Wildemar Wildenburger wrote: > Diez B. Roggisch wrote: > > It is that very apply. > > > And apply takes a function as argument + additional arguments, and executes > > that function, returning the result of that function-call. It was used > > before the > > > f(*args, **kwargs) > > > notation was introduced. > > > Now what we have here is "value" as function, passed as single argument to > > apply (because decorators are just callables), which will invoke "value" > > with no arguments. The result of that operation is the property-object, > > that thus is returned by apply. And in the end gets assigned to the name > > value in the cpu_ports-class. > > Sooo clever :). But apply is deprecated ... can I do the same thing some > other way? > > W Yes; check out the following: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502243 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410698 George From jadestar at idiom.com Fri May 11 19:09:37 2007 From: jadestar at idiom.com (James T. Dennis) Date: Fri, 11 May 2007 23:09:37 -0000 Subject: mmap thoughts Message-ID: <1178924977.507496@smirk> I've been thinking about the Python mmap module quite a bit during the last couple of days. Sadly most of it has just been thinking ... and reading pages from Google searches ... and very little of it as been coding. Mostly it's just academic curiosity (I might be teaching an "overview of programming" class in a few months, and I'd use Python for most of the practical examples to cover a broad range of programming topics, including the whole concept of memory mapping used, on the one hand, as a file access abstraction and as a form of inter-process shared memory, on the other). Initial observations: * The standard library reference could use some good examples. At least of those should show use of both anonymous and named mmap objects as shared memory. * On Linux (various versions) using Python 2.4.x (for at least 2.4.4 and 2.4.2) if I create on mmap'ing in one process, then open the file using 'w' or 'w+' or 'w+b' in another process then my first process dies with "Bus Error" This should probably be documented. (It's fine if I use 'a' (append) modes for opening the file). * It seems that it's also necessary to extend a file to a given size before creating a mapping on it. In other words you can't mmap a newly created, 0-length file. So it seems like the simplest example of a newly created, non-anonymous file mapping would be something like: sz = (1024 * 1024 * 1024 * 2 ) - 1 f=open('/tmp/mmtst.tmp','w+b') f.seek(sz) f.write('\0') f.flush() mm = mmap.mmap(f.fileno(), sz, mmap.MAP_SHARED) f.close() Even creating a zero length file and trying to create a zero-length mapping on it (with mmap(f.fileno(),0,...) ... with a mind towards using mmap's .resize() method on it doesn't work. (raises: EnvironmentError: "Errno 22: Invalid Argument"). BTW: the call to f.flush() does seem to be required at least in my environments (Linux under 2.6 kernels various distributions and the aforementioned 2.4.2 and 2.4.4 versions of Python. * The mmtst.tmp file is "sparse" of course. So its size in the example above is 2GB ... but the disk usage (du command) on it is only a few KB (depending on your filesystem cluster size etc). * Using a function like len(mm[:]) forces the kernel's filesystem to return a huge stream of NUL characters. (And might thrash your system caches a little). * On my SuSE/Novell 10.1 system, using Python 2.4.2 (their RPM 2.4.2-18) I found that anonymous mmaps would raise an EnvironmentError. Using the same code on 2.4.4 on my Debian and Fedora Core 6 system worked with no problem: anonmm == mmap.mmap(-1,4096,mmap.MAP_ANONYMOUS|mmap.MAP_SHARED) ... and also testing on their 2.4.2-18.5 update with the same results: Python 2.4.2 (#1, Oct 13 2006, 17:11:24) [GCC 4.1.0 (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import mmap >>> mm = mmap.mmap(-1,4096, mmap.MAP_ANONYMOUS|mmap.MAP_SHARED) Traceback (most recent call last): File "", line 1, in ? EnvironmentError: [Errno 22] Invalid argument >>> jadestar at dhcphostname:~> uname -a Linux dhcphostname 2.6.16.13-4-default #1 Wed May 3 ... * On the troublesome SuSE/Novell box using: f = open('/dev/zero','w+') anonmm == mmap.mmap(f.fileno(),4096, mmap.MAP_ANONYMOUS|mmap.MAP_SHARED) ... seems to work. However, a .resize() on that raises the same EnvironmentError I was getting before. * As noted in a few discussions in the past Python's mmap() function doesn't take an "offset" parameter ... it always uses an offset of 0 (It seems like a patch is slated for inclusion in some future release?) * On 32-bit Linux systems (or on systems running a 32-bit compilation of Python) 2GB is, of course, the upper limit of an mmap'ing The ability to map portions of larger files is a key motivation to include the previously mentioned "offset" patch. Other thoughts: (Going beyond initial observations, now) * I haven't tested this, but I presume that anonymous|shared mappings on UNIX can only be shared with child/descendant processes ... since there's no sort of "handle" or "key" that can be passed to unrelated processes via any other IPC method; so only fork() based inheritence will work. * Another thing I haven't tested, yet: how robust are shared mappings to adjacent/non-overlapping concurrent writes by multiple processes? I'm hoping that you can reliably have processes writing updates to small, pre-assigned, blocks in the mmap'ing without contention issues. I plan to write some "hammer test" code to test this theory ... and run it for awhile on a few multi-core/SMP systems. * It would be nice to building something like the threading Queue and/or POSH support for multi-process support over nothing but pure Python (presumably using the mmap module to pass serialized objects around). * The limitations of Python threading and the GIL for scaling on SMP and multi-core system are notorious; having a first-class, and reasonably portable standard library for supporting multi-PROCESS scaling would be of tremendous benefit now that such MP systems are becoming the norm. * There don't seem to be any currently maintained SysV IPC (shm, message, and semaphore) modules for Python. I guess some people have managed to hack something together using ctypes; but I haven't actually read, much less tested, any of that code. * The key to robust and efficient use of shared memory is going to be in the design and implementation of locking primitives for using it. * I'm guessing that some additional IPC method will be required to co-ordinate the locking --- something like Unix domain sockets, perhaps. At least I think it would be a practically unavoidable requirement for unrelated process to share memory. * For related processes I could imagine a scheme whereby the parent of each process passes a unique "mailbox" offset to each child and where that might be used to implement a locking scheme. It might work something like this: Master process (parent) creates mapping and initializes a lock mm[0:4] a child counter and a counter (also at pre-defined offsets) and a set of mailboxes (set to the max-number of children, or using a blocks of the mm in a linked-list). For each sub-process (fork()'d child) the master increments the counter, and passes a mailbox offset (counter + current mailbox offset) to it. The master then goes into a loop, scanning the mailboxes (or goes idle with a SIGUSR* handler that scans the mailboxes) Whenever there are any non-empty mailboxes the master appends corresponding PIDs to a lock-request queue; then it writes pops those PIDs and writes them into "lock" offset at mm[0] (perhaps sending a SIGUSR* to the new lock holder, too). That process now has the lock and can work on the shared memory When it's done it would clear the lock and signal the master All processes have read access to the memory while it's not locked. However, they have to read the lock counter first, copy the data into their own address, then verify that the lock counter has not be incremented in the interim. (All reads are double-checked to ensure that no changes could have occurred during the copying). ... there are alot of details I haven't considered about such a scheme (I'm sure they'll come up if I prototype such a system). Obvious one could envision more complex data structures which essentially create a sort of shared "filesystem" in the shared memory ... where the "master" process is analogous to the filesystem "driver" for it. Interesting cases for handling dead processes come up (the master could handle SIGCHLD by clearing locks held by the dearly departed) ... and timeouts/catatonic processes might be defined (master process kills the child before forcibly removing the lock). Recovery of the last of the "master" process might be possible (define a portion of the shared memory pool that holds the list of processes who become the new master ... first living one on that list assume control). But that raises new issues (can't depend on SIGCHLD in such a scheme checking for living processes would have to be done via kill 0 calls for example). It's easy to see how complicated all this could become. The question is, how simple could we make it and still have something useful? -- Jim Dennis, Starshine: Signed, Sealed, Delivered From gabor.urban at siemens.com Mon May 21 10:04:41 2007 From: gabor.urban at siemens.com (Urban, Gabor) Date: Mon, 21 May 2007 16:04:41 +0200 Subject: A few questions Message-ID: <38F58D7B92CB20438DF49D28B572CC6FE3B3C8@budgw09a.ww300.siemens.net> Jay wrote: " 1. What are your views about Python vs Perl? Do you see one as better than the other?" They are different languages. Perl is very powerfull if you use it knowing potential problems. Python is definitely much easier to learn and use. "2. Is there a good book to start with while learning Python? I'm currently reading 'Python Essential Reference' by David M. Beazley. So far it looks like a pretty good book, but would like more tutorials to work with (I've also been reading through the tutorials at 'python.org' which has some excellent stuff!)." I would suggest you to read Dive into Python. Very deep descriptions..... 3. I vote for Emacs :-)) Gabor Urban NMC - ART -------------- next part -------------- An HTML attachment was scrubbed... URL: From see.signature at no.spam Wed May 16 04:14:16 2007 From: see.signature at no.spam (Eric Brunel) Date: Wed, 16 May 2007 10:14:16 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> <4648294F.2000704@web.de> <46487a6c$0$2400$426a74cc@news.free.fr> <464a04e4$0$21147$7a628cd7@news.club-internet.fr> Message-ID: On Tue, 15 May 2007 21:07:30 +0200, Pierre Hanser wrote: > hello > > i work for a large phone maker, and for a long time > we thought, very arrogantly, our phones would be ok > for the whole world. > > After all, using a phone uses so little words, and > some of them where even replaced with pictograms! > every body should be able to understand appel, bis, > renvoi, m?vo, ... > > nowdays we make chinese, corean, japanese talking > phones. > > because we can do it, because graphics are cheaper > than they were, because it augments our market. > (also because some markets require it) > > see the analogy? Absolutely not: you're talking about internationalization of the user-interface here, not about the code. There are quite simple ways to ensure users will see the displays in their own language, even if the source code is the same for everyone. But your source code will not automagically translate itself to the language of the guy who'll have to maintain it or make it evolve. So the analogy actually seems to work backwards: if you want any coder to be able to read/understand/edit your code, just don't write it in your own language... -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From adamurbas at hotmail.com Fri May 11 22:41:47 2007 From: adamurbas at hotmail.com (adamurbas at hotmail.com) Date: 11 May 2007 19:41:47 -0700 Subject: need help with python In-Reply-To: <1178937249.263856.191460@p77g2000hsh.googlegroups.com> References: <1178934447.719778.197150@h2g2000hsg.googlegroups.com> <1178937249.263856.191460@p77g2000hsh.googlegroups.com> Message-ID: <1178937707.004412.22360@q75g2000hsh.googlegroups.com> On May 11, 9:34 pm, Paul McGuire wrote: > On May 11, 8:47 pm, adamur... at hotmail.com wrote: > > > > > ya so im pretty much a newb to this whole python thing... its pretty > > cool but i just started today and im already having trouble. i > > started to use a tutorial that i found somewhere and i followed the > > instructions and couldnt get the correct results. heres the code > > stuff... > > > temperature=input("what is the temperature of the spam?") > > if temperature>50: > > print "the salad is properly cooked." > > else: > > print "cook the salad some more." > > > ya i was trying to do that but when i told it what the spams > > temperature was, it just turned off... well it wasnt working at all at > > first until i realized that i hadnt been following the instructions > > completely correctly and that i was supposed to type that code up in a > > notepad then save and open with python... so ya thats when it asked me > > what temperature the spam was and i typed a number then it just closed > > itself... im not really sure what went wrong... itd be real nice if > > someone would be like a mentor or something... > > Well, this list has a varying level of mentoring and newbie-tolerance, > with more latitude for people who have made some effort to start with > before posting things like "here's my homework problem, please send me > the working code so I can hand it in." > > I just ran your code interactively at the Python prompt, and it runs > just fine. See? > > >>> temperature=input("what is the temperature of the spam?") > > what is the temperature of the spam?55>>> if temperature>50: > > ... print "the salad is properly cooked." > ... else: > ... print "the salad is properly cooked." > ... > the salad is properly cooked. > > I think the problem you are having is that, when you run your program > by double-clicking on the xyz.py file in a file browser, the OS > (Windows, I assume?) opens a separate console window, and runs the > program, and then at the end of the program, CLOSES the window. I > think your code is running just fine, I think your "the salad is > whatever" messages get printed out, but afterward, your program ends, > so the window closes before you can see how your salad turned out. > > A simple workaround you can do is to add to the end of your program > this statement: > > input("") > > This will cause the process to stop and wait for you to press the > RETURN key, giving you time to stop and admire your salad results > before closing the window. > > One final note: many people post in a "write like I talk" style. This > is okay while telling your story ("well it wasn't working at all at > first..."), and the ee cummings all-lower-case is passable, but please > drop the "ya"s. They are a verbal tic that may be okay in person, but > do not translate at all to written posts. At least you don't say > "like" every other word, and I thank you for that! :) > > You can get a sense of other writing styles by reading through the > comp.lang.python archives. I would also recommend that you might find > more folks in the "just getting started" phase posting to the python- > tutor mailing list (go tohttp://mail.python.org/mailman/listinfo/tutor), > and you can skim through posts there for many introductory topics. > > Good luck to you, and welcome to Python! > > -- Paul well... i just discovered another of my mistakes. i was writing it in notepad and not saving it as .py silly me... hoho ya that input thing to get it to make u press enter worked tho... but only with that one... ive got another one that i cant get to work even with the input message to press enter. Sorry about the bad grammar. I'm used to Myspace where no one gives a particular hoot about how you type. I hope this is better. I will follow that link though. Thanks for the help. From larry.bates at websafe.com Wed May 2 17:24:27 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 02 May 2007 16:24:27 -0500 Subject: __dict__s and types and maybe metaclasses... In-Reply-To: <1178140405.468223.146220@l77g2000hsb.googlegroups.com> References: <1178140405.468223.146220@l77g2000hsb.googlegroups.com> Message-ID: <1Nadna6BCcEWnKTbnZ2dnUVZ_u_inZ2d@comcast.com> Adam Atlas wrote: > Suppose I want to create a type (i.e. a new-style class via the usual > `class blah(...)` mechanism) but, during the process of creating the > type, I want to replace its __dict__ so I can override some behaviors > during the initial assignment of its members. That is, I have `class > blah(...): a = 123; b = 456; ...`, and I want to substitute my own > dict subclass which will thus receive __setitem__(a, 123), > __setitem__(b, 456), and so on. > > Is this possible? Maybe with metaclasses? I've experimented with them > a bit, but I haven't found any setup that works. > I think that most people accomplish this by: class blah: __initial_values={'a': 123, 'b': 456} def __init__(self): self.__dict__.update(self.__initialvalues) -Larry From antoanjamison at hotmail.com Thu May 3 07:58:41 2007 From: antoanjamison at hotmail.com (antoanjamison at hotmail.com) Date: 3 May 2007 04:58:41 -0700 Subject: Microsoft's Dynamic Languages Runtime (DLR) In-Reply-To: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> References: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> Message-ID: <1178193521.475127.24920@y80g2000hsf.googlegroups.com> On May 2, 8:22 pm, sturlamolden wrote: > On Monday Microsoft announced a new runtime for dynamic languages, > which they call "DLR". It sits on top of the conventional .NET runtime > (CLR) and provides services for dynamically typed languages like > Python or Lisp (thus the cross-posting). Apparently is is distributed > under a BSD-like open-source license. > > I am curious to know how it performs in comparison to CPython and an > efficient compiled Lisp like CMUCL. Speed is a major problem with > CPython but not with .NET or CMUCL, so it will be interesting to see > how the DLR performs in comparison. It would be great to finally see a > Python that runs on steroids, but knowing M$ bloatware my expectations > are not too high. > > Has anyone looked at the DLR yet? What are your impression? > > Jim Hugunin har written about the DLR in his blog: > > http://blogs.msdn.com/hugunin/ > > To cite one of the comments: "Fuck this microsoft bollocks! You just > stole the Lisp runtime ideas and fucked them up by stupid it salesman > lingo." (Khrishna) > > Sturla Molden If I looked at every crup they promote I would be braindead by now.Just look at the DataMining articles at Microsoft research. Piece of junk IMHO. Antoan From jorgen.maillist at gmail.com Wed May 9 03:07:20 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Wed, 9 May 2007 09:07:20 +0200 Subject: changing a var by reference of a list In-Reply-To: <4640e048$0$19020$426a34cc@news.free.fr> References: <5abcj4F2nv0p0U1@mid.uni-berlin.de> <4640e048$0$19020$426a34cc@news.free.fr> Message-ID: <11e49df10705090007w612b43c2k84fb9a505025e2ab@mail.gmail.com> Hi Bruno, Unfortunately SQLAlchemy will be too involved at this point I will have to rewrite a lot of code to remove my current DB solution and use that. Howerver I've learned from my mistake and the next project will use it, as it seems to be a nice way of mapping objects to databases.. I'v solved it by just sending back the record set from sqlite3 because I noticed sometimes a 1:1 mapping cannot be done from column value to variable anyway.. Thanks everyone, - Jorgen From nufuhsus at gmail.com Fri May 11 17:12:20 2007 From: nufuhsus at gmail.com (nufuhsus at gmail.com) Date: 11 May 2007 14:12:20 -0700 Subject: Interesting list Validity (True/False) In-Reply-To: References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> Message-ID: <1178917940.363627.216580@y5g2000hsa.googlegroups.com> On May 11, 5:07 pm, Carsten Haese wrote: > On Fri, 2007-05-11 at 12:28 -0700, nufuh... at gmail.com wrote: > > Hello all, > > > First let me appologise if this has been answered but I could not find > > an acurate answer to this interesting problem. > > > If the following is true: > > C:\Python25\rg.py>python > > 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. > > >>> [] == [] > > True > > >>> ['-o'] == [] > > False > > >>> ['-o'] == False > > False > > Your confusion stems from the fact that for a given object, the answer > to the following three questions can be vastly different: > a) Is the object identical to True? > b) Is the object equal to True? > c) Is the object considered to be True in an "if" statement? > > Observe: > > >>> def check_trueness(obj): > > ... if obj is True: print repr(obj), "is identical to True." > ... else: print repr(obj), "is not identical to True." > ... if obj == True: print repr(obj), "is equal to True." > ... else: print repr(obj), "is not equal to True." > ... if obj: print repr(obj), "is considered to be True by if." > ... else: print repr(obj), "is not considered to be True by if." > ...>>> check_trueness(True) > > True is identical to True. > True is equal to True. > True is considered to be True by if.>>> check_trueness(1) > > 1 is not identical to True. > 1 is equal to True. > 1 is considered to be True by if.>>> check_trueness([1]) > > [1] is not identical to True. > [1] is not equal to True. > [1] is considered to be True by if.>>> check_trueness([]) > > [] is not identical to True. > [] is not equal to True. > [] is not considered to be True by if. > > Testing whether an object is equal to True is a much stronger test than > whether it is considered to be True in an 'if' statement, and the test > for identity is stronger still. Testing whether an object is equal to > True or identical to True is useless in most Python programs. > > So, rather than doing this: > > if thing==True: > # blah > > Just do this: > > if thing: > # blah > > Hope this helps, > > -- > Carsten Haesehttp://informixdb.sourceforge.net- Hide quoted text - > > - Show quoted text - Thanks Carsten (& all), I will give the if thing: # blah trick. I guess I am starting to seem my own confusion. As Grant mentioned, I was comparing ['-o'] to True which of course is False :o) However, how would you test for the falsness of the object arg? From jadestar at idiom.com Mon May 14 21:04:20 2007 From: jadestar at idiom.com (James T. Dennis) Date: Tue, 15 May 2007 01:04:20 -0000 Subject: Hello gettext References: <1179180548.306413@smirk> Message-ID: <1179191060.339649@smirk> James T. Dennis wrote: ... just to follow-up my own posting --- as gauche as that is: > You'd think that using things like gettext would be easy. Superficially > it seems well documented in the Library Reference(*). However, it can > be surprisingly difficult to get the external details right. > * http://docs.python.org/lib/node738.html > Here's what I finally came up with as the simplest instructions, suitable > for an "overview of Python programming" class: > Start with the venerable "Hello, World!" program ... slightly modified > to make it ever-so-slightly more "functional:" > #!/usr/bin/env python > import sys > def hello(s="World"): > print "Hello,", s > if __name__ == "__main__": > args = sys.argv[1:] > if len(args): > for each in args: > hello(each) > else: > hello() > ... and add gettext support (and a little os.path handling on the > assumption that our message object files will not be readily > installable into the system /usr/share/locale tree): > #!/usr/bin/env python > import sys, os, gettext > _ = gettext.lgettext > mydir = os.path.realpath(os.path.dirname(sys.argv[0])) > localedir = os.path.join(mydir, "locale") > gettext.bindtextdomain('HelloPython', localedir) > gettext.textdomain('HelloPython') > def hello(s=_("World")): > print _("Hello,"), s Turns out this particular version is a Bad Idea(TM) if you ever try to import this into another script and use it after changing you os.environ['LANG'] value. I mentioned in another message awhile back that I have an aversion to using defaulted arguments other than by setting them as "None" and I hesitated this time and then thought: "Oh, it's fine in this case!" Here's my updated version of this script: ----------------------------------------------------------------------- #!/usr/bin/env python import gettext, os, sys _ = gettext.lgettext i18ndomain = 'HelloPython' mydir = os.path.realpath(os.path.dirname(sys.argv[0])) localedir = os.path.join(mydir, "locale") gettext.install(i18ndomain, localedir=None, unicode=1) gettext.bindtextdomain(i18ndomain, localedir) gettext.textdomain(i18ndomain) def hello(s=None): """Print "Hello, World" (or its equivalent in any supported language): Examples: >>> os.environ['LANG']='' >>> hello() Hello, World >>> os.environ['LANG']='es_ES' >>> hello() Hola, Mundo >>> os.environ['LANG']='fr_FR' >>> hello() Bonjour, Monde """ if s is None: s = _("World") print _("Hello,"), s def test(): import doctest doctest.testmod() if __name__ == "__main__": args = sys.argv[1:] if 'PYDOCTEST' in os.environ and os.environ['PYDOCTEST']: test() elif len(args): for each in args: hello(each) else: hello() ----------------------------------------------------------------------- ... now with doctest support. :) > if __name__ == "__main__": > args = sys.argv[1:] > if len(args): > for each in args: > hello(each) > else: > hello() > Note that I've only added five lines, the two modules to my import > line, and wrapped two strings with the conventional _() function. > This part is easy, and well-documented. > Running pygettext or GNU xgettext (-L or --language=Python) is > also easy and gives us a file like: > # SOME DESCRIPTIVE TITLE. > # Copyright (C) YEAR ORGANIZATION > # FIRST AUTHOR , YEAR. > # > msgid "" > msgstr "" > "Project-Id-Version: PACKAGE VERSION\n" > "POT-Creation-Date: 2007-05-14 12:19+PDT\n" > "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" > "Last-Translator: FULL NAME \n" > "Language-Team: LANGUAGE \n" > "MIME-Version: 1.0\n" > "Content-Type: text/plain; charset=CHARSET\n" > "Content-Transfer-Encoding: ENCODING\n" > "Generated-By: pygettext.py 1.5\n" > #: HelloWorld.py:10 > msgid "World" > msgstr "" > #: HelloWorld.py:11 > msgid "Hello," > msgstr "" > ... I suppose I should add the appropriate magic package name, > version, author and other values to my source. Anyone remember > where those are documented? Does pygettext extract them from the > sources and insert them into the .pot? > Anyway, I minimally have to change one line thus: > "Content-Type: text/plain; charset=utf-8\n" > ... and I suppose there are other ways to do this more properly. > (Documented where?) > I did find that I could either change that in the .pot file or > in the individual .po files. However, if I failed to change it > then my translations would NOT work and would throw an exception. > (Where is the setting to force the _() function to fail gracefully > --- falling back to no-translation and NEVER raise exceptions? > I seem to recall there is one somewhere --- but I just spent all > evening reading the docs and various Google hits to get this far; so > please excuse me if it's a blur right now). > Now we just copy these templates to individual .po files and > make our LC_MESSAGES directories: > mkdir locale && mv HelloPython.pot locale > cd locale > for i in es_ES fr_FR # ... > do > cp HelloPython.pot HelloPython_$i.po > mkdir -p $i/LC_MESSAGES > done > ... and finally we can work on the translations. > We edit each of the _*.po files inserting "Hola" and "Bonjour" and > "Mundo" and "Monde" in the appropriate places. And then process > these into .mo files and move them into place as follows: > for i in *_*.po; do > i=${i#*_} > msgfmt -o ./${i%.po}/LC_MESSAGES/HelloPython.mo > done > ... in other words HelloPython_es_ES.po is written to > ./es_ES/LC_MESSAGES/HelloPython.mo, etc. > This last part was the hardest to get right. > To test this we simply run: > $HELLO_PATH/HelloPython.py > Hello, World > export LANG=es_ES > $HELLO_PATH/HelloPython.py > Hola, Mundo > export LANG=fr_FR > $HELLO_PATH/HelloPython.py > Bonjour, Monde > export LANG=zh_ZH > $HELLO_PATH/HelloPython.py > Hello, World > ... and we find that our Spanish and French translations work. (With > apologies if my translations are technically wrong). > Of course I realize this only barely scratches the surface of I18n and > L10n issues. Also I don't know, offhand, how much effort would be > required to make even this trivial example work on an MS Windows box. > It would be nice to find a document that would cover the topic in more > detail while still giving a sufficiently clear and concise set of examples > that one could follow them without getting hung up on something stupid > like: "Gee! You have to create $LANG/LC_MESSAGES/ directories and put > the .mo files thereunder; the Python won't find them under directly > under $LANG nor under LC_MESSAGES/$LANG" ... and "Gee! For reasons > I don't yet understand you need call both the .bindtextdomain() AND > the .textdomain() functions." ... and even "Hmmm ... seems that we > don't need to import locale and call local.setlocale() despite what > some examples in Google seem to suggest"(*) > * http://www.pixelbeat.org/programming/i18n.html > (So, when to you need that and when is gettext.install() really > useful?) > (I gather that the setlocale() stuff is not for simple string > translations but for things like numeric string formatting > with "%d" % ... for example). -- Jim Dennis, Starshine: Signed, Sealed, Delivered From michael.forbes at gmail.com Tue May 1 20:28:05 2007 From: michael.forbes at gmail.com (Michael) Date: 1 May 2007 17:28:05 -0700 Subject: Why are functions atomic? In-Reply-To: <1178063341.779617.289690@o5g2000hsb.googlegroups.com> References: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> <1178044821.864741.235260@o5g2000hsb.googlegroups.com> <1178063341.779617.289690@o5g2000hsb.googlegroups.com> Message-ID: <1178065685.161372.81790@y80g2000hsf.googlegroups.com> A bit more info, but still no clear picture about why functions are mutable but have immutable copy symantics. There are arguments why functions should be immutable, but the decision was to make user- defined functions mutable. My question is still: why the present ummutable copy symantics? http://www.python.org/dev/peps/pep-0232/ From kyosohma at gmail.com Mon May 7 09:23:56 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 7 May 2007 06:23:56 -0700 Subject: Can Python Parse an MS SQL Trace? Message-ID: <1178544236.856685.288740@y80g2000hsf.googlegroups.com> Hi All, Can Python parse a trace file created with MS SQL's profiler? There are a few thousand lines in the trace file and I need to find the insert statements and the stored procedures. Unfortunately, I am not an SQL guru and was hoping Python could help. Any pointers are appreciated. Thanks! Mike From skip at pobox.com Wed May 2 21:56:40 2007 From: skip at pobox.com (Skip Montanaro) Date: Thu, 3 May 2007 01:56:40 +0000 (UTC) Subject: curses mystical error output References: <17977.2867.158091.217653@montanaro.dyndns.org> Message-ID: > I have a fairly simple curses app which is giving me this error: > > addstr() returned ERR I tried something else. Using both python 2.4 and SVN head (aka 2.6a0 sort of) I tried the curses regression test. Both versions crashed, though with somewhat different errors. Maybe the Solaris 10 curses stuff is toast? Skip From erikwickstrom at gmail.com Tue May 29 18:16:27 2007 From: erikwickstrom at gmail.com (erikcw) Date: 29 May 2007 15:16:27 -0700 Subject: Why isn't this query working in python? In-Reply-To: References: <1180103946.552760.239200@p47g2000hsd.googlegroups.com> <6e42ec490705250751i89d3cf3v3a3062690d0284aa@mail.gmail.com> <1180207521.072958.322770@p47g2000hsd.googlegroups.com> <1180225290.235515.274000@q19g2000prn.googlegroups.com> <1180279833.131269.136770@w5g2000hsg.googlegroups.com> Message-ID: <1180476987.550394.237260@q66g2000hsg.googlegroups.com> On May 28, 2:47 pm, "Gabriel Genellina" wrote: > En Mon, 28 May 2007 14:53:57 -0300, Dennis Lee Bieber > escribi?: > > > On Sun, 27 May 2007 20:35:28 -0400, Carsten Haese > > declaimed the following in comp.lang.python: > > >> On Sun, 2007-05-27 at 16:39 -0400, davel... at mac.com wrote: > >> > > sql = """SELECT payment_id FROM amember_payments WHERE > >> > > member_id=%s AND expire_date > NOW() AND completed=1 AND (product_id > >> > >>> 11 AND product_id <21)""", (self.uid) > > > It's confusing, as the example shown is not the common form for > > parameter passing on the .execute() call -- without the .execute() it is > > unclear. I presume the .execute() is using *sql to unpack the tuple... > > Yes, the original message said self.amember_cursor.execute(*sql) > It IS confusing... > > -- > Gabriel Genellina This is how I've always writing my queries. I learned it from some tutorial I found on Google when I started - what is the preferred/ pythonic way to write this query? Thanks! Erik From john at datavoiceint.com Thu May 10 16:47:20 2007 From: john at datavoiceint.com (HMS Surprise) Date: 10 May 2007 13:47:20 -0700 Subject: File modes Message-ID: <1178830039.962239.245800@e51g2000hsg.googlegroups.com> After reading a file is it possible to write to it without first closing it? I tried opening with 'rw' access and re-winding. This does not seem to work unless comments are removed. Also, does close force a flush? Thanks, jh #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ f = open('c:\\tempMaxq\\incidents.txt', 'rw') s = f.read() lst = s.split() incId = [] incId.extend([lst.pop(), lst.pop()]) #f.close() #f = open('c:\\tempMaxq\\incidents.txt', 'w') #f.seek(0) for el in lst: f.write(el + ' ') f.close() From sturlamolden at yahoo.no Wed May 2 15:15:44 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 2 May 2007 12:15:44 -0700 Subject: Lazy evaluation: overloading the assignment operator? Message-ID: <1178133344.415521.118710@n76g2000hsh.googlegroups.com> Python allows the binding behaviour to be defined for descriptors, using the __set__ and __get__ methods. I think it would be a major advantage if this could be generalized to any object, by allowing the assignment operator (=) to be overloaded. One particular use for this would be to implement "lazy evaluation". For example it would allow us to get rid of all the temporary arrays produced by NumPy. For example, consider the expression: y = a * b + c * d If this expression is evaluated bya Fortran 90/95 compiler, it will automatically generate code like do i = 1,n y(i) = a(i) * b(i) + c(i) * d(i) enddo On the other hand, conventional use of overloaded binary operators would result in something like this: allocate(tmp1,n) do i = 1,n tmp1(i) = a(i) * b(i) enddo allocate(tmp2,n) do i = 1,n tmp2(i) = c(i) * d(i) enddo allocate(tmp3,n) do i = 1,n tmp3(i) = tmp1(i) + tmp2(i) enddo deallocate(tmp1) deallocate(tmp2) do i = 1,n y(i) = tmp3(i) enddo deallocate(tmp3) Traversing memory is one of the most expensive thing a CPU can do. This approach is therefore extremely inefficient compared with what a Fortran compiler can do. However, if we could overload the assignment operator, there would be an efficient solution to this problem. Instead of constructing temporary temporary arrays, one could replace those with objects containing lazy expressions "to be evaluated sometime in the future". A statement like y = a * b + c * d would then result in something like this: tmp1 = LazyExpr('__mul__',a,b) # symbolic representation of "a * b" tmp2 = LazyExpr('__mul__',c,d) # symbolic representation of "c * d" tmp3 = LazyExpr('__add__',tmp1,tmp1) # symbolic "a * b + c * d" del tmp1 del tmp2 y = tmp3 # tmp3 gets evaluated as assignment is overloaded Should there be a PEP to overload the assignment operator? In terms of syntax, it would not be any worse than the current descriptor objects - but it would make lazy evaluation idioms a lot easier to implement. Sturla Molden From openopt at ukr.net Mon May 21 09:17:16 2007 From: openopt at ukr.net (dmitrey) Date: 21 May 2007 06:17:16 -0700 Subject: howto check does module 'asdf' exist? (is available for import) Message-ID: <1179753436.736228.321400@x35g2000prf.googlegroups.com> howto check does module 'asdf' exist (is available for import) or no? (without try/cache of course) Thx in advance, D. From stefan.behnel-n05pAM at web.de Wed May 16 04:31:42 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 16 May 2007 10:31:42 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464ab811$0$10185$9b4e6d93@newsspool4.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <46478694$0$1412$426a34cc@news.free.fr> <1hy252p.1anf7sr1p4yp12N%aleax@mac.com> <464988a4$0$20289$9b4e6d93@newsspool3.arcor-online.net> <464aaee8$0$10188$9b4e6d93@newsspool4.arcor-online.net> <464ab811$0$10185$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <464AC16E.1010609@web.de> Ren? Fleschenberg schrieb: > Gregor Horvath schrieb: >> Ren? Fleschenberg schrieb: >> >>> today, to the best of my knowledge. And "in some form or another" >>> basically means that the PEP would create more possibilities for things >>> to go wrong. That things can already go wrong today does not mean that >>> it does not matter if we create more occasions were things can go wrong >>> even worse. >> Following this logic we should not add any new features at all, because >> all of them can go wrong and can be used the wrong way. > > No, that does not follow from my logic. What I say is: When thinking > about wether to add a new feature, the potential benefits should be > weighed against the potential problems. I see some potential problems > with this PEP and very little potential benefits. > >> I love Python because it does not dictate how to do things. >> I do not need a ASCII-Dictator, I can judge myself when to use this >> feature and when to avoid it, like any other feature. > > *That* logic can be used to justify the introduction of *any* feature. *Your* logic can be used to justify dropping *any* feature. Stefan From paul at science.uva.nl Wed May 16 07:32:14 2007 From: paul at science.uva.nl (Paul Melis) Date: Wed, 16 May 2007 13:32:14 +0200 Subject: Splitting a quoted string. In-Reply-To: References: <1179312169.045429.80960@e65g2000hsc.googlegroups.com> Message-ID: Paul Melis wrote: > Hi, > > mosscliffe wrote: > >> I am looking for a simple split function to create a list of entries >> from a string which contains quoted elements. Like in 'google' >> search. >> >> eg string = 'bob john "johnny cash" 234 june' >> >> and I want to have a list of ['bob', 'john, 'johnny cash', '234', >> 'june'] >> >> I wondered about using the csv routines, but I thought I would ask the >> experts first. >> >> There maybe a simple function, but as yet I have not found it. > > > Here a not-so-simple-function using regular expressions. It repeatedly > matched two regexps, one that matches any sequence of characters except > a space and one that matches a double-quoted string. If there are two > matches the one occurring first in the string is taken and the matching > part of the string cut off. This is repeated until the whole string is > matched. If there are two matches at the same point in the string the > longer of the two matches is taken. (This can't be done with a single > regexp using the A|B operator, as it uses lazy evaluation. If A matches > then it is returned even if B would match a longer string). Here a slightly improved version which is a bit more compact and which removes the quotes on the matched output quoted string. import re def split_string(s): pat1 = re.compile('[^" ]+') pat2 = re.compile('"([^"]*)"') parts = [] m1 = pat1.search(s) m2 = pat2.search(s) while m1 or m2: if m1 and m2: if m1.start(0) < m2.start(0): match = 1 elif m2.start(0) < m1.start(0): match = 2 else: if len(m1.group(0)) > len(m2.group(0)): match = 1 else: match = 2 elif m1: match = 1 else: match = 2 if match == 1: part = m1.group(0) s = s[m1.end(0):] else: part = m2.group(1) s = s[m2.end(0):] parts.append(part) m1 = pat1.search(s) m2 = pat2.search(s) return parts print split_string('bob john "johnny cash" 234 june') print split_string('"abc""abc"') From novin01 at gmail.com Thu May 3 05:59:32 2007 From: novin01 at gmail.com (Dave) Date: Thu, 3 May 2007 09:59:32 +0000 (UTC) Subject: Using Bessel Functions References: <7a9982ec0705030235h23035156w4f0726e6cef52f@mail.gmail.com> Message-ID: amit soni gmail.com> writes: > Can anyone tell me what is the exact syntax for to use it. > Thank you,Amit > For example evaluating j1 @ 0 from scipy import special print special.j1(0) HTH, Dave From kyosohma at gmail.com Thu May 10 16:54:04 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 10 May 2007 13:54:04 -0700 Subject: How to installo???? In-Reply-To: References: Message-ID: <1178830444.735169.324830@p77g2000hsh.googlegroups.com> On May 10, 8:58 am, RonV wrote: > Just got a new Vista system and puter.... > > Installed a newer version of Python, up from 2.2 or so... > > Tried to install Win extensions, but have forgotten how it's done. > Clicking on setup in the Win Extsions package flashes a window by, > but cannot read it. and I don't see a way to load the setup into > Python without Win Extensions. > > Any suggestions? > > Thank you I would recommend using the command line. Open that up and then type something like this: python pathToWinExt\setup.py That should run it and when it's done, your command window should stay open. Hopefully it will tell you what happened. Since I don't have Vista and don't know if it will recognize the name "python", you may need to specify a path to it too. Good luck! Mike From cjw at sympatico.ca Sun May 13 20:47:48 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Sun, 13 May 2007 20:47:48 -0400 Subject: append In-Reply-To: <2adc542f0705101011y3164db06n3447c4263ae15249@mail.gmail.com> References: <1178816546.689849.255070@y5g2000hsa.googlegroups.com> <2adc542f0705101011y3164db06n3447c4263ae15249@mail.gmail.com> Message-ID: <4647B1B4.5020507@sympatico.ca> Sick Monkey wrote: > http://docs.python.org/tut/node7.html > > Yes there is a pop function. > > "An example that uses most of the list methods: > >>>> a = [66.25, 333, 333, 1, 1234.5] >>>> print a.count(333), a.count(66.25), a.count('x') > 2 1 0 >>>> a.insert(2, -1) >>>> a.append(333) >>>> a > [66.25, 333, -1, 333, 1, 1234.5, 333] >>>> a.index(333) > 1 >>>> a.remove(333) >>>> a > [66.25, -1, 333, 1, 1234.5, 333] >>>> a.reverse() >>>> a > [333, 1234.5, 1, 333, -1, 66.25] >>>> a.sort() >>>> a > [-1, 1, 66.25, 333, 333, 1234.5] > > " > > > On 10 May 2007 10:02:26 -0700, *HMS Surprise* > wrote: > > Trying not to be a whiner but I sure have trouble finding syntax in > the reference material. I want to know about list operations such as > append. Is there a pop type function? I looked in tutorial, language > reference, and lib for list, append, sequence. Is there a place where > us doofi ( who may not have our heads out in the sunlight) may find > all related syntax grouped together? > > thanx, > > jh > > -- > http://mail.python.org/mailman/listinfo/python-list > > Most of the syntax is set out in Sections 5, 6, 7 & 8 of the Language Reference Manual, with a very small part in Section 2. Colin W. From rurpy at yahoo.com Wed May 16 00:54:56 2007 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 15 May 2007 21:54:56 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464a25e9$0$10188$9b4e6d93@newsspool4.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649dd55$0$23144$9b4e6d93@newsspool1.arcor-online.net> <464a25e9$0$10188$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <1179291296.561359.286230@h2g2000hsg.googlegroups.com> On May 15, 3:28 pm, Ren? Fleschenberg wrote: > We all know what the PEP is about (we can read). The point is: If we do > not *need* non-English/ASCII identifiers, we do not need the PEP. If the > PEP does not solve an actual *problem* and still introduces some > potential for *new* problems, it should be rejected. So far, the > "problem" seems to just not exist. The burden of proof is on those who > support the PEP. I'm not sure how you conclude that no problem exists. - Meaningful identifiers are critical in creating good code. - Non-english speakers can not create or understand english identifiers hence can't create good code nor easily grok existing code. Considering the vastly greater number of non-English spreakers in the world, who are not thus unable to use Python effectively, seems like a problem to me. That all programers know enough english to create and understand english identifiers is currently speculation or based on tiny personaly observed samples. I will add my own personal observation supporting the opposite. A Japanese programmer friend was working on a project last fall for a large Japanese company in Japan. A lot of their programming was outsourced to Korea. While the liason people on both side communicated in a mixture of English and Japanese my understanding was the all most all the programmers spoke almost no English. The language used was Java. I don't know how they handled identifiers but I have no reason to believe they were English (though they may have been transliterated Japanese). Now that too is a tiny personaly observered sample so it carries no more weight than the others. But it is enough to make me question the original assertion thal all programmers know english. It's a big world and there are a lot of people out there. Drawing conclusions based on 5 or 50 or 500 personal contacts is pretty risky, particularly when being wrong means putting up major barriers to Python use for huge numbers of people. From paul at boddie.org.uk Fri May 25 19:18:51 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 25 May 2007 16:18:51 -0700 Subject: webbrowser module bug? In-Reply-To: References: <1180118146.617722.300670@g4g2000hsf.googlegroups.com> Message-ID: <1180135131.139874.237560@w5g2000hsg.googlegroups.com> Ron Adam wrote: > > Reseting the default browser with the gnome default application window > confirmed this. The browser selection can either have the quotes around > the args "%s" paremteter, or not depending on how and what sets it. > > Seems to me it should be quoted unless spaces in path names are never a > problem in Linux. So this could be both a python bug and a Gnome desktop > bug. Firefox probably does the right thing by putting the quotes around > it, but that causes problems for webbrowser.py, which doesn't expect them. Quoting arguments in the way described is the safe, easy option (with some potential problems with ' characters that can be worked around), and I imagine that it's done precisely because other applications could pass a path with spaces as the URL, and that such applications would be invoking the command in a shell environment. Sadly, this conflicts with any other precautionary measures, causing a degree of "overquoting". Resetting the GNOME default is a workaround, but I'm not convinced that it would be satisfactory. What happens if you try and open an HTML file, in the file browser or some other application which uses the desktop preferences, where the filename contains spaces? Paul From martin at v.loewis.de Sat May 5 15:32:11 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 05 May 2007 21:32:11 +0200 Subject: Python regular expressions just ain't PCRE In-Reply-To: <1178323901.381993.47170@e65g2000hsc.googlegroups.com> References: <1178323901.381993.47170@e65g2000hsc.googlegroups.com> Message-ID: <463CDBBB.9090306@v.loewis.de> > Are there any plans to support these features in re? This question is impossible to answer. I don't have such plans, and I don't know of any, but how could I speak for the hundreds of contributors to Python world-wide, including those future contributors which haven't contributed *yet*. Do you have plans for such features in re? Regards, Martin From Eric_Dexter at msn.com Mon May 21 21:34:30 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 21 May 2007 18:34:30 -0700 Subject: Python and GUI In-Reply-To: References: <1179761984.704369.116310@b40g2000prd.googlegroups.com> Message-ID: <1179797669.781282.146060@q75g2000hsh.googlegroups.com> On May 21, 10:50 am, brad wrote: > sdoty... at gmail.com wrote: > > Just wondering on what peoples opinions are of the GUIs avaiable for > > Python? > > We have used wxPython with great results. It's cross platform. Can use > native OS widgets and is easy to program. Compiles easily to exe > binaries for Windows users as well. > > Best of luck, > Brad I don't recoment gtk because it doesn't install well on python 2.5 on windows. It is a shame because it has alot of realy nice 3d packages. I would stick with wxpython and tkinter for general use gui use there are other options for the high tek 3d stuff From info at egenix.com Thu May 10 11:34:22 2007 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Thu, 10 May 2007 17:34:22 +0200 Subject: ANN: eGenix mxODBC Distribution 3.0.0 (mxODBC Database Interface) Message-ID: <46433B7E.6080306@egenix.com> ________________________________________________________________________ ANNOUNCING eGenix.com mxODBC Database Interface Version 3.0.0 Our commercially supported Python extension providing ODBC database connectivity to Python applications on Windows and Unix platforms This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-mxODBC-Distribution-3.0-GA.html ________________________________________________________________________ ABOUT The mxODBC Database Interface allows users to easily connect Python applications to just about any database on the market today - on both Windows and Unix platforms in a highly portable and convenient way. This makes mxODBC the ideal basis for writing cross-platform database programs and utilities in Python. mxODBC is included in the eGenix.com mxODBC Distribution for Python, a commercial part of the eGenix.com mx Extension Series, a collection of professional quality software tools which enhance Python's usability in many important areas such as ODBC database connectivity, fast text processing, date/time processing and web site programming. The package has proven its stability and usefulness in many mission critical applications and various commercial settings all around the world. * About Python: Python is an object-oriented Open Source programming language which runs on all modern platforms (http://www.python.org/). By integrating ease-of-use, clarity in coding, enterprise application connectivity and rapid application design, Python establishes an ideal programming platform for todays IT challenges. * About eGenix: eGenix is a consulting and software product company focused on providing professional quality services and products to Python users and developers (http://www.egenix.com/). ________________________________________________________________________ NEWS mxODBC 3.0 has received a large number of enhancements and supports more ODBC drivers than ever. Some highlights: * mxODBC has been ported to Python 2.5. * We've worked a lot on the Unicode support and made it more robust, especially on Unix platforms where the ODBC Unicode support has stabilized over the last few years. You can now issue commands using Unicode and exchange Unicode data with the database in various configurable ways. * We've also added a methods to give you more control of the connections and cursors as well as the .callproc() method for calling stored procedures that mxODBC 2.0 was missing. * Multiple result sets via the .nextset() are also supported, so working with stored procedures should be a lot easier now. * Another highlight is the added support for Python's datetime module types and the option to use strings for date/time processing (e.g. to be able to use timezones in timestamps if that's supported by the database). * Python's decimal module is now supported as well and it's possible to configure mxODBC to return Decimal types for numeric values. * mxODBC 3.0 received full 64-bit support, so that you can run mxODBC (and all other mx Extensions) on e.g. AMD64 platforms. * We've switched from the old distutils wininst installer to the new MSI installer for the Windows Python 2.5 build. This gives you a lot more options for automatic installs, including unattended installs. See http://www.python.org/download/releases/2.5/msi/ for details. Note that in order to avoid confusion, we've decided to rename the eGenix.com mx Commercial Distribution to eGenix.com mxODBC Distribution with this release. The commercial distribution has always only contained the mxODBC package, so this was an obvious step to clarify things for our users. As always we are providing pre-compiled versions of the package for Windows, Linux, Mac OS X, FreeBSD and Solaris as well as sources which allow you to install the package on all other supported platforms. ________________________________________________________________________ DOWNLOADS The download archives and instructions for installing the package can be found at: http://www.egenix.com/products/python/mxODBC/ IMPORTANT: In order to use the eGenix mx Commercial package you will first need to install the eGenix mx Base package which can be downloaded from here: http://www.egenix.com/products/python/mxBase/ ________________________________________________________________________ UPGRADING Please note that mxODBC 2.0 does not support Python 2.5 on 64-bit platforms due to the Py_ssize_t changes in the Python C API. You are encouraged to upgrade to the new mxODBC 3.0 release, if you plan to deploy on 64-bit platforms and use Python 2.5 as basis for your applications. ________________________________________________________________________ LICENSES & COSTS This release brings you all the new features and enhancements in mxODBC that were previously only available in through our mxODBC Zope Database Adapter. Like the Zope product, mxODBC now requires that you install a license in order to use it. You can request 30-day evaluation licenses by writing to sales at egenix.com, stating your name (or the name of the company) and the number of eval licenses that you need. We will then issue you licenses and send them to you by email. Please make sure that you can receive ZIP file attachments on the email you specify in the request, since the license files are send out as ZIP attachements. _______________________________________________________________________ SUPPORT Commercial support for these packages is available from eGenix.com. Please see http://www.egenix.com/services/support/ for details about our support offerings. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, May 10 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 timr at probo.com Fri May 4 02:19:58 2007 From: timr at probo.com (Tim Roberts) Date: Fri, 04 May 2007 06:19:58 GMT Subject: Replacement for HTMLGen? References: <463a70b1$0$16345$88260bb3@free.teranews.com> Message-ID: "Joshua J. Kugler" wrote: > >I realize that in today's MVC-everything world, the mere mention of >generating HTML in the script is near heresy, but for now, it's what I ened >to do. :) > >That said, can someone recommend a good replacement for HTMLGen? I used to be a huge fan of HTMLgen. I built a couple of web sites on them, still in use 7 years later. However, in the time since then, I have come to believe that templating is a better answer. Now, the simple truth is that you need to use the scheme that makes sense to you. For me, templating (Cheetah is my favorite, www.cheetahtemplate.org) makes more sense than building the page bit by bit in Python code, and the separation of function and presentation makes things easier to maintain. In my opinion, of course. ;) -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From luc.saffre at gmail.com Mon May 7 00:55:19 2007 From: luc.saffre at gmail.com (luc.saffre at gmail.com) Date: 6 May 2007 21:55:19 -0700 Subject: invoke user's standard mail client In-Reply-To: References: <1178266064.922925.125760@y80g2000hsf.googlegroups.com> <463D7E30.8070307@pythonmeister.com> Message-ID: <1178513719.809289.205280@o5g2000hsb.googlegroups.com> On May 6, 10:08 am, Stefan Sonnenberg-Carstens wrote: > Stefan Sonnenberg-Carstens schrieb: > > > Gabriel Genellina schrieb: > > >> En Fri, 04 May 2007 05:07:44 -0300, luc.saf... at gmail.com > >> escribi?: > > >>> the simplest way to launch the user's standard mail client from a > >>> Python program is by creating a mailto: URL and launching the > >>> webbrowser: > >>> But this method is limited: you cannot specify a file to be attached > >>> to the mail. And I guess that there would be problems if the body text > >>> is too complex. > >>> Does somebody know about a better method? > >>> It should be possible at least on Windows, since Acrobat Reader is > >>> able to do it. > > >> On Windows you can use MAPI. > > > import win32api > > win32api.ShellExecute(0,'open','mailto:',None,None,0) > > For completeness > > import win32api > win32api.ShellExecute(0,'open','mailto: g... at python.org',None,None,0) That's equivalent to what the webbrowser module does in my example. Except that your program won't work on Unix. Luc From arnoreg at gmail.com Mon May 28 05:15:51 2007 From: arnoreg at gmail.com (Arno Stienen) Date: Mon, 28 May 2007 11:15:51 +0200 Subject: xmlrpclib hangs execution In-Reply-To: <465890FB.4030405@utwente.nl> References: <45AC0631.8080601@ctw.utwente.nl> <465890FB.4030405@utwente.nl> Message-ID: <465A9DC7.2010708@gmail.com> Perhaps I should be a bit more specific. When using this code to connect to a remote XML-RPC server (C++, xmlrpc++0.7 library): import xmlrpclib server = xmlrpclib.Server("http://10.10.101.62:29500") print server.Connection_Request("roberto") the Python command line 'hangs' until I kill the server. Then, the correct output is suddenly displayed: {'state': 0, 'id_session': '2Z3EUSLJFA13', 'port': 29501, 'str': 'Connection accepted. Session attached.'} Yet a slightly simpler call works flawlessly: import xmlrpclib server = xmlrpclib.Server("http://10.10.101.62:29500") print server.Info_RT('Master') {'state': 0, 'str': 'Info_RT'} Looking at the TCP packages (using Wireshark), the first Connection_Request flow as follows (c=python client,s= xml-rpcserver): 1 c>s SYN 2 s>c SYN,ACK 3 c>s ACK 4 c>s PSH,ACK (setting content-type: text/xml) 5 s>c ACK 6 c>s PSH,ACK (xml-rpc request) 7 s>c ACK 8 s>c PSH,ACK (xml-rpc results, correct) 9 c>s ACK At this point, Python 'hangs' until I kill (-9) the server (28 seconds later), and then these last packages are send: 10 s>c FIN,ACK 11 c>s FIN,ACk 12 s>c ACK After which Python continues and prints the xml-rpc results on the screen. Strangely, before Python hangs, it has already received the package with the results, but doesn't do anything with it. For comparison, this is the package flow for the Info_RT method, which returns within a second with the correct result on the Python command line: 1 c>s SYN 2 s>c SYN,ACK 3 c>s ACK 4 c>s PSH,ACK (setting content-type: text/xml) 5 s>c ACK 6 c>s PSH,ACK (xml-rpc request) 7 s>c ACK 8 s>c PSH,ACK (xml-rpc results, correct) 9 s>c FIN,ACK 10 c>s ACK 11 c>s FIN,ACk 12 s>c ACK Notice the reverse order of packages 9 and 10. Could this be it? Is Python waiting until the server sends a FIN package? But if so, why? Looking at the Python trace, this might be it. A diff between the trace of the killed Connection_Request and the Info_RT resulted only in expected differences (due to different length of parameters). But when diffing the traces of the killed and non-killed Connection_Request, something else is visible. The killed Connection_Request ends with: [...] string:318: return sep.join(words) xmlrpclib:866: self._type = "params" xmlrpclib:769: try: xmlrpclib:770: f = self.dispatch[tag] xmlrpclib:771: except KeyError: xmlrpclib:772: pass # unknown tag ? xmlrpclib:1273: if sock: xmlrpclib:1274: response = sock.recv(1024) xmlrpclib:1277: if not response: xmlrpclib:1278: break xmlrpclib:1283: file.close() socket:218: try: socket:219: if self._sock: socket:220: self.flush() socket:232: if self._wbuf: socket:222: self._sock = None xmlrpclib:1284: p.close() xmlrpclib:530: self._parser.Parse("", 1) # end of data xmlrpclib:531: del self._target, self._parser # get rid of circular references xmlrpclib:1286: return u.close() xmlrpclib:741: if self._type is None or self._marks: xmlrpclib:743: if self._type == "fault": xmlrpclib:745: return tuple(self._stack) socket:225: try: socket:226: self.close() socket:218: try: socket:219: if self._sock: socket:222: self._sock = None xmlrpclib:1386: if len(response) == 1: xmlrpclib:1387: response = response[0] xmlrpclib:1389: return response __main__:26: print result {'state': 0, 'id_session': 'QDLY3GP9FBM5', 'port': 29501, 'str': 'Connection accepted. Session attached.'} But the non-killed Connection_Request looks like: [...] return sep.join(words) xmlrpclib:866: self._type = "params" xmlrpclib:769: try: xmlrpclib:770: f = self.dispatch[tag] xmlrpclib:771: except KeyError: xmlrpclib:772: pass # unknown tag ? xmlrpclib:1273: if sock: xmlrpclib:1274: response = sock.recv(1024) socket:225: try: socket:226: self.close() socket:218: try: socket:219: if self._sock: socket:220: self.flush() socket:232: if self._wbuf: socket:222: self._sock = None (In the diff there is a gap between the xmlrpclib:1274 and socket:225 lines, as compared to the killed Connection_Request; perhaps Ctrl+C still executes the "socket try close" lines?) If you want to do your own 'diff' on the Python traces, or look at the TCP packages in more details with Wireshark, here are the files for the correctly working Info_RT and faulty Connection_Request methods: http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-infort-python.ws http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-infort-python-ws.txt http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-infort-trace.txt http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-conreq-python.ws http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-conreq-python-ws.txt http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-conreq-trace.txt http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-conreq-trace-hardbreak.txt (The first three ConReq files all include killing the server after ~28 seconds, thus resulting in the correct output. In the fourth files, tracing is stopped before the server is killed. It is therefor the trace up to the 'hanging point'. Note that the first two Wireshark packages are not TCP, but ARP, thus the file has a total of 14 packages, not 12 as above.) Really, any help here is appreciated! Kind regards, Arno. Arno Stienen wrote: > Hello all, > > It has been a while, but I finally found the time to further investigate > my problems with connecting Python to a RTAI-XML server. As I cannot > tell if the problems I'm facing are caused by RTAI-XML (or more > precisely, the xmlrpc++0.7 library) or Python (xmlrpclib), I'm posting > this message on both the RTAI as the Python mailing list. > > Just to recap, here are the symptoms I described earlier. > > I am using two computers. One is running the RTAI-patched real-time > linux kernel, and this computer controls my robotic hardware. On this > RTAI computer I installed the RTAI-XML server, which uses incoming > XML-RPC calls to control real-time processes on the server. RTAI-XML is > programmed in C++, using the xmlrpc++0.7 library. > > The second is a desktop machine (Windows XP or Ubuntu), from which a > XML-RPC connection can be made to the RTAI computer. Although in theory > it should make no difference if I use C, C++, Java or Python to make the > connection, in practise I can get the Java connection running, but have > problems using Python. And I really like to use Python to quickly create > interfaces! > > When connecting with Python on the desktop computer to the RTAI-XML > server running on my RTAI machine, I used the following code. > > import xmlrpclib > server = xmlrpclib.Server("http://10.10.101.62:29500") > print server.Info_RT('Master') > > This results in the correct output: > > {'state': 0, 'str': 'Info_RT'} > > Yet, this is only an information call. The really interesting part > should comes when I ask the server to open a connection: > > import xmlrpclib > server = xmlrpclib.Server("http://10.10.101.62:29500") > print server.Connection_Request("roberto") > > But then nothing happens. Python just hangs and is unresponsive. Until, > I kill the RTAI-XML server on the RTAI computer! And then suddenly the > correct output appears on the desktop command line: > > {'state': 0, 'id_session': '2Z3EUSLJFA13', 'port': 29501, > 'str': 'Connection accepted. Session attached.'} > > (Using an alternative Python XML-RPC library '#import pyxmlrpclib as > xmlrpclib' makes no difference to the result.) > > So what happens? I did some experiments. I did some package sniffing > with Wireshark and I did Python tracing. I stored the sniffing results > in both the Wireshark as plain text format. The files for the first > Info_RT examples are here: > > http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-infort-python.ws > http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-infort-python-ws.txt > http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-infort-trace.txt > > The files for the second, not correctly working example are here: > > http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-conreq-python.ws > http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-conreq-python-ws.txt > http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-conreq-trace.txt > http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-conreq-trace-hardbreak.txt > > The first three files all include killing the server after ~30 seconds, > thus resulting in the correct output. In the fourth files, tracing is > stopped before the server is killed. It is therefor the trace up to the > 'hanging point'. > > Any, really any, suggestions are appreciated! > > Kind regards, > Arno Stienen. From nospam at invalid.com Sat May 26 04:17:26 2007 From: nospam at invalid.com (Jack) Date: Sat, 26 May 2007 01:17:26 -0700 Subject: Large Amount of Data References: Message-ID: I have tens of millions (could be more) of document in files. Each of them has other properties in separate files. I need to check if they exist, update and merge properties, etc. And this is not a one time job. Because of the quantity of the files, I think querying and updating a database will take a long time... Let's say, I want to do something a search engine needs to do in terms of the amount of data to be processed on a server. I doubt any serious search engine would use a database for indexing and searching. A hash table is what I need, not powerful queries. "John Nagle" wrote in message news:nfR5i.4273$C96.1640 at newssvr23.news.prodigy.net... > Jack wrote: >> I need to process large amount of data. The data structure fits well >> in a dictionary but the amount is large - close to or more than the size >> of physical memory. I wonder what will happen if I try to load the data >> into a dictionary. Will Python use swap memory or will it fail? >> >> Thanks. > > What are you trying to do? At one extreme, you're implementing > something > like a search engine that needs gigabytes of bitmaps to do joins fast as > hundreds of thousands of users hit the server, and need to talk seriously > about 64-bit address space machines. At the other, you have no idea how > to either use a database or do sequential processing. Tell us more. > > John Nagle From kw at codebykevin.com Tue May 15 19:38:12 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Tue, 15 May 2007 19:38:12 -0400 Subject: tkFileDialog.askopenfilename() In-Reply-To: <1179270010.433011.23580@y80g2000hsf.googlegroups.com> References: <1179270010.433011.23580@y80g2000hsf.googlegroups.com> Message-ID: <32eeb$464a4466$4275d90a$23243@FUSE.NET> rahulnag22 at yahoo.com wrote: > Hi, > When I call tkFileDialog.askopenfilename() , the dialog box opens with > the current directory as the default directory. Is it possible to open > the dialog box with a directory other than the current directory. Can > we pass in a user defined starting directory. > Thanks > Rahul > Use the "initialdir" flag: filename = askopenfilename(title="Open File", initialdir=(os.path.expanduser('~/')) HTH, Kevin -- Kevin Walzer Code by Kevin http://www.codebykevin.com From erikwickstrom at gmail.com Sun May 27 11:30:33 2007 From: erikwickstrom at gmail.com (erikcw) Date: 27 May 2007 08:30:33 -0700 Subject: Why isn't this query working in python? In-Reply-To: <1180225290.235515.274000@q19g2000prn.googlegroups.com> References: <1180103946.552760.239200@p47g2000hsd.googlegroups.com> <6e42ec490705250751i89d3cf3v3a3062690d0284aa@mail.gmail.com> <1180207521.072958.322770@p47g2000hsd.googlegroups.com> <1180225290.235515.274000@q19g2000prn.googlegroups.com> Message-ID: <1180279833.131269.136770@w5g2000hsg.googlegroups.com> On May 26, 8:21 pm, John Machin wrote: > On May 27, 5:25 am, erikcw wrote: > > > > > On May 25, 11:28 am, Carsten Haese wrote: > > > > On Fri, 2007-05-25 at 09:51 -0500, Dave Borne wrote: > > > > > I'm trying to run the following query: > > > > ... > > > > > member_id=%s AND expire_date > NOW() AND completed=1 AND (product_id > > > > > Shouldn't you be using the bind variable '?' instead of '%s' ? > > > > The parameter placeholder for MySQLdb is, indeed and unfortunately, %s. > > > The OP is using parameter substitution correctly, though in an > > > obfuscated fashion. 'sql' is a misnamed tuple containing both the query > > > string *and* the parameters, which is being unpacked with '*' into two > > > arguments to the execute call. > > > > The only problem I see is that the parameters should be a sequence, i.e. > > > (self.uid,) instead of just (self.uid). > > > > HTH, > > > > -- > > > Carsten Haesehttp://informixdb.sourceforge.net > > > I tried adding the comma to make it a sequence - but now change. > > > ('SELECT payment_id FROM amember_payments WHERE member_id=%s AND > > expire_date > NOW() AND completed=1 AND (product_id >11 AND product_id > > <21)', (1608L,)) > > () > > > What else could it be? > > Possibly a type mismatch. How is member_id declared in the CREATE > TABLE? For diagnostic purposes, try passing in (1608,) and ('1608',). Here is a copy of the table schema and the first 2 rows. -- phpMyAdmin SQL Dump -- version 2.9.0.2 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: May 27, 2007 at 11:29 AM -- Server version: 5.0.27 -- PHP Version: 4.4.2 -- -- Database: `lybp_lybp` -- -- -------------------------------------------------------- -- -- Table structure for table `amember_payments` -- CREATE TABLE `amember_payments` ( `payment_id` int(11) NOT NULL auto_increment, `member_id` int(11) NOT NULL default '0', `product_id` int(11) NOT NULL default '0', `begin_date` date NOT NULL default '0000-00-00', `expire_date` date NOT NULL default '0000-00-00', `paysys_id` varchar(32) NOT NULL default '', `receipt_id` varchar(32) NOT NULL default '', `amount` decimal(12,2) NOT NULL default '0.00', `completed` smallint(6) default '0', `remote_addr` varchar(15) NOT NULL default '', `data` text, `time` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP, `aff_id` int(11) NOT NULL default '0', `payer_id` varchar(255) NOT NULL default '', `coupon_id` int(11) NOT NULL default '0', `tm_added` datetime NOT NULL default '0000-00-00 00:00:00', `tm_completed` datetime default NULL, `tax_amount` decimal(12,2) NOT NULL default '0.00', PRIMARY KEY (`payment_id`), KEY `member_id` (`member_id`), KEY `payer_id` (`payer_id`), KEY `coupon_id` (`coupon_id`), KEY `tm_added` (`tm_added`,`product_id`), KEY `tm_completed` (`tm_completed`,`product_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=11020 ; -- -- Dumping data for table `amember_payments` -- INSERT INTO `amember_payments` VALUES (423, 107, 1, '2004-10-01', '2004-10-21', 'authorize_aim', '5687944', 3.95, 1, '', NULL, '2004-11-30 19:21:43', 0, '', 0, '2004-11-30 19:21:43', '2004-11-30 19:21:43', 0.00); INSERT INTO `amember_payments` VALUES (422, 107, 1, '2004-10-22', '2004-11-21', 'authorize_aim', '5873225', 9.95, 1, '', NULL, '2004-11-30 19:22:18', 0, '', 0, '2004-11-30 19:20:13', '2004-11-30 19:20:13', 0.00); Thanks for your help! Erik From vel.accel at gmail.com Wed May 23 05:48:03 2007 From: vel.accel at gmail.com (D.Hering) Date: 23 May 2007 02:48:03 -0700 Subject: Shared Memory Space - Accross Apps & Network In-Reply-To: Message-ID: <1179913683.260600.283420@q69g2000hsb.googlegroups.com> On May 23, 4:04 am, Tim Golden wrote: > Robert Rawlins - Think Blue wrote: > > > I've got an application that runs on an embedded system, the application > > uses a whole bunch or dicts and other data types to store state and other > > important information. > > I'm looking to build a small network of these embedded systems, and I'd love > > to have them all share the same set or data. Is it possible to share the > > applications variables across multiple applications, so certain lists are > > like a 'pool' written to by the different systems? I'm sure I could cobble > > something together by writing the lists to shared files instead of keeping > > them in RAM, but that feels a little inefficient. I'd like to try and > > configure some form of master/slave relationship between my applications if > > possible. > > I was really surprised you hadn't received a whole > slew of answers for this (even if they were: search > the newsgroup for the last time this was asked!) But > then I noticed that the post hadn't appeared on Google > Groups, at least. I read things via the mailing list; > is it possible your post hasn't made it across to > Usenet either? > > Just to get the ball rolling, I'd suggest two things: > > Pyro -http://pyro.sf.net > > This is actively maintained and has been going for a while. > We use it here (on a fairly small scale) and I know that > others use it elsewhere for bigger things. It's based on > a threaded socket server so whenever someone starts to say: > "I know; I'll roll my own threaded socket server", I'm > inclined to say: "Don't reinvent the wheel; try Pyro". > > PyLinda -http://www-users.cs.york.ac.uk/~aw/pylinda/ > > This implements the tuplespace paradigm. It's great > fun to use, but as far as I know this implementation > was a PhD project and lacks the robustness and wide > use of other things. That said, it works perfectly > well within its remit and might be a good match for > what you're trying to do. > > No doubt other people can chime in with suggestions > > TJG Possibly, IPython's new interactive parallel environment is what you are looking for: http://ipython.scipy.org/moin/Parallel_Computing From howe.steven at gmail.com Tue May 15 02:14:23 2007 From: howe.steven at gmail.com (Steven Howe) Date: Mon, 14 May 2007 23:14:23 -0700 Subject: removing spaces between 2 names In-Reply-To: <1179208842.114189.233060@e65g2000hsc.googlegroups.com> References: <1179208842.114189.233060@e65g2000hsc.googlegroups.com> Message-ID: <46494FBF.9090801@gmail.com> saif.shakeel at gmail.com wrote: > Hi, > Suppose i have a string stored in variable,how do i remove the > space between them,like if i have the name: > "USDT request" in a variable.i need "USDTrequest",without any space . > Thanks > > from string import replace st = 'abcd acdfg xtit' st.replace(' ','') 'abcdacdfgxtit' sph -- HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 From jyoung79 at kc.rr.com Mon May 21 22:33:42 2007 From: jyoung79 at kc.rr.com (jay) Date: Mon, 21 May 2007 21:33:42 -0500 Subject: A few questions Message-ID: <836B1022-9253-4D0C-B428-04D0DA8775FE@kc.rr.com> Wow!! Thanks so much for your quick and helpful replies! I really appreciate it!! :-) I tried installing off 'wxPython2.8-osx-ansi-2.8.4.0-universal10.4- py2.5.dmg' on my OS 10.4.9 system which wouldn't install. So I installed off 'python-2.5-macosx.dmg' and then installed off 'wxPython2.8-osx-ansi-2.8.4.0-universal10.4-py2.5.dmg' which seemed to work. I find the instructions confusing as to what to install. After this I went to the tutorial and started trying out some of the examples. I pasted the code to separate text files and then ran them through a Terminal window. This stuff is freaking cool!!! Now I just have to figure out how this all works! Anyway, I had one more quick question... in order to run wxPython apps, do I have to have MacPython, etc. loaded on each Mac (or PC) in order for it to run any apps I write? Or is there a way to compile the code to where I can distribute an app I write and the other users don't need to load anything in order to run the app? Thanks again for your help with all this. I really appreciate you all taking the time to look and answer our questions. Jay From johnmasters at oxtedonline.net Mon May 14 13:16:51 2007 From: johnmasters at oxtedonline.net (John K Masters) Date: Mon, 14 May 2007 18:16:51 +0100 Subject: GUI tutorial In-Reply-To: References: Message-ID: <20070514171651.GA5239@spookie1.spookiegate> On 15:03 Mon 14 May , Jarek Zgoda wrote: > John K Masters napisa?(a): > > > Can someone point me in the direction of a good tutorial on programming > > python with a GUI? I'm just starting out with python and have written a > > few scripts successfully but would like to add a graphical front end to > > them to make it easier for my work colleagues, most of whom have never > > used a command line, to use. > > Each of GUI frameworks/libraries has its own tutorial and some even more > than one... The choice is directly related to what library you would use. Thanks to all for the advice. I shall start with Py-GTK and see how it goes. Regards, John -- War is God's way of teaching Americans geography Ambrose Bierce (1842 - 1914) From rex at abc.def Fri May 4 07:44:47 2007 From: rex at abc.def (Rex Turnbull) Date: Fri, 04 May 2007 13:44:47 +0200 Subject: Calling Exe from Python In-Reply-To: References: Message-ID: <463B1CAF.4060408@abc.def> muhamad.abbas : > Hello Folks, > > This is what i am required to do. > Call an executable from my python script, and when the executable is > finished running, i should continue with my python script. > > I have tried "os.exec()" but it calls the executable and never returns > to the calling python script. > I tried "os.fork" it will start an independent process, > since logic of my program depends on the results of executable. > > I am unable to figure, how to do it. > Hope you folks would help me. > > ~JinBaba > I use import os os.spawnl(os.P_WAIT, pathToExe, pathToExe, parm1, parm2, parm3, ) Remember that pathToExe must also be the first parameter. There are many other flavors of os.spawn, check documentation! Good luck, Rex From david at zettazebra.com Sun May 6 11:39:33 2007 From: david at zettazebra.com (David Clymer) Date: Sun, 06 May 2007 11:39:33 -0400 Subject: Crypto plaintext padding Message-ID: <1178465973.4345.12.camel@zepto.home.zettazebra.com> I'm using pycrypto's AES module, and am attempting to automate the padding of the plaintext (the size of the text to be encrypted must be a multiple of 16). However, my padding scheme sometimes fails to calculate the necessary padding correctly, and I'm not sure why. Using the text 'foo bar', it fails, but if I do 'foo bars' it works. Randomized testing fails sometimes and not others. Any pointers as to what I might be doing wrong (code attached)? -davidc -- gpg-key: http://www.zettazebra.com/files/key.gpg -------------- next part -------------- A non-text attachment was scrubbed... Name: test.py Type: text/x-python Size: 3135 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From mail at timgolden.me.uk Tue May 8 06:12:52 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 08 May 2007 11:12:52 +0100 Subject: Specification for win32com.client package In-Reply-To: <332916.34962.qm@web63414.mail.re1.yahoo.com> References: <332916.34962.qm@web63414.mail.re1.yahoo.com> Message-ID: <46404D24.4040602@timgolden.me.uk> Peter Fischer wrote: > Hello, (sorry, the first message bounced; because it is urgent and I wait since > yesterday, here it's again): > > > I am searching for documentation about the interface the win32com package > provides, especially win32com.client. I searched the web and Mark Hammond?s > homepage but only found example code using Dispatch() and DispatchEx() etc. > Isn?t there a full list of the functions win32.com.client provides? Or do I have to > use makepy to somehow generate documentation (how)? > I would be thankful if someone could give me a hook about that. > > Best regards, Peter. I'm afraid you're pretty much out of luck on full documentation, Peter. Mark Hammond & Andy Robinson's book (of several years ago) is still being published: http://www.amazon.com/exec/obidos/tg/detail/-/1565926218?v=glance and certainly contains quite a bit of information on the subject. The .chm which comes with the pywin32 extensions has some information (although not much). Examples from the python-win32 list and this mailing list plus examples from around the web, plus finally the source code itself are pretty much staple fare for people working in the Win32 area under Python. Obviously, what it needs is someone or someones with the energy to get that Python Win32 wiki underway, but at the moment all my energies are devoted elsewhere, I'm afraid. TJG From siona at chiark.greenend.org.uk Tue May 15 12:35:47 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 15 May 2007 17:35:47 +0100 (BST) Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <1hy2qg3.iqfvwnrvr9kjN%aleax@mac.com> Message-ID: Aldo Cortesi wrote: > [ ... ] There is no general way to detect homoglyphs and "convert them to >a normal form". Observe: > >import unicodedata >print repr(unicodedata.normalize("NFC", u"\u2160")) >print u"\u2160" >print "I" FYI, those come out as two very clearly distinct glyphs in the default terminal font I have here. (The ROMAN NUMERAL ONE has no cross-bars, and is more likely to be confused with "|".) -- \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 saif.shakeel at gmail.com Fri May 11 07:36:48 2007 From: saif.shakeel at gmail.com (saif.shakeel at gmail.com) Date: 11 May 2007 04:36:48 -0700 Subject: module error for elementtree In-Reply-To: <1178868155.638154.112200@h2g2000hsg.googlegroups.com> References: <1178867119.666923.204000@h2g2000hsg.googlegroups.com> <1178868155.638154.112200@h2g2000hsg.googlegroups.com> Message-ID: <1178883408.495131.253680@p77g2000hsh.googlegroups.com> On May 11, 12:22 pm, half.ital... at gmail.com wrote: > On May 11, 12:05 am, saif.shak... at gmail.com wrote: > > > > > > > #!/usr/bin/env python > > > from elementtree import ElementTree as Element > > tree = et.parse("testxml.xml") > > > for t in tree.getiterator("SERVICEPARAMETER"): > > if t.get("Semantics") == "localId": > > t.set("Semantics", "dataPackageID") > > > tree.write("output.xml") > > > Hi, > > For the above code to work elementtree is > > imported in first line ,but when running it says : > > ImportError: No module named elementtree.ElementTree > > Does thie module exists as default or a patch is needed? > > Thanks > > http://groups.google.com/group/comp.lang.python/browse_frm/thread/e09... > > Read carefully.- Hide quoted text - > > - Show quoted text - The commands are given in that link are more so for a linux system .I am developing in windows.how should i go about to make it work From development-2006-8ecbb5cc8aREMOVETHIS at ANDTHATm-e-leypold.de Wed May 23 13:46:09 2007 From: development-2006-8ecbb5cc8aREMOVETHIS at ANDTHATm-e-leypold.de (Markus E Leypold) Date: Wed, 23 May 2007 19:46:09 +0200 Subject: The Concepts and Confusions of Prefix, Infix, Postfix and Fully Functional Notations References: <1179936917.652372.24780@q69g2000hsb.googlegroups.com> Message-ID: <1oveejxwke.fsf@hod.lan.m-e-leypold.de> > On 2007-05-23, Xah Lee wrote: >> The Concepts and Confusions of Prefix, Infix, Postfix and Fully >> Functional Notations >> >> Xah Lee, 2006-03-15 > > Xah, why do you post year-old essays to newsgroups that couldn't care > less about them? And even more to the point -- why does he post now again the same drivel he already posted on the 9th of May 2007? And will we now treated to repeats of his garbage every 2 weeks? The answer to your question is very simple: Xah Lee is a troll. Regards -- Markus From pabloski at giochinternet.com Mon May 7 15:46:41 2007 From: pabloski at giochinternet.com (pabloski at giochinternet.com) Date: Mon, 07 May 2007 19:46:41 GMT Subject: is for reliable? Message-ID: Hi to all I have a question about the for statement of python. I have the following piece of code where cachefilesSet is a set that contains the names of 1398 html files cached on my hard disk for fn in cachefilesSet: fObj = codecs.open( baseDir + fn + '-header.html', 'r', 'iso-8859-1' ) u = fObj.read() v = u.lower() rows = v.split('\x0a') contentType = '' for r in rows: if r.find('content-type') != -1: y = r.find(':') if y != -1: z = r.find(';', y) if z != -1: contentType = r[y+1:z].strip() cE = r[z+1:].strip() characterEncoding = cE.strip('charset = ') else: contenType = r[y+1:].strip() characterEncoding = '' break if contentType == 'text/html': processHTMLfile( baseDir + fn + '-body.html', characterEncoding, cardinalita ) fileCnt += 1 if fileCnt % 100 == 0: print fileCnt this code stops at the 473th file instead of reaching 1398 however I changed the for and substituted it with a while in this way while cachefilesSet: fn = cachefilesSet.pop() ....... ....... the while loop reaches the 1398th file and is some 3-4 times faster than the for loop How is this possible? From wildemar at freakmail.de Thu May 31 13:57:57 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Thu, 31 May 2007 19:57:57 +0200 Subject: Is PEP-8 a Code or More of a Guideline? In-Reply-To: <002d01c7a39f$607de760$240110ac@Muse> References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <5c1jpkF2tl0ilU1@mid.individual.net> <1180539790.654176.26900@q75g2000hsh.googlegroups.com> <646aw86i.fsf@mail.com> <465ecb3c$0$29072$426a74cc@news.free.fr> <002d01c7a39f$607de760$240110ac@Muse> Message-ID: <465F0CA5.40404@freakmail.de> Warren Stringer wrote: > i.prefer.dots -- no, seriously > > sure it's slow, but forces you the think about names in a new way. > Are you now suggesting that "addinfourl()" should actually be called "url()", placed in a module named "info", which is part of a package called "add", so as to enable you to call "add.info.url()"? May I assume it wouldn't bother you having millions of packages containing only one module each (plus their __init__.py's) where the modules only provide around one function. OK, go ahead. Modify the whole Python-library to conform to that style and then send us the bill from your psychiatrist. This may be a nice idea for the Next Overwhelming Programming Escapade (Codename: NOPE), but you can just forget about it in Python. Excuse my mocking, but while typing dots is far easier for US and German keyboards, this may be a whole different story for any other layout (I forget how it goes with the french layout; shift for the dot or the comma?). Back to the drawing boards! ;) /W PS You may want to elaborate on the "new way to think about names". Maybe you have a point which I just don't see. From rene at korteklippe.de Wed May 16 03:24:14 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Wed, 16 May 2007 09:24:14 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> <4648294F.2000704@web.de> <46487a6c$0$2400$426a74cc@news.free.fr> <464977D3.6010703@web.de> <464993e7$0$23148$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <464ab19d$0$23146$9b4e6d93@newsspool1.arcor-online.net> Steven D'Aprano schrieb: >> Any program that uses non-English identifiers in Python is bound to >> become gibberish, since it *will* be cluttered with English identifiers >> all over the place anyway, wether you like it or not. > > It won't be gibberish to the people who speak the language. Hmmm, did you read my posting? By my experience, it will. I wonder: is English an acquired language for you? -- Ren? From carsten at uniqsys.com Tue May 15 11:34:35 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 15 May 2007 11:34:35 -0400 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179236673.893122.28800@w5g2000hsg.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> Message-ID: <1179243275.3385.84.camel@dot.uniqsys.com> On Tue, 2007-05-15 at 06:44 -0700, George Sakkis wrote: > After 175 replies (and counting), the only thing that is clear is the > controversy around this PEP. Most people are very strong for or > against it, with little middle ground in between. I'm not saying that > every change must meet 100% acceptance, but here there is definitely a > strong opposition to it. Accepting this PEP would upset lots of people > as it seems, and it's interesting that quite a few are not even native > english speakers. While it is true that many of the PEP's opponents here on c.l.p are not native English speakers, they are largely European or "Europeanized" people. Many European people don't seem to realize that there are entirely different cultures where people speak entirely different languages written in entirely different writing systems, and English is not widely spoken in many of those cultures. China comes to mind as but one example of many. Allowing people to use identifiers in their native language would definitely be an advantage for people from such cultures. That's the use case for this PEP. It's easy for Euro-centric people to say "just suck it up and use ASCII", but the same people would probably starve to death if they were suddenly teleported from Somewhere In Europe to rural China which is so unimaginably different from what they know that it might just as well be a different planet. "Learn English and use ASCII" is not generally feasible advice in such cultures. In my opinion, the principles of freedom and fostering global adoption of Python, require that this PEP be accepted. The objections for reasons of reduced code readability are valid, but I think the open source community is good enough at regulating itself and the community will predominantly *make the choice* to stick to ASCII-only identifiers. For programmers that are afraid of accidentally allowing non-ASCII identifiers from patches, we might want to explore the possibility of having Python's behavior switchable between ASCII and non-ASCII identifiers, either by a compiler setting, environment variable, a "from __future__" import, or similar mechanism. Regards, -- Carsten Haese http://informixdb.sourceforge.net From forumgogo at gmail.com Fri May 18 01:25:53 2007 From: forumgogo at gmail.com (forumgogo) Date: 17 May 2007 22:25:53 -0700 Subject: Support you the best free forum! Message-ID: <1179465953.458190.274050@h2g2000hsg.googlegroups.com> also ,its a spam.but if you need,come on .thank you . support you the best free forum .www.forumgogo.com Free Unlimited Storage Free Unlimited Bandwidth Free Free Subdomain Free More Skins Free No annoying pop-ups Free 99% Uptime Free Daily Backups Free Fast, Friendly Tech Support So,what's that? That's our free forum named http://www.forumgogo.com We have the human_based management also provide you human_based forum service. You needn't,we won't ! This is a great site that is completely free, and can make some cool forums, here's an example of one, you can make your own topic, polls, and replies etc, and you can have an accout for every member. This next link is an example of a forum made from invisionfree. http://support.forumgogo.com From paul at boddie.org.uk Thu May 3 10:27:11 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 3 May 2007 07:27:11 -0700 Subject: My Python annoyances In-Reply-To: References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> Message-ID: <1178202431.147195.249790@u30g2000hsc.googlegroups.com> On 3 Mai, 15:49, Ben Collver wrote: > I rewrote my code in Python and I found myself running into many of the > same hassles that I run into with other languages: inaccurate and > incomplete documentation, a maze of little platform-specific quirks to > work around in the base classes, and a macho community of users. I'm sorry to hear about that. If by "macho" you mean people who insist that things are good enough as they are, and that newcomers should themselves adapt to whatever they may discover, instead of things being improved so that they are more intuitive and reliable for newcomers and experienced developers alike, then I'd certainly be interested in undermining that culture. > The python web site recommended Dive Into Python, so I learned by > reading that. It has several examples that don't work because the > Python base classes have changed behavior. I should have taken that as > lesson. Really Dive Into Python should be a sufficient guide, and it was perhaps the best introduction to the language when it was written. It is very unfortunate that the language has changed in a number of ways (and exhibits continued change) whilst effort into documenting what is already there remains neglected amongst the people making all the changes. > I tried to write portable Python code. The zlib CRC function returned > different results on architectures between 32 bit and 64 bit > architectures. I filed a bug report. It was closed, without a comment > from the person who closed it. I get the unspoken message: bug reports > are not welcome. Can you provide the bug identifier? Bug reports are generally welcome, and despite complaints about patch reviews, I've found people reviewing things I've submitted. > I installed Cygwin on a Windows machine. I try to quit from an > interactive Python session. It tells me that on my platform, I must > press Control-Z to exit. I press Control-Z and it makes Python a > background process. Yes, Ctrl-Z exits Python in the standard Windows edition. Since Cygwin provides a POSIX-like environment, Ctrl-D should be used instead. If the documentation is wrong, a bug report or patch should be filed against the software. > I tried to use the XML.minidom. The documentation here is minimal as > well. So I read up on other web sites. It turns out that the interface > has changed quite a bit from the documentation I found on other web > sites. Where are the much loved docstrings? In 2.3 minidom, they are > sparse and cryptic. I really don't know what to say about the PyXML/xmlcore situation. I don't use ElementTree and hardly use PyXML or minidom, but something really should have been done about the maintenance of the established libraries rather than declaring them as legacy items and pretending that they don't exist. > Between 2.4 and 2.5, tempfile returns a different type of object. My > code cannot have a single test, it has check for type(obj) == file or > obj.__class__ == tempfile._TemporaryFileWrapper. Try using isinstance or relying on "deeper" knowledge of how the object will be used. > I decided to make a tkinter front-end for a Python program. I decided > to go with tkinter because it is included with many Python > installations, so it maximizes the chance for my program to run out of > the box. > > The tkinter documentation on the Python site mainly consists of loose > notes and links to other sites. The documentation on other sites is > great, if you already know how to use tkinter. I ran into bugs in > TkAqua which make the grid layout unusable for me. So I will need to > ask potential users to install Xcode, X11, and mac ports, if they want > to run my program. Take a look at the python.org Wiki for links to other resources on Tkinter: http://wiki.python.org/moin/TkInter Or consider other graphical frameworks: http://wiki.python.org/moin/GuiProgramming > In short, there is plenty of room for improvement. Admittedly these are > not problems with the language definition. But I downloaded a Python > distribution, and the problems are Python specific. My opinions, already expressed, include the observation that the core development community is more interested in extending the language than in strengthening the standard library (and its documentation). It should be noted that the proposed standard library reorganisation, which is a very conservative affair, has actually been postponed until after the release of Python 3.0a1 according to a message I read recently. And yet, if you read people's lists about what they "hate" about Python (amongst actual users of Python), guess which thing almost always comes up? http://www.google.com/search?q=%22things+I+hate+about+Python%22 Paul From gagsl-py2 at yahoo.com.ar Tue May 1 18:36:30 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 01 May 2007 19:36:30 -0300 Subject: Having problems accepting parameters to a function References: <1178037488.163487.114930@l77g2000hsb.googlegroups.com> <1178039183.030942.86270@y5g2000hsa.googlegroups.com> <1178039953.223506.52760@y80g2000hsf.googlegroups.com> <1178055738.454313.182040@l77g2000hsb.googlegroups.com> Message-ID: En Tue, 01 May 2007 18:42:18 -0300, rh0dium escribi?: > Let me expand a bit more - I am working on a threading class and I > want to be able to push on the Queue a list of args. If you run the > following program - I am failing to understand how to push items onto > the queue in a manner so that func2 recognizes them as kwargs not as > args. Can anyone help me with this. You can put a tuple in the queue: the first item being the positional arguments, the second item being a dictionary used as keyword arguments. py> from Queue import Queue py> q = Queue() py> q.put(((1,2,3),{"a":100, "b":200})) py> q.put(((),dict(boca=2,racing=2))) py> def f(*args, **kw): ... print "args", args ... for k in kw: ... print k, kw[k] ... py> item = q.get() py> f(*item[0], **item[1]) args (1, 2, 3) a 100 b 200 py> args, kw = q.get() py> f(*args, **kw) args () racing 2 boca 2 -- Gabriel Genellina From nagle at animats.com Mon May 7 00:29:54 2007 From: nagle at animats.com (John Nagle) Date: Mon, 07 May 2007 04:29:54 GMT Subject: My newbie annoyances so far In-Reply-To: <1178504008.035594.216920@o5g2000hsb.googlegroups.com> References: <1177688082.758043.133920@r30g2000prh.googlegroups.com> <_9pYh.1787$uJ6.894@newssvr17.news.prodigy.net> <1178400807.051103.95690@q75g2000hsh.googlegroups.com> <1hxp15f.1bvtgo11ydx3cvN%aleax@mac.com> <1178504008.035594.216920@o5g2000hsb.googlegroups.com> Message-ID: <6Xx%h.20332$JZ3.15645@newssvr13.news.prodigy.net> Isaac Gouy wrote: > On May 6, 6:09 pm, John Nagle wrote: > >>Alex Martelli wrote: >> >>>John Nagle wrote: >> >>>>igo... at yahoo.com wrote: >> >>>>>On Apr 27, 9:07 am, John Nagle wrote: >> >>>>>>The CPython implementation is unreasonably slow compared >>>>>>to good implementations of other dynamic languages such >>>>>>as LISP and JavaScript. >> My point is that there are optimizing hard-code compiler implementations >>of many dynamic languages, including LISP, Self, and Smalltalk, but not Python. > > > I guess Lisp is a safe-ish example but I don't think Self really made > it out of the lab, and it really depends which Smalltalk > implementation you have in mind and what you think about Pysco. See http://research.sun.com/self/papers/third-generation.html on a high performance Self implementation. That laid the groundwork for Java's JIT system. Here are some early Tamarin benchmarks. http://www.playercore.com/pub/Tamarin/Avmplus_vs._javascript.htm Tamarin doesn't do type inference, though, so they get the best performance only with type declarations. John Nagle From q16941 at motorola.com Thu May 24 07:13:21 2007 From: q16941 at motorola.com (ashish) Date: Thu, 24 May 2007 16:43:21 +0530 Subject: Xml parser Message-ID: <46557351.9050205@motorola.com> Hi All, I want to know weather is there any api available in python for parsing xml(XML parser) Regards Ashish From stefan.behnel-n05pAM at web.de Wed May 23 07:44:27 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 23 May 2007 13:44:27 +0200 Subject: xml.parsers.expat loading xml into a dict and whitespace In-Reply-To: References: <163f0ce20705222316x7d6247a7hea019e7fd2aa2ee2@mail.gmail.com> Message-ID: <4654291B.8060504@web.de> kaens wrote: > Now the code looks like this: > > import xml.etree.ElementTree as etree > > optionsXML = etree.parse("options.xml") > options = {} > > for child in optionsXML.getiterator(): > if child.tag != optionsXML.getroot().tag: > options[child.tag] = child.text > > for key, value in options.items(): > print key, ":", value Three things to add: Importing cElementTree instead of ElementTree should speed this up pretty heavily, but: Consider using iterparse(): http://effbot.org/zone/element-iterparse.htm *untested*: from xml.etree import cElementTree as etree iterevents = etree.iterparse("options.xml") options = {} for event, child in iterevents: if child.tag != "parent": options[child.tag] = child.text for key, value in options.items(): print key, ":", value Note that this also works with lxml.etree. But using lxml.objectify is maybe actually what you want: http://codespeak.net/lxml/dev/objectify.html *untested*: from lxml import etree, objectify # setup parser = etree.XMLParser(remove_blank_text=True) lookup = objectify.ObjectifyElementClassLookup() parser.setElementClassLookup(lookup) # parse parent = etree.parse("options.xml", parser) # get to work option1 = parent.option1 ... # or, if you prefer dictionaries: options = vars(parent) for key, value in options.items(): print key, ":", value Have fun, Stefan From rtw at freenet.co.uk Tue May 29 15:16:05 2007 From: rtw at freenet.co.uk (Rob Williscroft) Date: Tue, 29 May 2007 14:16:05 -0500 Subject: Connection acception with confirmation References: <1180462910.584445.256400@j4g2000prf.googlegroups.com> Message-ID: no`name` wrote in news:1180462910.584445.256400 at j4g2000prf.googlegroups.com in comp.lang.python: > maybe someone have some ideas how to block first stdin in main > function and get stdin from the thread when here is a new connection? > No, but you could instead use a Queue: http://docs.python.org/lib/module-Queue.html so that your main thread reads stdin and then uses an instance of Queue to post the 'y's and 'n's it recives to your server thread. Rob. -- http://www.victim-prime.dsl.pipex.com/ From bbxx789_05ss at yahoo.com Thu May 17 12:39:43 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 17 May 2007 09:39:43 -0700 Subject: omissions in python docs? Message-ID: <1179419983.750044.65030@n59g2000hsh.googlegroups.com> Hi, 1) The shelve module doesn't list close() as a method. 2) The fnmatch module does not even mention translate(). I have a hard time believing I am the first one to notice those omissions. Are the docs just old and poorly maintained? Or, is there some reason those methods were omitted? From warren at muse.com Wed May 30 17:31:23 2007 From: warren at muse.com (Warren Stringer) Date: Wed, 30 May 2007 14:31:23 -0700 Subject: c[:]() In-Reply-To: <1180554872.3356.30.camel@dot.uniqsys.com> References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com><1180504773.374529.161740@q66g2000hsg.googlegroups.com><002801c7a2eb$288a8750$240110ac@Muse> <1180554872.3356.30.camel@dot.uniqsys.com> Message-ID: <003601c7a301$dfcff0b0$240110ac@Muse> Hmmm, this is for neither programmer nor computer; this is for a user. If I wanted to write code for the benefit for the computer, I'd still be flipping switches on a PDP-8. ;-) This is inconsistent: why does c[:][0]() work but c[:]() does not? Why does c[0]() has exactly the same results as c[:][0]() ? Moreover, c[:][0]() implies that a slice was invoked So, tell me, for scheduling a lot of asynchronous events, what would be more readable than this: bidders = [local_members] + [callin_members] bidders[:].sign_in(roster) ... \~/ > -----Original Message----- > From: python-list-bounces+warren=muse.com at python.org [mailto:python-list- > bounces+warren=muse.com at python.org] On Behalf Of Carsten Haese > Sent: Wednesday, May 30, 2007 12:55 PM > To: python-list at python.org > Subject: Re: c[:]() > > On Wed, 2007-05-30 at 11:48 -0700, Warren Stringer wrote: > > I want to call every object in a tupple, like so: > > > > #------------------------------------------ > > def a: print 'a' > > def b: print 'b' > > c = (a,b) > > > > >>>c[:]() # i wanna > > [...] > > Is there something obvious that I'm missing? > > Yes: Python is not Perl. > > Python is based on the principle that programmers don't write computer > code for the benefit of the computer, but for the benefit of any > programmer who has to read their code in the future. Terseness is not a > virtue. To call every function in a tuple, do the obvious: > > for func in funcs: func() > > HTH, > > -- > Carsten Haese > http://informixdb.sourceforge.net > > > -- > http://mail.python.org/mailman/listinfo/python-list From mikeminer53 at hotmail.com Wed May 23 12:43:33 2007 From: mikeminer53 at hotmail.com (mkPyVS) Date: 23 May 2007 09:43:33 -0700 Subject: Resizing listbook's listview pane In-Reply-To: <1179932659.180278.72990@w5g2000hsg.googlegroups.com> Message-ID: <1179938613.529380.140240@p47g2000hsd.googlegroups.com> Sorry, copied from wxpython submit as well.. I'm using wxpython 2.8... Primariy I want the resize to happen programatically during object creation/post creation... I can worry about app size changes later. Thanks, From rasmussen.bryan at gmail.com Tue May 22 03:08:10 2007 From: rasmussen.bryan at gmail.com (bryan rasmussen) Date: Tue, 22 May 2007 09:08:10 +0200 Subject: Slightly OT: Why all the spam? In-Reply-To: References: Message-ID: <3bb44c6e0705220008y10f5deb7v86ed82d3f8241761@mail.gmail.com> Well two things I would suppose: 1. relative popularity and volume of the group leads spammers to put more resources towards spamming the group. 2. I seem to remember that python-list is also a usenet group? non-moderated, meaning it is tough to ban people? Actually, it would be nice to know if anybody has any good filters worked up that will work in Gmail for reading python-list. Cheers, Bryan Rasmussen On 5/22/07, Joel Hedlund wrote: > Does anyone know why we get so much spam to this group? It's starting to > get embarrasing to read at work and that's just not how it should be. > > Cheers! > /Joel > -- > http://mail.python.org/mailman/listinfo/python-list > From adamurbas at hotmail.com Fri May 11 22:21:56 2007 From: adamurbas at hotmail.com (adamurbas at hotmail.com) Date: 11 May 2007 19:21:56 -0700 Subject: need help with python In-Reply-To: References: <1178934447.719778.197150@h2g2000hsg.googlegroups.com> Message-ID: <1178936516.292808.279500@e65g2000hsc.googlegroups.com> On May 11, 9:11 pm, "Ian Clark" wrote: > On 11 May 2007 18:47:27 -0700, adamur... at hotmail.com > > > > wrote: > > ya so im pretty much a newb to this whole python thing... its pretty > > cool but i just started today and im already having trouble. i > > started to use a tutorial that i found somewhere and i followed the > > instructions and couldnt get the correct results. heres the code > > stuff... > > > temperature=input("what is the temperature of the spam?") > > if temperature>50: > > print "the salad is properly cooked." > > else: > > print "cook the salad some more." > > > ya i was trying to do that but when i told it what the spams > > temperature was, it just turned off... well it wasnt working at all at > > first until i realized that i hadnt been following the instructions > > completely correctly and that i was supposed to type that code up in a > > notepad then save and open with python... so ya thats when it asked me > > what temperature the spam was and i typed a number then it just closed > > itself... im not really sure what went wrong... itd be real nice if > > someone would be like a mentor or something... > > I'm making a couple of assumptions here (correct me if I'm wrong): > > 1. You're using windows > 2. You double clicked on the .py file > > What this does is open up a new terminal window and start execution of > the program. The program will execute to completion and then the > window will close automatically without waiting for you to tell it to > (lovely isn't it?). To get around this you have a couple options: > > 1. Run the script from the command line > 2. Put this at the end of the .py file: input('Press ENTER to continue') > > Ian ok u used a bunch of fancy words in there... im not sure what a .py file is... i am using windows... i dont know what a terminal window is but im gonna asume that it is when you click the python thing... ya i kinda understand what ur sayin but the thing is i wanted it to give feedback to my question and why would it do that... hmmm very confusing... im not sure how to run the script from the command line... oh yeah the enter thing worked. thanks for that... oh the command line must be the lil black box... if i put it there then it will give me a bunch of syntax this and error that kinda stuff... thats why im putin it in the notepad and plus the tutorial said to... From charl.loubser at gmail.com Fri May 4 06:43:04 2007 From: charl.loubser at gmail.com (Merrigan) Date: 4 May 2007 03:43:04 -0700 Subject: ftplib acting weird Message-ID: <1178275384.656955.269830@h2g2000hsg.googlegroups.com> Hi All, I have written a little script to upload some files to an ftp folder. The problem is as follows : I wrote the script on my windows laptop, and I want to run it from mylinux server. Everything worked fine so I uploaded it to my linux machine. Every time I tun the script I get the following error: *************************************************************************************************************************** [root at moses ftpsync]# python ftpsync.py !!!!!!!!!! The Connection to the Server Could not be established. Please Check all neccesary settings and run the script again. Thank you !!!!!!!!!! Traceback (most recent call last): File "ftpsync.py", line 194, in ? ftplisting() File "ftpsync.py", line 83, in ftplisting ftpconn.cwd(remotedir) #This changes to the remote directory File "/usr/lib64/python2.4/ftplib.py", line 494, in cwd return self.voidcmd(cmd) File "/usr/lib64/python2.4/ftplib.py", line 245, in voidcmd self.putcmd(cmd) File "/usr/lib64/python2.4/ftplib.py", line 175, in putcmd self.putline(line) File "/usr/lib64/python2.4/ftplib.py", line 170, in putline self.sock.sendall(line) AttributeError: 'NoneType' object has no attribute 'sendall' [root at moses ftpsync]# *************************************************************************************************************************** When I copy the same piece of scripting and run it from the python command shell, it works... what am I doing wrong? I have double checked everything about a million times, but to no avail. Blessings! From Carlos.Hanson at gmail.com Thu May 3 11:54:22 2007 From: Carlos.Hanson at gmail.com (Carlos Hanson) Date: 3 May 2007 08:54:22 -0700 Subject: Organizing code - import question In-Reply-To: References: Message-ID: <1178207662.200235.252900@e65g2000hsc.googlegroups.com> On May 3, 8:41 am, Brian Blais wrote: > Hello, > > I am trying to organize some of my code, and am having a little trouble with the > import logic. I find I often have something like: > > MyPackage/ > Part1/ # wants to use functions in Common/ > __init__.py # does "from MyClass1 import MyClass1", etc,... > MyClass1.py > MyClass1a.py # depends on MyClass1 > MyClass1b.py # depends on MyClass1 > > Part2/ # wants to use functions in Common/ > __init__.py # does "from MyClass2 import MyClass2", etc,... > MyClass2.py # depends on MyClass1 also, such as containing a list of MyClass1 > MyClass2a.py # depends on MyClass2 > MyClass2b.py # depends on MyClass2 > > Common/ > __init__.py # does "import fun1,fun2", etc,... > fun1.py > fun2.py > > So I have some common utilities that both classes want to access, and I have two > separate class definitions, of which one depends on the other. In MyClass2.py, I > can't seem to do: > > import Common.fun1 > > or > > from Part1.MyClass1 import MyClass1 > > I think I am either missing some syntax/path thing, or I am thinking about the > organization in entirely the wrong way. Currently, as a hack, I am simply copying > the code from Common into the other two directories, and making a link to the Part1 > directory in the Part2 so I can import it. There must be a better way, yes? > > thanks, > > Brian Blais > > -- > ----------------- > > bbl... at bryant.edu > http://web.bryant.edu/~bblais It looks like you need __init__.py in MyPackage. Then you can import starting with MyPackage. For example, you might use one of the following: import MyPackage from MyPackage.Common import * etc -- Carlos Hanson From misterwang at gmail.com Fri May 18 11:48:35 2007 From: misterwang at gmail.com (Peter Wang) Date: 18 May 2007 08:48:35 -0700 Subject: (Modular-)Application Framework / Rich-Client-Platform in Python In-Reply-To: References: <1179485905.764950.124000@p77g2000hsh.googlegroups.com> Message-ID: <1179503315.889565.166710@q75g2000hsh.googlegroups.com> On May 18, 10:15 am, Wildemar Wildenburger wrote: > stefaan wrote: > > To make it short again:http://code.enthought.com/ets/ > > Nice, seems very interesting. Bit of a bitch to set up, as it appears > from scanning the site, but that might be it. Actually, just this week, we completed a major SVN reorganization and from this point forward, all of the libraries in ETS will be released as eggs. In fact, eggs have been available for a long time for python 2.4, and now we have them for python 2.5 as well. The "Eclipse in python" you're looking for is actually called Envisage, and it is part of ETS: https://svn.enthought.com/enthought/wiki/Envisage The "Dev Guide" has some tutorials etc.: https://svn.enthought.com/enthought/wiki/EnvisageDevGuide Note that Envisage != ETS. "ETS" is the term for the whole bundle of various Enthought libraries, including Traits, Chaco, Pyface, etc. Envisage does require some of these others (notably Traits and Pyface), but they are all available as eggs. > Now for the everlasting circle of evaluating, feature-wanting, > to-write-myself-deciding, failing, for-the-next-big-idea-waiting, > asking, evaluationg, ... Chime in on the mailing list if you have any questions. It's pretty active and many people on it have lots of experience with Envisage. -Peter From gert.cuykens at gmail.com Fri May 25 20:55:42 2007 From: gert.cuykens at gmail.com (gert) Date: 25 May 2007 17:55:42 -0700 Subject: How to get started as a xhtml python mysql freelancer ? In-Reply-To: References: <1180136893.220560.49340@q75g2000hsh.googlegroups.com> Message-ID: <1180140942.239003.94640@h2g2000hsg.googlegroups.com> On May 26, 2:09 am, Paul McNett wrote: > gert wrote: > > I made something that i was hoping it could make people happy enough > > so i could make a living by providing support for commercial use of > >http://sourceforge.net/projects/dfo/ > > > But in reality i am a lousy sales men and was wondering how you people > > sell stuff as a developer ? > > In my experience, you don't make money by selling support unless you are > a large company selling support for a large project or a wide array of > projects. The people that will use your library will mostly be > developers and not end-users, after all. > > To make money from things you develop, I think you need to take your > library and either build an application that has wide appeal and sell > that, or sell yourself as a custom developer that can build the > application the customer needs, using the tools you are comfortable > with. You can then build in the cost of developing your library that you > will reuse for the custom applications. And where do you find customers, most people i talk too fall a sleep let alone understand when i say the word xhtml ? > What does it do exactly. Forum, shop, appointments, invoice, EAN13 barcode or just simple sql statements web based. Code is very straight forward. Applications included are just examples of what mod_python basically can do for you. From C.delete_this.Sanders at BoM.GOv.AU Tue May 1 22:11:24 2007 From: C.delete_this.Sanders at BoM.GOv.AU (Charles Sanders) Date: Wed, 02 May 2007 12:11:24 +1000 Subject: scaling In-Reply-To: References: <1178029348.453693.33510@u30g2000hsc.googlegroups.com> Message-ID: <4637f34c$0$14017$c30e37c6@lon-reader.news.telstra.net> Gabriel Genellina wrote: [snip] > if x elif x>maxvalue: yield top > else: yield (x-minvalue)*top/(maxvalue-minvalue) [snip] Personally, I find yield min(top,max(0,(x-minvalue)*top/(maxvalue-minvalue))) or scaled_value = (x-minvalue)*top/(maxvalue-minvalue) yield min(top,max(0,scaled_value)) clearer, but I am aware that others disagree with this. Charles From tjreedy at udel.edu Mon May 28 13:09:10 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 28 May 2007 13:09:10 -0400 Subject: Formal interfaces with Python References: Message-ID: "Florian Lindner" wrote in message news:f3ees4$eud$1 at news.in.tum.de... | Hello, | some time ago I've heard about proposals to introduce the concecpt of | interfaces into Python. I found this old and rejected PEP about that: | http://www.python.org/dev/peps/pep-0245/ | | What is the current status of that? Check http://www.python.org/dev/peps/pep-3119/ Related are http://www.python.org/dev/peps/pep-3124/ http://www.python.org/dev/peps/pep-3141/ From steve at holdenweb.com Thu May 31 20:21:37 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 31 May 2007 20:21:37 -0400 Subject: implementing callback function In-Reply-To: <008a01c7a3ca$cabf1470$6701a8c0@aristotle> References: <008a01c7a3ca$cabf1470$6701a8c0@aristotle> Message-ID: Ron Provost wrote: > Within an application I'm working on. The app is written in multiple > layers such that lower layers provided services to higher layers. > Ideally in such an architecture, the high-level objects know about > lower-level ones, but lower-level objects know nothing about the > higher-level ones. There's only one problem. When this software was > originally wirtten, one of the low-level objects was given knowledge of > a higher-level object. This creates a really ugly dependency that I > want to eliminate. > > My solution (at least what I'm trying to implement) is a classic one. > When a low-level routine needs info from a higher-level routine, let the > higher-level routine provide a callback which the lower-level routine > can call. In this way, the lower-level routine knows nothing about > higher-level routines. > > However, Python is complaining about my implementation. It raises an > exception: TypeError: unbound method fn_impl() must be called with X > instance as first argument (got int instance instead) > > For simplicity, I've narrowed it down to a bit of sample code. class X > is my low-level service. > > class X( object ): > fn = None > > @staticmethod > def callX( n ): > return X.fn( n ) > > > Now, the following global stuff represents my higher-level routines: > > def fn_impl( n ): # my callback > return n + 1 > > X.fn = fn_impl # register my callback > > Now I can do something which forces my callback (fn_impl) to get called > > print X.callX( 3 ) > > > I think I would get '4' printed but instead get the above error. What > am I doing wrong? > Normally the callback would be an instance variable, not a class variable, so each instance could have its own callback. Why use a class at all if all instances use the same callback? So I don't really understand why callX is a static method either. How about (untested): class X(object): def __init__(self, callback): self.callback = callback def callX(self, n): return self.callback(n) def fn_impl(n): return n+1 x = X(fn_impl) print x.callX(3) If I'm right, you should see 4 if you paste this into an interpreter. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From gagsl-py2 at yahoo.com.ar Wed May 2 02:10:06 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 02 May 2007 03:10:06 -0300 Subject: os.path.join References: <1178072869.844914.59010@u30g2000hsc.googlegroups.com> <1178083903.677905.32710@c35g2000hsg.googlegroups.com> Message-ID: En Wed, 02 May 2007 02:31:43 -0300, escribi?: > A better question is why this doesn't work. > >>>> pathparts = ["/foo", "bar"] >>>> os.path.join(pathparts) > ['/foo', 'bar'] > > This should return a string in my opinion. I think it's a bug, but because it should raise TypeError instead. The right usage is os.path.join(*pathparts) -- Gabriel Genellina From tommy.nordgren at comhem.se Wed May 30 07:53:30 2007 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Wed, 30 May 2007 13:53:30 +0200 Subject: Unicode to HTML entities In-Reply-To: <1180453921.357081.89500@n15g2000prd.googlegroups.com> References: <1180453921.357081.89500@n15g2000prd.googlegroups.com> Message-ID: <4813A2AF-19FA-4F17-87EF-25B7CEE7AEBD@comhem.se> On 29 maj 2007, at 17.52, Clodoaldo wrote: > I was looking for a function to transform a unicode string into > htmlentities. Not only the usual html escaping thing but all > characters. > > As I didn't find I wrote my own: > > # -*- coding: utf-8 -*- > from htmlentitydefs import codepoint2name > > def unicode2htmlentities(u): > > htmlentities = list() > > for c in u: > if ord(c) < 128: > htmlentities.append(c) > else: > htmlentities.append('&%s;' % codepoint2name[ord(c)]) > > return ''.join(htmlentities) > > print unicode2htmlentities(u'S?o Paulo') > > Is there a function like that in one of python builtin modules? If not > is there a better way to do it? > > Regards, Clodoaldo Pinto Neto > In many cases, the need to use html/xhtml entities can be avoided by generating utf8- coded pages. ------------------------------------------------------ "Home is not where you are born, but where your heart finds peace" - Tommy Nordgren, "The dying old crone" tommy.nordgren at comhem.se From carsten at uniqsys.com Tue May 8 16:06:56 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 08 May 2007 16:06:56 -0400 Subject: chdir() In-Reply-To: <1178652809.436141.176900@u30g2000hsc.googlegroups.com> References: <1178652809.436141.176900@u30g2000hsc.googlegroups.com> Message-ID: <1178654816.3357.96.camel@dot.uniqsys.com> On Tue, 2007-05-08 at 12:54 -0700, HMS Surprise wrote: > Tried executing os.chdir("c:\twill") from a python Tk shell and got > the error message: > > WindowsError: [Error 123] The filename, directory name, or volume > label syntax is incorrect: 'c:\twill'. Backslash-t is a tab character, so you're trying to chdir to C:will, which is not a valid path name. Use a forward slash, double up the backslash, or use a raw string literal: os.chdir("c:/twill") os.chdir("c:\\twill") os.chdir(r"c:\twill") HTH, -- Carsten Haese http://informixdb.sourceforge.net From david at boddie.org.uk Wed May 16 04:50:58 2007 From: david at boddie.org.uk (David Boddie) Date: 16 May 2007 01:50:58 -0700 Subject: Distributing programs depending on third party modules. In-Reply-To: <-J6dnUQxANzMB9fbRVnzvAA@telenor.com> References: <53357$4649c4a6$4275d90a$20775@FUSE.NET> <-J6dnUQxANzMB9fbRVnzvAA@telenor.com> Message-ID: <1179305458.664062.121800@l77g2000hsb.googlegroups.com> On May 16, 7:44 am, Tina I wrote: > A binary would be ideal. I'll look into the freeze modules and > Pyinstaller. Even if they don't handle huge things like Qt it would be a > step in the right direction if it handles smaller third part modules. > And maybe the smartest thing to do would be to dump PyQt and just > go for tkinter, however ugly it is :/ It's may be worth reading this message before making such a drastic decision: http://www.riverbankcomputing.com/pipermail/pyqt/2007-May/016092.html David ;-) From mail at timgolden.me.uk Fri May 11 11:45:21 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 11 May 2007 16:45:21 +0100 Subject: Better way to isolate string In-Reply-To: <1178897702.872729.72050@y5g2000hsa.googlegroups.com> References: <1178896888.721679.207240@n59g2000hsh.googlegroups.com> <1178897702.872729.72050@y5g2000hsa.googlegroups.com> Message-ID: <46448F91.5000201@timgolden.me.uk> HMS Surprise wrote: > I suppose a one liner would look better, but I am alway leery of these > things 'breaking'. > > t = s.split('">')[-1].split('<')[0] > s ='G132153' Only if you're competing in an obscurity competition ;) If you're really confined to built-ins (ie you can't import a single module) then just go with your original solution. Why not? If you can import modules, then you want to look at the urlparser and cgi modules, I suspect. TJG From konrad.hinsen at laposte.net Tue May 22 03:42:44 2007 From: konrad.hinsen at laposte.net (Konrad Hinsen) Date: Tue, 22 May 2007 09:42:44 +0200 Subject: Installing Python in a path that contains a blank In-Reply-To: <15e66e4e0705211534w2876b365n176c759a9ccc15e3@mail.gmail.com> References: <46521C71.8010602@lexicon.net> <15e66e4e0705211534w2876b365n176c759a9ccc15e3@mail.gmail.com> Message-ID: <9E32EA51-E194-4E7A-A06E-40C52476E896@laposte.net> On 22.05.2007, at 00:34, Greg Donald wrote: > On 5/21/07, John Machin wrote: >> Is there not a similar trick on MacOS X? > > It's called a symlink: > > ln -s /Users/gdonald /foo Right, but since I have no write permissions anywhere except in my home directory (whose path already has the blank), links won't help me. Konrad. From aspineux at gmail.com Thu May 24 13:02:21 2007 From: aspineux at gmail.com (aspineux) Date: 24 May 2007 10:02:21 -0700 Subject: modifying values of List or Dictionary when iterating on them Message-ID: <1180026141.723991.303810@p47g2000hsd.googlegroups.com> Hello I just want to update the data inside List or Dictionary without adding or deleting object. is this correct ? l=[1, 2, 3] for i, v in enumerate(l): l[i]=v+1 d=dict(a=1, b=2, c=3) for k, v in d.iteritems(): d[k]=d[k]+1 Both works, but : are they correct ? are they optimum for big structure ? Thanks From timr at probo.com Sat May 5 19:42:33 2007 From: timr at probo.com (Tim Roberts) Date: Sat, 05 May 2007 23:42:33 GMT Subject: High resolution sleep (Linux) References: <1178274122.142071.91740@y5g2000hsa.googlegroups.com> Message-ID: John wrote: > >The table below shows the execution time for this code snippet as >measured by the unix command `time': > >for i in range(1000): > time.sleep(inter) > >inter execution time ideal >0 0.02 s 0 s >1e-4 4.29 s 0.1 s >1e-3 4.02 s 1 s >2e-3 4.02 s 2 s >5e-3 8.02 s 5 s > >Hence it seems like the 4 s is just overhead and that the time.sleep >method treats values below approximately 0.001 as 0. > >Is there a standard way (or slick trick) to get higher resolution? If >it is system dependent it's acceptable but not very nice :) Consider what you're asking here. The operating system can only age the timer list and re-evaluate process ready states when a process goes into kernel mode, either by releasing the CPU or hitting the end of its time slice. In order to know that a process has reached the end of its time slice, it has to be interrupted by something, typically the timer interrupt. In order to provide 10us sleep resolution, the timer interrupt would have to fire every 10us. The overhead of handling the timer interrupt and rescheduling that often is quite significant. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From bbxx789_05ss at yahoo.com Sat May 19 13:41:53 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 19 May 2007 10:41:53 -0700 Subject: Many-to-many pattern possiable? In-Reply-To: <1179592414.652507.4110@p77g2000hsh.googlegroups.com> References: <1179592414.652507.4110@p77g2000hsh.googlegroups.com> Message-ID: <1179596513.126461.282380@n59g2000hsh.googlegroups.com> On May 19, 10:33 am, Jia Lu wrote: > Hi all > > I see dict type can do 1-to-1 pattern, But is there any method to do > 1-to-many, many-to-1 and many-to-many pattern ? How about: one_to_many = {"a":[10, "red", 2.5]} many_to_1 = {("red", 2.5, 3):"hello"} many_to_many = {("red", 2.5, 3):[10, 20, 30]} In reality, everything is mapped 1-1. I wonder if there is a computer language where that isn't the case? From nogradi at gmail.com Tue May 1 06:08:21 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Tue, 1 May 2007 12:08:21 +0200 Subject: sqlite for mac? In-Reply-To: <1177993261.572563.70370@n76g2000hsh.googlegroups.com> References: <1177993261.572563.70370@n76g2000hsh.googlegroups.com> Message-ID: <5f56302b0705010308h5c3f64a8ka05cd92de879f6bd@mail.gmail.com> > Does sqlite come in a mac version? > The interface (pysqlite) is part of the python 2.5 standard library but you need to install sqlite itself separately (as far as I remember) from www.sqlite.org Daniel From aahz at pythoncraft.com Wed May 30 20:28:39 2007 From: aahz at pythoncraft.com (Aahz) Date: 30 May 2007 17:28:39 -0700 Subject: Off Topic: What is the good book to learn Python ? References: <1180549522.350380.276570@q66g2000hsg.googlegroups.com> Message-ID: In article , kaens wrote: > >I would also recommend to stay away from any "for dummies" or "in x >(hours/days)" books. They can be decent introductory material, but >unless you are really really new to programming, you probably wouldn't >be getting enough information to justify the cost of the book (and a >lot of times they have a lot of bad practices in them) Maybe you should try actually reading _Python for Dummies_. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From san.gujar at gmail.com Tue May 22 11:00:14 2007 From: san.gujar at gmail.com (sandeep patil) Date: 22 May 2007 08:00:14 -0700 Subject: how to use python to checking password on servlet Message-ID: <1179846014.641052.118540@36g2000prm.googlegroups.com> my application design on java servlet i want to check password in python & return result again servlet to forward to next page. how to set session in python .get session From mensanator at aol.com Fri May 25 23:22:38 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 25 May 2007 20:22:38 -0700 Subject: Long double in Python In-Reply-To: References: Message-ID: <1180149758.889834.108080@q66g2000hsg.googlegroups.com> On May 25, 2:40?pm, Charles Vejnar wrote: > Hi, > > I have a C library using "long double" numbers. I would like to be able to > keep this precision in Python (even if it's not portable) : for the moment I > have to cast the "long double" numbers to "double" numbers. > > 1st solution . Is it possible that by re-compiling Python, Python Float object > becomes "long double" C type instead of "double" ? > 2nd solution : Numpy. In memory, a "numpy.longdouble" is a C "long double" or > a string ? Have you tried gmpy? import gmpy print 'default precision' for e in xrange(10): r = gmpy.mpq(2**e,3**e) # rational print gmpy.mpf(r) # float print print '128-bit precision' for e in xrange(10): r = gmpy.mpq(2**e,3**e) print gmpy.mpf(r,128) ## default precision ## 1.0 ## 0.666666666666666666667 ## 0.444444444444444444444 ## 0.296296296296296296296 ## 0.197530864197530864198 ## 0.131687242798353909465 ## 0.08779149519890260631 ## 0.0585276634659350708733 ## 0.0390184423106233805822 ## 0.0260122948737489203882 ## ## 128-bit precision ## 1.0 ## 0.6666666666666666666666666666666666666667 ## 0.4444444444444444444444444444444444444444 ## 0.2962962962962962962962962962962962962963 ## 0.1975308641975308641975308641975308641975 ## 0.1316872427983539094650205761316872427984 ## 0.08779149519890260631001371742112482853224 ## 0.05852766346593507087334247828074988568816 ## 0.03901844231062338058222831885383325712544 ## 0.02601229487374892038815221256922217141696 > > Thank you. > > Charles From jzgoda at o2.usun.pl Mon May 14 03:39:54 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Mon, 14 May 2007 09:39:54 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: Alexander Schmolck napisa?(a): >>> So, please provide feedback, e.g. perhaps by answering these >>> questions: >>> - should non-ASCII identifiers be supported? why? >> No, because "programs must be written for people to read, and only >> incidentally for machines to execute". Using anything other than "lowest >> common denominator" (ASCII) will restrict accessibility of code. This is >> not a literature, that requires qualified translators to get the text >> from Hindi (or Persian, or Chinese, or Georgian, or...) to Polish. >> >> While I can read the code with Hebrew, Russian or Greek names >> transliterated to ASCII, I would not be able to read such code in native. > > Who or what would force you to? Do you currently have to deal with hebrew, > russian or greek names transliterated into ASCII? I don't and I suspect this > whole panic about everyone suddenly having to deal with code written in kanji, > klingon and hieroglyphs etc. is unfounded -- such code would drastically > reduce its own "fitness" (much more so than the ASCII-transliterated chinese, > hebrew and greek code I never seem to come across), so I think the chances > that it will be thrust upon you (or anyone else in this thread) are minuscule. I often must read code written by people using some kind of cyrillic (Russians, Serbs, Bulgarians). "Native" names transliterated to ascii are usual artifacts and I don't mind it. > BTW, I'm not sure if you don't underestimate your own intellectual faculties > if you think couldn't cope with greek or russian characters. On the other hand > I wonder if you don't overestimate your ability to reasonably deal with code > written in a completely foreign language, as long as its ASCII -- for anything > of nontrivial length, surely doing anything with such code would already be > orders of magnitude harder? While I don't have problems with some of non-latin character sets, such as greek and cyrillic (I was attending school in time when learning Russian was obligatory in Poland and later I learned Greek), there are a plenty I wouldn't be able to read, such as Hebrew, Arabic or Persian. -- Jarek Zgoda "We read Knuth so you don't have to." From kw at codebykevin.com Tue May 15 10:33:08 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Tue, 15 May 2007 10:33:08 -0400 Subject: Distributing programs depending on third party modules. In-Reply-To: References: Message-ID: <53357$4649c4a6$4275d90a$20775@FUSE.NET> Tina I wrote: > Hi list, > > Is there a preferred way to distribute programs that depends on third > party modules like PyQt, Beautifulsoup etc? I have used setuptools and > just having the setup script check for the existence of the required > modules. If they're not found I have it exit with a message that it need > this or that installed. > > But this is not very convenient for the end user and I have got a few > complaints about it. Am I missing something in setuptools or is there a > better way to do it (except for bundling the modules in the package > which seem like a rather nasty workaround)? > > Thanks > Tina What platform are you doing this on? On the Linux platform, "dependency hell" of this sort is pretty much unavoidable, because there are so many different packaging systems (apt, rpm, and so on): it's standard to let the package manager handle these dependencies. And yes, it is frustrating for end users. On Windows and the Mac, bundling all the modules isn't a "nasty workaround"; it's the standard behavior. End users on those platforms expect complete application packages, including all supporting libraries, to be provided by the developers. The standard tools for doing this are py2exe for Windows (http://www.py2exe.org/) and py2app for Mac (http://svn.pythonmac.org/py2app/py2app/trunk/doc/index.html). There are other methods for distributing "frozen binaries," including the freeze module that ships with Python itself, cx_freeze, and PyInstaller: these three may work on Linux/Unix as well as Windows (they are not supported on the Mac). But the methods above are generally the ones most widely used. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From mail at timgolden.me.uk Tue May 8 08:34:54 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 08 May 2007 13:34:54 +0100 Subject: Specification for win32com.client package In-Reply-To: <23617.87850.qm@web63415.mail.re1.yahoo.com> References: <23617.87850.qm@web63415.mail.re1.yahoo.com> Message-ID: <46406E6E.9000501@timgolden.me.uk> Peter Fischer wrote: > Hello Tim, > > thank you for your answer and sorry for the multiple e-mails. Thank you also for > the hint on the book. I already read into it in our local library. Its good, but a > little outdated (Jan. 2000) as I mentioned in > > http://mail.python.org/pipermail/python-list/2007-May/438800.html Ah, yes. Didn't spot that. Although the book is outdated, so is COM! It's been around in pretty much its present format for wasily as long as that. > Do you know, whether something has changed, since the book was written, in > the use of the dcomcnfg tool? I wouldn't know, but I doubt it; it looks pretty old-fashioned to me. Worth checking some microsoft newsgroups. > I am not clear what steps are necessary under today's WinXP Professional > to get DCOM run. But it is said that it shouldn't be difficult. Certainly I've got no problem running simple stuff. My main area of expertise - WMI - uses it under the covers and it only gives me problems when there's security involved. > One short question back to the documentation: I read that 'makepy' could be > helpful to generate documentation to the package? AFAIK, makepy's got nothing to do with the pywin32 docs. It can be used to generate a proxy Python module for an existing COM package, eg: from win32com.client import gencache xl = gencache.EnsureDispatch ("Excel.Application") # # Behind the scenes this has called makepy to generate # a module which on my machine is under # c:\python24\lib\site-packages\win32com\gen_py # help (xl.__class__) Sorry I can't be more help. I know Mark Hammond follows the python-win32 list; I don't know if he follows the main Python list, so it might be worth posting to python-win32. TJG From half.italian at gmail.com Wed May 23 16:22:45 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 23 May 2007 13:22:45 -0700 Subject: Parallel/distributed generator In-Reply-To: <1179943256.575473.62610@q66g2000hsg.googlegroups.com> Message-ID: <1179948840.975791.236940@n15g2000prd.googlegroups.com> On May 23, 11:00 am, George Sakkis wrote: > I'm looking for any existing packages or ideas on how to implement the > equivalent of a generator (in the Python sense, i.e.http://www.python.org/dev/peps/pep-0255/) in a parallel/distributed > way. As a use case, imagine a function that generates a range of > primes. I'd like to be able to do something along the following lines: > > def iterprimes(start=1, end=None): > # ... > yield prime > > # rpc-related initialization > ... > rpc_proxy = some_rpc_lib(iterprimes, start=1e6, end=1e12) > for prime in proxy: > print prime > > Is there any module out there that does anything close to this ? > > George Parellel Python? http://www.parallelpython.com/content/view/17/31/#SUM_PRIMES I've never used it, but looks like it does what you are looking for. ~Sean From attn.steven.kuo at gmail.com Tue May 1 13:42:29 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 1 May 2007 10:42:29 -0700 Subject: sqlite for mac? In-Reply-To: <1178039558.882802.214030@n59g2000hsh.googlegroups.com> References: <1177993261.572563.70370@n76g2000hsh.googlegroups.com> <1178039558.882802.214030@n59g2000hsh.googlegroups.com> Message-ID: <1178041349.798184.268640@l77g2000hsb.googlegroups.com> On May 1, 10:12 am, 7stud wrote: > On May 1, 4:08 am, "Daniel Nogradi" wrote: > > > > Does sqlite come in a mac version? > > > The interface (pysqlite) is part of the python 2.5 standard library > > but you need to install sqlite itself separately (as far as I > > remember) fromwww.sqlite.org > > > Daniel > > I'm using python 2.4.4 because the download said there were more mac > modules available for 2.4.4. than 2.5, and I can't seem to locate a > place to download sqlite for mac. Did you install Xcode on your Mac? If so then you should have access to a C compiler allowing you to compile sqlite from source: http://sqlite.org/download.html I checked fink (finkproject.org) but that web site shows no binary distributions for sqlite3: http://pdb.finkproject.org/pdb/package.php/sqlite3 -- Hope this helps, Steven From prad at towardsfreedom.com Fri May 4 22:46:15 2007 From: prad at towardsfreedom.com (prad) Date: Fri, 04 May 2007 19:46:15 -0700 Subject: Looping over lists In-Reply-To: <64D2C5F9-2896-47C3-8606-B021DB9D378A@mac.com> References: <64D2C5F9-2896-47C3-8606-B021DB9D378A@mac.com> Message-ID: <200705041946.15810.prad@towardsfreedom.com> On Friday 04 May 2007 18:40:53 Tommy Grav wrote: > Can anyone help me with the right approach for this > in python? for each in a: for item in a[a.index(each)+1:]: print each,item will produce 1 2 1 3 1 4 1 5 2 3 2 4 2 5 3 4 3 5 4 5 a.index(each) gives the index of the each value in the a list. then you just add 1 to it so you start at the index value beside each's index. -- In friendship, prad ... with you on your journey Towards Freedom http://www.towardsfreedom.com (website) Information, Inspiration, Imagination - truly a site for soaring I's From steve at holdenweb.com Sat May 19 21:53:00 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 19 May 2007 21:53:00 -0400 Subject: regex matching question In-Reply-To: <464FA8B7.9070408@lexicon.net> References: <1179595319.239229.262160@l77g2000hsb.googlegroups.com> <464F86F0.8080100@lexicon.net> <1179620336.327038.253920@h2g2000hsg.googlegroups.com> <464FA8B7.9070408@lexicon.net> Message-ID: John Machin wrote: > On 20/05/2007 10:18 AM, bullockbefriending bard wrote: >>> Instead of the "or match.group(0) != results" caper, put \Z (*not* $) at >>> the end of your pattern: >>> mobj = re.match(r"pattern\Z", results) >>> if not mobj: >> as the string i am matching against is coming from a command line >> argument to a script, is there any reason why i cannot get away with >> just $ given that this means that there is no way a newline could find >> its way into my string? > > No way? Famous last words :-) > > C:\junk>type showargs.py > import sys; print sys.argv > > C:\junk>\python25\python > 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 subprocess > >>> subprocess.call('\\python25\\python showargs.py teehee\n') > ['showargs.py', 'teehee\n'] > 0 > >>> > > > certainly passes all my unit tests as well as >> \Z. or am i missing the point of \Z ? >> The simple shell command python prog.py "argument containing a newline" would suffice to reject the "no newlines" hypothesis in Unix-like systems. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From nagle at animats.com Thu May 31 01:37:06 2007 From: nagle at animats.com (John Nagle) Date: Thu, 31 May 2007 05:37:06 GMT Subject: is there a standard way to "install" egg-files under windows ? In-Reply-To: <5c5u7lF2v1pm3U1@mid.uni-berlin.de> References: <4c205$465dbe2b$d443bb3a$17537@news.speedlinq.nl> <5c5u7lF2v1pm3U1@mid.uni-berlin.de> Message-ID: <6at7i.6773$5j1.4204@newssvr21.news.prodigy.net> Diez B. Roggisch wrote: > Stef Mientki schrieb: > >> hello, >> >> after 4 months playing around with Python, >> and I still have troubles with egg files. >> Sometimes it works, sometimes it doesn't. >> >> If I google on "python egg", I get lost of links, >> which contains huge pages of information, >> and I'm totally scared off. ".egg" files are actually ".zip" files. So you can rename them to ".zip" and unpack them where they need to go. This is usually easier than debugging "easy_install". John Nagle From sidewinder.asu at gmail.com Tue May 22 21:49:04 2007 From: sidewinder.asu at gmail.com (Christopher Anderson) Date: Tue, 22 May 2007 18:49:04 -0700 Subject: Windows Debugging w/o MS Message-ID: <5a12a1120705221849u3ac673e0ga77c0961f845a5a9@mail.gmail.com> Hello all. I have a fairly fundamental question that I have been googling like crazy, but I can only seem to find really outdated or unreliable info: I am trying to build an extension module written in C++ on windows XP. I am trying to use only open-source tools, such as mingw. I'm using the Python 2.5 official, and it seems to compile my module just fine (I'm using the --compiler=mingw32). I can also import the module. The problem is, when I attempt to use it, I get a segfault. Now, I'm pretty sure this segfault is just a bug in my C++ code. So of course, I would like to debug this thing somehow. I tried using the mingw gdb giving it my python.exe to run, but obviously this python has no debug info, and wasn't even compiled with mingw. I was hoping it would still somehow debug my extension module right, but when I do a backtrace after it segfaults, I get nothing useful. I've tried compiling python from source, and my extension module, using MSVC8 (free express version), and I managed to get this to work. The thing is, I don't want to have to recompile every single python package I need (wxPython, SciPy, etc). So basically, I need some general advice for how to compile and debug extension modules on windows using only open-source tools. I am still amazed that MSVC7.1 was chosen for the official python release and not mingw, has anyone explained this? Thank you so much for your time, Chris Anderson From kyosohma at gmail.com Tue May 29 09:51:44 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 29 May 2007 06:51:44 -0700 Subject: wxpython demo error on debian etch In-Reply-To: <1180445918.523446.133300@g4g2000hsf.googlegroups.com> References: <1180445918.523446.133300@g4g2000hsf.googlegroups.com> Message-ID: <1180446704.521350.72450@k79g2000hse.googlegroups.com> On May 29, 8:38 am, BartlebyScrivener wrote: > If there is a wxPython on Debian user in the house? I am using the > version of the demo that came with the apt-get download of wxPython. > > I thought I'd followed the instructions for installing and unpacking > the wxPython demo program. It appears to run after a fashion, but I > also get this at the commandline. > > Any help much appreciated. > > (python:5865): Gtk-CRITICAL **: gtk_window_realize_icon: assertion > `info->icon_pixmap == NULL' failed > Traceback (most recent call last): > File "/usr/lib/python2.4/site-packages/wx-2.6-gtk2-unicode/wx/ > _misc.py", line 1286, in Notify > self.notify() > File "/usr/lib/python2.4/site-packages/wx-2.6-gtk2-unicode/wx/ > _core.py", line 13637, in Notify > self.result = self.callable(*self.args, **self.kwargs) > File "/home/rick/bin/wxPython/Main.py", line 1713, in ShowMain > if self.fc.IsRunning(): > File "/usr/lib/python2.4/site-packages/wx-2.6-gtk2-unicode/wx/ > _core.py", line 13481, in __getattr__ > raise PyDeadObjectError(self.attrStr % self._name) > wx._core.PyDeadObjectError: The C++ part of the MySplashScreen object > has been deleted, attribute access no longer allowed. > > Thanks, > > Rick The problem is probably that it's older. I'm guessing it's either a bug that's been fixed or something that's deprecated. The wxPython website details how to get the latest version of wxPython (2.8.4) here: http://wxpython.org/download.php I'm not an expert with the wxPython errors. I would recommend that you also ask at the wxPython user's group: http://wxpython.org/maillist.php Hope that helps a little! Mike From S.Mientki-nospam at mailbox.kun.nl Mon May 28 11:43:14 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Mon, 28 May 2007 17:43:14 +0200 Subject: ten small Python programs In-Reply-To: References: Message-ID: <301fc$465af7b4$d443bb3a$22913@news.speedlinq.nl> Steve Howell wrote: > I've always thought that the best way to introduce new > programmers to Python is to show them small code > examples. > This is really a nice piece of missing Python. Sorry I didn't follow this thread accurately, but have you considered to produce an example environment like in wxPython ? The wxPython demo program is written as an interactive tutorial, with a few hundred examples, nicely ordered in groups. The user can view the demo, the code and the help text. The user can also change the code and see the results right away. It would even be nicer, if everybody could drop her/his examples in a standard way, so they would be automatically incorporated in something like the wxPython interactive demo. cheers, Stef Mientki From mail at timgolden.me.uk Mon May 7 09:34:19 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 07 May 2007 14:34:19 +0100 Subject: Can Python Parse an MS SQL Trace? In-Reply-To: <1178544236.856685.288740@y80g2000hsf.googlegroups.com> References: <1178544236.856685.288740@y80g2000hsf.googlegroups.com> Message-ID: <463F2ADB.6040205@timgolden.me.uk> kyosohma at gmail.com wrote: > Can Python parse a trace file created with MS SQL's profiler? There > are a few thousand lines in the trace file and I need to find the > insert statements and the stored procedures. Unfortunately, I am not > an SQL guru and was hoping Python could help. > Mike Mike, Can I suggest that, since the answer is more to do with parsing and less to do with MSSQL (which simply generated the output) that you post an example of a trace file to some web location to see if anyone wants to pick up the challenge? I'm not at work so I don't have access to MSSQL, but I seem to remember that you can output/save as XML, which may make things easier (or at least interest a different group of people in having a look). I'm quite certain it can by done by Python; I did consider it myself a couple of months back, but my colleague spotted the problem before I'd really got into the code! TJG From arunmail at gmail.com Thu May 10 18:19:53 2007 From: arunmail at gmail.com (lazy) Date: 10 May 2007 15:19:53 -0700 Subject: Newbie question about string(passing by ref) In-Reply-To: <1178834254.099555.306750@l77g2000hsb.googlegroups.com> References: <1178833397.076720.279940@l77g2000hsb.googlegroups.com> <1178833659.400428.185630@u30g2000hsc.googlegroups.com> <1178834254.099555.306750@l77g2000hsb.googlegroups.com> Message-ID: <1178835593.771846.270750@u30g2000hsc.googlegroups.com> Thanks all. > the function you pass it to assigns some other value to the variable, > that's all it's doing: reassigning a local name to point to somewhere > else in memory. So, just to make sure even if I return a value, there is no copy done. Is it correct? For eg: def blah: long_str="...." return long_str my_str=blah() <=== So here there is no copy done but, my_str points to the same memory where long_str was created. Thanks again. On May 10, 2:57 pm, Adam Atlas wrote: > On May 10, 5:47 pm, Adam Atlas wrote: > > > On May 10, 5:43 pm, lazy wrote: > > > > I want to pass a string by reference. > > > Don't worry, all function parameters in Python are passed by reference. > > Actually, just to clarify a little bit if you're understanding "pass > by reference" in the sense used in PHP, sort of C, etc.: In Python, > you have objects and names. When I say all function parameters are > passed by reference, I don't mean you're actually passing a reference > to the *variable*. (Like in PHP where you pass a variable like &$foo > and the function can change that variable's value in the caller's > scope.) You can never pass a reference to a variable in Python. But on > the other hand, passing a parameter never causes the value to be > copied. Basically, you have a variable that's a reference to an object > somewhere in memory, and passing it to a function gives that > function's scope a new pointer to that same location in memory. So if > the function you pass it to assigns some other value to the variable, > that's all it's doing: reassigning a local name to point to somewhere > else in memory. From gagsl-py2 at yahoo.com.ar Wed May 2 02:12:31 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 02 May 2007 03:12:31 -0300 Subject: Problem with inspect.getfile References: <1178041715.206440.134530@y80g2000hsf.googlegroups.com> <1178085235.386994.258310@e65g2000hsc.googlegroups.com> Message-ID: En Wed, 02 May 2007 02:53:55 -0300, elventear escribi?: > Found the offending code. I was importing between files that were at > the same level of the hierarchy without using absolute references. > Coded worked fine, but inspect didn't. Was this gaffe on my part? Or > was inspect supposed to handle it? Could you provide an example? -- Gabriel Genellina From martin at v.loewis.de Tue May 8 17:12:01 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 08 May 2007 23:12:01 +0200 Subject: Another easy pair of questions In-Reply-To: <1178655556.202998.241870@e65g2000hsc.googlegroups.com> References: <1178655556.202998.241870@e65g2000hsc.googlegroups.com> Message-ID: <4640E7A1.7000902@v.loewis.de> > In a python Tk shell in Windows, what is the equivalent of unix's pwd? os.getcwd() > In a python Tk shell in Windows, is there an easy way to reoeat an > earlier command, similar to Tcl/Tk's hist? Press the cursor-up key. Martin From pavlovevidence at gmail.com Wed May 30 21:44:08 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 30 May 2007 18:44:08 -0700 Subject: Is PEP-8 a Code or More of a Guideline? In-Reply-To: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> Message-ID: <1180575848.698433.289180@h2g2000hsg.googlegroups.com> On May 26, 11:36 pm, Paul McGuire wrote: > Steve, sorry for taking your thread down a rathole. I hope we can > move any further PEP-8-related discussion (if the point merits any) to > this thread. Identifiers should just allow spaces. first element.get item(selected value) This is not a joke. I don't mean Python should necessarily do this (though it could be done without any ambiguity or backward incompatibility: there is currently nowhere in Python where two identifiers can be separated by only a space), but new languages should be designed to allow it. Carl Banks From stefan.behnel-n05pAM at web.de Tue May 15 09:03:00 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 15 May 2007 15:03:00 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <4649ae4a$0$20289$9b4e6d93@newsspool3.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476081.7080609@web.de> <46498514$0$6402$9b4e6d93@newsspool2.arcor-online.net> <4649882E.3060005@web.de> <46499940$0$10199$9b4e6d93@newsspool4.arcor-online.net> <46499BF9.30209@web.de> <4649a2c1$0$10193$9b4e6d93@newsspool4.arcor-online.net> <4649A429.3010406@web.de> <4649ae4a$0$20289$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <4649AF84.7010208@web.de> Ren? Fleschenberg wrote: > Stefan Behnel schrieb: >> And: if it's not a project you will ever getin touch with - what do >> you care? > > I just fear that I *will* get in touch with identifiers using non-ASCII > symbols if this PEP is implemented. That's easy to prevent: just keep your fingers from projects that work with them and make sure that projects you start do not use them. Stefan From aleax at mac.com Thu May 3 00:59:56 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 2 May 2007 21:59:56 -0700 Subject: How to check if a string is empty in python? References: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> <1178138964.503290.254060@o5g2000hsb.googlegroups.com> <1178139155.260722.153750@n59g2000hsh.googlegroups.com> <463917d1$0$2415$426a74cc@news.free.fr> <1178149602.018706.309200@o5g2000hsb.googlegroups.com> Message-ID: <1hxia3n.19x773917p8esxN%aleax@mac.com> mensanator at aol.com wrote: ... > >>> import gmpy > >>> gmpy.mpz(11) > mpz(11) > >>> gmpy.mpz('11',10) > mpz(11) > >>> gmpy.mpz(11,10) > > Traceback (most recent call last): > File "", line 1, in > gmpy.mpz(11,10) > TypeError: gmpy.mpz() with numeric argument needs exactly 1 argument > > The mpz conversion takes two arguments if and only if s is a string, > else it takes 1 argument. So being non-empty is insufficient. Being a string AND being non-empty is insufficient too -- just try gmpy.mpz("Hello, I am a string and definitely not empy!", 10) on for size. Alex From Goofy.throat6 at gmail.com Thu May 17 14:49:22 2007 From: Goofy.throat6 at gmail.com (Goofy.throat6 at gmail.com) Date: 17 May 2007 11:49:22 -0700 Subject: ^% Britney Spears Tits Explode!!!!! Message-ID: <1179427762.406923.72700@q75g2000hsh.googlegroups.com> http://scargo.in/ - Download britneys pics and videos for free!!!!! From walterbyrd at iname.com Wed May 16 17:36:07 2007 From: walterbyrd at iname.com (walterbyrd) Date: 16 May 2007 14:36:07 -0700 Subject: How do I count the number of spaces at the left end of a string? Message-ID: <1179351367.714864.47190@l77g2000hsb.googlegroups.com> I don't know exactly what the first non-space character is. I know the first non-space character will be * or an alphanumeric character. From sanxiyn at gmail.com Sun May 20 13:41:50 2007 From: sanxiyn at gmail.com (Sanghyeon Seo) Date: Mon, 21 May 2007 02:41:50 +0900 Subject: [ANN] IronPython Community Edition r6 Message-ID: <5b0248170705201041lf3446f3t94e7e4ab86d5b0c@mail.gmail.com> This is the sixth release of IronPython Community Edition (IPCE). Download from SourceForge: http://sourceforge.net/projects/fepy FePy project aims to provide enhancements and add-ons for IronPython. http://fepy.sourceforge.net/ This release is built with Mono 1.2.3.1. As this release has dropped a patch to support Mono without Socket.{Send,Receive}BufferSize implementation, it won't work with Mono versions below 1.2.3. It has been a long time (more than 5 months) since the last release. In the mean time, DLR-based IronPython 2.0 Alpha 1 was revealed, and it was subsequently ported to Mono. As this codebase is still new, IPCE will be based on IronPython 1.1 for the time being. Also note that IronPython 2.0 Alpha 1 has significant performance regression on Mono (but not on MS.NET) compared to IronPython 1.1. http://lists.ironpython.com/pipermail/users-ironpython.com/2007-May/004915.html Changes in this release follow. IronPython Updated to IronPython 1.1. Libraries Huge improvements to AST support. Support inspect.getargspec(). Pickle integration with .NET Serialization. platform module that can handle IronPython. (Anthony Baxter) Implement os.access(). (Rachel Hestilow) Bundles pybench benchmark (thanks to platform module). pyflakes code checker (thanks to AST support). wsgiref synced to 2.5.1. Patches You can read the summary of applied patches here. http://fepy.sourceforge.net/patches.html New in this release: patch-ironpython-import-hack -- Seo Sanghyeon From half.italian at gmail.com Sun May 13 00:04:31 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 12 May 2007 21:04:31 -0700 Subject: __dict__ for instances? In-Reply-To: References: Message-ID: <1179029071.282774.116050@h2g2000hsg.googlegroups.com> On May 12, 5:20 pm, Ivan Voras wrote: > While using PyGTK, I want to try and define signal handlers > automagically, without explicitly writing the long dictionary (i.e. I > want to use signal_autoconnect()). > > To do this, I need something that will inspect the current "self" and > return a dictionary that looks like: > > { > "method_name" : self.method_name > > } > > Class.__dict__ does something very similar, but when I use it, either > I'm doing something wrong or it doesn't return methods bound to "self", > and python complains a wrong number of arguments is being passed to the > methods (one instead of two). > > instance.__dict__ on the other hand returns an empty dictionary. > > This looks like it should be easy, but I can't find the solution :( > > -- > (\__/) > (O.o) > (> < ) > > This is Bunny. > Copy Bunny into your signature to help him on his way to world domination! > > signature.asc > 1KDownload I think you want "dir(instance)" __dict__ returns the instance variables and values as a dictionary, but doesn't return methods. dir() returns a list of the instance's methods and variables. Then you'd need to iterate over the list with type() looking for instance methods instance = Class.Class() dict = {} methods = [f for f in dir(instance) if str(type(instance.f)) == ""] for m in methods: dict[m.name] = m The above is untested. I'm sure there is a better way to do this. ~Sean From jstroud at mbi.ucla.edu Mon May 21 07:52:52 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 21 May 2007 04:52:52 -0700 Subject: converting strings to most their efficient types '1' --> 1, 'A' ---> 'A', '1.2'---> 1.2 In-Reply-To: <3LW3i.1216$C96.305@newssvr23.news.prodigy.net> References: <1179529661.555196.13070@k79g2000hse.googlegroups.com> <464E6F32.7070200@lexicon.net> <61B3i.6880$H_.138@newssvr21.news.prodigy.net> <464F93C1.8030305@lexicon.net> <42T3i.29504$Um6.11611@newssvr12.news.prodigy.net> <465017A0.1030901@lexicon.net> <3LW3i.1216$C96.305@newssvr23.news.prodigy.net> Message-ID: I need to correct myself here before someone else does. I didn't actually reverse the probabilities as promised for the failing case. It was late last night and I was starting to get a little cloudy. > Pf(D|H) = 0.2 (We *guess* a 20% chance by random any column is Int.) This can be read instead as "probability that it will fail the test given that it is really from an Int column", which is 20% of the time. > Pf(D|H') = 0.80 (80% of Ints fail because of carpel tunnel, ennui, etc.) This can be read as "probability it will fail the test if it is not really from an Int column". That would be Pf(D|H') = 0.95 (e.g. testing the inability to cast to Int is a pretty bad test for Int because it gives false positives 95% of the time). This change doesn't change the conclusions of the example, with the P_3(H|D) = 0.1505882 (lower than 20%, but no where near the 0.001 cutoff to conclude the column is not Int) and the final probability P_7(H|D) = 0.9986247 (rounding up to our 0.999 criteria for confidence that it is an Int ;). James From duncan.booth at invalid.invalid Fri May 11 11:09:03 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 May 2007 15:09:03 GMT Subject: Newbie look at Python and OO References: <1178812734.860473.236370@y80g2000hsf.googlegroups.com> <1178832102.256466.235020@l77g2000hsb.googlegroups.com> <13490canfv56c9c@corp.supernews.com> Message-ID: Grant Edwards wrote: > http://www.ariel.com.au/jokes/An_Interview_with_Bjarne_Stroustrup.html > > Maybe BS thought he was joking, but IMO, it's true. > > "Stroustrup: Remember the length of the average-sized 'C' > project? About 6 months. Not nearly long enough for a guy > with a wife and kids to earn enough to have a decent > standard of living. Take the same project, design it in C++ > and what do you get? I'll tell you. One to two years." > I doubt very much that BS was involved at any point in writing it. You forgot to quote the bit at the end: [Note - for the humor-impaired, not a true story] From bbxx789_05ss at yahoo.com Tue May 15 19:02:58 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 15 May 2007 16:02:58 -0700 Subject: inherit from file and create stdout instance? In-Reply-To: <1179267498.154549.58370@h2g2000hsg.googlegroups.com> References: <1179267498.154549.58370@h2g2000hsg.googlegroups.com> Message-ID: <1179270178.281061.34860@k79g2000hse.googlegroups.com> On May 15, 4:18 pm, MisterPete wrote: > How can I inherit from file but stil create an instance that writes to > stdout? > ----------- > I'm writing a file-like object that has verbosity options (among > some other things). I know I could just set self.file to a file object > rather than inheriting from file. I started with something like this > (simplified for clarity): > > class Output(object): > def __init__(self, file=sys.stdout, verbosity=1): > self.verbosity = verbosity > self.file = file > > def write(self, string, messageVerbosity=1): > if messageVerbosity <= self.verbosity: > self.file.write(string) > ... > > but it is frustrating me that if I try to inherit from file it > works fine for regular files but I can't figure out a clean way to > instantiate an object that writes to stdout using sys.stdout. > something like the following: > > class Output(object): > def __init__(self, file=sys.stdout, verbosity=1): > self.verbosity = verbosity > self.file = file > > def write(self, string, messageVerbosity=1): > if messageVerbosity <= self.verbosity: > self.file.write(string) > ... > > I hope that's clear. Is it just a bad idea to inherit from file to > create a class to write to stdout or am I missing something? Any > insight is appreciated. > > Thanks, > Pete Your code works for me: import sys class Output(file): def __init__(self, file=sys.stdout, verbosity=1): self.verbosity = verbosity self.file = file def write(self, string, messageVerbosity=1): if messageVerbosity <= self.verbosity: self.file.write(string) o = Output() o.write("this goes to a console window") f = open("aaa.txt", "w") o = Output(f) o.write("this goes to a file") From tijs_news at artsoftonline.com Wed May 30 09:03:08 2007 From: tijs_news at artsoftonline.com (Tijs) Date: Wed, 30 May 2007 15:03:08 +0200 Subject: How to print this character u'\u20ac' to DOS terminal References: <1180501468.957322.106650@z28g2000prd.googlegroups.com> <465D0A6B.1000203@v.loewis.de> <1180508736.598924.26170@r19g2000prf.googlegroups.com> Message-ID: <465d760d$0$338$e4fe514c@news.xs4all.nl> ??????????????? wrote: > But the string contained the u'\u20ac' is get from remote host. Is > there any method to decode it to the local 'mbcs'? remote_string = u'\u20ac' try: local_string = remote_string.encode('mbcs') except: # no mbcs equivalent available print "encoding error" else: # local_string is now an 8-bit string print "result:", local_string # if console is not mbcs, you should see incorrect result assert result == '\x80' Mbcs is windows-only so I couldn't test this. If your application handles text, it may be easier to just leave everything in Unicode and encode to utf-8 for storage? Regards, Tijs From basilisk96 at gmail.com Mon May 21 23:11:42 2007 From: basilisk96 at gmail.com (Basilisk96) Date: 21 May 2007 20:11:42 -0700 Subject: A few questions In-Reply-To: References: Message-ID: <1179803502.052509.183290@e65g2000hsc.googlegroups.com> > After this I went to the tutorial and started trying out some of the > examples. I pasted the code to separate text files and then ran them > through a Terminal window. This stuff is freaking cool!!! Now I > just have to figure out how this all works! > "wxPython in Action" is a decent book for learning wxPython: http://www.manning.com/rappin/ As with any GUI toolkit, there is a learning curve until you get used to how the components work together. But there is enough hands-on material to get started with simple GUI apps. > Anyway, I had one more quick question... in order to run wxPython > apps, do I have to have MacPython, etc. loaded on each Mac (or PC) in > order for it to run any apps I write? Or is there a way to compile > the code to where I can distribute an app I write and the other users > don't need to load anything in order to run the app? Again, I can't speak for Macs, but I know that for Windows there is one package suitably called "py2exe", available from http://www.py2exe.org/ which allows you to freeze your code and distribute it to multiple users as an executable file plus some extra baggage files containing bytecode and necessary DLL's, including the Python interpreter itself. This way, the end user does not need to install Python, wxPython, or any other Python libraries used by your project, nor does the end user even need to know anything about Python. Pros? The app is ready to run as shipped. Cons? Relatively large size of the distributable package - a typical simple GUI app is 6MB+ when packaged this way. Although... with the acres of storage space available on today's media, this is hardly a problem. :) From draghuram at gmail.com Tue May 1 15:31:25 2007 From: draghuram at gmail.com (draghuram at gmail.com) Date: 1 May 2007 12:31:25 -0700 Subject: Grabbing the output of a long-winded shell call (in GNU/Linux) In-Reply-To: <46378364$1@news.bezeqint.net> References: <46378364$1@news.bezeqint.net> Message-ID: <1178047885.767785.35320@h2g2000hsg.googlegroups.com> On May 1, 2:23 pm, Efrat Regev wrote: > So my question is if there's a way to "grab" the output as it's being > generated. It doesn't matter if the solution is blocking (as opposed to > callback based), since threads can handle this. I just don't know how to > "grab" the output. I appreciate your time in reading (and answering > this), as I've been googling several hours for this. There may be more pythonic solution than what I suggest here but this is what I have done when I needed similar functionality. Basically run your command in the background and redirect its stdout/err to a temp file. You may run the command either in the background or in a separate thread. You can then run the command "tail --retry -- pid= -n+0 -F " and grab the output. The tail command exits once the real command is done. Raghu. From nagle at animats.com Tue May 8 21:23:50 2007 From: nagle at animats.com (John Nagle) Date: Tue, 08 May 2007 18:23:50 -0700 Subject: High resolution sleep (Linux) In-Reply-To: References: <1178274122.142071.91740@y5g2000hsa.googlegroups.com> Message-ID: <8l90i.911$UU.403@newssvr19.news.prodigy.net> Hendrik van Rooyen wrote: > "Tim Roberts" wrote" > It is also possible to keep the timer list sorted by "expiry date", > and to reprogram the timer to interrupt at the next expiry time > to give arbitrary resolution, instead of implementing a regular 'tick'. Yes, and that's a common feature in real-time operating systems. If you're running QNX, you can expect that if your high priority task delays to a given time, you WILL get control back within a millisecond of the scheduled time. Even tighter timing control is available on some non-x86 processors. Some CPUs even have hardware support for a sorted event list. The Intel 8061, which ran the engines of most Ford cars in the 1980s, had that. But no way are you going to get consistent timing resolution like that from Python. It's an interpreter with a garbage collector, after all. John Nagle From charles.vejnar at isb-sib.ch Sat May 26 05:07:37 2007 From: charles.vejnar at isb-sib.ch (Charles Vejnar) Date: Sat, 26 May 2007 11:07:37 +0200 Subject: Long double in Python In-Reply-To: <200705252140.34353.charles.vejnar@isb-sib.ch> References: <200705252140.34353.charles.vejnar@isb-sib.ch> Message-ID: <200705261107.37352.charles.vejnar@isb-sib.ch> Hi, Thanks for both suggestions. I have indeed tried gmpy. For me, it's not very important to choose between numpy or gmpy. I hope I won't be off topic. But, as I told you before, I have a C library using "long double" numbers and I would like to be able to use it in Python. I try to build a module with Swig but I didn't find the C function to use in the wrapper to have a "numpy.longdouble" (or the equivalent in gmpy). Is it something possible ? Charles From siasookhteh at gmail.com Wed May 23 07:07:19 2007 From: siasookhteh at gmail.com (Siah) Date: 23 May 2007 04:07:19 -0700 Subject: Basic Class/Instance Question Message-ID: <1179918439.085344.171330@u30g2000hsc.googlegroups.com> Ready to go insane here. Class A, taking on a default value for a variable. Instantiating two separate objects of A() gives me a shared val list object. Just see the example bellow: class A(object): def __init__(self, val=[]): self.val=val obj1 = A() obj2 = A() print obj1 is obj2 # False - as expected print obj1.val is obj2.val # True! - Why... oh god WHY ----------- Using python 2.4. Is this a bug with this version of python? How can I trust the rest of the universe is still in place? Could she still like me? Many questions I have. Lets start with the python problem for now. Thanks, Sia From ptmcg at austin.rr.com Sun May 27 04:25:38 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 27 May 2007 01:25:38 -0700 Subject: Is PEP-8 a Code or More of a Guideline? In-Reply-To: References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> Message-ID: <1180254338.292249.29520@h2g2000hsg.googlegroups.com> On May 27, 1:25 am, Steven Bethard wrote: > Stefan Sonnenberg-Carstens wrote: > > Paul McGuire schrieb: > >> I'm starting a new thread for this topic, so as not to hijack the one > >> started by Steve Howell's excellent post titled "ten small Python > >> programs". > > >> In that thread, there was a suggestion that these examples should > >> conform to PEP-8's style recommendations, including use of > >> lower_case_with_underscores style for function names. I raised some > >> questions about this suggestion, since I liked the names the way they > >> were, but as a result, part of the discussion has drifted into a > >> separate track about PEP-8, and naming styles. > > > I prefer mixedCaseStyle, and I think that should be "standard", as this > > style is commonly > > used in all "major" languages , for example Java,C++,C#. > > It shortens the identifiers but leaves the meaning intact. > > The argument for under_score_names is usually that non-native speakers > can more easily find the word boundaries. Not being a non-native speaker > ;-) I can't verify that one, but it's pretty plausible given the current > amount of money spent on research on automatic word-segmentation for > languages like Chinese. =) > > STeVe- Hide quoted text - > > - Show quoted text - Here is the thread from python-dev where this change (from "mixedCase is no better or worse than lower_case_with_underscores" to "should use l_c_w_u") was discussed, a year ago last December: http://mail.python.org/pipermail/python-dev/2005-December/058750.html At first, Guido seemed ambivalent, and commented on the contentiousness of the issue, but it seems that the "non-English speakers can more easily find word breaks marked with underscores" justification tipped the scale in favor of lower_case_with_underscores. The PEP itself on www.python.org seems to have been updated as recently as May 17 of this year, but I don't seen any way to identify what the change history is. So, those who are the stewards of the core source code have nailed down thier coding standard to be l_c_w_u, so if sometime in the future I find myself working on any code in the Python std libs, l_c_w_u is the style to be followed. It just looks so old-fashioned... Whatev. -- Paul From wildemar at freakmail.de Thu May 17 14:09:22 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Thu, 17 May 2007 20:09:22 +0200 Subject: (Modular-)Application Framework / Rich-Client-Platform in Python Message-ID: <464C9A52.5060903@freakmail.de> To make it short: Is there something like this already? There seem to loads of python frameworks for Web-Apps, but I have a hard time finding one for desktop-apps. I imagine it wouldn't be too hard (if still time consuming) whipping up something simple myself, but I thought, I'd ask here before diving into it. greets wildemar From martin at v.loewis.de Thu May 17 09:07:14 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 17 May 2007 15:07:14 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179236673.893122.28800@w5g2000hsg.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> Message-ID: <464C5382.6080403@v.loewis.de> > After 175 replies (and counting), the only thing that is clear is the > controversy around this PEP. Most people are very strong for or > against it, with little middle ground in between. I'm not saying that > every change must meet 100% acceptance, but here there is definitely a > strong opposition to it. Accepting this PEP would upset lots of people > as it seems, and it's interesting that quite a few are not even native > english speakers. I believe there is a lot of middle ground, but those people don't speak up. I interviewed about 20 programmers (none of them Python users), and most took the position "I might not use it myself, but it surely can't hurt having it, and there surely are people who would use it". 2 people were strongly in favor, and 3 were strongly opposed. Of course, those people wouldn't take a lot of effort to defend their position in a usenet group. So that the majority of the responses comes from people with strong feelings either way is no surprise. Regards, Martin From grante at visi.com Thu May 24 16:59:25 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 24 May 2007 20:59:25 -0000 Subject: trouble converting c++ bitshift to python equivalent References: <1180037677.633613.30160@u30g2000hsc.googlegroups.com> Message-ID: <135bv5d8d5r8re6@corp.supernews.com> On 2007-05-24, Steve Holden wrote: >> i have two string bytes i need to push into a single (short) int, like >> so in c: >> >> temp = strBuf[2]; >> >> temp = (temp<<7)+(strBuf[1]); > You should really use the struct module for that type of conversion, The struct module doesn't know how to deal with the OP's case where only 7 bits are used from each byte. OTOH, if the 7 was a typo and he really wanted to shift by 8 bits, then struct is an option. > but you also need to know that indexing of lists and tuples > starts at 0, not 1. Ah yes. I wondered about that also, but I assumed what he acutally had was a two-byte field in a longer string. -- Grant Edwards grante Yow! Jesuit priests are at DATING CAREER DIPLOMATS!! visi.com From half.italian at gmail.com Thu May 24 23:24:49 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 24 May 2007 20:24:49 -0700 Subject: sockets, gethostname() changing In-Reply-To: <1180062244.266857.300830@m36g2000hse.googlegroups.com> References: <1180062244.266857.300830@m36g2000hse.googlegroups.com> Message-ID: <1180063489.535893.182970@x35g2000prf.googlegroups.com> On May 24, 8:04 pm, 7stud wrote: > Hi, > > I'm experimenting with a basic socket program(from a book), and both > the client and server programs are on my computer. In both programs, > I call socket.gethostname(), but I discovered that when I am connected > to the internet, both the client and server hang and nothing happens. > I discovered that the hostname of my computer automatically changes to > that of my isp when I'm connected to the internet, and presumably the > server program on my computer cannot listen on my isp's address(host, > port). Is there a way to make the hostname of my computer static, so > that it doesn't change to my isp's hostname when I connect to the > internet. I'm using mac os 10.4.7. Why does my computer's hostname > dynamically change in the first place? > > server program: > ------------------- > import socket > > s = socket.socket() > > host = socket.gethostname() > print host > port = 1274 > s.bind((host, port)) > > s.listen(5) > while("Ctrl-C hasn't been entered"): > c, addr = s.accept() #blocks and waits for client connection > print "Got socket connection from", addr > c.send("Thank you for connecting. Now get lost.") > c.close() > > client program: > ------------------- > import socket > > s = socket.socket() > > host = socket.gethostname() > port = 1274 > > s.connect((host, port)) > print s.recv(1024) > s.close() I can't imagine why your hostname would be changing, unless you installed some of their proprietary software thats messing around with things. What is the hostname set to in Sys Prefs->Sharing? Try setting it there. What are the before and after connection names you get? ~Sean From tjreedy at udel.edu Fri May 11 13:36:01 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 11 May 2007 13:36:01 -0400 Subject: software testing articles References: <1178889267.152525.230420@e65g2000hsc.googlegroups.com> Message-ID: wrote in message news:1178889267.152525.230420 at e65g2000hsc.googlegroups.com... | Have you ever been interested in software testing? Giving you an in | depth analysis/knowledge on software testing!! Random non-Python IT topics are spam. Please desist. [Link to page with 75% ads deleted] From wicijowski at gmail.com Thu May 17 04:29:33 2007 From: wicijowski at gmail.com (janislaw) Date: 17 May 2007 01:29:33 -0700 Subject: removing common elemets in a list In-Reply-To: <1179296224.885877.187200@q23g2000hsg.googlegroups.com> References: <1179296224.885877.187200@q23g2000hsg.googlegroups.com> Message-ID: <1179390573.546294.228480@w5g2000hsg.googlegroups.com> On May 16, 8:17 am, saif.shak... at gmail.com wrote: > Hi, > Suppose i have a list v which collects some numbers,how do i > remove the common elements from it ,without using the set() opeartor. > Thanks There was a similar thread on polish python newsletter. The following post displays 4 different approaches and explores timings: http://groups.google.com/group/pl.comp.lang.python/msg/dc3618b18e63f3c9 Fortunately, python code is universal. From andy.terrel at gmail.com Thu May 3 21:21:36 2007 From: andy.terrel at gmail.com (Andy Terrel) Date: 3 May 2007 18:21:36 -0700 Subject: Decorating class member functions Message-ID: <1178241696.641350.292210@n59g2000hsh.googlegroups.com> Okay does anyone know how to decorate class member functions? The following code gives me an error: Traceback (most recent call last): File "decorators2.py", line 33, in s.update() File "decorators2.py", line 13, in __call__ retval = self.fn.__call__(*args,**kws) TypeError: update() takes exactly 1 argument (0 given) ------------------ #! /usr/bin/env python class Bugger (object): def __init__ (self, module, fn): self.module = module self.fn = fn def __call__ (self,*args, **kws): ret_val = self.fn(*args,**kws) return ret_val def instrument (module_name): ret_val = lambda x: Bugger(module_name, x) return ret_val class Stupid: def __init__(self): self.val = 1 @instrument("xpd.spam") def update(self): self.val += 1 s = Stupid() s.update() From tjansson60 at gmail.com Mon May 14 17:13:50 2007 From: tjansson60 at gmail.com (Thomas Jansson) Date: 14 May 2007 14:13:50 -0700 Subject: Creating a function to make checkbutton with information from a list? In-Reply-To: References: <1178993091.198864.94590@k79g2000hse.googlegroups.com> Message-ID: <1179177230.342042.49570@o5g2000hsb.googlegroups.com> On 13 Maj, 08:45, Peter Otten <__pete... at web.de> wrote: > Thomas Jansson wrote: > > Dear all > > > I am writing a program with tkinter where I have to create a lot of > > checkbuttons. They should have the same format but should have > > different names. My intention is to run the functions and the create > > all the buttons with the names from the list. > > > I now the lines below doesn't work, but this is what I have so far. I > > don't really know how call the element in the dict use in the for > > loop. I tried to call +'item'+ but this doesn't work. > > > def create_checkbox(self): > > self.checkbutton = ["LNCOL", "LFORM", "LPOT", "LGRID", "LERR", > > "LCOMP"] > > for item in self.checkbutton: > > self.+'item'+Checkbutton = Chekcbutton(frame, onvalue='t', > > offvalue='f', variable=self.+'item'+) > > self.+'item'+Checkbutton.grid() > > > How should I do this? > > You /could/ use setattr()/getattr(), but for a clean design putting the > buttons (or associated variables) into a dictionary is preferrable. > > def create_checkbuttons(self): > button_names = ["LNCOL", "LFORM", "LPOT", "LGRID", "LERR", "LCOMP"] > self.cbvalues = {} > for row, name in enumerate(button_names): > v = self.cbvalues[name] = IntVar() > cb = Checkbutton(self.frame, variable=v) > label = Label(self.frame, text=name) > cb.grid(row=row, column=0) > label.grid(row=row, column=1) > > You can then find out a checkbutton's state with > > self.cbvalues[name].get() > > Peter Both of you for your answers I ended up using the last one since it seemed least complicated to new python programmer as my self. In the case that anyone should ever read the post again and would like to see what I ended up with: self.button_names = ["LPOT", "LNCOL", "LFORM", "LGRID", "LERR", "LCOMP", "LMAP", "LPUNCH", "LMEAN"] button_state = ["t" , "t" , "t" , "t" , "f" , "f" , "f" , "t" , "f" ] self.cbvalues = {} for row, name in enumerate(self.button_names): v = self.cbvalues[name] = StringVar() # It is a string variable so, t or f can be store here self.cb = Checkbutton(frame, onvalue="t", offvalue="f", variable=v) label = Label(frame, text=name) label.grid(row=row+15, column=0, sticky=W) self.cb.grid(row=row+15, column=1, sticky=W) if button_state[row] == "t": self.cb.select() else: self.cb.deselect() Kind regards Thomas Jansson From wildemar at freakmail.de Wed May 23 08:52:36 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Wed, 23 May 2007 14:52:36 +0200 Subject: Basic Class/Instance Question In-Reply-To: References: <1179918439.085344.171330@u30g2000hsc.googlegroups.com> <46542543$0$6795$426a74cc@news.free.fr> Message-ID: <46543914.80308@freakmail.de> Antoon Pardon wrote: >> This is a FAQ. Default arguments are only evaled once - when the def >> statement is evaled (which is usually at import time). The solution is >> simple: don't use mutable objects as default arguments: >> > > An immutable object would have given the same behaviour in this case > > class A(object): > def __init__(self, val = ()): > self.val=val > > obj1 = A() > obj2 = A() > > print obj1 is obj2 # False > print obj1.val is obj2.val # True > > Yeah, but is that a problem? Since you can not change them anyway, there's no harm. W From martin at v.loewis.de Wed May 2 17:10:24 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 02 May 2007 23:10:24 +0200 Subject: How to check if a string is empty in python? In-Reply-To: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> References: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> Message-ID: <4638fe40$0$1098$9b622d9e@news.freenet.de> noagbodjivictor at gmail.com schrieb: > How to check if a string is empty in python? > if(s == "") ?? Exactly so. "not s" works as well. Martin From Leisure.208 at gmail.com Mon May 7 13:45:51 2007 From: Leisure.208 at gmail.com (Leisure.208 at gmail.com) Date: 7 May 2007 10:45:51 -0700 Subject: After the Deletion of Google Answers, . U Got Questions Fills the Gap Answering and Asking the Tough Questions Message-ID: <1178559951.933883.134750@l77g2000hsb.googlegroups.com> My friend asked some tough questions http://ugotquestions.blogspot.com/2007_05_01_archive.html unlike yahoo answers ( Which Generates Content with Answers ) U got questions picks only the best, Real Person Questions.,yeah so there is this second book called E.T. and the BOOK OF THE GREEN PLANET... yeah, what happens in it... i heard he dies, and what happend to elliot.... this has been bugging me for years...so someone please tell mehttp://ugotquestions.blogspot.com/2007_04_01_archive.html - i start my car and shut it off 4 to 5 times it starts fine but when i continue repeat this procedure for another 2 to 3 times then it dies. it doesnt start at all. the headlights and all other lights dont go dim so might not be the battery. then i have to wait for 3 to 5 minutes for it to start again. it does crank slowly sometime then start. the alternator was replaced 2 years ago so was the battery. the car has 129000miles its 01 maxima. automatic. as far as i think it could be the starter...http://ugotquestions.blogspot.com/2007/05/y-alert-yahoo- answers_7473.html 1- if you ask anyone in the town that: Are you a wise human? and he says yes, what you can say about him? 2- tree mathematicians are talking about their trip to this town: 1st man says: in my trip to the town, I ask John (a people of the town) are you a wise human? and with his reply, I could not rcognize what is he. 2nd man says: I also ask John are you a loony human? and with his reply, I could not recognize what is he too. 3rd man says: I also ask John are you a wise devil? and with his...http:// ugotquestions.blogspot.com/2007/05/y-alert-yahoo-answers_7075.html Which major should I choose before law school if I want to practice criminal and civil law and I also want in the future be a judge.The majors that I like are criminal justice,politcal science and finance.But I don't know which should I choose.I already know the speech that law schools don't care about your mayor but I want to know which one of those three could help me more in my goals fo practice criminal and civil law and be a judge.Thanks a lot....http:// ugotquestions.blogspot.com/2007/05/y-alert-yahoo-answers_6058.html Everyday I wake up to my mom yelling about something I did. All she does is come home from work sit on the couch and watch a movie she gets from blockbuster everyday while we are suppose to be doing chores. She dosnt let us watch her movies becuase she pays for them,. we dont have cable and we havnt gone grocery shopping in two months becuase she says we dont hav the money.( while she gets take out everyday at work and a blockbuster movie everyday to. )She told me i cant wash my clothes for... shaw loves this. From charl.loubser at gmail.com Mon May 7 08:14:34 2007 From: charl.loubser at gmail.com (Merrigan) Date: 7 May 2007 05:14:34 -0700 Subject: long lists In-Reply-To: References: <1178522894.357829.28250@u30g2000hsc.googlegroups.com> Message-ID: <1178540073.988964.196860@w5g2000hsg.googlegroups.com> On May 7, 10:18 am, Steven D'Aprano wrote: > On Mon, 07 May 2007 00:28:14 -0700, Merrigan wrote: > > 1. I have the script popping all the files that need to be checked into > > a list, and have it parsing the list for everything...Now the problem is > > this : The sever needs to check (at the moment) 375 files and eliminate > > those that don't need reuploading. This number will obviously get bigger > > and bigger as more files gets uploaded. Now, the problem that I'm having > > is that the script is taking forever to parse the list and give the > > final result. How can I speed this up? > > By writing faster code??? > > It's really hard to answer this without more information. In particular: > > - what's the format of the list and how do you parse it? > > - how does the script decide what files need uploading? > > -- > Steven. Hi, Thanx for the reply, The Script it available at this url : http://www.lewendewoord.co.za/theScript.py P.S. I know it looks like crap, but I'm a n00b, and not yet through the OOP part of the tutorial. Thanx in advance! From cstawarz at csail.mit.edu Thu May 31 14:07:00 2007 From: cstawarz at csail.mit.edu (Christopher Stawarz) Date: Thu, 31 May 2007 14:07:00 -0400 Subject: Standalone HTTP parser? Message-ID: Does anyone know of a standalone module for parsing and generating HTTP messages? I'm looking for something that will take a string and return a convenient message object, and vice versa. All the Python HTTP parsing code I've seen is either intimately bound to the corresponding socket I/O operations (e.g. httplib, httplib2, BaseHTTPServer) and/or buried in somebody's framework (e.g. Twisted). I want to write some HTTP servers/clients that do asynchronous I/O using my own engine (multitask), so I need a HTTP package that won't insist on doing the I/O for me. Thanks, Chris Stawarz From electronixtar at gmail.com Mon May 7 21:22:07 2007 From: electronixtar at gmail.com (est) Date: 7 May 2007 18:22:07 -0700 Subject: Newbie prob: How to write a file with 3 threads? In-Reply-To: <_lJ%h.12611$3P3.10440@newsread3.news.pas.earthlink.net> References: <1178440537.257526.40980@y5g2000hsa.googlegroups.com> <1178485944.755068.321740@y5g2000hsa.googlegroups.com> <1178522026.763041.319940@e65g2000hsc.googlegroups.com> <_lJ%h.12611$3P3.10440@newsread3.news.pas.earthlink.net> Message-ID: <1178587327.571785.156800@w5g2000hsg.googlegroups.com> On May 8, 1:29 am, Dennis Lee Bieber wrote: > On 7 May 2007 00:13:46 -0700, est declaimed > the following in comp.lang.python: > > > > > I'll try Queue.Queue, thank you. I didn't expect that multithread > > write a file is so troublesome > > Multiple writers to a file, threaded or not (ie, multiple processes, > hosts on network, etc.), is always a pain unless one can ensure that all > writers use a common locking mode to prevent overlapping calls. If all > the writers are internal to one program, one can implement internal > locks -- if external one needs OS support for multi-process locking (VMS > common event flag clusters, for example). Easier to dedicate one > (internal) writer and use the naturally locked Queue to control access. > -- > 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/ I guess I will write multiple files, one thread one file, and after all threads terminates, I combine the files. That's a cheaper solution, I think. From p at ulmcnett.com Thu May 24 15:56:51 2007 From: p at ulmcnett.com (Paul McNett) Date: Thu, 24 May 2007 12:56:51 -0700 Subject: Python script not mapping our site correctly? In-Reply-To: <1180031606.747537.306030@r3g2000prh.googlegroups.com> References: <1180031606.747537.306030@r3g2000prh.googlegroups.com> Message-ID: <4655EE03.4040104@ulmcnett.com> michael.buonomo at gmail.com wrote: > We have been using the Google recommended python script for about a > year. Which script would that be? Googling for 'python script' yields approx. 27 million hits. > We recently realized that the script was not crawling our sites > url's, but just our folders which reside on the server. The behavior of the script recently changed, or you were running the script for a year not realizing what its purpose was? > The python > script seems to be designed for 'non database' sites, not a site which > is using .asp, and has dynamic pages. It sounds like your script is just traversing a directory structure on disk, presumably indexing the text in the files found there. I think it sounds like (but I'm guessing, here) that you want what is known as a web crawler, that communicates via http with your site, follows links, and indexes the resulting pages. > We are an ecommerce site. What are other ecommerce sites using to > create an xml file? XML is mostly used to persist data of one sort or another. What kind of XML file do you want to create? > Are they using the python script? We aren't going to be able to help you with this question until you become *much more specific*: + Which python script? Where did you download it from and what is it called? + What is the purpose of the XML you want generated? (WAG: Submit to Froogle?) + What pages do you want indexed? Usually, for database-driven ecommerce sites, for developing lists of products for submission to places like Froogle, I don't go via the web interface at all: I write python scripts (there's that word again!) to connect to the database, and run queries to determine the results, run that through a template for each line that figures out things such as the URL of the page that represents the product, etc.) But I hesitate to say much more until we understand what you want your python script to do. -- pkm ~ http://paulmcnett.com From steve at REMOVE.THIS.cybersource.com.au Sun May 13 00:02:30 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 13 May 2007 14:02:30 +1000 Subject: Interesting list Validity (True/False) References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> <1178914190.166662.285410@p77g2000hsh.googlegroups.com> <1178915791.584216.293130@l77g2000hsb.googlegroups.com> <1178918808.091358.233740@o5g2000hsb.googlegroups.com> <1179017740.656323.209590@e51g2000hsg.googlegroups.com> <1179020634.130689.171960@o5g2000hsb.googlegroups.com> Message-ID: On Sat, 12 May 2007 18:43:54 -0700, mensanator at aol.com wrote: > On May 12, 8:10?pm, Carsten Haese wrote: >> On Sat, 2007-05-12 at 17:55 -0700, mensana... at aol.com wrote: >> > On May 12, 12:56?pm, Carsten Haese wrote: >> > > On Fri, 2007-05-11 at 14:26 -0700, mensana... at aol.com wrote: >> > > > if arg==True: >> >> > > > tests the type property (whether a list is a boolean). >> >> > > That sounds nonsensical and incorrect. Please explain what you mean. >> >> > >> > Sec 2.2.3: >> > Objects of different types, except different numeric types and >> > different string types, never compare equal; >> > I should point out that only applies to built-in types, not custom classes. >> That doesn't explain what you mean. How does "if arg==True" test whether >> "a list is a boolean"? > >>>> type(sys.argv) > >>>> type(True) > That still doesn't make sense. However, using my incredible psychic ability to read between the lines, I think what Mensanator is trying (but failing) to say is that "if arg==True" first tests whether arg is of type bool, and if it is not, it knows they can't be equal. That's not actually correct. We can check this: >>> import dis >>> def test(arg): ... return arg == True ... >>> dis.dis(test) 2 0 LOAD_FAST 0 (arg) 3 LOAD_GLOBAL 0 (True) 6 COMPARE_OP 2 (==) 9 RETURN_VALUE As you can see, there is no explicit type test. (There may or may not be an _implicit_ type test, buried deep in the Python implementation of the COMPARE_OP operation, but that is neither here nor there.) Also, since bool is a subclass of int, we can do this: >>> 1.0+0j == True True > Actually, it's this statement that's non-sensical. > > > "if arg==True" tests whether the object known as arg is equal to the > object known as True. > Not at all, it makes perfect sense. X == Y always tests whether the argument X is equal to the object Y regardless of what X and Y are. > None of these four examples are "equal" to any other. That's actually wrong, as you show further down. >>>> a = 1 >>>> b = (1,) >>>> c = [1] >>>> d = gmpy.mpz(1) >>>> >>>> type(a) > >>>> type(b) > >>>> type(c) > >>>> type(d) > >>>> a==b > False >>>> b==c > False >>>> a==d > True See, a and d are equal. > And yet a==d returns True. So why doesn't b==c > also return True, they both have a 1 at index position 0? Why should they return true just because the contents are the same? A bag of shoes is not the same as a box of shoes, even if they are the same shoes. Since both lists and tuples are containers, neither are strings or numeric types, so the earlier rule applies: they are different types, so they can't be equal. gmpy.mpz(1) on the other hand, is both a numeric type and a custom class. It is free to define equal any way that makes sense, and it treats itself as a numeric type and therefore says that it is equal to 1, just like 1.0 and 1+0j are equal to 1. -- Steven. From paul at boddie.org.uk Wed May 9 18:29:34 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 9 May 2007 15:29:34 -0700 Subject: Towards faster Python implementations - theory In-Reply-To: References: <1210i.7468$2v1.2505@newssvr14.news.prodigy.net> <1178705421.711371.182770@e65g2000hsc.googlegroups.com> Message-ID: <1178749774.254178.308960@e65g2000hsc.googlegroups.com> John Nagle wrote: > > Modifying "at a distance" is exactly what I'm getting at. That's the > killer from an optimizing compiler standpoint. The compiler, or a > maintenance programmer, looks at a block of code, and there doesn't seem > to be anything unusual going on. But, if in some other section of > code, something does a "setattr" to mess with the first block of code, > something unusual can be happening. This is tough on both optimizing > compilers and maintenance programmers. Agreed. It's tempting to look at some code and say which types one thinks are being manipulated, but the actual program behaviour can be quite different. Adding explicit type declarations "anchors" the names to a very restrictive set of types - typically those permitted through interfaces or inheritance in many object-oriented languages - and the challenge, as we've already discussed, is to attempt to "anchor" the names when they are in a sense "floating free" without any explicit annotations from the programmer. Python also presents other challenges. Unlike systems programming languages, almost nothing is a local operation: each Python function is mostly a product of function calls and the occasional conditional or looping construct, themselves wired up using yet more function calls. Whilst the expection is that most of these will return sensible results (eg. a call to the iter method on a sequence returns an iterator), there isn't any guarantee that this will be the case, and even then the precise iterator involved can vary. Some might claim that the class of operations which could be done locally are precisely the ones which would benefit from identification and optimisation, namely those involving primitive types, yet some pretty good solutions for such cases exist already: Pyrex, various numeric packages, and so on. > Python has that capability mostly because it's free in an > "everything is a dictionary" implementation. ("When all you have > is a hash, everything looks like a dictionary".) But that limits > implementation performance. Most of the time, nobody is using > "setattr" to mess with the internals of a function, class, or > module from far, far away. But the cost for that flexibility is > being paid, unnecessarily. I've heard claims that virtual machines are evolving to make dictionary-based access more performant, and I guess Microsoft's DLR and any JVM improvements might point in that direction, but Shed Skin shows the way by avoiding such things entirely. > I'm suggesting that the potential for "action at a distance" somehow > has to be made more visible. > > One option might be a class "simpleobject", from which other classes > can inherit. ("object" would become a subclass of "simpleobject"). > "simpleobject" classes would have the following restrictions: > > - New fields and functions cannot be introduced from outside > the class. Every field and function name must explicitly appear > at least once in the class definition. Subclassing is still > allowed. I suppose one could mandate that only methods defined inside class blocks belong to the class and subclasses, and that various kinds of optimisations can then be applied to the code in those methods such that the self parameter's type is constrained in a way probably already imposed by CPython. This would forbid the adding of functions to classes and instances after the fact, but in my fairly conservative world of programming, I hardly ever do such things. I do add attributes to instances outside those instances (by the above definition) quite often, though. > - Unless the class itself uses "getattr" or "setattr" on itself, > no external code can do so. This lets the compiler eliminate the > object's dictionary unless the class itself needs it. I think this is a natural progression from determining the access needs of particular classes and their objects. > This lets the compiler see all the field names and assign them fixed slots > in a fixed sized object representation. Basically, this means simple objects > have a C/C++ like internal representation, with the performance that comes > with that representation. Yes, I agree that this would be desirable. > With this, plus the "Shed Skin" restrictions, plus the array features of > "numarray", it should be possible to get computationally intensive code > written in Python up to C/C++ levels of performance. Yet all the dynamic > machinery of Python remains available if needed. > > All that's necessary is not to surprise the compiler. One thing I had cause to think about again today was the cost of function invocations. Python not only has pervasive dynamic dispatch, but there are also such things as *args and **kwargs and the cost of dealing with them. However, such things are very useful in integrating components and extending class hierarchies, so I wouldn't want to see them vanish in their entirety. Paul From kurt.michalke at googlemail.com Thu May 10 16:46:45 2007 From: kurt.michalke at googlemail.com (kurt.michalke at googlemail.com) Date: 10 May 2007 13:46:45 -0700 Subject: do not use stunnix Message-ID: <1178830005.542088.252660@o5g2000hsb.googlegroups.com> Various chanels and groups are flooded with information about a thing called stunnix web server. Do not ever consider using it. It will in spite of all the marketing blah give you more pain than you can bear. We licensed it for a CD-ROM and ended up having to issue it three (!) times. Cheers, Kurt From tennessee at tennessee.id.au Thu May 3 01:04:20 2007 From: tennessee at tennessee.id.au (Tennessee Leeuwenburg) Date: Thu, 3 May 2007 15:04:20 +1000 Subject: [python-advocacy] Need Help in Preparing for Study of Python by Forrester Research In-Reply-To: <46388BC8.9000806@taupro.com> References: <46388BC8.9000806@taupro.com> Message-ID: <43c8685c0705022204t1655f7b9x13a3172c7f6226cf@mail.gmail.com> I've read through the document. It seems basically okay, although highly web-oriented. There are still *some* desktop developers left in the world! I was a little disappointed not to see more on the community -- e.g. engagement of the community, activity in support fora, availability of books and tutorials etc. The questions looked like a reasonable checklist if you were developing an enterprise web app, but didn't really turn out very much about the language itself, or cover elegance, programming style. It would probably be good to see a few standard algorithms implemented in each language rather than allowing each language to submit whatever they like. A bit of both might be nice. Just my 2c. Cheers, -T On 5/2/07, Jeff Rush wrote: > Forrester Research is doing a study on dynamic languages and has asked that > Python be represented. As advocacy coordinator I've volunteered to drive > this, collecting answers from the community and locating representatives to > participate in interviews. > > The goal of the study is to: > > - identify the criteria to use for evaluating such languages > - identify the relevant choices of dynamic languages > - identify how the different dynamic languages stack up > - examine where dynamic languages work best > > Initially, they'd like feedback (not yet the answers themselves) from us > regarding their proposed evaluation criteria - questions to add or that give > no value, rewording to make them more clear. I've posted their draft > criteria, which came as a spreadsheet at: > > http://dfwpython.org/uploads/ForresterPrep/DynamicLanguagesCriteria.xls > > Later, between May 8 and 25, the researchers will need to interview via 1-hour > telephone calls, several developers with experience using Python. And they > want to also interview one person with an executive viewpoint, able to > describe relevant background, positioning, value proposition, customer base, > and strategic vision. > > And later they would also like snippets of Python code that illustrate the > power of Python, and I hope to call upon community members to help in > producing that. The snippets do not have to be originally written and can be > pulled from existing projects. > > But those steps come later. For now let's focus on analysis of the evaluation > criteria at the above URL. Time is short as they'd like that feedback by May > 3, so please get any responses to me as soon as possible. And be thinking who > would best represent the executive view of Python in an interview. > > Thanks for your help, > > Jeff Rush > Advocacy Coordinator > _______________________________________________ > Advocacy mailing list > Advocacy at python.org > http://mail.python.org/mailman/listinfo/advocacy > From tjreedy at udel.edu Tue May 1 18:13:19 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 1 May 2007 18:13:19 -0400 Subject: Comparing bitmap images for differences? References: <1178024505.768505.262270@h2g2000hsg.googlegroups.com> Message-ID: wrote in message news:1178024505.768505.262270 at h2g2000hsg.googlegroups.com... |I know it's a long shot but does anyone have any pointers to generic | algorithms - or, even better, Python code - for comparing images and | computing a value for the "difference" between them? If PIL and the other posted ideas are not enough, another approach is to convert the image from PIL format to NumPy array format. (pygame has functions to do this, I believe, since it uses NumPy (actually the older Numerical Python at present) for its surface arrays.) You can then do most any calculation you want. tjr From mobiledreamers at gmail.com Tue May 1 17:32:29 2007 From: mobiledreamers at gmail.com (mobiledreamers at gmail.com) Date: Tue, 1 May 2007 14:32:29 -0700 Subject: Cleaning up repeated whitespaces and newlines Message-ID: Hi guys i m trying out newline characters and to clean them up a\n\n\n\n\n\n\n\n\nsss\n\n\n\n\n\n\n\n\n\n\nvvvv\n\n\n\nvsa\n\n\n\nasf\n\nafs hello guys im trying to replace \n\n\n\n\n\n\n\n\n with \n thanks for help \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n also with \n as the browser gives \r carrriage returns thanks for any help or pointers -------------- next part -------------- An HTML attachment was scrubbed... URL: From nszabolcs at gmail.com Wed May 30 05:57:35 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 30 May 2007 02:57:35 -0700 Subject: writing to a file In-Reply-To: <1180515758.671628.43200@k79g2000hse.googlegroups.com> References: <1180515758.671628.43200@k79g2000hse.googlegroups.com> Message-ID: <1180519055.398825.235940@q69g2000hsb.googlegroups.com> montyphy... at gmail.com wrote: > as i understand there are two ways to write data to a file: using > f.write("foo") and print >>f, "foo". well print will add a '\n' or ' ' if you use ',' after it > what i want to know is which one is faster (if there is any difference there shouldn't be any noticable difference > in speed) since i'm working with very large files. of course, if there > is any other way to write data to a file, i'd love to hear about it other ways: os.system('cat file1 >> file2') or subprocess.Popen or print but sys.stdout = f or ctypes + printf/fputs/.. and probably there are other obscure ways, but the intended way is obviously f.write nsz From thin.myrna at spamhaters.com Fri May 18 12:08:05 2007 From: thin.myrna at spamhaters.com (Thin Myrna) Date: Fri, 18 May 2007 18:08:05 +0200 Subject: Why canNOT import from a local directory ? References: <1179503376.706409.185930@w5g2000hsg.googlegroups.com> Message-ID: <464dcf65$0$3806$5402220f@news.sunrise.ch> Jia Lu wrote: > Hi all > > I created a folder named *lib* and put a py file *lib.py* in it. > In the upper folder I created a py file as: > > > import lib.lib > > def main(): > """ > __doc__ > """ > lib.lib.test() > > > # //////////////////////////////////////// > if __name__ == "__main__": > main() > > > But I got an error : > #.:python main.py > Traceback (most recent call last): > File "main.py", line 6, in ? > import lib.lib > ImportError: No module named lib.lib > > Why ? You need to define a file __init__.py in your newly created lib directory. HTH Thin From knipknap at gmail.com Tue May 22 07:09:34 2007 From: knipknap at gmail.com (Samuel) Date: 22 May 2007 04:09:34 -0700 Subject: Components for a client/server architecture In-Reply-To: References: <5bd99qF2s85heU1@mid.uni-berlin.de> Message-ID: <1179832174.277250.160560@z28g2000prd.googlegroups.com> On May 22, 3:10 am, Josiah Carlson wrote: > That snippet of code shows that acquiring a lock does release the GIL. Of course, that does not mean that the (possible) issues no longer apply. However, I decided to hack up a quick prototype and see how it goes. If it doesn't work it shouldn't be too hard to switch to IronPython. > You should also consider XML-RPC. Setting up and using XML-RPC in > Python is quite easy (see the recipes in the Python cookbook), both as a > server and client. It's nice and simple, but more in the SOAP domain of things. As for CORBA, I had a closer look at Omniorb and it looks powerful, pretty much exactly what I was looking for. Thanks! -Samuel From josiah.carlson at sbcglobal.net Sat May 12 14:20:59 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Sat, 12 May 2007 11:20:59 -0700 Subject: preferred windows text editor? In-Reply-To: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> References: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> Message-ID: <0wn1i.1610$mR2.1332@newssvr22.news.prodigy.net> T. Crane wrote: > Right now I'm using Notepad++. What are other people using? If you are looking for editors written in Python (that are generally multiplatform using wxPython), there are a few listed: http://wiki.wxpython.org/wxPythonPit_Apps . If you are looking for editors with Python support, there is a listing on the Python wiki: http://wiki.python.org/moin/PythonEditors I use PyPE (http://pype.sf.net) for most of my editing needs. - Josiah From siasookhteh at gmail.com Wed May 23 07:48:06 2007 From: siasookhteh at gmail.com (Siah) Date: 23 May 2007 04:48:06 -0700 Subject: Basic Class/Instance Question In-Reply-To: <46542543$0$6795$426a74cc@news.free.fr> Message-ID: <1179920886.075123.217410@h2g2000hsg.googlegroups.com> Bruno, I got my lesson today, first get your morning coffee before posting and of course avoid mutable objects as default arguments. Silly post, perhaps. Good to hear universe is in place. I should have rtffaq, though that's not why she left... Sia From hanser at club-internet.fr Tue May 15 14:47:20 2007 From: hanser at club-internet.fr (Pierre Hanser) Date: Tue, 15 May 2007 20:47:20 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46498cb1$0$6411$9b4e6d93@newsspool2.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <4648252D.5020704@web.de> <46483740.4050406@web.de> <46498cb1$0$6411$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <464a0029$0$21149$7a628cd7@news.club-internet.fr> Ren? Fleschenberg a ?crit : > IMO, the burden of proof is on you. If this PEP has the potential to > introduce another hindrance for code-sharing, the supporters of this PEP > should be required to provide a "damn good reason" for doing so. So far, > you have failed to do that, in my opinion. All you have presented are > vague notions of rare and isolated use-cases. you want to limit my liberty of using appealing names in my language. this alone should be enough to accept the pep! From ptmcg at austin.rr.com Tue May 15 18:13:34 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 15 May 2007 15:13:34 -0700 Subject: Name of function caller In-Reply-To: <1179266351.304587.182070@n59g2000hsh.googlegroups.com> References: <1179266351.304587.182070@n59g2000hsh.googlegroups.com> Message-ID: <1179267214.735025.167470@l77g2000hsb.googlegroups.com> On May 15, 4:59 pm, HMS Surprise wrote: > Is there a way that a function may access the doc string or func_name > of the caller? > > Thanks, > > jvh Yes. The inspect module allows you to look up the call stack for information on the caller, the caller's caller, local vars, etc. -- Paul From sjmachin at lexicon.net Wed May 2 18:26:32 2007 From: sjmachin at lexicon.net (John Machin) Date: 2 May 2007 15:26:32 -0700 Subject: Slicing Arrays in this way In-Reply-To: <4638fe20$0$16403$88260bb3@free.teranews.com> References: <4638fe20$0$16403$88260bb3@free.teranews.com> Message-ID: <1178144792.759932.313190@l77g2000hsb.googlegroups.com> On May 3, 8:03 am, Tobiah wrote: > >>> elegant_solution([1,2,3,4,5,6,7,8,9,10]) > [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] > What is your definition of "elegant"? What about other dimensions of code quality like "robust" and "fast"? What have you tried? Here's one possibility: zip(source[::2], source[1::2]) [I'm presuming you won't be upset by getting tuples instead of lists] From gagsl-py2 at yahoo.com.ar Tue May 8 19:08:33 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 08 May 2007 20:08:33 -0300 Subject: __getattr__ and __getattribute__ References: Message-ID: En Tue, 08 May 2007 08:22:03 -0300, km escribi?: > i find it difficult to understand the difference between the magic > methods > __getattr__ and __getattribute__ > and so donot know when to use former or later. > can someone brief me on it ? This is better understood with a bit of history. On earlier Python versions (before 2.2) the only object model available was what we now call "classic classes". Classic instances hold their attributes in a dictionary, called __dict__. Attribute lookup starts at this instance dictionary; if not found, continues in the class, and its parent class, all along the inheritance tree. If still not found, __getattr__ (if it exists) is called, and should return the attribute value or raise AttributeError. That is, __getattr__ is called *last*, and *only* when the attribute was not previously found in the usual places. Since Python 2.2, there are "new style classes" available; they inherit directly or indirectly from object. A new style instance may not even have a __dict__. An existing __getattribute__ method is tried *first*; it should return the attribute value or raise AttributeError. If no custom __getattribute__ exists, the default object.__getattribute__ is used. As a last resort, if __getattr__ is defined, it is called. OTOH, there is a single version of __setattr__, which is always invoked when setting an attribute. -- Gabriel Genellina From grante at visi.com Thu May 24 17:09:43 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 24 May 2007 21:09:43 -0000 Subject: Python and GUI References: <1179761984.704369.116310@b40g2000prd.googlegroups.com> <4651CDBC.1070508@ulmcnett.com> <5abb0$4655ee4c$d443bb3a$510@news.speedlinq.nl> <135bs4dfpdl8q33@corp.supernews.com> <8abbd$4655f7b0$d443bb3a$21589@news.speedlinq.nl> Message-ID: <135bvon3ej90a0e@corp.supernews.com> On 2007-05-24, Stef Mientki wrote: >>>> Finally, consider wax (http://zephyrfalcon.org/labs/wax.html). In my >>>> view, this is *exactly* what python needs, and its not being maintained >>>> anymore as far as I can tell. What I like about it is: >>>> >>>> 1) it is small...I can include the entire wax distribution in >>>> my app with only a 780k footprint. >>>> >>>> 2) it is a very thin layer on wx, so when something doesn't quite work, >>>> I can immediately fall back onto wx, mixing and matching wax and wx >>>> objects. it's just that the wax objects have more pythonic calling and >>>> use properties >>> >>> Sorry I don't know wax, but I wonder "a GUI designer without >>> screenshots", is that Pythonic ;-) >> >> Uh, wha? > > quote original message: > "I am looking for a pythonic, professional looking GUI framework." >> Who are you quoting about the screenshots? > Sorry, maybe I'm not Pythonic enough, but talking about "GUI > framework", the first thing I want to see are screenshots. 0) While wax is a GUI framework, it is not a GUI designer, so I was wondering who you were quoting when you wrote "a GUI designer [...]". 1) Wax doesn't have any effect on the appearance of applications, only on the appearance of the Python code used to write the applications. So, screenshots are irrelevent. If you want screenshots of what wxWidgets apps look like, there are lots of them at wxWidgets.org. But, since wxWidgets generally uses "native" widgets, wxWidget apps look pretty much like any other app on the given platform. -- Grant Edwards grante Yow! WHOA!! Ken and Barbie at are having TOO MUCH FUN!! visi.com It must be the NEGATIVE IONS!! From malaclypse2 at gmail.com Thu May 3 08:39:56 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Thu, 3 May 2007 08:39:56 -0400 Subject: ascii to unicode line endings In-Reply-To: <1178122765.162546.59680@l77g2000hsb.googlegroups.com> References: <1178122765.162546.59680@l77g2000hsb.googlegroups.com> Message-ID: <16651e80705030539y478390d3s52de1210ec3d58c8@mail.gmail.com> On 2 May 2007 09:19:25 -0700, fidtz at clara.co.uk wrote: > The code: > > import codecs > > udlASCII = file("c:\\temp\\CSVDB.udl",'r') > udlUNI = codecs.open("c:\\temp\\CSVDB2.udl",'w',"utf_16") > udlUNI.write(udlASCII.read()) > udlUNI.close() > udlASCII.close() > > This doesn't seem to generate the correct line endings. Instead of > converting 0x0D/0x0A to 0x0D/0x00/0x0A/0x00, it leaves it as 0x0D/ > 0x0A That code (using my own local files, of course) basically works for me. If I open my input file with mode 'r', as you did above, my '\r\n' pairs get transformed to '\n' when I read them in and are written to my output file as 0x00 0x0A. If I open the input file in binary mode 'rb' then my output file shows the expected sequence of 0x00 0x0D 0x00 0x0A. Perhaps there's a quirk of your version of python or your platform? I'm running Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 -- Jerry From arkanes at gmail.com Fri May 4 16:12:53 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 4 May 2007 15:12:53 -0500 Subject: Why are functions atomic? In-Reply-To: <1178308779.454269.166550@e65g2000hsc.googlegroups.com> References: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> <1178044821.864741.235260@o5g2000hsb.googlegroups.com> <1178063341.779617.289690@o5g2000hsb.googlegroups.com> <1178065685.161372.81790@y80g2000hsf.googlegroups.com> <1178083318.404304.76100@q75g2000hsh.googlegroups.com> <1178260571.160570.299160@p77g2000hsh.googlegroups.com> <1178308779.454269.166550@e65g2000hsc.googlegroups.com> Message-ID: <4866bea60705041312u23bace27m6c70b7bd96b4a8f6@mail.gmail.com> On 4 May 2007 12:59:39 -0700, Michael wrote: > On May 4, 9:19 am, John Nagle wrote: > > > ... def g(): > > > ... x = x + 1 > > > > Too cute. Don't nest functions in Python; the scoping model > > isn't really designed for it. > > How can you make generators then if you don't nest? > There's all kinds of good reasons to nest functions, and the "scoping model isn't really designed for it" somewhat overstates the case - it's not relevant to many of the reasons you might nest functions, and it's not (much) of a problem for the rest of them. What you can't do is rebind values in the enclosing scope, unless the enclosing scope is global. That's a real, but fairly minor, limitation and you'll be able to explicitly address your enclosing scope in 3k (or perhaps sooner). From siona at chiark.greenend.org.uk Fri May 18 08:49:48 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 18 May 2007 13:49:48 +0100 (BST) Subject: How to convert a number to binary? References: <1179444832.775573.55830@y80g2000hsf.googlegroups.com> <1179445546.307017.275850@p77g2000hsh.googlegroups.com> <1179474308.939323.74720@p77g2000hsh.googlegroups.com> Message-ID: Lyosha wrote: >On May 17, 11:04 pm, Stargaming wrote: >> dec2bin = lambda x: (dec2bin(x/2) + str(x%2)) if x else '' > [ ... ] >I guess the reason I couldn't come up with something like this was >being brainwashed that lambda is a no-no. > >And python2.5 funky ?: expression comes in handy! def dec2bin(x): return x and (dec2bin(x/2)+str(x%2)) or '' does the same job without lambda or Python 2.5 (and note that the usual warning about a and b or c doesn't apply here as b is guaranteed to evaluate as true). -- \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 roger.miller at nova-sol.com Fri May 18 17:57:27 2007 From: roger.miller at nova-sol.com (Roger Miller) Date: 18 May 2007 14:57:27 -0700 Subject: Random selection In-Reply-To: <20070518103926.65bb8ea7.tartifola@gmail.com> References: <20070518103926.65bb8ea7.tartifola@gmail.com> Message-ID: <1179525447.415249.75800@w5g2000hsg.googlegroups.com> On May 17, 10:39 pm, Tartifola wrote: > Hi, > I have a list with probabilities as elements > > [p1,p2,p3] > > with of course p1+p2+p3=1. I'd like to draw a > random element from this list, based on the probabilities contained in > the list itself, and return its index. > > Any help on the best way to do that? > Thanks This of course depends on your definition of "best". There is a fast and simple technique if all probabilities are multiples of 1/n for a reasonably small n, or if you are willing to round them to such. Suppose for example that the probabilities are [0.42, 0.23, 0.35]. Create a list of 100 items with 42 0's, 23 1's, and 35 2's, then select a random element using random.choice() or equivalent. From steve at holdenweb.com Thu May 17 10:48:03 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 17 May 2007 10:48:03 -0400 Subject: Execute commands from file In-Reply-To: <1179387023.005808.60670@o5g2000hsb.googlegroups.com> References: <1179320782.594398.67980@u30g2000hsc.googlegroups.com> <464b370c$0$3808$5402220f@news.sunrise.ch> <1179387023.005808.60670@o5g2000hsb.googlegroups.com> Message-ID: i3dmaster wrote: > On May 16, 1:05 pm, Steve Holden wrote: >> Martin Blume wrote: >>> "tmp123" schrieb > >>>> We have very big files with python commands >>>> (more or less, 500000 commands each file). >>>> It is possible to execute them command by command, >>> inp = open(cmd_file) >>> for line in inp: >>> exec line >>> might help. You don't get quite the same feeling as >>> "like if the commands was typed one after the other >>> in a interactive session", but perhaps this helps. >>> Warning: the code above is without any error checks. >>> You might also run into security problems, the example >>> above assumes you trust your input. >>> HTH. YMMV. >>> Martin >> The problem with this approach is that each line executes without any >> connection to the environment created by previous lies. >> >> Try it on a file that reads something like >> >> xxx = 42 >> print xxx >> >> and you will see NameError raised because the assignment hasn't affected >> the environment for the print statement. >> >> 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 your way to fame!! >> holdenweb.blogspot.com squidoo.com/pythonology >> tagged items: del.icio.us/steve.holden/python >> All these services currently offer free registration! >> -------------- Thank You for Reading ---------------- > > cat file: > > x = 100 > print x > > cat file.py: > #!/usr/bin/python2.4 > > import os.path > import sys > > file, ext = os.path.splitext(sys.argv[0]) > f = open(file,'rb') > for i in f: > exec i > >> ./file.py > 100 > > Don't see the problem though. > No, because there isn't one. Now try adding a function definition and see how well it 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 ------------------ Asciimercial --------------------- Get on the web: Blog, lens and tag your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From bhochstetler at gmail.com Wed May 2 14:40:03 2007 From: bhochstetler at gmail.com (bhochstetler at gmail.com) Date: 2 May 2007 11:40:03 -0700 Subject: hp 11.11 64 bit python 2.5 build gets error "import site failed" Message-ID: <1178131203.719353.91360@y80g2000hsf.googlegroups.com> I am on a hp 11.11 machine doing a 64 bit python 2.5 build. When I get my python executable created and run it, I get the error: "import site failed" OverflowError: signed integer is greater than the maximum. This is happening in the convertsimple() routine when it tries to return a signed int: ival = PyInt_AsLong(arg) the ival is larger than what is defined in INT_MAX. Why is this happening in a standard HP 64 bit build? Any help on fixing this problem is greatly appreciated. Brad From mike.terrell at earthlink.net Tue May 8 15:10:44 2007 From: mike.terrell at earthlink.net (Michael A. Terrell) Date: Tue, 08 May 2007 19:10:44 GMT Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> <08qk33t594ih0ulmjmev90d22lkfnotgoe@4ax.com> <463C2A3A.8332D211@hotmail.com> <0k8p33h90bp5tfajedb4bmd2eik8gfi2ho@4ax.com> Message-ID: <4640CB37.907C9988@earthlink.net> James Beck wrote: > > Yep, you must have access to better drugs than I do. > You get to hallucinate your stuff up. > Don't forget to adjust your tin beanie! Its not a beanie. He had his head tin plated. :( -- Service to my country? Been there, Done that, and I've got my DD214 to prove it. Member of DAV #85. Michael A. Terrell Central Florida From gh at gregor-horvath.com Wed May 16 11:14:32 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Wed, 16 May 2007 17:14:32 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <7x4pmg716p.fsf@ruckus.brouhaha.com> <4648EC26.8020907@v.loewis.de> Message-ID: Eric Brunel schrieb: > Highly improbable in the general context. If I stumble on a source code > in Chinese, Russian or Hebrew, I wouldn't be able to figure out a single > sound. If you get source code in a programming language that you don't know you can't figure out a single sound too. How is that different? If someone decides to make *his* identifiers in Russian he's taking into account that none-Russian speakers are not going to be able to read the code. If someone decides to program in Fortran he takes into account that the average Python programmer can not read the code. How is that different? It's the choice of the author. Taking away the choice is not a good thing. Following this logic we should forbid all other programming languages except Python so everyone can read every code in the world. Gregor From carsten at uniqsys.com Mon May 28 09:50:24 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 28 May 2007 09:50:24 -0400 Subject: itertools.groupby In-Reply-To: <7x8xb939ut.fsf@ruckus.brouhaha.com> References: <1180295221.3163.9.camel@localhost.localdomain> <1180313441.598026.198230@d30g2000prg.googlegroups.com> <7x8xb939ut.fsf@ruckus.brouhaha.com> Message-ID: <1180360224.3152.25.camel@localhost.localdomain> On Sun, 2007-05-27 at 20:28 -0700, Paul Rubin wrote: > fst = operator.itemgetter(0) > snd = operator.itemgetter(1) > > def bates(fd): > # generate tuples (n,d) of lines from file fd, > # where n is the record number. Just iterate through all lines > # of the file, stamping a number on each one as it goes by. > n = 0 # record number > for d in fd: > if d.startswith('New Record'): n += 1 > yield (n, d) > > def records(fd): > for i,d in groupby(bates(fd), fst): > yield imap(snd, d) Now there's a clever variation of the Schwartzian transform: decorate, groupby, undecorate. That's a nice example of groupby, but it could benefit from using better variable names. -- Carsten Haese http://informixdb.sourceforge.net From warren at muse.com Wed May 30 14:48:47 2007 From: warren at muse.com (Warren Stringer) Date: Wed, 30 May 2007 11:48:47 -0700 Subject: c[:]() In-Reply-To: <1180504773.374529.161740@q66g2000hsg.googlegroups.com> References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180504773.374529.161740@q66g2000hsg.googlegroups.com> Message-ID: <002801c7a2eb$288a8750$240110ac@Muse> I want to call every object in a tupple, like so: #------------------------------------------ def a: print 'a' def b: print 'b' c = (a,b) >>>c[:]() # i wanna TypeError: 'tupple' object is not callable >>>c[0]() # expected a >>>c[:][0] # huh? a >>> [i() for i in c] # too long and ...huh? a b [None,None] #------------------------------------------ Why? Because I want to make Python calls from a cell phone. Every keystroke is precious; even list comprehension is too much. Is there something obvious that I'm missing? Warren Today's quote: "HELLO PARROT! wakey wakey!" From aahz at pythoncraft.com Sun May 6 19:19:27 2007 From: aahz at pythoncraft.com (Aahz) Date: 6 May 2007 16:19:27 -0700 Subject: Error in python.org homepage. References: <1178013832.880214.134660@l77g2000hsb.googlegroups.com> Message-ID: In article , Steve Holden wrote: >Terry Reedy wrote: >> wrote in message >> news:1178013832.880214.134660 at l77g2000hsb.googlegroups.com... >> | Hi to all!!! >> | >> | I sended an email to webmaster at python dot org, but was blocked... >> | why?.... >> >> No idea > >I doubt very much that the poster was blocked. It's likely that he >received an email auto-response as a first-time poster, and may not have >understood it. Allessio, if that's the case please let me know if you >think we could improve the message to make it easier to understand. It's also possible that Allessio got hit by the broken alias for webmaster at python.org, which got fixed yesterday (not sure when it got broken). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Look, it's your affair if you want to play with five people, but don't go calling it doubles." --John Cleese anticipates Usenet From carsten at uniqsys.com Tue May 15 13:08:20 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 15 May 2007 13:08:20 -0400 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <4649dd55$0$23144$9b4e6d93@newsspool1.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649dd55$0$23144$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <1179248900.3385.95.camel@dot.uniqsys.com> On Tue, 2007-05-15 at 18:18 +0200, Ren? Fleschenberg wrote: > Carsten Haese schrieb: > > Allowing people to use identifiers in their native language would > > definitely be an advantage for people from such cultures. That's the use > > case for this PEP. It's easy for Euro-centric people to say "just suck > > it up and use ASCII", but the same people would probably starve to death > > if they were suddenly teleported from Somewhere In Europe to rural China > > which is so unimaginably different from what they know that it might > > just as well be a different planet. "Learn English and use ASCII" is not > > generally feasible advice in such cultures. > > This is a very weak argument, IMHO. How do you want to use Python > without learning at least enough English to grasp a somewhat decent > understanding of the standard library? Let's face it: To do any "real" > programming, you need to know at least some English today, and I don't > see that changing anytime soon. And it is definitely not going to be > changed by allowing non-ASCII identifiers. Even if it were impossible to do "real programming" in Python without knowing English (which I will neither accept nor reject because I don't have enough data either way), I don't think Python should be restricted to "real" programming only. Python (the programming language) is an inherently easy-to-learn language. I find it quite plausible that somebody in China might want to teach their students programming before teaching them English. The posts on this thread by a teacher from China confirm this suspicion. Once the students learn Python and realize that there are lots of Python resources "out there" that are only in English, that will be a motivation for them to learn English. Requiring all potential Python programmers to learn English first (or assuming that they know English already) is an unacceptable barrier of entry. -- Carsten Haese http://informixdb.sourceforge.net From hate at spam.com Sun May 13 04:11:07 2007 From: hate at spam.com (Jesse) Date: Sun, 13 May 2007 10:11:07 +0200 Subject: Popen and wget, problems In-Reply-To: <87d515ejil.fsf@merkury.smsnet.pl> References: <4645a6a6$0$8615$dbd49001@news.wanadoo.nl> <87d515ejil.fsf@merkury.smsnet.pl> Message-ID: <4646c812$0$95655$dbd43001@news.wanadoo.nl> Thx Rob! Your solution works perfect! "Rob Wolfe" wrote in message news:87d515ejil.fsf at merkury.smsnet.pl... > "Jesse" writes: > >> Hi all, I have a problem using wget and Popen. I hope someone can help. >> >> >> -- Problem -- >> I want to use the command: >> wget -nv -O "dir/cpan.txt" "http://search.cpan.org" >> and capture all it's stdout+stderr. >> (Note that option -O requires 'dir' to be existing before wget is >> executed) >> >> Popen doesn't work, while os.system and shell do. Popen will give the >> error: >> dir/cpan.txt: No such file or directory >> >> While os.system and shell will give the correct result: >> 06:52:40 URL:http://search.cpan.org/ [3657/3657] -> "dir1/cpan.txt" [1] > > [...] > >> -- Python Code using Popen with cmd arg list -- >> # imports >> import os >> from subprocess import Popen, PIPE >> >> # vars and create dir >> cmd_set = ['wget', '-nv', '-O dir/cpan.txt', 'http://search.span.org'] >> cmd = ' '.join(cmd_set) >> print "cmd: " + cmd >> try: >> os.makedirs('dir') >> except: >> print 'dir already exists' >> >> >> # execute using Popen (does NOT work) >> proc = Popen(cmd_set, stdout=PIPE, stderr=PIPE) >> return_code = proc.wait() >> if return_code == 0: >> print "Success:\n%s" % (proc.stdout.read() + proc.stderr.read()) >> else: >> print "Failure %s:\n%s" % (return_code, proc.stderr.read() + >> proc.stdout.read()) >> >> >> # execute using os.system (does work) >> os.system(cmd) >> >> >> -- Python code output of Popen -- >> Failure 1: >> dir/cpan.txt: No such file or directory >> >> >> -- Question -- >> Why is Popen unable to correctly execute the wget, while os.system can? > > I don't know exactly why in this case Popen doesn't work, > but the counterpart of os.system is Popen with option shell=True > and the first parameter should be a string instead of list. > That seems to work: > proc = Popen("wget -nv -O dir/cpan.txt http://search.span.org", > shell=True, stdout=PIPE, stderr=PIPE) > > and this variant seems to work too: > cmd_set = ['wget', '-nv', '-O', 'dir/cpan.txt', 'http://search.span.org'] > > -- > HTH, > Rob From rahulnag22 at yahoo.com Wed May 9 12:37:32 2007 From: rahulnag22 at yahoo.com (rahulnag22 at yahoo.com) Date: 9 May 2007 09:37:32 -0700 Subject: tkinter - Screen Resolution Message-ID: <1178728652.490682.239650@u30g2000hsc.googlegroups.com> Hi, I have developed a GUI using tkinter (grid geometory manager). The structure is a top frame containing multiple subframes. Each subframe has a combination of widgets like(Entry, label, button,listboxes). The subframes are placed with a padx and pady offset with regards to the other subframes. And the widgets within these subframes have their own padx and pady offsets. The GUI runs fine on my linux box, but on a different linux box things get wierd. I see things like- 1) The frame width increasing 2) The widget padx translating to much bigger offsets with reference to the subframe edges 3) Widget widths like that for Entry become bigger I Know its to do with the screen resolution settings and user settings on different machines. Can anyone point me in the right direction(before I start looking into it)as how to account for different screen resolutions so as to have as uniform a GUI look as possible across different user machines. A smaller version of my GUI layout looks something like--> ===============Top Frame================= = - SubFrame - ---------SubFrame--------- = - - - ''''''''''''''''''''''''''''''''' - = - - - ' Widget ' - = - - - ''''''''''''''''''''''''''''''''' - = - Widget - ----------------------------- = - - = - - ---------SubFrame--------- = - - - - = - - - ''''''''''''''''''''''''''''''''' - = - Widget - - ' Widget ' - = - - - ''''''''''''''''''''''''''''''''' - = - - - - = - - - ''''''''''''''''''''''''''''''''' - = - - - ' Widget ' - = - Widget - - ''''''''''''''''''''''''''''''''' - = --------------- ----------------------------- ========================================= Thanks Rahul From sjmachin at lexicon.net Sat May 26 21:34:40 2007 From: sjmachin at lexicon.net (John Machin) Date: 26 May 2007 18:34:40 -0700 Subject: Large Amount of Data In-Reply-To: References: <1180228756.574525.16110@q19g2000prn.googlegroups.com> Message-ID: <1180229680.523041.128650@o11g2000prd.googlegroups.com> On May 27, 11:24 am, "Jack" wrote: > I'll save them in a file for further processing. Further processing would be what? Did you read the remainder of what I wrote? From aleax at mac.com Fri May 25 10:41:02 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 25 May 2007 07:41:02 -0700 Subject: sockets, gethostname() changing References: <1180062244.266857.300830@m36g2000hse.googlegroups.com> <1180063489.535893.182970@x35g2000prf.googlegroups.com> <1180065033.520142.37050@q66g2000hsg.googlegroups.com> <1180076739.557165.196900@x35g2000prf.googlegroups.com> Message-ID: <1hynrtd.tvqdopconrxnN%aleax@mac.com> wrote: ... > > and I'm not connected to the internet and I run the program, I get: > > > > my-names-computer.local > > > > When I'm connected to the internet, I get: > > > > dialup-9.999.999.999.dial9.xxxxxxx.level9.net > > That would bug me to high hell. A router in the middle would probably > stop that. Looks like a DHCP configuration issue to me; one might try the remedies suggested at . Alex From gigs at hi.t-com.hr Thu May 10 13:26:07 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Thu, 10 May 2007 19:26:07 +0200 Subject: searching algorithm Message-ID: Hi all! I have text file (english-croatian dictionary) with words in it in alphabetical order. This file contains 179999 words in this format: english word: croatian word I want to make instant search for my gui Instant search, i mean that my program search words and show words to user as user type letters. yes, it needs to be fast Can someone give me some points (approaches) how to make this Should i make indexes and go with file.seek or should breake dictionary in peaces and put words that start with a in one and with b in another... ????? So if i have this words absinth:pelin absinthe:pelin absolute:apsolutan absolute:apsolutni kod absolute:apsolutno absolute:čist absolute:nesumnjiv absolute:potpun absolute:savr?en absolute coordinates:apsolutne koordinate absolute frequency:apsolutna učestalost absolute gap:apsolutni jaz absolute line spacing:apsolutni međurazmak linija absolute majority:apsolutna većina absolute pointing device:apsolutni pokazivački uređaj absolute quantity:apsolutni udio absolute value:apsolutna vrijednost absolute zero:apsolutna nula absolutely:apsolutno absolutely:bezuvjetno absolutely:nezavisno absolutely:potpuno absolutely:samostalno absolutely:sasvim absolution:odrje?enje absolution:opro?taj absolutism:apsolutizam absolve:odrije?iti absolve:osloboditi absorb:absorbirati absorb:apsorbirati absorb:crpsti if user type: "abs" program should list all words above in english and in croatian if user type: "absorb" than program should list last 3 words in english and in croatian any help would be appreciate! my apologies for bad english From jstroud at mbi.ucla.edu Tue May 8 00:11:53 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 07 May 2007 21:11:53 -0700 Subject: interesting exercise In-Reply-To: <1178595952.641173.76540@y80g2000hsf.googlegroups.com> References: <1178595952.641173.76540@y80g2000hsf.googlegroups.com> Message-ID: Michael Tobis wrote: > I want a list of all ordered permutations of a given length of a set > of tokens. Each token is a single character, and for convenience, they > are passed as a string in ascending ASCII order. > > For example > > permute("abc",2) > > should return ["aa","ab","ac","ba","bb","bc","ca","cb","cc"] > > and permute("13579",3) should return a list of 125 elements > ["111","113", ... ,"997","999"] > > permute("axc",N) or permute("2446",N) should raise ValueError as the > alphabet is not strictly sorted. > > I have a reasonably elegant solution but it's a bit verbose (a couple > dozen lines which I'll post later if there is interest). Is there some > clever Pythonism I didn't spot? > > thanks > mt > 1. You oughtta go ahead and post it. 2. Have you checked out xpermutations? http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/190465 James From gabor.urban at siemens.com Fri May 18 04:46:48 2007 From: gabor.urban at siemens.com (Urban, Gabor) Date: Fri, 18 May 2007 10:46:48 +0200 Subject: Python Newbie Suggestions Message-ID: <38F58D7B92CB20438DF49D28B572CC6FE3B3C6@budgw09a.ww300.siemens.net> Stephen wrote: " For a newbie any material referenced should be current and include what is available in Python 2.5." I disagree. A newbie should learn Python and and Python programming . Not the latest should be the best choice.... Gabor Urban NMC - ART -------------- next part -------------- An HTML attachment was scrubbed... URL: From bbxx789_05ss at yahoo.com Fri May 25 19:24:06 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 25 May 2007 16:24:06 -0700 Subject: problem with eval while using PythonCard In-Reply-To: References: <1180130097.439585.308510@g4g2000hsf.googlegroups.com> <1180130703.577624.167360@u30g2000hsc.googlegroups.com> Message-ID: <1180135446.101683.205830@o5g2000hsb.googlegroups.com> On May 25, 4:43 pm, "Michal Lipinski" wrote: > now it's working just fine. but still I dont know why eval dont work ? > > and thx for help > > 25 May 2007 15:05:03 -0700, 7stud : > > > > > Here's a complete example: > > > ################### > > #create object 's': > > > class S(object):pass > > class X(object):pass > > class Y(object):pass > > > s = S() > > s.components = X() > > s.components.d1 = Y() > > s.components.d2 = Y() > > s.components.d3 = Y() > > ###################### > > > ###################### > > set some initial values: > > for i in range(1, 4): > > obj = getattr(s.components, "d" + str(i)) > > obj.text = "hello world" > > ##################### > > > ##################### > > #change the values: > > for i in range(1, 4): > > getattr(s.components, "d" + str(i)).text = "goodybe" > > ##################### > > > ##################### > > #print out the new values: > > for i in range(1, 4): > > print getattr(s.components, "d" + str(i)).text > > ##################### > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > Pozdrawiam > > Micha? Lipi?ski > > http://lipton.kom.pl 1) Don't use eval() 2) Don't use eval() 3) eval() only works on python "expressions". In python, an assignment statement is not an expression. From anton.vredegoor at gmail.com Tue May 15 05:07:02 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Tue, 15 May 2007 11:07:02 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> <4648294F.2000704@web.de> <46487a6c$0$2400$426a74cc@news.free.fr> Message-ID: Duncan Booth wrote: > Recently there has been quite a bit of publicity about the One Laptop Per > Child project. The XO laptop is just beginning rollout to children and > provides two main programming environments: Squeak and Python. It is an > exciting thought that that soon there will be millions of children in > countries such as Nigeria, Brazil, Uruguay or Nepal[*] who have the > potential to learn to program, but tragic if the Python community is too > arrogant to consider it acceptable to use anything but English and ASCII. Please don't be too quick with assuming arrogance. I have studied social psychology for eleven years and my thesis was just about such a subject. I even held a degree in social psychology for some time before my government in their infinite wisdom decided to 'upgrade' the system so that only people holding *working* positions at a university would be able to convert their degrees to the new system. I suspect discerning people can still sense a twinge of disagreement with that in my professional attitude. However I still think the results of my research were valid. The idea was to try and measure whether it would be better for foreign students visiting the Netherlands to be kept in their own separate groups being able to speak their native language and to hold on to their own culture versus directly integrating them with the main culture by mixing them up with Dutch student groups (in this case the main culture was Dutch). I think I my research data supported the idea that it is best even for the foreigners themselves to adapt as quickly as possible to the main culture and start to interact with it by socializing with 'main culture' persons. My research at that time didn't fit in at all with the political climate of the time and subsequently it was impossible for me to find a job. That didn't mean that I forgot about it. I think a lot of the same ideas would help the OLPC project so that they will not make the same mistake of creating separate student populations. I believe -but that is a personal belief which I haven't been able to prove yet by doing research- that those people currently holding positions of power in the main culture actively *prevent* new groups to integrate because it would threaten their positions of power. So instead of having a favorable view of teachers who are 'adapting' to their students culture I have in fact quite the opposite view: Those teachers are actually harming the future prospects of their students. I'm not sure either whether they do it because they're trying to protect their own positions or are merely complicit to higher up political forces. Whatever you make of my position I would appreciate if you'd not directly conclude that I'm just being arrogant or haven't thought about the matter if I am of a different opinion than you. > Yes, any sensible widespread project is going to mandate a particular > language for variable names and comments, but I see no reason at all why > they all have to use English. Well I clearly do see a reason why it would be in their very best interest to immediately start to use English and to interact with the main Python community. > [*] BTW, I see OLPC Nepal is looking for volunteer Python programmers this > Summer: if anyone fancies spending 6+ weeks in Nepal this Summer for no > pay, see http://www.mail-archive.com/devel at laptop.org/msg04109.html Thanks. I'll think about it. The main problem I see for my participation is that I have absolutely *no* personal funds to contribute to this project, not even to pay for my trip to that country or to pay my rent while I'm abroad. A. From bbxx789_05ss at yahoo.com Sat May 19 14:58:15 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 19 May 2007 11:58:15 -0700 Subject: docs patch: dicts and sets In-Reply-To: References: <_5-dnU7aIN73j9LbnZ2dnUVZ_uCinZ2d@comcast.com> <1179593927.503393.127350@u30g2000hsc.googlegroups.com> <1179596822.923443.67500@k79g2000hse.googlegroups.com> Message-ID: <1179601094.940650.276120@w5g2000hsg.googlegroups.com> On May 19, 12:36 pm, Steve Holden wrote: > The last thing I want to read in a language's documentation is an > ill-informed and sometimes interminable argument about a particular feature. > Yet some readers will be able to get to the bottom of an issue they are having by reading those comments. From yavannadil at yahoo.com Fri May 4 00:34:20 2007 From: yavannadil at yahoo.com (yavannadil at yahoo.com) Date: 3 May 2007 21:34:20 -0700 Subject: How do I get type methods? In-Reply-To: References: <1178220806.664557.245780@c35g2000hsg.googlegroups.com> Message-ID: <1178253260.075515.43810@q75g2000hsh.googlegroups.com> On May 4, 3:21 am, Stargaming wrote: > What's wrong about `dir()`? > x = MyClass() > x.f() I want to cashe pointers to Python functions in a non-Python app. 'dir()' requires an argument, and I want to get function pointers before I have any variable of given type or class. That's why 'MyClass.f(x)' I'm not against 'dir(MyClass)'; the question is, what should I 'dir()' to get methods of 'pyuno' type instance? Sincerely yours, Dmitri From michael at jedimindworks.com Wed May 16 15:50:31 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Wed, 16 May 2007 14:50:31 -0500 Subject: removing common elemets in a list In-Reply-To: <1179329801.699092.154700@o5g2000hsb.googlegroups.com> References: <1179296224.885877.187200@q23g2000hsg.googlegroups.com> <1179329801.699092.154700@o5g2000hsb.googlegroups.com> Message-ID: <85B28D6C-578E-4C59-AFD6-48ABE859DDDD@jedimindworks.com> On May 16, 2007, at 10:36 AM, John Zenger wrote: > On May 16, 2:17 am, saif.shak... at gmail.com wrote: >> Hi, >> Suppose i have a list v which collects some numbers,how do i >> remove the common elements from it ,without using the set() opeartor. >> Thanks > > Submit this as your homework answer -- it will blow your TA's mind! > > import base64 > def uniq(v): > return > eval(base64.b64decode > ('c29ydGVkKGxpc3Qoc2V0KHYpKSxrZXk9bGFtYmRhIHg6di5pbmRleCh4KSk='),local > s()) Nice! But I think he said he couldn't use set() ;-) From george.sakkis at gmail.com Tue May 29 23:42:23 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 29 May 2007 20:42:23 -0700 Subject: Rats! vararg assignments don't work In-Reply-To: <1180496033.608791.35840@g37g2000prf.googlegroups.com> References: <1180496033.608791.35840@g37g2000prf.googlegroups.com> Message-ID: <1180496542.955320.5430@m36g2000hse.googlegroups.com> On May 29, 11:33 pm, Matimus wrote: > Your attemtp: > > [code] > first, rest = arglist[0], arglist[1:] > [/code] > > Is the most obvious and probably the most accepted way to do what you > are looking for. As for adding the fucntionality you first suggested, > it isn't likely to be implemented. The first step would be to write a > PEP though. The time machine did it again: http://www.python.org/dev/peps/pep-3132/. George From nagle at animats.com Tue May 1 12:34:09 2007 From: nagle at animats.com (John Nagle) Date: Tue, 01 May 2007 09:34:09 -0700 Subject: Why are functions atomic? In-Reply-To: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> References: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> Message-ID: Michael wrote: > Why are functions atomic? (I.e. they are not copied.) Because Python has objects for when you need to associate state with a function. John Nagle From grante at visi.com Fri May 11 15:55:28 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 11 May 2007 19:55:28 -0000 Subject: Interesting list Validity (True/False) References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> Message-ID: <1349ihg6j1e1k95@corp.supernews.com> On 2007-05-11, nufuhsus at gmail.com wrote: > Then why do I get the following results: > C:\Python25\rg.py>help.py -o > print arg ['-o'] > type(arg): > arg is True? False > help.py version 1.0 Copyright RDEG (c) 2007 > ['-o'] is an unrecognized option. > Progam Exit (0) You got those results because that's what your program does. Were you intending it to do something else? If so, you're going to have to explain what you wanted, because we can't read your mind. -- Grant Edwards grante Yow! Hey, wait at a minute!! I want a visi.com divorce!! ... you're not Clint Eastwood!! From iltchevi at gmail.com Fri May 18 18:51:40 2007 From: iltchevi at gmail.com (ici) Date: 18 May 2007 15:51:40 -0700 Subject: Compiling Python code within a module In-Reply-To: References: Message-ID: <1179528700.031053.307480@k79g2000hse.googlegroups.com> On May 19, 12:52 am, Mitko Haralanov wrote: > For various reason, what I need to do is be able to send some Python > code (mostly entire functions in the form of a string) to a remote > server (written in Python), have that server compile the code and > insert it in the local namespace so it is available to be called at a > later time. > > I have gotten the sending and receiving part already written and that > works. However, I can't get the compiling part! I have looked at the > compile module and while it is able to compile the code I am not > entirely sure what to do with the returned code object so it get's > inserted as a local function. > > I would appreciate any help that you guys might be able to offer? > > Thanks > > -- > Mitko Haralanov m... at qlogic.com > Senior Software Engineer 650.934.8064 > System Interconnect Group http://www.qlogic.com > > ========================================== > The "cutting edge" is getting rather dull. > -- Andy Purshottam exec it :) --- Example--- exec(compile(""" def test(): import os for i in os.listdir('.'): print i """,'', 'exec')) test() --- End example--- Now you have test() function available in namespace where executed example Po-zdravi From fadereu at gmail.com Mon May 28 01:42:51 2007 From: fadereu at gmail.com (DJ Fadereu) Date: 27 May 2007 22:42:51 -0700 Subject: Help with PySMS In-Reply-To: <1180302791.160909.91570@k79g2000hse.googlegroups.com> References: <1180264285.477306.137830@r19g2000prf.googlegroups.com> <1180302791.160909.91570@k79g2000hse.googlegroups.com> Message-ID: <1180330971.611017.247510@x35g2000prf.googlegroups.com> On May 28, 1:53 am, Petr Jakes wrote: > Maybe you can try python binding for gammu, which works great for me. > HTH > Petr Jakes > > http://cihar.com/gammu/python/ I'm going to try and setup Gammu today. I'm using a DKU-2 cable connection. The Gammu guide says that:"Before you will try connect to Gammu, you have to install gnapplet application in phone first. Later steps depends on connection type. For example for Bluetooth use "bluerfgnapbus" connection and model "gnap" and device addresss as "port". You can read notes described below for infrared and Bluetooth too. Cables connections (DKE-2, DKU-2, etc.) are not supported by gnapplet now." Now I'm having some trouble catching Bluetooth on my laptop, I don't know why - maybe the radio died. So now it's unclear whether this gnapplet thingie stillneeds to be on my Nokia 6300 even if I'm going through the cable route. Any hints? From bbxx789_05ss at yahoo.com Thu May 17 12:22:08 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 17 May 2007 09:22:08 -0700 Subject: Newbie: Joining Lists In-Reply-To: <1179395397.157566.209330@l77g2000hsb.googlegroups.com> References: <1179395397.157566.209330@l77g2000hsb.googlegroups.com> Message-ID: <1179418928.143129.16320@n59g2000hsh.googlegroups.com> On May 17, 3:49 am, mosscliffe wrote: > I have been playing with GLOB and OS.PATH and it all works, but is > there a better way of getting GLOB to recognise, multiple patterns at > one call (ONE). > A better way? You haven't posted a way to do that. And a quick perusal of the docs for the glob module shows that glob uses some very simplistic unix like pattern matching, and there are only 4 symbols you can use. None of them allow alternate patterns, so, no, you can't match multiple patterns in one pass. You can use os.listdir() and regexes if you want. > Also is it possible to join lists, without the horrid concatenation > code I have Horrid? What did you have in mind? You can use the += operator: filenames += glob.glob(pattern) If your aversion to concatenation runs too deep, you could use a loop: for file in glob.glob(pattern): filenames.append(file) From shuimuliang at gmail.com Tue May 29 22:20:39 2007 From: shuimuliang at gmail.com (shuimuliang at gmail.com) Date: 29 May 2007 19:20:39 -0700 Subject: tag py-compile errors,[develop with Eclipse and pyAnt] Message-ID: <1180491639.440787.132280@i13g2000prf.googlegroups.com> I configured Eclipse according to the paper http://www.ibm.com/developerworks/library/os-ecant/index.html. But, when I build the ant file,it failed with the following message: Could not create task or type of type: py-compile. I hava added pyAntTasks.jar to ${eclipse}/plugins/ org.apache.ant_version/. How to solve this problem,thanks. From gagsl-py2 at yahoo.com.ar Wed May 23 04:23:40 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 23 May 2007 05:23:40 -0300 Subject: Module listing in order. References: <1179905562.541601.264400@m36g2000hse.googlegroups.com> Message-ID: En Wed, 23 May 2007 04:32:42 -0300, Ramashish Baranwal escribi?: > I want to get a module's contents (classes, functions and variables) > in the order in which they are declared. Using dir(module) therefore > doesn't work for me as it returns a list in alphabetical order. As an Once the module is created, you can't: its namespace is a dictionary, with no key ordering. So you have to play with the module creation: get some kind of dictionary that remembers insertion order, and use it as the globals argument to __import__. (Some builtin operations require a true dictionary or use it in a non-polimorphic way, so this may or may not work - you'll have to try and please follow up with your findings) -- Gabriel Genellina From john at datavoiceint.com Mon May 14 10:00:06 2007 From: john at datavoiceint.com (HMS Surprise) Date: 14 May 2007 07:00:06 -0700 Subject: Time In-Reply-To: <1178927105.482975.174760@y5g2000hsa.googlegroups.com> References: <1178916216.893542.257320@y80g2000hsf.googlegroups.com> <1178916422.065108.312920@l77g2000hsb.googlegroups.com> <1178920014.621031.301860@n59g2000hsh.googlegroups.com> <1178927105.482975.174760@y5g2000hsa.googlegroups.com> Message-ID: <1179151205.987222.54910@k79g2000hse.googlegroups.com> Thanks for posting. I sure am sorry that I wasted your time. I should have started the post stating I am using jython 2.2.3 and apparently it has no datetime module. But I will keep datetime in mind for future reference. Since I had no datetime I cobbled out the following. Seems to work thus far. Posted here for the general amusement of the list. Regards, jvh ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ from time import * s = '05/11/2007 1:23 PM' t = s.split() mdy = t[0].split('/') hrMn = t[1].split(':') if t[2] == 'PM': hrMn[0] = int(hrMn[0]) + 12 tuple =(int(mdy[2]), int(mdy[0]), int(mdy[1]), hrMn[0], int(hrMn[1]), 0,0,0,0) print tuple eTime = mktime(tuple) print 'eTime', eTime From mccredie at gmail.com Wed May 16 19:48:39 2007 From: mccredie at gmail.com (Matimus) Date: 16 May 2007 16:48:39 -0700 Subject: Declaring variables In-Reply-To: <1179334649.990688.73320@o5g2000hsb.googlegroups.com> References: <1179334649.990688.73320@o5g2000hsb.googlegroups.com> Message-ID: <1179359317.494376.259990@n59g2000hsh.googlegroups.com> On May 16, 9:57 am, HMS Surprise wrote: > I looked in the language but did not find a switch for requiring > variables to be declared before use. > > Is such an option available? > > Thanks, > > jvh You do have to declare a variable before use. You do so by assigning it a value. You can't use a variable before it has been assigned. In some ways this is less ambiguous than even C where you can declare a variable without assigning a value. Also note that this caries the type information, since the variable is of whatever type was assigned to it. The only thing it doesn't do is give a unique flag that says "hey this is where I'm declared", although I suppose you could do that with a comment. Matt From r.grimm at science-computing.de Sat May 19 11:33:51 2007 From: r.grimm at science-computing.de (Rainer Grimm) Date: Sat, 19 May 2007 17:33:51 +0200 Subject: Beginner question: module organisation In-Reply-To: <1179148188.698342.317080@w5g2000hsg.googlegroups.com> References: <1179148188.698342.317080@w5g2000hsg.googlegroups.com> Message-ID: Mail.To.Nathaniel at gmail.com wrote: > Hello :) > > I am new to python and I don't have much expirience in object-oriented > technologies neither. > > The problem is the following: I have to create a simple python > template script that will always follow the same algorithm, let's say: > - read a mesh > - transform the mesh (let's say, refine) > > The last step should be a kind of a black box: > - the same input data format > - some algorithme inside > - the same output data format > > A number of different refine methods should be implemented. The end- > user must be able to write easily a new method and call it from the > base script without any major change. > > Something like this would be a solution (no classes created, no OO > programming): > - a module defining REFINE1(mesh), REFINE2(mesh), ... > - in the script: > from MODULE import REFINE2 as REFINE > REFINE(mesh) > > Is it a proper solution for this kind of problem? How would you > implement this kind of task? > Hello. Have a look at the classical GangOfFour design pattern book. You can especially with the template methode design the processing of your data. The strategy pattern will help you to vary the algroithm in your processing. To be concret, in your base class you define the processing of the data. There are two distinct methods to do it. delegate the variation of the algorithmns to other objects => strategy pattern override the steps of the processing in subclasses => template method Regards, Rainer -- _________________________creating IT solutions Rainer Grimm scVENUS Schulungsleiter science + computing ag phone +49(0)7071 9457-253 Hagellocher Weg 73 fax +49(0)7071 9457-511 D-72070 Tuebingen, Germany r.grimm at science-computing.de www.science-computing.de From bscrivener42 at gmail.com Sun May 13 14:03:20 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: 13 May 2007 11:03:20 -0700 Subject: need help with python In-Reply-To: <1179069008.711095.301770@p77g2000hsh.googlegroups.com> References: <1178934447.719778.197150@h2g2000hsg.googlegroups.com> <1178988911.443161.287350@k79g2000hse.googlegroups.com> <1179069008.711095.301770@p77g2000hsh.googlegroups.com> Message-ID: <1179079400.882861.111220@y80g2000hsf.googlegroups.com> On May 13, 10:10 am, adamur... at hotmail.com wrote: > > That is one of my problems, I don't know exactly how the whole command > line thing works. That's why I pointed you to the link. The ActiveState distribution will automatically add the correct paths to your environment and tell Windows that .py files are executable Python files and so on. Get ActiveState installed. Get comfortable with the Python IDE. Then follow the instructions in Alan Gauld's tutorial. http://www.freenetpages.co.uk/hp/alan.gauld/ Especially, in your case, the GETTING STARTED section, which includes a subsection called "The Windows Command Prompt" rd From jackson at hotmail.com Fri May 25 19:03:15 2007 From: jackson at hotmail.com (Bill Jackson) Date: Fri, 25 May 2007 16:03:15 -0700 Subject: matplotlib, usetex In-Reply-To: References: Message-ID: Alexander Schmolck wrote the following on 05/25/2007 02:33 PM: > (BTW what happens if you do axis([0,128,0,128])). In [1]: import pylab In [2]: pylab.axis([0,128,0,128]) In [3]: pylab.show() --------------------------------------------------------------------------- Traceback (most recent call last) /usr/lib/python2.5/site-packages/matplotlib/backends/backend_gtk.py in expose_event(self, widget, event) 282 x, y, w, h = self.allocation 283 self._pixmap_prepare (w, h) --> 284 self._render_figure(self._pixmap, w, h) 285 self._need_redraw = False 286 /usr/lib/python2.5/site-packages/matplotlib/backends/backend_gtk.py in _render_figure(self, pixmap, width, height) 270 """ 271 self._renderer.set_width_height (width, height) --> 272 self.figure.draw (self._renderer) 273 274 /usr/lib/python2.5/site-packages/matplotlib/figure.py in draw(self, renderer) 542 543 # render the axes --> 544 for a in self.axes: a.draw(renderer) 545 546 # render the figure text /usr/lib/python2.5/site-packages/matplotlib/axes.py in draw(self, renderer, inframe) 1061 1062 for zorder, i, a in dsu: -> 1063 a.draw(renderer) 1064 1065 self.transData.thaw() # release the lazy objects /usr/lib/python2.5/site-packages/matplotlib/axis.py in draw(self, renderer, *args, **kwargs) 559 tick.set_label1(label) 560 tick.set_label2(label) --> 561 tick.draw(renderer) 562 if tick.label1On and tick.label1.get_visible(): 563 extent = tick.label1.get_window_extent(renderer) /usr/lib/python2.5/site-packages/matplotlib/axis.py in draw(self, renderer) 159 if self.tick2On: self.tick2line.draw(renderer) 160 --> 161 if self.label1On: self.label1.draw(renderer) 162 if self.label2On: self.label2.draw(renderer) 163 /usr/lib/python2.5/site-packages/matplotlib/text.py in draw(self, renderer) 836 def draw(self, renderer): 837 self.update_coords(renderer) --> 838 Text.draw(self, renderer) 839 if self.get_dashlength() > 0.0: 840 self.dashline.draw(renderer) /usr/lib/python2.5/site-packages/matplotlib/text.py in draw(self, renderer) 348 349 renderer.draw_tex(gc, x, y, line, --> 350 self._fontproperties, angle) 351 return 352 /usr/lib/python2.5/site-packages/matplotlib/backend_bases.py in draw_tex(self, gc, x, y, s, prop, angle, ismath) 379 380 def draw_tex(self, gc, x, y, s, prop, angle, ismath='TeX!'): --> 381 raise NotImplementedError 382 383 def draw_text(self, gc, x, y, s, prop, angle, ismath=False): : In [4]: From tjansson60 at gmail.com Sat May 12 14:04:51 2007 From: tjansson60 at gmail.com (Thomas Jansson) Date: 12 May 2007 11:04:51 -0700 Subject: Creating a function to make checkbutton with information from a list? Message-ID: <1178993091.198864.94590@k79g2000hse.googlegroups.com> Dear all I am writing a program with tkinter where I have to create a lot of checkbuttons. They should have the same format but should have different names. My intention is to run the functions and the create all the buttons with the names from the list. I now the lines below doesn't work, but this is what I have so far. I don't really know how call the element in the dict use in the for loop. I tried to call +'item'+ but this doesn't work. def create_checkbox(self): self.checkbutton = ["LNCOL", "LFORM", "LPOT", "LGRID", "LERR", "LCOMP"] for item in self.checkbutton: self.+'item'+Checkbutton = Chekcbutton(frame, onvalue='t', offvalue='f', variable=self.+'item'+) self.+'item'+Checkbutton.grid() How should I do this? Kind regards Thomas Jansson From ashokagk at gmail.com Thu May 31 21:53:51 2007 From: ashokagk at gmail.com (Ashok) Date: Thu, 31 May 2007 18:53:51 -0700 Subject: get message form ie Message-ID: <1180662831.833019.214020@o11g2000prd.googlegroups.com> Hi, Is there any way i can get a message form internet explorer into my python script when internet explorer completes loading a page? _____ ashok From different.engine at gmail.com Fri May 11 15:32:55 2007 From: different.engine at gmail.com (different.engine at gmail.com) Date: 11 May 2007 12:32:55 -0700 Subject: stealth screen scraping with python? Message-ID: <1178911975.308104.297380@n59g2000hsh.googlegroups.com> Folks: I am screen scraping a large volume of data from Yahoo Finance each evening, and parsing with Beautiful Soup. I was wondering if anyone could give me some pointers on how to make it less obvious to Yahoo that this is what I am doing, as I fear that they probably monitor for this type of activity, and will soon ban my IP. -DE From wildemar at freakmail.de Thu May 24 02:28:40 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Thu, 24 May 2007 08:28:40 +0200 Subject: Properties/Decorators [WAS: Can I reference 1 instance of an object by more names ? rephrase] In-Reply-To: <5bju51F2taechU1@mid.uni-berlin.de> References: <4654289a$0$2326$426a74cc@news.free.fr> <5bj1ddF2sd0aoU1@mid.uni-berlin.de> <5bju51F2taechU1@mid.uni-berlin.de> Message-ID: <46553098.2030607@freakmail.de> Diez B. Roggisch wrote: > Deprecated doesn't mean it's not available. Is that so? ;) But it certainly means that some time in the not-too-distant future "apply" will vanish. > And even if it goes away, > you can simply write it yourself: > > def apply(f, *args, **kwargs): > return f(*args, **kwargs) > Do you know that feeling you have, when you've just been shown something really surprising but utterly simple, that blows you away so much that for a moment the whole world seems like magic and you feel you are just a mundane pencilhead? I get that a lot ... ;) W From jorgen.maillist at gmail.com Thu May 10 04:33:15 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Thu, 10 May 2007 10:33:15 +0200 Subject: preferred windows text editor? In-Reply-To: <1178783872.463067.297280@o5g2000hsb.googlegroups.com> References: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> <1178749301.768963.278070@w5g2000hsg.googlegroups.com> <1178783872.463067.297280@o5g2000hsb.googlegroups.com> Message-ID: <11e49df10705100133u33e94f84kdb762d3d7d756b24@mail.gmail.com> I prefer PsPad. If you like Notepad++, PSPad might be a better choice. More intuitive. I've used Notepad++ for a while, I really disliked the fact that every new install my settings XML file would get overwritten, and what does that guy have with Comic sans MS? Every default style is hard coded into the app, to that strange oddly looking style for comments etc. Anyway, I do not want to get too personal. PsPad is very nice, I also use more python-like editors like SPE and UliPad. - Jorgen On 10 May 2007 00:57:52 -0700, Ant wrote: > On May 9, 11:21 pm, BartlebyScrivener wrote: > ... > > I too vote for VIM. I use it on both Windows XP and Debian Etch. I > > can't find anything it doesn't do. > > I also use Vim (well, GVim). > > The only thing I find missing is an integrated console for running > code snippets/entire scripts. The runscript plugin is OK, but lacks > interactive use. I have been thinking about some way of interacting > with a Python shell using sockets to send snippets directly to the > shell from Vim, but haven't had time to get very far. > > What method of executing code snippets in a Python shell do other Vim > users use? Other than just copy/paste? > > -- > http://mail.python.org/mailman/listinfo/python-list > From jzgoda at o2.usun.pl Wed May 9 03:28:17 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Wed, 09 May 2007 09:28:17 +0200 Subject: Gui thread and async jobs. In-Reply-To: <1178627450.408287.139070@p77g2000hsh.googlegroups.com> References: <1178627450.408287.139070@p77g2000hsh.googlegroups.com> Message-ID: king kikapu napisa?(a): > Hi, i am reading the book "Python Cookbook, 2nd edition" and i > encountered a very handy recipe, the one that is called "Combining > GUIs and Asynchronous I/O with Threads" > > It is talking about retain a main GUI thread, doing async work with > worker threads and have both talk through a Queue object to dispatch > their messages, so the main (GUI) thread remain responsive. > It has a very good example by using Tkinter and Qt that is indeed > working. The only point that make me wonder is that the QUI thread has > to use some polling to check for messages in the Queue. > > Author said that another alternatives exists (by not doing polling) > but the complexity makes them non-practical for the 90% of ocassions. > I remember in C# we deal with that sort of things with events/ > delegates. > Hos the same thing is possible in Python, has anyone any link(s) to > have a look ? Another option, although not a silver bullet, is to use a message dispatcher, like Louie (http://www.pylouie.org/). Unfortunately, the Louie dispatcher seems to be synchronous, so I wouldn't recommend it for the environment with "high density" of events. If your application dispatches a message then sits idle for some time, Louie will fit perfectly as the queuing of messages will not happen. Otherwise there would be no advantage other than code simplification. And this counts always. :) -- Jarek Zgoda "We read Knuth so you don't have to." From mikeminer53 at hotmail.com Wed May 23 12:43:49 2007 From: mikeminer53 at hotmail.com (mkPyVS) Date: 23 May 2007 09:43:49 -0700 Subject: Resizing listbook's listview pane In-Reply-To: <1179932659.180278.72990@w5g2000hsg.googlegroups.com> Message-ID: <1179938629.812240.141440@p47g2000hsd.googlegroups.com> Sorry, copied from wxpython submit as well.. I'm using wxpython 2.8... Primariy I want the resize to happen programatically during object creation/post creation... I can worry about app size changes later. Thanks, From cf at seehomepage.com Tue May 1 07:53:46 2007 From: cf at seehomepage.com (Candida Ferreira) Date: Tue, 01 May 2007 11:53:46 GMT Subject: PyGEP: Gene Expression Programming for Python Message-ID: Dear All, There's another open source GEP library released under the GNU. Its owner is Ryan O'Neil, a graduate student from George Mason University. In his words, "PyGEP is a simple library suitable for academic study of Gene Expression Programming in Python 2.5, aiming for ease of use and rapid implementation. It provides standard multigenic chromosomes; a population class using elitism and fitness scaling for selection; mutation, crossover and transposition operators; and some standard GEP functions and linkers." PyGEP is hosted at: http://code.google.com/p/pygep/ It looks really nice and a good GEP implementation and Ryan seems to be working really hard to maintain and improve it. So please go take a look and join the project. Best wishes, Candida --- Candida Ferreira, Ph.D. Founder and Director, Gepsoft http://www.gene-expression-programming.com/author.asp GEP: Mathematical Modeling by an Artificial Intelligence. 2nd Edition, Springer, 2006 http://www.gene-expression-programming.com/Books/index.asp GeneXproTools 4.0 -- Data Mining Software Join Associates and earn 10% in referral fees! http://www.gepsoft.com/ From tmp123 at menta.net Thu May 3 03:28:03 2007 From: tmp123 at menta.net (tmp123) Date: 3 May 2007 00:28:03 -0700 Subject: pack/unpack zero terminated string In-Reply-To: <1178140425.827144.57150@q75g2000hsh.googlegroups.com> References: <1178114191.580368.59520@c35g2000hsg.googlegroups.com> <1178140425.827144.57150@q75g2000hsh.googlegroups.com> Message-ID: <1178177283.529278.271210@p77g2000hsh.googlegroups.com> On May 2, 11:13 pm, John Machin wrote: > On May 3, 12:01 am, Laurent Pointal wrote: > > > > > > > > >tmp123a ?crit : > > > > Hello, > > > > Thanks for your time. > > > > After review the "struct" documentation, it seems there are no option > > > to pack/unpack zero terminated strings. > > > > By example, if the packed data contains: byte + zero terminated string > > > + zero terminated string + byte, it seems no possible to unpack it > > > using "struct". > > > > Please, has someone any hint or pointer to another librarian to be > > > used? > > > May look at xstruct too > > >http://www.sis.nl/python/xstruct/xstruct.shtml > > Hi, Laurent, > > It's a reasonable presumption that the OP needs to unpack *variable- > length* zero-terminated strings, otherwise why is he asking? This > would need a new format type e.g. "z". > > xstruct doesn't appear to offer variable-length strings, and is frozen > in time (October 1999) -- inspection of the source shows that it is a > copy of Python 1.5.2 structmodule.c with added stuff. > > The OP might like to try a bit of DIY in Python, along the following > lines: > > C:\junk>type unpackz.py > def getz(strg, start=0): > zpos = strg.index('\0', start) > return strg[start:zpos], zpos + 1 > > def getB(strg, start=0): > return ord(strg[start]), start + 1 > > def unpack_BzzB(strg): > pos = 0 > r0, pos = getB(strg, pos) > r1, pos = getz(strg, pos) > r2, pos = getz(strg, pos) > r3, pos = getB(strg, pos) > assert pos == len(strg) > return r0, r1, r2, r3 > > x = chr(42) + 'foo\0' + 'mumble\0' + '\xff' > print unpack_BzzB(x) > print unpack_BzzB('\0' * 4) > > C:\junk>unpackz.py > (42, 'foo', 'mumble', 255) > (0, '', '', 0) > > HTH, > John Hello John, Totally true, the solution you propose is the one I'm using now. The subject was, before to start from scratch, try to reuse something existing. Another possibility was to modify the "struct" package with the new option, but it seems a mixed C-Python implementation, and I do not like to start having compatibility problems in the C elements. Kind regards. From gagsl-py2 at yahoo.com.ar Mon May 7 03:28:42 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 07 May 2007 04:28:42 -0300 Subject: invoke user's standard mail client References: <1178266064.922925.125760@y80g2000hsf.googlegroups.com> <1178513538.133114.81940@p77g2000hsh.googlegroups.com> Message-ID: En Mon, 07 May 2007 01:52:18 -0300, luc.saffre at gmail.com escribi?: > On May 6, 9:50 am, "Gabriel Genellina" wrote: >> On Windows you can use MAPI. > But how? I could not find any starting point. Get the pywin32 package (Python for Windows extensions) from sourceforge, install it, and look into the win32comext\mapi\demos directory. > I found examples about sending mail directly, which gives me the > impression that MAPI is just Microsoft's version of SMTP. This is not > what I need. I need the user's client to start, so that the user may > edit the message and decide herself whether she clicks on the Send > button to really send it. No, it should launch the email client (Outlook Express by example) and let the user confirm it. I think there were some flags to suppress the GUI or the confirmation, but they're not honored anymore, I presume. At least Eudora warns the user on such attempts. -- Gabriel Genellina From deepbroke6 at gmail.com Sat May 19 23:04:40 2007 From: deepbroke6 at gmail.com (deepbroke6 at gmail.com) Date: 19 May 2007 20:04:40 -0700 Subject: L@@K Free Pussy and Tit flash Download! Message-ID: <1179630280.622332.221210@u30g2000hsc.googlegroups.com> http://nudepicks.blogspot.com/ - take it easy these girls like it deep try the pussy flash game for free! From nogradi at gmail.com Thu May 17 13:36:42 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Thu, 17 May 2007 19:36:42 +0200 Subject: [ANN] markup.py 1.7 Message-ID: <5f56302b0705171036w3d009b67tbfd0e8f6375a02f7@mail.gmail.com> A new release is available for markup.py, a module for generating HTML/XML output painlessly and practically without any learning curve. The goal of markup.py is to be able to quickly put together documents in an ad hoc basis so if you need anything for production look for something else, e.g. ElementTree. Downloads are here: http://markup.sourceforge.net/ From rex at no_spam.dicad.de Thu May 24 07:21:50 2007 From: rex at no_spam.dicad.de (Rex Turnbull) Date: Thu, 24 May 2007 13:21:50 +0200 Subject: 0 == False but [] != False? In-Reply-To: References: <1179982400.412340.178710@g4g2000hsf.googlegroups.com> <1rda53hphn117k5scvcqrc7c2e37utfhgu@4ax.com> Message-ID: Steven D'Aprano : > On Thu, 24 May 2007 06:59:32 +0000, Tim Roberts wrote: > >> As a general rule, I've found code like "if x == False" to be a bad idea in >> ANY language. > > > Surely that should be written as "if (x == False) == True"? > > Why compare to False? " if not x : ... " It really doesn't matter if x is False or if it evaluates to False. Many things evaluate to False like [], (), 0, "", None and a few other things. >>> def tf(thing): ... if thing : print "True thing", thing ... elif not thing : print "False thing",thing ... else : print "No thing" ... >>> tf([]) False thing [] >>> tf([1]) True thing [1] >>> a = () >>> tf(a) False thing () >>> a=(0) >>> tf(a) False thing 0 >>> a= (1,2,3) >>> tf(a) True thing (1, 2, 3) >>> tf("abc") True thing abc >>> tf("") False thing >>> From mail at timgolden.me.uk Wed May 2 03:47:30 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 02 May 2007 08:47:30 +0100 Subject: Dynamic File Name Open() In-Reply-To: <001c01c78c7c$d14657f0$73d307d0$@rawlins@thinkbluemedia.co.uk> References: <001c01c78c7c$d14657f0$73d307d0$@rawlins@thinkbluemedia.co.uk> Message-ID: <46384212.1040308@timgolden.me.uk> Robert Rawlins - Think Blue wrote: > I'm trying to open a file using open() but the name of the file is created > dynamically as a variable, but also has part of a static path. For instance, > the file may be called 'dave' and will always be in '/my/files/here/'. Well that's an absolutely normal way of doing things, so if my toy example below doesn't make things clear, you'd better post a code fragment and/or some traceback. import os, sys path = "c:/temp" for filename in ["chas.txt", "dave.txt"]: f = open (os.path.join (path, filename)) print filename print f.read () print f.close () TJG From bscrivener42 at gmail.com Sun May 27 08:45:44 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: 27 May 2007 05:45:44 -0700 Subject: ten small Python programs In-Reply-To: References: Message-ID: <1180269944.944150.135930@q66g2000hsg.googlegroups.com> On May 26, 1:43 pm, Steve Howell wrote: > ------ > parentRabbits, babyRabbits = (1, 1) > while babyRabbits < 100: > print 'This generation has %d rabbits' % > babyRabbits > parentRabbits, babyRabbits = (babyRabbits, > parentRabbits + babyRabbits) > > ------ > # def defines a method in Python > def tax(itemCharge, taxRate = 0.05): > return itemCharge * taxRate > print '%.2f' % tax(11.35) > print '%.2f' % tax(40.00, 0.08) > For the person new to programming (doesn't come from C or other languages), I think you need to add a separate explanation of string formatting and how it works, or at least add a comment that tells them you are using string formatting so that they can search and find out how it works. If your aim is to teach simple programming concepts, why confuse them so early on with fancy interpolation? Something like # uses Python string formatting # http://docs.python.org/lib/typesseq-strings.html but really I think it will just be a distraction rd From duprez at hinet.net.au Mon May 28 20:25:00 2007 From: duprez at hinet.net.au (Mick Duprez) Date: 28 May 2007 17:25:00 -0700 Subject: Python command line error Message-ID: <1180398300.682311.224210@i38g2000prf.googlegroups.com> Hi All, I've installed Python 2.5 on a number of machines but on one I'm having problems with the CLI. If I fire up the 'cmd' dos box and type 'python' I get a line of gibberish and it locks up the cli, if I run the 'command' dos box I get a few lines of garbage and it crashes/closes the dos box. I've tried a re-install, checked my system paths etc but I can't get it to work, it works ok for running scripts from a dbl click in explorer for instance and from Idle, I just can't run scripts from the command line. I have installed - xp pro sp2 Python25 wxPython2.8 unicode PIL numpy any clues to what's causing this behavior? tia, Mick. From mensanator at aol.com Sat May 5 00:35:59 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 4 May 2007 21:35:59 -0700 Subject: How to check if a string is empty in python? In-Reply-To: <1hxls08.1821ogi1l0n338N%aleax@mac.com> References: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> <1178154290.811928.208900@h2g2000hsg.googlegroups.com> <1hxia6q.18rflwk1mez8vhN%aleax@mac.com> <1hxls08.1821ogi1l0n338N%aleax@mac.com> Message-ID: <1178339759.459508.248510@p77g2000hsh.googlegroups.com> On May 4, 9:19???pm, a... at mac.com (Alex Martelli) wrote: > Larry Bates wrote: > > ? ?... > > > Isn't deprecated like depreciated but not quite to zero yet? > > No. ?"To deprecate" comes from a Latin verb meaning "to ward off a > disaster by prayer"; when you're saying you deprecate something, you're > saying you're praying for that something to disappear, go away; in a > secular context, you're earnestly imploring people to NOT do it. > > "To depreciate" comes from a Latin verb meaning "to reduce the price"; > when you're saying you depreciate something, you're saying you put on > that something a lower price (and, by extension, a lower value) than it > has (or, more commonly, used to have). ?You're not necessarily saying > it's worth nothing at all (accountants sometimes deem an asset "fully > depreciated" to mean something close to that, but the adverb "fully" is > crucial to this meaning), just that it's worth "less than before". But doesn'y "partially depreciated" also mean "less than before"? I thought "fully depreciated" meant the value AS AN ASSET was now 0, not the actual value, such as when my company replaces my perfectly functioning computer because it is "fully depreciated" (the company can no longer extract any tax benefits from it). > > The two terms got somewhat entwined, no doubt because their spelling is > so similar (even though etimology and pronunciation are poles apart), > but the "correct" meanings and usage are still well distinct. > > Alex From exarkun at divmod.com Mon May 21 08:22:19 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 21 May 2007 08:22:19 -0400 Subject: NEWBIE: Extending a For Statement. In-Reply-To: <1179749446.179064.222990@z28g2000prd.googlegroups.com> Message-ID: <20070521122219.30678.1067389696.divmod.quotient.3277@ohm> On 21 May 2007 05:10:46 -0700, mosscliffe wrote: >I keep seeing examples of statements where it seems conditionals are >appended to a for statement, but I do not understand them. > >I would like to use one in the following scenario. > >I have a dictionary of > >mydict = { 1: 500, 2:700, 3: 800, 60: 456, 62: 543, 58: 6789} > >for key in mydict: > if key in xrange (60,69) or key == 3: > print key,mydict[key] > >I would like to have the 'if' statement as part of the 'for' >statement. > >I realise it is purely cosmetic, but it would help me understand >python syntax a little better. Only list comprehensions and generator expressions support this extension to the loop syntax. [key, mydict[key] for key in mydict if key in xrange(60, 69) or key == 3] (key, mydict[key] for key in mydict if key in xrange(60, 69) or key == 3] For the statement form of 'for', there is no syntactic way to combine it with 'if' into a single statement. Jean-Paul From sjmachin at lexicon.net Sat May 19 20:18:09 2007 From: sjmachin at lexicon.net (John Machin) Date: Sun, 20 May 2007 10:18:09 +1000 Subject: converting strings to most their efficient types '1' --> 1, 'A' ---> 'A', '1.2'---> 1.2 In-Reply-To: <61B3i.6880$H_.138@newssvr21.news.prodigy.net> References: <1179529661.555196.13070@k79g2000hse.googlegroups.com> <464E6F32.7070200@lexicon.net> <61B3i.6880$H_.138@newssvr21.news.prodigy.net> Message-ID: <464F93C1.8030305@lexicon.net> On 19/05/2007 9:17 PM, James Stroud wrote: > John Machin wrote: >> The approach that I've adopted is to test the values in a column for >> all types, and choose the non-text type that has the highest success >> rate (provided the rate is greater than some threshold e.g. 90%, >> otherwise it's text). >> >> For large files, taking a 1/N sample can save a lot of time with >> little chance of misdiagnosis. > > > Why stop there? You could lower the minimum 1/N by straightforward > application of Bayesian statistics, using results from previous tables > as priors. > The example I gave related to one file out of several files prepared at the same time by the same organisation from the same application by the same personnel using the same query tool for a yearly process which has been going on for several years. All files for a year should be in the same format, and the format should not change year by year, and the format should match the agreed specifications ... but this doesn't happen. Against that background, please explain to me how I can use "results from previous tables as priors". Cheers, John From idaku2 at gmail.com Sat May 12 14:03:01 2007 From: idaku2 at gmail.com (idaku2 at gmail.com) Date: 12 May 2007 11:03:01 -0700 Subject: [Newbie] design question Message-ID: <1178992981.143066.279690@o5g2000hsb.googlegroups.com> Hi all Suppose I have class ShoppingCart which has one method called buy(), and class Buyer who has one reference to ShoppingCart... Can I also have method buy() in class Buyer, which will then called ShoppingCard.buy(), and also do some other stuff? Is this legal design pattern, have methods with same name? Thanks in advance. From newsgroups at nospam.demon.co.uk Thu May 17 06:02:31 2007 From: newsgroups at nospam.demon.co.uk (Douglas Woodrow) Date: Thu, 17 May 2007 11:02:31 +0100 Subject: Execute commands from file References: <1179320782.594398.67980@u30g2000hsc.googlegroups.com> <464b370c$0$3808$5402220f@news.sunrise.ch> <1179387023.005808.60670@o5g2000hsb.googlegroups.com> Message-ID: On Thu, 17 May 2007 00:30:23, i3dmaster wrote >f = open(file,'rb') >for i in f: > exec i Why are you opening the file in binary mode? -- Doug Woodrow From robin at reportlab.com Wed May 16 12:45:07 2007 From: robin at reportlab.com (Robin Becker) Date: Wed, 16 May 2007 17:45:07 +0100 Subject: calldll for Python 2.5 In-Reply-To: References: Message-ID: <464B3513.6000209@chamonix.reportlab.co.uk> Thomas Heller wrote: > Larry Bates schrieb: >> I've implemented several libraries using calldll (originally on >> Python 2.2) and posted recipe on ASPN for a general implementation >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146847. >> If I were doing it over again today, I would use ctypes, but I >> have thousands of lines of library code that are dependent on >> calldll. Anyone out there have a version that works with Python >> 2.5 so I don't have to a massive rewrite? > > Can't you write a calldll replacement with ctypes? > > > Thomas > I just tried and the latest calldll compiles pretty much out of the box and so I sent him the pyd. Just more legacy code; eventually calldll won't compile and then the conversion will be forced anyhow. -- Robin Becker From fabien.lyon at isismpp.fr Thu May 31 08:01:44 2007 From: fabien.lyon at isismpp.fr (fabien.lyon) Date: Thu, 31 May 2007 14:01:44 +0200 Subject: TR: embeded python progam into visual C++ application crash Message-ID: <1DC9064A1EB94845987C198ADF4E11201594AE@messagix.ISISTHIBAUD.local> -----Message d'origine----- De : fabien.lyon [mailto:fabien.lyon at isismpp.fr] Envoy? : mercredi 30 mai 2007 20:16 ? : 'python-list at python.org' Objet : RE: embeded python progam into visual C++ application crash > hello, > The C++ application uses a python module which wraps commands set for CVS > management: > checkout, checkin and tag. > We used python2.5.1 and Visual C++ 6.0 2.5.1 is compiled with Visual Studio 2005 - I hope you had no problems with VC++ 6.0? > The problem we get is: > After a good import and definition of python functions we have a random > unhandled exception (from python25.dll) when calling python interface > function several times. > All the python module has been tested using the python IDLE. > > > This the C++ sequence code we used: > > Py_initialize() > Py_Import("moduleName") > cvs_init() // cvs view initialisation handled > by > python script init() > cvs_set_tag() // cvs commit and tag handled by python > script settag() > // the exception occured here >> Neither Py_initialize nor Py_Import functions exist - so please post >> actual code. >> -- >> Gabriel Genellina Ho sorry you are right (this pb disturbs me too much). Investigation and efforts has been helpfull, so we have found the problem. This is the following description : void InterfaceTestConfigPython_C::InitCVS(CString path_vue_bench_p, CString path_vue_test_p) { PyObject *pArgs= NULL, *pValue= NULL; PyObject *pPathVueBench= NULL, *pPathVueTest= NULL ; //python objects for each python function argument pPathVueBench = PyString_FromString((LPCTSTR)path_vue_bench_p); pPathVueTest = PyString_FromString((LPCTSTR)path_vue_test_p); //python object to collect all arguments pArgs = PyTuple_New(2); PyTuple_SetItem(pArgs, 0, pPathVueBench); PyTuple_SetItem(pArgs, 1, pPathVueTest); // python function call pValue = PyObject_CallObject(pFuncInit_m, pArgs); // clean up memory Py_DECREF(pArgs); // process return value if (pValue != NULL) { .... // clean up memory Py_DECREF(pValue); } // clean up memory Py_DECREF(pPathVueBench ); Py_DECREF(pPathVueTest); } The problem we get come from a wrong code. The last two lines, calling Py_DECREF, are not mandatory and make the python interpreter in a bad day. When the InitCVS() function call Py_DECREF(pArgs) the memory allocated for pPathVueBench and pPathVueTest is free (i guess) because the PyTuple_SetItem(pArgs, 0, pPathVueBench) steals the reference of the python object you add into the tuple pArgs like the python documentation tells. So we have suppressed the last clean up memory in the InitCVS() function and now the program is running as expected. I join the C++ object code if this can help someone. -------------- next part -------------- A non-text attachment was scrubbed... Name: InterfaceTestConfigPython_C.cpp Type: application/octet-stream Size: 9077 bytes Desc: not available URL: From http Sun May 27 23:28:26 2007 From: http (Paul Rubin) Date: 27 May 2007 20:28:26 -0700 Subject: itertools.groupby References: <1180295221.3163.9.camel@localhost.localdomain> <1180313441.598026.198230@d30g2000prg.googlegroups.com> Message-ID: <7x8xb939ut.fsf@ruckus.brouhaha.com> Raymond Hettinger writes: > The groupby itertool came-out in Py2.4 and has had remarkable > success (people seem to get what it does and like using it, and > there have been no bug reports or reports of usability problems). > All in all, that ain't bad (for what 7stud calls a poster child). I use the module all the time now and it is great. Basically it gets rid of the problem of the "lump moving through the snake" when iterating through a sequence, noticing when some condition changes, and having to juggle an element from one call to another. That said, I too found the docs a little confusing on first reading. I'll see if I can go over them again and suggest improvements. Here for me is a typical example: you have a file of multi-line records. Each record starts with a marker saying "New Record". You want to iterate through the records. You could do it by collecting lines til you see a new record marker, then juggling the marker into the next record somehow; in some situations you could do it by some kind of pushback mechanism that's not supported in the general iterator protocol (maybe it should be); I like to do it with what I call a "Bates stamp". (A Bates stamp is a rubber stamp with a serial numbering mechanism, so each time you operate it the number goes higher by one. You use it to stamp serial numbers on pages of legal documents and that sort of thing). I use enumerate to supply Bates numbers to the lines from the file, incrementing the number every time there's a new record: fst = operator.itemgetter(0) snd = operator.itemgetter(1) def bates(fd): # generate tuples (n,d) of lines from file fd, # where n is the record number. Just iterate through all lines # of the file, stamping a number on each one as it goes by. n = 0 # record number for d in fd: if d.startswith('New Record'): n += 1 yield (n, d) def records(fd): for i,d in groupby(bates(fd), fst): yield imap(snd, d) This shows a "straight paper path" approach where all the buffering and juggling is hidden inside groupby. From dthompso at email.arizona.edu Mon May 7 14:52:45 2007 From: dthompso at email.arizona.edu (D Unit) Date: Mon, 7 May 2007 11:52:45 -0700 (PDT) Subject: SOAPpy parameters in sequence Message-ID: <10363179.post@talk.nabble.com> Hi, I am trying to send a message to a SOAP implementation where the parameters must in sequence. I am creating a SOAPProxy and then sending the message with: proxy.methodName(paramName=value, paramName2=value2) Is there a way to explicitly set the order of parameters? If not, is there a way to manually set the SOAP message body and send the message? Thanks -- View this message in context: http://www.nabble.com/SOAPpy-parameters-in-sequence-tf3705624.html#a10363179 Sent from the Python - python-list mailing list archive at Nabble.com. From bj_666 at gmx.net Mon May 28 03:25:17 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 28 May 2007 09:25:17 +0200 Subject: Can python create a dictionary from a list comprehension? References: <1180299312.207986.4340@k79g2000hse.googlegroups.com> <1180299814.129770.93220@o11g2000prd.googlegroups.com> Message-ID: In <1180299814.129770.93220 at o11g2000prd.googlegroups.com>, half.italian wrote: > [entries.__setitem__(int(d.date.strftime('%m'))], d.id) for d in > links] > > btw...I was curious of this too. I used 'dir(dict)' and looked for a > method that might do what we wanted and bingo! This is really ugly. Except `__init__()` it's always a code smell if you call a "magic" method directly instead of using the corresponding syntactic sugar or built in function. And using a list comprehension just for side effects is misleading because the reader expects a (useful) list to be build when stumbling over a list comp and it's wasteful because an unnecessary list of `None`\s is build and thrown away for no reason other than to have a one liner. This is not Perl! ;-) Ciao, Marc 'BlackJack' Rintsch From fabian.conrad at gmail.com Sat May 12 00:11:06 2007 From: fabian.conrad at gmail.com (fabian.conrad at gmail.com) Date: 11 May 2007 21:11:06 -0700 Subject: help with Python C-API, tuple object Message-ID: <1178943066.289330.58690@w5g2000hsg.googlegroups.com> Hi, sorry for the rather basic question but I've searched everywhere and don't find an answer. I want to call PyObject_CallObject from the Python C-API and pass a tuple I've created from a C-array How can I pass the tuple as an object rather then having to declare the python function with the number of arguments equal to the no of elements in the tuple? Example: C-Code fragment: PyObject *pArgs = PyTuple_New(3); //module is imported and function object is build and checked for (i=0; i<3; i++){ pInt = PyInt_FromLong(i); error = PyTuple_SetItem(pArgs, i, pInt); } pValue=PyObject_CallObject(pFunc, pArgs);//returns NULL!!! Python Script: def length(a): length = len(a) return length From mcl.office at googlemail.com Wed May 16 08:38:38 2007 From: mcl.office at googlemail.com (mosscliffe) Date: 16 May 2007 05:38:38 -0700 Subject: Splitting a quoted string. In-Reply-To: References: <1179312169.045429.80960@e65g2000hsc.googlegroups.com> Message-ID: <1179319118.666906.145000@q23g2000hsg.googlegroups.com> Thank you very much for all for your replies. I am now much wiser to using regex and CSV. As I am quite a newbie, I have had my 'class' education improved as well. Many thanks again Richard On May 16, 12:48 pm, Duncan Booth wrote: > mosscliffe wrote: > > I am looking for a simple split function to create a list of entries > > from a string which contains quoted elements. Like in 'google' > > search. > > > eg string = 'bob john "johnny cash" 234 june' > > > and I want to have a list of ['bob', 'john, 'johnny cash', '234', > > 'june'] > > > I wondered about using the csv routines, but I thought I would ask the > > experts first. > > > There maybe a simple function, but as yet I have not found it. > > You probably need to specify the problem more completely. e.g. Can the > quoted parts of the strings contain quote marks? If so how what are the > rules for escaping them. Do two spaces between a word mean an empty field > or still a single string delimiter. > > Once you've worked that out you can either use re.split with a suitable > regular expression, or use the csv module specifying your desired dialect: > > >>> class mosscliffe(csv.Dialect): > > delimiter = ' ' > quotechar = '"' > doublequote = False > skipinitialspace = False > lineterminator = '\r\n' > quoting = csv.QUOTE_MINIMAL > > >>> csv.register_dialect("mosscliffe", mosscliffe) > >>> string = 'bob john "johnny cash" 234 june' > >>> for row in csv.reader([string], dialect="mosscliffe"): > > print row > > ['bob', 'john', 'johnny cash', '234', 'june'] From elventear at gmail.com Mon May 14 11:30:08 2007 From: elventear at gmail.com (elventear) Date: 14 May 2007 08:30:08 -0700 Subject: Recursion limit problems In-Reply-To: References: <1178921877.442519.165740@u30g2000hsc.googlegroups.com> Message-ID: <1179156607.972787.252340@e51g2000hsg.googlegroups.com> On May 11, 11:54 pm, "Terry Reedy" wrote: > > Without seeing the full code and the exception traceback, my guess is that > your __hash__ somehow calls itself due to a refence loop in your object. A > simple example of a loop: > a = []; a.append(a) > Now, list objects are not hashable, but if they were, and the hash were > value based (like your), then hash(a) would call hash(a) would call > hash(a).... You were right, I had forgotten that in some instances I had some data that recursively pointed to the source. Thanks! From see_below_no_spam at yahoo.es Tue May 15 12:49:56 2007 From: see_below_no_spam at yahoo.es (Javier Bezos) Date: Tue, 15 May 2007 18:49:56 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649dd55$0$23144$9b4e6d93@newsspool1.arcor-online.net> Message-ID: "Ren? Fleschenberg" escribi? en el mensaje news:4649dd55$0$23144$9b4e6d93 at newsspool1.arcor-online.net... > This is a very weak argument, IMHO. How do you want to use Python > without learning at least enough English to grasp a somewhat decent > understanding of the standard library? By heart. I know a few _very good_ programmers who are unable to understand an English text. Knowing English helps, of course, but is not required at all. Of course, they don't know how to name identifiers in English, but it happens they _cannot_ give them proper Spanish names, either (I'm from Spain). +1 for the PEP, definitely. > But having, for example, things like open() from the stdlib in your code > and then ?ffnen() as a name for functions/methods written by yourself is > just plain silly. It makes the code inconsistent and ugly without > significantly improving the readability for someone who speaks German > but not English. Agreed. I always use English names (more or less :-)), but this is not the PEP is about. Javier ---------------------------------- http://www.texytipografia.com From bdesth.quelquechose at free.quelquepart.fr Thu May 10 17:55:28 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 10 May 2007 23:55:28 +0200 Subject: Newbie look at Python and OO In-Reply-To: <1178830137.877510.290070@w5g2000hsg.googlegroups.com> References: <1178812734.860473.236370@y80g2000hsf.googlegroups.com> <464380c4$0$25791$426a74cc@news.free.fr> <1178830137.877510.290070@w5g2000hsg.googlegroups.com> Message-ID: <46438ac1$0$3265$426a74cc@news.free.fr> walterbyrd a ?crit : > Thanx for all the replies, I may be slowly getting it. But, can > anybody explain this? > > >>>>a = 'hello' >>>>b = 'hello' >>>>a is b > > True > >>>>a = 'hello there' >>>>b = 'hello there' >>>>a is b > > False > Python - well, CPython (the reference C implementation) at least - tries to optimize memory usage by "interning" (caching/reusing) string objects when possible. You'll find a similar behaviour with integers: >>> a = 5 >>> b = 5 >>> a is b True >>> a = 50000 >>> b = 50000 >>> a is b False >>> IOW, this is an implementation detail. FWIW, you should not use identity tests on immutable objects (the None object set aside) - since they are immutable, equality test is enough. From slava.maslov at gmail.com Sun May 6 08:23:54 2007 From: slava.maslov at gmail.com (Vyacheslav Maslov) Date: Sun, 6 May 2007 19:23:54 +0700 Subject: [python 2.4] unable to construct tuple with one item Message-ID: <271115400705060523t2f1c23e4ndc87e612384d4951@mail.gmail.com> Hi, all! I found out different behavior of python interpeter related to tuples and lists with one item only. I have simple example >>> print type(()) it's ok, we have just constructed empty tuple >>> print type((4)) but when i add exactly one item to my tuple i get atomaric int instead of tuple!!! why? >>> print type((4,)) this problem can be avoided by adding comma after first item >>> print type([4]) but finally, python constructs list with one item without any problem. So, the main question is why using syntax like [X] python constuct list with one item, but when i try to construct tuple with one item using similar syntax (X) python do nothing? P.S. python 2.4 -------------- next part -------------- An HTML attachment was scrubbed... URL: From DustanGroups at gmail.com Mon May 21 08:52:53 2007 From: DustanGroups at gmail.com (Dustan) Date: 21 May 2007 05:52:53 -0700 Subject: NEWBIE: Extending a For Statement. In-Reply-To: References: <1179749446.179064.222990@z28g2000prd.googlegroups.com> Message-ID: <1179751973.199316.248370@x35g2000prf.googlegroups.com> On May 21, 7:22 am, Jean-Paul Calderone wrote: > On 21 May 2007 05:10:46 -0700, mosscliffe wrote: > > > > >I keep seeing examples of statements where it seems conditionals are > >appended to a for statement, but I do not understand them. > > >I would like to use one in the following scenario. > > >I have a dictionary of > > >mydict = { 1: 500, 2:700, 3: 800, 60: 456, 62: 543, 58: 6789} > > >for key in mydict: > > if key in xrange (60,69) or key == 3: > > print key,mydict[key] > > >I would like to have the 'if' statement as part of the 'for' > >statement. > > >I realise it is purely cosmetic, but it would help me understand > >python syntax a little better. > > Only list comprehensions and generator expressions support this extension > to the loop syntax. > > [key, mydict[key] for key in mydict if key in xrange(60, 69) or key == 3] > (key, mydict[key] for key in mydict if key in xrange(60, 69) or key == 3] ack! >>> (key, mydict[key] for key in mydict if key in xrange(60, 69) or key == 3] File "", line 1 (key, mydict[key] for key in mydict if key in xrange(60, 69) or key == 3] ^ SyntaxError: invalid syntax Perhaps you meant that second one to be: (key, mydict[key] for key in mydict if key in xrange(60, 69) or key == 3) > For the statement form of 'for', there is no syntactic way to combine it > with 'if' into a single statement. But there is a dumb hack to get it to happen, but I'm not going to it here, because Guido never meant for generator expressions to be used that way. To the OP: I would suggest you just live what might seem like excess indentation; it's good for your eyes. > Jean-Paul From aspineux at gmail.com Thu May 31 08:58:22 2007 From: aspineux at gmail.com (aspineux) Date: 31 May 2007 05:58:22 -0700 Subject: file reading by record separator (not line by line) In-Reply-To: <1180615143.228557.258760@g4g2000hsf.googlegroups.com> References: <1180614374.027569.235540@g4g2000hsf.googlegroups.com> <1180615143.228557.258760@g4g2000hsf.googlegroups.com> Message-ID: <1180616302.063134.108170@p77g2000hsh.googlegroups.com> something like name=None lines=[] for line in open('yourfilename.txt'): if line.startwith('>'): if name!=None: print 'Here is the record', name print lines print name=line.stripr('\r') lines=[] else: lines.append(line.stripr('\n')) On 31 mai, 14:39, Lee Sander wrote: > I wanted to also say that this file is really huge, so I cannot > just do a read() and then split on ">" to get a record > thanks > lee > > On May 31, 1:26 pm, Lee Sander wrote: > > > Dear all, > > I would like toreada really hugefilethat looks like this: > > > > name1.... > > > line_11 > > line_12 > > line_13 > > ...>name2 ... > > > line_21 > > line_22 > > ... > > etc > > > where line_ij is just a free form text on that line. > > > how can ireadfileso that every time i do a "read()" i get exactly > > onerecord > > up to the next ">" > > > many thanks > > Lee From luismgz at gmail.com Wed May 16 23:54:50 2007 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M=2E_Gonz=E1lez?=) Date: 16 May 2007 20:54:50 -0700 Subject: Python Web Programming - looking for examples of solid high-traffic sites In-Reply-To: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> Message-ID: <1179374090.513636.41350@y80g2000hsf.googlegroups.com> On May 16, 6:04 pm, Victor Kryukov wrote: > Hello list, > > our team is going to rewrite our existing web-site, which has a lot of > dynamic content and was quickly prototyped some time ago. > > Today, as we get better idea of what we need, we're going to re-write > everything from scratch. Python is an obvious candidate for our team: > everybody knows it, everybody likes it, it has *real* objects, nice > clean syntax etc. > > Our main requirement for tools we're going to use is rock-solid > stability. As one of our team-members puts it, "We want to use tools > that are stable, has many developer-years and thousands of user-years > behind them, and that we shouldn't worry about their _versions_." The > main reason for that is that we want to debug our own bugs, but not > the bugs in our tools. > > Our problem is - we yet have to find any example of high-traffic, > scalable web-site written entirely in Python. We know that YouTube is > a suspect, but we don't know what specific python web solution was > used there. > > TurboGears, Django and Pylons are all nice, and provides rich features > - probably too many for us - but, as far as we understand, they don't > satisfy the stability requirement - Pylons and Django hasn't even > reached 1.0 version yet. And their provide too thick layer - we want > something 'closer to metal', probably similar to web.py - > unfortunately, web.py doesn't satisfy the stability requirement > either, or so it seems. > > So the question is: what is a solid way to serve dynamic web pages in > python? Our initial though was something like python + mod_python + > Apache, but we're told that mod_python is 'scary and doesn't work very > well'. > > And althoughhttp://www.python.org/about/quotes/lists many big names > and wonderful examples, be want more details. E.g. our understanding > is that Google uses python mostly for internal web-sites, and > performance is far from perfect their. YouTube is an interesting > example - anybody knows more details about that? > > Your suggestions and comments are highly welcome! > > Best Regards, > Victor. Take a look at reddit.com . It's been developed with WEBPY and it receives millions of visits every day. There are also many sites built with Django (check their website) with a lot of traffic and very good performance And I'm sure other frameworks can show other success stories... just check their websites. Luis From notro at tronnes.org Wed May 9 12:55:42 2007 From: notro at tronnes.org (Noralf Trřnnes) Date: Wed, 9 May 2007 18:55:42 +0200 Subject: ctypes: Problems using Windows-DLL from VB example code Message-ID: <4641fd20$1@news.broadpark.no> Hi I'm trying to use a DLL from Python using ctypes. The call to dso_lib.capture_hold_chk() does return 232. So it seem to work. The call to dso_lib.port_init(init_data) gives: WindowsError: exception: access violation reading 0x00000006 Any suggestions? Thanks. Noralf Here is my python code: import os from ctypes import * # Hardware control data class A_INIT(Structure): _fields_ = [("time_d_va", c_long), ("tri_in_sel", c_int), ("ch1_div", c_int), ("ch1_in_sel", c_int), ("ch2_div", c_int), ("ch2_in_sel", c_int), ("ram_rw_mode", c_int), ("ram_copy_mode", c_int), ("ram_copy_delay", c_int), ("ho_mode", c_int), ("ho_mode1", c_int), ("CH", c_int), ("TRI_12E", c_int), ("Ch1_To_Gnd", c_int), ("Ch2_To_Gnd", c_int)] dso_lib_filepath = os.path.join(os.path.dirname(__file__), 'dso_2100usb_s.dll') dso_lib = cdll.LoadLibrary(dso_lib_filepath) init_data = A_INIT() init_data.time_d_va = 0 init_data.tri_in_sel = 7 init_data.ch1_div = 4 init_data.ch1_in_sel = 1 init_data.ch2_div = 4 init_data.ch2_in_sel = 1 init_data.ram_rw_mode = 1 init_data.ram_copy_mode = 14 init_data.ram_copy_delay = 0 init_data.ho_mode = 1 init_data.ho_mode1 = 0 init_data.CH = 0 init_data.TRI_12E = 0 init_data.Ch1_To_Gnd = 0 init_data.Ch2_To_Gnd = 0 print dso_lib.capture_hold_chk() # returns 232 print dso_lib.port_init(init_data) # WindowsError exception Here is the code from a Visual Basic example using the DLL: Type A_INIT 'hardware control data time_d_va As Long tri_in_sel As Integer ch1_div As Integer ch1_in_sel As Integer ch2_div As Integer ch2_in_sel As Integer ram_rw_mode As Integer ram_copy_mode As Integer ram_copy_delay As Integer ho_mode As Integer ho_mode1 As Integer CH As Integer TRI_12E As Integer Ch1_To_Gnd As Integer Ch2_To_Gnd As Integer End Type Public init_data As A_INIT Public RESULT As Integer Public Declare Function port_init Lib "dso_2100usb_s.dll" (init_data As A_INIT) As Integer Sub init() init_data.ch1_div = 4 init_data.ch1_in_sel = 1 init_data.Ch1_To_Gnd = 0 init_data.ch2_div = 4 init_data.ch2_in_sel = 1 init_data.Ch2_To_Gnd = 0 init_data.ho_mode = 1 RESULT = port_init(init_data) End Sub From python at rcn.com Sat May 19 05:23:47 2007 From: python at rcn.com (Raymond Hettinger) Date: 19 May 2007 02:23:47 -0700 Subject: RFC - n-puzzle.py In-Reply-To: <1179530104.645902.135250@p77g2000hsh.googlegroups.com> References: <1179530104.645902.135250@p77g2000hsh.googlegroups.com> Message-ID: <1179566627.583978.304810@n59g2000hsh.googlegroups.com> On May 18, 4:15 pm, Phoe6 wrote: > Hi All, > I would like to request a code and design review of one of my program. > n-puzzle.pyhttp://sarovar.org/snippet/detail.php?type=snippet&id=83 > Its a N-puzzle problem solver ( Wikipedia page andhttp://norvig.com/ltd/test/n-puzzle.lisp > ) > > I have used OO Python for the above program and would like comments on > my approach as I am just starting with OOP. > > Thanks > Senthil Nice job, this doesn't look like a beginner program at all. For feedback, here's a few nits: Instead of: if key + x in range(0, self.tsize): write: if 0 <= key + x < self.tsize: Instead of: mdist = mdist + jumps + steps write: mdist += jumps + steps Instead of: least_paths = [] for st in exp_sts: if self.manhattan_distance(st) == short_path: least_paths.append(st) write: least_paths = [st for st in exp_sts if self.manhattan_distance(st) == short_path] Instead of: short_path = mdists[0] if mdists.count(short_path) > 1: write: short_path = mdists[0] if short_path in mdists[1:]: Instead of: if node != 0: write: if node: Raymond From torriem at chem.byu.edu Tue May 22 11:49:57 2007 From: torriem at chem.byu.edu (Michael L Torrie) Date: Tue, 22 May 2007 09:49:57 -0600 Subject: Slightly OT: Why all the spam? In-Reply-To: <3bb44c6e0705220008y10f5deb7v86ed82d3f8241761@mail.gmail.com> References: <3bb44c6e0705220008y10f5deb7v86ed82d3f8241761@mail.gmail.com> Message-ID: <1179848997.22230.4.camel@contra.chem.byu.edu> On Tue, 2007-05-22 at 09:08 +0200, bryan rasmussen wrote: > Well two things I would suppose: > > 1. relative popularity and volume of the group leads spammers to put > more resources towards spamming the group. > > 2. I seem to remember that python-list is also a usenet group? > non-moderated, meaning it is tough to ban people? > > Actually, it would be nice to know if anybody has any good filters > worked up that will work in Gmail for reading python-list. It appears that people using nntp to read this list aren't seeing the spam because the moderators expire the messages as they find them. However, by then the messages have already hit the mailman gateway. Thus you may want to consider reading c.l.p via nntp when at work. Lately all the spams contain a url to a certain site, so you can probably procmail filter based on that. The spam does not appear to be random-bot generated, but targeted spam by a single person or entity. Which makes it easier to filter out. > > > Cheers, > Bryan Rasmussen > > > From solisgb at gmail.com Sat May 19 06:56:21 2007 From: solisgb at gmail.com (luis) Date: 19 May 2007 03:56:21 -0700 Subject: dislin titlin and string decode Message-ID: <1179572181.557824.213350@k79g2000hse.googlegroups.com> Hello! I have an unespectedn result with dislin titlin dislin.metafl ('WMF') dislin.disini () .... a="Andr?s or Ram?n" dislin.titlin (a.encode("Latin-1"), 1) # not error raised, is ok .... dislin.disfin () In the output file all is ok but the title is Andr s or Ram n Thanks in advance! From rridge at caffeine.csclub.uwaterloo.ca Tue May 15 12:02:42 2007 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Tue, 15 May 2007 12:02:42 -0400 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: wrote: >So, please provide feedback, e.g. perhaps by answering these >questions: >- should non-ASCII identifiers be supported? why? Ross Ridge wrote: > I think the biggest argument against this PEP is how little similar > features are used in other languages Carsten Haese wrote: >That observation is biased by your limited sample. No. I've actually looked hard to find examples of source code that use non-ASCII identifiers. While it's easy to find code where comments use non-ASCII characters, I was never able to find a non-made up example that used them in identifiers. > You only see open source code that chooses to restrict itself to ASCII >and mostly English identifiers to allow for easier code sharing. There >could be millions of kids in China learning C# in native Mandarin and >you'd never know about it. No, there's tons of code written by kids learning programming languages from all over the world scattered all over the Internet. Regardless of what my observations are, I think that you need a better argument than a bunch of children in China that may very well not exist. This PEP, like similar features in other langauges is being made and advocated by people who don't actually want to use it. It's made on the presumption that somehow developers in China and other places its proponents aren't familar with desperately want this feature but are somehow incapable of advocating for it themselves let alone implementing it. The burden of proof should be on this PEP's proponents to show that it will be actually be used. Is this PEP even justified by anyone going to the trouble of asking for it to be implemented in the first place? >How would a choice of identifiers interact in any way with Python's >standard or third-party libraries? The only things that get passed >between an application and the libraries are objects that neither know >nor care what identifiers, if any, are attached to them. A number of libraries and utilities, including those included with the standard Python distribution work with Python identifiers. The PEP gives one example, but it doesn't really give much though as to how much of the standard library might be affected. If the proponents of this PEP think it will actually be used, then the implementation section of this PEP should be updated to include making all aspects of the standard Python distribution, the interpreter, libraries and utilities fully support non-ASCII identifiers. These hypothetical Chinese students are going to happy if IDLE doesn't highlight identifiers correctly, or the carret in a syntax error doesn't point to the right place. Hmm... normalizing identifiers could cause problems with module names. If Python searches the filesystem for the module using the normalized version of the name different from the one that appears in the source code it could end up surprising users. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From carsten at uniqsys.com Fri May 11 17:15:01 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 11 May 2007 17:15:01 -0400 Subject: Interesting list Validity (True/False) In-Reply-To: <1178917671.463649.102720@p77g2000hsh.googlegroups.com> References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> <1349ihg6j1e1k95@corp.supernews.com> <1349km0g41b565@corp.supernews.com> <1178917671.463649.102720@p77g2000hsh.googlegroups.com> Message-ID: <1178918101.1820.35.camel@dot.uniqsys.com> On Fri, 2007-05-11 at 14:07 -0700, nufuhsus at gmail.com wrote: > OK. Then how would you differenciate between a call with an option > versus one without (e.g. help.py -o (where arg == ['-o']) Vs. help.py > (where arg == []))? if arg: print "With options" else: print "Without options" -- Carsten Haese http://informixdb.sourceforge.net From kerny404 at gmail.com Tue May 8 17:20:58 2007 From: kerny404 at gmail.com (andrea) Date: 8 May 2007 14:20:58 -0700 Subject: Designing a graph study program In-Reply-To: <5ab6p3F2ni551U1@mid.uni-berlin.de> References: <1178619753.077639.112510@q75g2000hsh.googlegroups.com> <5ab3mgF2o5bfbU1@mid.uni-berlin.de> <1178622700.228390.237310@n59g2000hsh.googlegroups.com> <5ab6p3F2ni551U1@mid.uni-berlin.de> Message-ID: <1178659258.820806.110380@l77g2000hsb.googlegroups.com> On 8 Mag, 13:55, "Diez B. Roggisch" wrote: > > Ok thank you very much I'll try with that. > > But I have some design doubts, I'd like to keep the algorithm (for > > example bfs) as clean as possible, being independent from the drawing > > methods. > > And how could I make it step through algorithms without having a more > > complicated code? Maybe using threads? > > Along the lines of what Marc said: > > Use two graph-implementations that share the same interface regarding the > algorithms, but one will emit events to some observer for each operation on > the graph - edge/node adding/removal, attribute changing and so forth. > > Thus the algorithm is kept clean, and all that you can visualize anyway is > available to you. > > diez Interesting but what do you mean for two graph-implementatio that share the same interface?? I don't have abstract classes or interfaces in python, am I wrong? Thanks From a-alpha at otenet.gr Sat May 19 04:00:18 2007 From: a-alpha at otenet.gr (g - a - l - l - e - r - y) Date: Sat, 19 May 2007 11:00:18 +0300 Subject: PAMELA DAVID Message-ID: PAMELA DAVID www.alphasearch.gr -------------- next part -------------- An HTML attachment was scrubbed... URL: From nagle at animats.com Tue May 22 12:10:42 2007 From: nagle at animats.com (John Nagle) Date: Tue, 22 May 2007 16:10:42 GMT Subject: Components for a client/server architecture In-Reply-To: References: <5bd99qF2s85heU1@mid.uni-berlin.de> Message-ID: <6CE4i.22920$JZ3.15279@newssvr13.news.prodigy.net> Duncan Grisby wrote: > In article , > Samuel wrote: > > [...] > >>>Sounds like CORBA to me. CORBA has a very mature and good implementation >>>for Python called OmniORB, and interoperability with other orbs (the >>>ones available for e.g. Java) is very good - as CORBA as standard is >>>mature. You don't hear much about CORBA any more. It used to be derided as a bulky way to marshall data, but then came XML. Gnome and OpenOffice both use CORBA internally. But they don't talk to each other that way; the implementations aren't compatible. John Nagle From s.mientki at id.umcn.nl Wed May 30 08:29:13 2007 From: s.mientki at id.umcn.nl (stef) Date: Wed, 30 May 2007 14:29:13 +0200 Subject: Python 2.5 and WXPython demo's In-Reply-To: References: <1180523448.993195.59180@q69g2000hsb.googlegroups.com> Message-ID: <974af$465d6e19$83aef404$30110@news1.tudelft.nl> Wildemar Wildenburger wrote: > Andrew P wrote: >> Hello, >> >> I am new (very) to Python and have just down loaded the latest version >> of Python (2.5) and WXPython (2.8). >> >> For some reason I cannot get the WXPython demo to run at all. I run >> windows XP and it can't find a program to run the demo. Any advice? >> (apologies if this has been posted before). >> >> > There *should* be a link in your startmenu in the wxPython group. I'm > quite positive, but not 100% sure. I think it has the snake-icon. But > if it's really not there (as you suggested), simply go the the folder > you installed the demo to and run demo.py. > > Maybe there's a blunder in the installer for the 2.8 demo? Anyone? Can't answer that, but on one from two (almost identical) PC's, I had trouble too, the other went fluently. On both PC's, there was an older wxPython (2.6 I believe), (which from what I've read should be no problem at all), which wasn't overruled, by some specific file (wx.pth) to point to the newest. The effect is that the demo tries to run, can't find aiw?? or something like that and crashes (on fast PC's you actually just see a dos box flashing). Editing the wx.pth file solved the problem. cheers, Stef Mientki From xmlhacker at gmail.com Mon May 21 00:41:02 2007 From: xmlhacker at gmail.com (M. David Peterson) Date: Sun, 20 May 2007 22:41:02 -0600 Subject: [IronPython] [ANN] IronPython Community Edition r6 In-Reply-To: <5b0248170705201041lf3446f3t94e7e4ab86d5b0c@mail.gmail.com> References: <5b0248170705201041lf3446f3t94e7e4ab86d5b0c@mail.gmail.com> Message-ID: Nice! > http://www.oreillynet.com/windows/blog/2007/05/seo_sanghyeonipce_ironpython_c_2.html On 5/20/07, Sanghyeon Seo wrote: > > This is the sixth release of IronPython Community Edition (IPCE). > > Download from SourceForge: > http://sourceforge.net/projects/fepy > > FePy project aims to provide enhancements and add-ons for IronPython. > http://fepy.sourceforge.net/ > > This release is built with Mono 1.2.3.1. As this release has dropped a > patch to support Mono without Socket.{Send,Receive}BufferSize > implementation, it won't work with Mono versions below 1.2.3. > > It has been a long time (more than 5 months) since the last release. > In the mean time, DLR-based IronPython 2.0 Alpha 1 was revealed, and > it was subsequently ported to Mono. As this codebase is still new, > IPCE will be based on IronPython 1.1 for the time being. > > Also note that IronPython 2.0 Alpha 1 has significant performance > regression on Mono (but not on MS.NET) compared to IronPython 1.1. > > http://lists.ironpython.com/pipermail/users-ironpython.com/2007-May/004915.html > > Changes in this release follow. > > IronPython > > Updated to IronPython 1.1. > > Libraries > > Huge improvements to AST support. > Support inspect.getargspec(). > Pickle integration with .NET Serialization. > platform module that can handle IronPython. (Anthony Baxter) > Implement os.access(). (Rachel Hestilow) > > Bundles > > pybench benchmark (thanks to platform module). > pyflakes code checker (thanks to AST support). > wsgiref synced to 2.5.1. > > Patches > > You can read the summary of applied patches here. > http://fepy.sourceforge.net/patches.html > > New in this release: > patch-ironpython-import-hack > > -- > Seo Sanghyeon > _______________________________________________ > users mailing list > users at lists.ironpython.com > http://lists.ironpython.com/listinfo.cgi/users-ironpython.com > -- /M:D M. David Peterson http://mdavid.name | http://www.oreillynet.com/pub/au/2354 | http://dev.aol.com/blog/3155 -------------- next part -------------- An HTML attachment was scrubbed... URL: From wim.vogelaaratmc2worlddotorg Mon May 28 04:20:16 2007 From: wim.vogelaaratmc2worlddotorg (Wim Vogelaar) Date: Mon, 28 May 2007 10:20:16 +0200 Subject: Can python create a dictionary from a list comprehension? References: <1180299312.207986.4340@k79g2000hse.googlegroups.com> Message-ID: <465a90a8$0$55856$dbd43001@news.wanadoo.nl> > Example: > > a = [1,2,3,4,5,6,7,8,9,10] > > aDict = dict([(x,x+1) for x in a if x%2==0]) > > print aDict > When I run this program I get: {8: 9, 2: 3, 4: 5, 10: 11, 6: 7} why this output isn't ordered, giving: {2: 3, 4: 5, 6: 7, 8: 9, 10: 11 } From john at datavoiceint.com Wed May 9 14:23:02 2007 From: john at datavoiceint.com (HMS Surprise) Date: 9 May 2007 11:23:02 -0700 Subject: input Message-ID: <1178734982.030496.300310@q75g2000hsh.googlegroups.com> Just wanted a input routine that would let me pause my jython program until I press enter. Searched tutorial, lang ref, and lib and found input and raw_input. Both hang the program and it must be killed. s = raw_input('--> ') What has Mr Duh done wrong now? jh From dthompso at email.arizona.edu Mon May 7 15:28:08 2007 From: dthompso at email.arizona.edu (D Unit) Date: Mon, 7 May 2007 12:28:08 -0700 (PDT) Subject: SOAPpy parameters in sequence In-Reply-To: <10363179.post@talk.nabble.com> References: <10363179.post@talk.nabble.com> Message-ID: <10363807.post@talk.nabble.com> I figured it out. The SOAPPRoxy class has an attribute 'SOAPPRoxy.config.argsOrdering' You can set it to a dict. Each key is the name of a method, and the value is a list with the attributes in the correct order. -Dave D Unit wrote: > > Hi, > > I am trying to send a message to a SOAP implementation where the > parameters must in sequence. I am creating a SOAPProxy and then sending > the message with: > > proxy.methodName(paramName=value, paramName2=value2) > > Is there a way to explicitly set the order of parameters? > If not, is there a way to manually set the SOAP message body and send the > message? > > Thanks > -- View this message in context: http://www.nabble.com/SOAPpy-parameters-in-sequence-tf3705624.html#a10363807 Sent from the Python - python-list mailing list archive at Nabble.com. From nirnimesh at gmail.com Fri May 25 06:07:58 2007 From: nirnimesh at gmail.com (Nirnimesh) Date: 25 May 2007 03:07:58 -0700 Subject: optparse: list out entered values Message-ID: <1180087678.416600.316860@z28g2000prd.googlegroups.com> I'm using optparse.OptionParser for parsing command line arguments. parser = optparse.OptionParser() parser.add_option("-x", "--xample", help="example", default="nothing", dest="ex") options = parser.parse_args()[0] python example.py -x value I'm in search of a method to list out all the entered options along with the values. something which gives me: ex => value help => example version => blah blah.. I expected such a method to be there already. I could use dir(options) but it's kinda ugly and would require eliminating the "unwanted" variables. print dir(options) ['__doc__', '__eq__', '__init__', '__module__', '__ne__', '__repr__', '__str__', '_update', '_update_careful', '_update_loose', 'ensure_value', 'ex', 'read_file', 'read_module'] Any help would be greatly appreciated. Nirnimesh From steven at REMOVE.THIS.cybersource.com.au Sun May 13 22:41:41 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 14 May 2007 02:41:41 -0000 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: On Mon, 14 May 2007 09:42:13 +1000, Aldo Cortesi wrote: > I don't > want to be in a situation where I need to mechanically "clean" > code (say, from a submitted patch) with a tool because I can't > reliably verify it by eye. But you can't reliably verify by eye. That's orders of magnitude more difficult than debugging by eye, and we all know that you can't reliably debug anything but the most trivial programs by eye. If you're relying on cursory visual inspection to recognize harmful code, you're already vulnerable to trojans. > We should learn from the plethora of > Unicode-related security problems that have cropped up in the last > few years. Of course we should. And one of the things we should learn is when and how Unicode is a risk, and not imagine that Unicode is some sort of mystical contamination that creates security problems just by being used. > - Non-ASCII identifiers would be a barrier to code exchange. If I > know > Python I should be able to easily read any piece of code written > in it, regardless of the linguistic origin of the author. If PEP > 3131 is accepted, this will no longer be the case. But it isn't the case now, so that's no different. Code exchange regardless of human language is a nice principle, but it doesn't work in practice. How do you use "any piece of code ... regardless of the linguistic origin of the author" when you don't know what the functions and classes and arguments _mean_? Here's a tiny doc string from one of the functions in the standard library, translated (more or less) to Portuguese. If you can't read Portuguese at least well enough to get by, how could you possibly use this function? What would you use it for? What does it do? What arguments does it take? def dirsorteinsercao(a, x, baixo=0, elevado=None): """da o artigo x insercao na lista a, e mantem-na a supondo classificado e classificado. Se x estiver ja em a, introduza-o a direita do x direita mais. Os args opcionais baixos (defeito 0) e elevados (len(a) do defeito) limitam a fatia de a a ser procurarado. """ # not a non-ASCII character in sight (unless I missed one...) [Apologies to Portuguese speakers for the dogs-breakfast I'm sure Babel- fish and I made of the translation.] The particular function I chose is probably small enough and obvious enough that you could work out what it does just by following the algorithm. You might even be able to guess what it is, because Portuguese is similar enough to other Latin languages that most people can guess what some of the words might mean (elevados could be height, maybe?). Now multiply this difficulty by a thousand for a non-trivial module with multiple classes and dozens of methods and functions. And you might not even know what language it is in. No, code exchange regardless of natural language is a nice principle, but it doesn't exist except in very special circumstances. > A Python > project that uses Urdu identifiers throughout is just as useless > to me, from a code-exchange point of view, as one written in Perl. That's because you can't read it, not because it uses Unicode. It could be written entirely in ASCII, and still be unreadable and impossible to understand. > - Unicode is harder to work with than ASCII in ways that are more > important > in code than in human-language text. Humans eyes don't care if two > visually indistinguishable characters are used interchangeably. > Interpreters do. There is no doubt that people will accidentally > introduce mistakes into their code because of this. That's no different from typos in ASCII. There's no doubt that we'll give the same answer we've always given for this problem: unit tests, pylint and pychecker. -- Steven. From snorble at hotmail.com Sun May 27 18:11:44 2007 From: snorble at hotmail.com (snorble at hotmail.com) Date: 27 May 2007 15:11:44 -0700 Subject: How to do this in python with regular expressions In-Reply-To: <1180093895.743196.75510@b40g2000prd.googlegroups.com> References: <1180093895.743196.75510@b40g2000prd.googlegroups.com> Message-ID: <1180303904.622857.260730@q75g2000hsh.googlegroups.com> On May 25, 6:51 am, Jia Lu wrote: > Hi all > > I'm trying to parsing html with re module. > > html = """ >
  • > > > > > > > >
    DATA1DATA2DATA3 HT>DATA4
    DATA5DATA6DATA7DATA8
    > """ > > I want to get DATA1-8 from that string.(DATA maybe not english words.) > Can anyone tell me how to do it with regular expression in python? > > Thank you very much. # example1.py # This example will print out more than what's in the HTML table. It would also print # out text between tags, and so on. import HTMLParser class DataParser(HTMLParser.HTMLParser): def handle_data (self, data): data = data.strip() if data: print data html = '''
    DATA1DATA2DATA3DATA4
    DATA5DATA6DATA7DATA8
    ''' parser = DataParser() parser.feed(html) parser.close() example1.py output: $ python example1.py DATA1 DATA2 DATA3 DATA4 DATA5 DATA6 DATA7 DATA8 # example2.py # This example uses the re module to pull out only the table portions of HTML. This # should only print out data between
    tags. Notice that there is some # data between the tags that is not present in the output. import HTMLParser import re class DataParser(HTMLParser.HTMLParser): def handle_data (self, data): data = data.strip() if data: print data html = ''' body data 1
    table 1 data 1
    table 1 data 2
    table 2 data 1
    table 2 data 2
    body data 2 ''' tables_list = re.findall('.*?
    ', html, re.DOTALL | re.IGNORECASE) tables_html = str.join(' ', tables_list) parser = DataParser() parser.feed(tables_html) parser.close() example2.py output: $ python example2.py table 1 data 1 table 1 data 2 table 2 data 1 table 2 data 2 # example3.py # This example does basically the same thing as example2.py, but it uses HTMLParser # to keep track of whether the data is between
    tags. import HTMLParser class DataParser(HTMLParser.HTMLParser): def __init__ (self): HTMLParser.HTMLParser.__init__(self) self.table_count = 0 def handle_starttag (self, tag, attrs): if tag == 'table': self.table_count += 1 def handle_endtag (self, tag): if tag == 'table': self.table_count -= 1 def handle_data (self, data): data = data.strip() if data and self.table_count > 0: print data html = ''' body data 1
    table 1 data 1
    table 1 data 2
    table 2 data 1
    table 2 data 2
    body data 2 ''' parser = DataParser() parser.feed(html) parser.close() example3.py output: $ python example3.py table 1 data 1 table 1 data 2 table 2 data 1 table 2 data 2 From misterwang at gmail.com Fri May 18 16:08:10 2007 From: misterwang at gmail.com (Peter Wang) Date: 18 May 2007 13:08:10 -0700 Subject: (Modular-)Application Framework / Rich-Client-Platform in Python In-Reply-To: References: <1179485905.764950.124000@p77g2000hsh.googlegroups.com> <1179503315.889565.166710@q75g2000hsh.googlegroups.com> Message-ID: <1179518890.097465.170200@o5g2000hsb.googlegroups.com> On May 18, 1:10 pm, Wildemar Wildenburger wrote: > I'm not sure, but you guys seem a bit Windows-centric. I have yet to > find out if the egg-approach actually works for Linux (and Mac, though I > don't use it) as well. It does. We have several linux and mac-based developers here. (I'm on a mac most of the time.) I am currently running most of the ETS libraries from eggs. It's certainly true that the large, monolithic Enthought Python Edition that was offered in the past was only available for windows, but that's gone now and has been replaced with the egg-based distribution. > I've seen some mentioning of binary dependencies, > which makes me frown a bit. We'll just see. The Traits package has a small C extension that builds on all platforms that I've seen. Most of the other binary dependencies are for graphical things like the plotting library. If you just plan to use Envisage, you won't need those. > Yeah, I've been reading through that for the past couple of hours, seems > pretty sweet and reasonably simple. > I can see your reorg, by the way: The example .py files are not where > they're advertised to be. Better be quick with that, even solid software > with buggy documentation is buggy software ... ;) I'll file a ticket for that. :) -Peter From bronger at physik.rwth-aachen.de Thu May 17 16:00:12 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 17 May 2007 22:00:12 +0200 Subject: Regexes: How to handle escaped characters References: <87tzubqniq.fsf@wilson.homeunix.com> Message-ID: <87irarqkz7.fsf@wilson.homeunix.com> Hall?chen! James Stroud writes: > Torsten Bronger wrote: > >> I need some help with finding matches in a string that has some >> characters which are marked as escaped (in a separate list of >> indices). Escaped means that they must not be part of any match. >> >> [...] > > You should probably provide examples of what you are trying to do > or you will likely get a lot of irrelevant answers. Example string: u"Hollo", escaped positions: [4]. Thus, the second "o" is escaped and must not be found be the regexp searches. Instead of re.search, I call the function guarded_search(pattern, text, offset) which takes care of escaped caracters. Thus, while re.search("o$", string) will find the second "o", guarded_search("o$", string, 0) won't find anything. But how to program "guarded_search"? Actually, it is about changing the semantics of the regexp syntax: "." doesn't mean anymore "any character except newline" but "any character except newline and characters marked as escaped". And so on, for all syntax elements of regular expressions. Escaped characters must spoil any match, however, the regexp machine should continue to search for other matches. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From chris at newcenturycomputers.net Tue May 22 10:18:39 2007 From: chris at newcenturycomputers.net (Chris Gonnerman) Date: Tue, 22 May 2007 09:18:39 -0500 Subject: Python on Vista installation issues Message-ID: <4652FBBF.7010409@newcenturycomputers.net> I'm having errors installing Python extensions on Vista. I'm running Python 2.5, and every extension install produces "cannot create" errors. For instance, win32all 210 says: Could Not Create: pywin32-py2.5 Could Not Set Key Value: Python 2.5 pywin32-210 Could Not Set Key Value: (followed by the uninstaller command) Other extensions produce similar errors. I haven't thoroughly tested this system yet, so I don't know if any of this is really causing a problem. Can anyone tell me how to fix or avoid this problem? -- ------------------------------------------------------------------------------- Chris Gonnerman Owner, New Century Computers Phone 660-213-3822 Fax 660-213-3339 From JoeSalmeri at hotmail.com Fri May 18 19:46:58 2007 From: JoeSalmeri at hotmail.com (Joe Salmeri) Date: Fri, 18 May 2007 19:46:58 -0400 Subject: pyodbc data corruption problem Message-ID: I have found a data corruption problem with pyodbc. OS = Windows XP SP2 DB = Microsoft Access XP PROBLEM: When selecting columns from a table that are of type Memo the value returned is padded with a bunch of null characters at the end. The problems does not seem to occur until the length of the Memo column exceeds 2048 bytes. I have attached several scripts to help demonstrate the problem. To recreate the problem: 1. Create a blank Access database named test. 2. Create a ODBC DSN named test for that database 3. Run the createtable.py script to create the table and load it with the dummy data 4. Run the broke.py script to show the problem. The issue is when the data value is > 2048 bytes. The size in the createtable.py is 2046 bytes plus 3 bytes at the end that contain "JOE" for a total of 2049 bytes. If you change it from 2046 to 2045 (or less) then the problem does not occur. # # createtable.py script # import pyodbc dbs = pyodbc.connect('dsn=test') c = dbs.cursor() try: sql = 'drop table test_memo' c.execute(sql) dbs.commit() except: # ignore drop table failure pass sql = 'create table test_memo (c1 int not null, c2 memo not null)' c.execute(sql) dbs.commit() sql = 'insert into test_memo values(1, ?)' c2_value = '1' * 2046 c2_value = '%sJOE' % (c2_value) c.execute(sql, (c2_value,)) dbs.commit() c.close() dbs.close() # # broke.py script # import pyodbc dbs = pyodbc.connect('dsn=test') c = dbs.cursor() sql = 'select c2, len(c2) as c2_db_len from test_memo where c1 = 1' c.execute(sql) row = c.fetchone() ( c2, c2_db_len ) = row print repr(c2) print 'c2 length :', len(c2) print 'c2_db_length :', c2_db_len print 'before nul length:', len(c2[0:c2.find('\x00')]) c.close() dbs.close() From jgodoy at gmail.com Fri May 18 19:18:51 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Fri, 18 May 2007 20:18:51 -0300 Subject: Python Web Programming - looking for examples of solid high-traffic sites References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> <464da0a9$0$25891$426a74cc@news.free.fr> Message-ID: <87ps4xlnz8.fsf@gmail.com> John Nagle writes: > As a direct result of this, neither the Linux distro builders like > Red Hat nor major hosting providers provide Python environments that > just work. That's reality. Try SuSE, OpenSUSE, Ubuntu... They "just work". I've never had any problem installing any library or module for Python. Even the ones that require huge libraries or compiling something. -- Jorge Godoy From zootwoman at gmail.com Wed May 16 22:41:51 2007 From: zootwoman at gmail.com (The Librarian) Date: 16 May 2007 19:41:51 -0700 Subject: Jessica Simpson Sports new "Boob Job"!!!@ In-Reply-To: References: <1179126576.229946.109600@k79g2000hse.googlegroups.com> <1179165104.582094.200400@l77g2000hsb.googlegroups.com> Message-ID: <1179369711.202104.126020@o5g2000hsb.googlegroups.com> On May 16, 3:44 pm, "gtski" wrote: > "wb" wrote in message > > news:1179165104.582094.200400 at l77g2000hsb.googlegroups.com...> On May 14, 2:09 am, ready.or.speci... at gmail.com wrote: > > > If her boobs getting any bigger she won't be able to stand up. > > Im afraid of boobs. they are not on men I suck. oh yeah?? http://forums.seriouszone.com/attachment.php?attachmentid=11422&stc=1&d=1043257915 From tom at finland.com Sun May 13 01:34:35 2007 From: tom at finland.com (tom at finland.com) Date: Sun, 13 May 2007 05:34:35 GMT Subject: keyword checker - keyword.kwlist In-Reply-To: References: <5UK0i.237$Hb2.206@read3.inet.fi> Message-ID: Gabriel Genellina kirjoitti: > En Thu, 10 May 2007 17:03:13 -0300, escribi?: > my_input = raw_input("...").strip() > > as Peter Otten suggested before > > --Gabriel Genellina > Ok, it seems to work with strip(). Thanks for your help. Do you guys have any clue why mine previous code doesn't work? From half.italian at gmail.com Fri May 25 16:04:10 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 25 May 2007 13:04:10 -0700 Subject: sockets, gethostname() changing In-Reply-To: <1180062244.266857.300830@m36g2000hse.googlegroups.com> References: <1180062244.266857.300830@m36g2000hse.googlegroups.com> Message-ID: <1180123450.448644.11230@x35g2000prf.googlegroups.com> On May 24, 8:04 pm, 7stud wrote: > Hi, > > I'm experimenting with a basic socket program(from a book), and both > the client and server programs are on my computer. In both programs, > I call socket.gethostname(), but I discovered that when I am connected > to the internet, both the client and server hang and nothing happens. > I discovered that the hostname of my computer automatically changes to > that of my isp when I'm connected to the internet, and presumably the > server program on my computer cannot listen on my isp's address(host, > port). Is there a way to make the hostname of my computer static, so > that it doesn't change to my isp's hostname when I connect to the > internet. I'm using mac os 10.4.7. Why does my computer's hostname > dynamically change in the first place? > > server program: > ------------------- > import socket > > s = socket.socket() > > host = socket.gethostname() > print host > port = 1274 > s.bind((host, port)) > > s.listen(5) > while("Ctrl-C hasn't been entered"): > c, addr = s.accept() #blocks and waits for client connection > print "Got socket connection from", addr > c.send("Thank you for connecting. Now get lost.") > c.close() > > client program: > ------------------- > import socket > > s = socket.socket() > > host = socket.gethostname() > port = 1274 > > s.connect((host, port)) > print s.recv(1024) > s.close() Try setting an environment variable for 'hostname' using this: http://www.versiontracker.com/dyn/moreinfo/macosx/15073 Either way, its a good program to have. ~Sean From nogradi at gmail.com Tue May 8 18:07:38 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Wed, 9 May 2007 00:07:38 +0200 Subject: Mod Python Question In-Reply-To: <1178656466.059754.193160@e51g2000hsg.googlegroups.com> References: <1178656466.059754.193160@e51g2000hsg.googlegroups.com> Message-ID: <5f56302b0705081507i69d32e83j5ee5eef8038fbfc7@mail.gmail.com> > I am very new to Python and Mod_Python and I am running into what > looks like a caching problem. > > I have the following code: > --------------------------------------- > from mod_python import apache > from folder import Messenger > > def handler(req): > > msg = Messenger(req): > > # using req.write > > msg.write("hello world") > > return apache.OK > ----------------------------------------- > So the Messenger class has the method "write" which calls req.write. > This will output "hello world" in the browser. However, when I go into > Messenger and change the method name from "write" to anything else, it > still works. It is as if the class is being cached. I have deleted pyc > but that has not done anything either. What is going on? This has come up on the mod_python list a number of times, please see these threads, among others: http://www.modpython.org/pipermail/mod_python/2004-October/016567.html http://www.modpython.org/pipermail/mod_python/2004-February/014959.html http://www.modpython.org/pipermail/mod_python/2005-April/017859.html http://www.modpython.org/pipermail/mod_python/2005-July/018619.html and especially these articles: http://www.dscpl.com.au/wiki/ModPython/Articles/ModuleImportingIsBroken http://www.dscpl.com.au/wiki/ModPython/Articles/BasicsOfModuleImporting Actually the mod_python list is very responsive one to mod_python questions probably much more than this (the python list). You can sign up here: http://mailman.modpython.org/mailman/listinfo/mod_python HTH, Daniel From saif.shakeel at gmail.com Fri May 18 02:59:38 2007 From: saif.shakeel at gmail.com (saif.shakeel at gmail.com) Date: 17 May 2007 23:59:38 -0700 Subject: Unusual i/o problems In-Reply-To: References: <1179325595.708882.289510@e65g2000hsc.googlegroups.com> Message-ID: <1179471578.531264.51220@u30g2000hsc.googlegroups.com> On May 16, 7:55 pm, Peter Otten <__pete... at web.de> wrote: > saif.shak... at gmail.com wrote: > > output_file = open(test_file,"w") > ... > > input_xml_sec = open(output_file,'r') > > Can you spot the problem now? To prevent it, use a naming convention that > allows you to distinguish between file /names/ and file /objects/. > > > But i am getting an error on this line > > (input_xml_sec = open(output_file,'r')).I have tried to figure out but > > not able to debug.Can someone throw some light or anything they feel > > could be going wrong somewhere. > > In the future, to make it as easy as possible to help you, please post the > actual traceback which contains valuable hints about the error you > encountered even if you cannot make sense of it. > > Peter Hi, I am running the exe from command prompt,but i am not able to see the error as it goes off very quickly.How do i capture the error (traceback).I tried putting an input prompt after the expected line of error but wont work.Is there a command to capture the error. Thanks From duncan.booth at invalid.invalid Thu May 3 05:51:25 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 3 May 2007 09:51:25 GMT Subject: Why are functions atomic? References: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> <1178044821.864741.235260@o5g2000hsb.googlegroups.com> <1178063341.779617.289690@o5g2000hsb.googlegroups.com> <1178065685.161372.81790@y80g2000hsf.googlegroups.com> <1178083318.404304.76100@q75g2000hsh.googlegroups.com> <1hxh78n.1dtxf9b1vd8r04N%aleax@mac.com> Message-ID: aleax at mac.com (Alex Martelli) wrote: >> Is there a reason for using the closure here? Using function >> defaults seems to give better performance: > > What measurements show you that...? > ... > > brain:~ alex$ python -mtimeit -s'import powi; p=powi.powerfactory1(3)' > 'p(27)' > 1000000 loops, best of 3: 0.485 usec per loop > > brain:~ alex$ python -mtimeit -s'import powi; p=powi.powerfactory2(3)' > 'p(27)' > 1000000 loops, best of 3: 0.482 usec per loop Your own benchmark seems to support Michael's assertion although the difference in performance is so slight that it is unlikely ever to outweigh the loss in readability. Modifying powi.py to reduce the weight of the function call overhead and the exponent operation indicates that using default arguments is faster, but you have to push it to quite an extreme case before it becomes significant: def powerfactory1(exponent, plus): def inner(x): for i in range(1000): res = x+exponent+plus return res return inner def powerfactory2(exponent, plus): def inner(x, exponent=exponent, plus=plus): for i in range(1000): res = x+exponent+plus return res return inner C:\Temp>\python25\python -mtimeit -s "import powi; p=powi.powerfactory1 (3,999)" "p(27)" 10000 loops, best of 3: 159 usec per loop C:\Temp>\python25\python -mtimeit -s "import powi; p=powi.powerfactory2 (3,999)" "p(27)" 10000 loops, best of 3: 129 usec per loop From howe.steven at gmail.com Fri May 18 03:53:55 2007 From: howe.steven at gmail.com (Steven Howe) Date: Fri, 18 May 2007 00:53:55 -0700 Subject: alternative to eclipse [ python ide AND cvs ] In-Reply-To: References: Message-ID: <464D5B93.7080502@gmail.com> Stargaming wrote: > yomgui schrieb: > > Hi, > > Eclipse is just not really working on linux 64 bit > (I tried ubuntu and centos, it is freesing and crashing > and extremly slow) > > I use eclipse for python and cvs, what is "the" good alternative ? > > thanks > > yomgui > Fond of Komodo. Seems to run most of my python programming tasks. Has breakpoints/debugging, introspection, projects and the professional version supports CVS. The only issue I have is that they (ActiveState.com) just raised the price of the personal IDE way too high. I'll be using my older version (3.1) for a while. If I used it at work, I'd certainly have my boss splurge the 200 odd dollar price. But, in their favor, they have a editor version for free. I 'think' it doesn't have the damn fine debugging or CVS feature though. sph -- HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 From newsgroups at debain.org Sun May 20 17:27:37 2007 From: newsgroups at debain.org (Samuel) Date: Sun, 20 May 2007 21:27:37 +0000 (UTC) Subject: Components for a client/server architecture Message-ID: Hi, I am looking for some recommendations for client/server technologies and for the communication involved. I am currently planning to port a Perl application that has grown out of proportion to another language and architecture. For this purpose, I am investigating technologies that best fit the requirements. The current plan for the architecture of the ported software includes: - A client/server model, where the server provides a service for configuring network devices and the client provides a user interface that runs on Unix. - Java (and possibly Jython) or Mono/C# (or possibly IronPython) on the server. Requirements are: A strong and fair threading model. This is actually what drove me away from Perl and what essentially prevents using a normal Python interpreter on the server. I don't know whether the GIL and starvation issues also apply to IronPython or Jython. Sharing non thread-aware objects of arbitrary type between threads without any restriction is absolutely necessary (this is not possible in Perl). - Perl or Python on the client side. Clients have to provide a UI (a web application is not an option). Unfortunately, I have very little experience with client/server architectures and the protocols involved, so I would like to collect your recommendations as a starting point for further research: - Are there any standard protocols that make it easy to share objects between Java/Jython/IronPython and Python or Perl over the network? I am thinking of a portable, language independent object (de-)serialization, if such a thing exists. Having a defined protocol/interface between the client and the server that makes it easy to switch technologies on either side of the architecture is a strong requirement. - How does bi-directional communication in such a protocol work? I am assuming that the client should not poll the server for callbacks, OTOH, leaving a TCP connection open also does not seem right. - What is the security model of that protocol? If my description of the project is inaccurate or too incomplete I apologize; the problem is that I still find it hard to tell which requirements actually matter. If you have any pointers that might be of interest for such an architecture, please let me know. -Samuel From grante at visi.com Thu May 10 12:25:35 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 10 May 2007 16:25:35 -0000 Subject: Newbie look at Python and OO References: <1178812734.860473.236370@y80g2000hsf.googlegroups.com> Message-ID: <1346hrvgve90nea@corp.supernews.com> On 2007-05-10, walterbyrd wrote: > 2) list assignment handling, pointing two vars to the same list: Python doesn't have variables. It has objects to which you can bind names. > But with lists: >>>> a = list("1234") That creates a list object and binds the name "a" to it. >>>> b = a That binds the name b to that same object. You now have two names bound a single object. >>>> a.append("5") Now you modify that object. >>>> a,b > (['1', '2', '3', '4', '5'], ['1', '2', '3', '4', '5']) > > b changes even though I have not touched b. You modified the object to which the name "b" is bound. > I know why, but this is not what I would ordinarilly expect, Stop thinking in "C". ;) > it does not seem intuitive. When one attempts to use intuition devloped in one environment in a different environment it is often wrong. That's why brains have capability to change. > And, > IMO, it gets worse: > >>>> a = list("1234") >>>> b = a Again, you have a single object to which both names "a" and "b" are bound. >>>> a = a + ['5'] Now you've created a new object and bound the name "a" to it. You now have two objects and the name "b" is still bound to the original one. >>>> a,b > (['1', '2', '3', '4', '5'], ['1', '2', '3', '4']) > Sometimes changing a changes b, and sometimes not. You're thinking wrongly. Start thinking about objects/names and not about "variables". > You also have to remember that subseqent changes to a will not > change b - after some operation but not others. To those who > think in Python, I'm sure this all seems normal. Yes, it does. > But, having programmed in about one dozen other language, this > seems downright bizare to me. I know why it works like this, > but it seems like an odd way to do things. If those dozen other languages all used the "variable" paradigm (fixed regions of storage with fixed names) rather than the object/name binding paradigm, then yes, it probably seems like an odd way to do things. If you grew up using base-12, then base-10 seems like an odd way to do things. > 3) ambiguous use of the form: this.that() Nope, it always means exactly the same thing: look up the "that" attribute of object "this", and then call it. Are you confused by the fact that modules are objects? > Sometimes, this.that() means module.funcion() as in: > >>>> os.dirlist(".") Call the "dirlist" attribute of the object to which the name "os" is bound. > Other times, "this" is sort of like a parameter to the "that" > function: > >>>> a = list("1234") >>>> "_".join(a) > '1_2_3_4_5' Call the "join" attribute of the anonymous string object "_". > And still other times, is seems that "this" is an object, acted upon > by "that" : > >>>> a = list("1234") >>>> b = "_".join(a) >>>> b.split("_") > ['1', '2', '3', '4', '5'] Call the "split" attribute of the object to which the name "b" is bound. > Again, those who think in Python, will understand right away that: > > math.count(x) > > is counting the substring "x" in the "math" string. No, that isn't obvious at all unless we've previously been told that the name "math" is bound to a string object and we happen to know that a string object's "count" attribute is a bound method that counts occurances of the passed substring. > But can you see where that might be confused to be a function > called count() in the math module? A python programmer would think that it's calling the "count" attribute of whatever the name "math" is bound to. The name "math" might be bound to a module, a string, or some other type of object. > I'm not complaining. Python is a great language in many > respects. But, I would take some issue with those claiming > Python is intuitive and easy. Unlearning old habits is always difficult. > IMO: there seems to be many ambiguous, unintuitve, and > confusing, aspects to Python. Certainly if you're thinking about it using the wrong set of concepts. -- Grant Edwards grante Yow! I'm continually AMAZED at at th'breathtaking effects visi.com of WIND EROSION!! From elliot at bentlogic.net Tue May 1 21:36:35 2007 From: elliot at bentlogic.net (Elliot Peele) Date: Tue, 01 May 2007 21:36:35 -0400 Subject: os.path.join Message-ID: <1178069795.3201.1.camel@localhost.localdomain> Why does os.path.join('/foo', '/bar') return '/bar' rather than '/foo/bar'? That just seems rather counter intuitive. Elliot From sjmachin at lexicon.net Mon May 7 07:21:50 2007 From: sjmachin at lexicon.net (John Machin) Date: 7 May 2007 04:21:50 -0700 Subject: msbin to ieee In-Reply-To: <1178525916.145819.264070@n59g2000hsh.googlegroups.com> References: <1178487847.671199.108140@h2g2000hsg.googlegroups.com> <1178502738.104124.3840@h2g2000hsg.googlegroups.com> <1178525916.145819.264070@n59g2000hsh.googlegroups.com> Message-ID: <1178536910.566119.6650@o5g2000hsb.googlegroups.com> On May 7, 6:18 pm, revuesbio wrote: > On 7 mai, 03:52, John Machin wrote: > > > On May 7, 7:44 am, revuesbio wrote: > > > > Hi > > > Does anyone have the python version of the conversion from msbin to > > > ieee? > > > Thank u > > > Yes, Google has it. Google is your friend. Ask Google. It will lead > > you to such as: > > >http://mail.python.org/pipermail/python-list/2005-August/337817.html > > > HTH, > > John > > Thank you, > > I've already read it but the problem is always present. this script is > for double precision MBF format ( 8 bytes). It would have been somewhat more helpful had you said what you had done so far, even posted your code ... > I try to adapt this script for single precision MBF format ( 4 bytes) > but i don't find the right float value. > > for example : 'P\xad\x02\x95' will return '0.00024924660101532936' If you know what the *correct* value is, you might like to consider shifting left by log2(correct_value/erroneous_value) :-) Do you have any known correct pairs of (mbf4 string, decimal_float value)? My attempt is below -- this is based on a couple of descriptive sources that my friend Google found, with no test data. I believe the correct answer for the above input is 1070506.0 i.e. you are out by a factor of 2 ** 32 def mbf4_as_float(s): m0, m1, m2, m3 = [ord(c) for c in s] exponent = m3 if not exponent: return 0.0 sign = m2 & 0x80 m2 |= 0x80 mant = (((m2 << 8) | m1) << 8) | m0 adj = 24 + 128 num = mant * 2.0 ** (exponent - adj) if sign: return -num return num HTH, John From claird at lairds.us Mon May 7 06:26:53 2007 From: claird at lairds.us (Cameron Laird) Date: Mon, 7 May 2007 10:26:53 +0000 Subject: invoke user's standard mail client References: <1178266064.922925.125760@y80g2000hsf.googlegroups.com> Message-ID: In article , Cameron Laird wrote: >In article <1178266064.922925.125760 at y80g2000hsf.googlegroups.com>, >luc.saffre at gmail.com wrote: >>Hello, >> >>the simplest way to launch the user's standard mail client from a >>Python program is by creating a mailto: URL and launching the >>webbrowser: >> >>def mailto_url(to=None,subject=None,body=None,cc=None): >> """ >> encodes the content as a mailto link as described on >> http://www.faqs.org/rfcs/rfc2368.html >> Examples partly taken from >> http://selfhtml.teamone.de/html/verweise/email.htm >> """ >> url = "mailto:" + urllib.quote(to.strip(),"@,") >> sep = "?" >> if cc: >> url+= sep + "cc=" + urllib.quote(cc,"@,") >> sep = "&" >> if subject: >> url+= sep + "subject=" + urllib.quote(subject,"") >> sep = "&" >> if body: >> # Also note that line breaks in the body of a message MUST be >> # encoded with "%0D%0A". (RFC 2368) >> body="\r\n".join(body.splitlines()) >> url+= sep + "body=" + urllib.quote(body,"") >> sep = "&" >> return url >> >>import webbrowser >>url = mailto_url(...) >>webbrowser.open(url,new=1) >> >>(Excerpt from >>http://svn.berlios.de/wsvn/lino/trunk/src/lino/tools/mail.py?op=file&rev=0&sc=0) >> >>But this method is limited: you cannot specify a file to be attached >>to the mail. And I guess that there would be problems if the body text >>is too complex. >> >>Does somebody know about a better method? >>It should be possible at least on Windows, since Acrobat Reader is >>able to do it. > . > . > . >Portland http://ct.enews.eweek.com/rd/cts?d=186-6281-53-799-798304-697089-0-0-0-1 > >is the best standardization of this problem we have under Linux. > >I'll address Windows in a subsequent follow-up. A. Apologies! I'm sorry about the URL above; it was completely wrong. I intended . B. The best approach I know under Windows is to invoke start mailto:$ADDRESS 1. That invocation does *not* communicate subject, attachments, ... To do so adequately involves application-specific work, as other follow-ups have mentioned. 2. "start" has its own complexities. The best invocation from console-based Python is likely to be start /w "" mailto:$ADDRESS From p at ulmcnett.com Mon May 21 12:50:04 2007 From: p at ulmcnett.com (Paul McNett) Date: Mon, 21 May 2007 09:50:04 -0700 Subject: Python and GUI In-Reply-To: <1179761984.704369.116310@b40g2000prd.googlegroups.com> References: <1179761984.704369.116310@b40g2000prd.googlegroups.com> Message-ID: <4651CDBC.1070508@ulmcnett.com> sdoty044 at gmail.com wrote: > Just wondering on what peoples opinions are of the GUIs avaiable for > Python? Python has, I believe, 4 compelling choices for GUI library: Tkinter, wxPython, PyQt, and PyGTK. Like everything in life, each has their relative merits and downsides. Briefly, here are my feelings on each, but I'm mostly versed in wxPython. Tkinter: Pros: comes with Python out of the box; terse; easy Cons: owner-drawn (not-native OS widgets); limited in out-of box functionality; kind of ugly wxPython: Pros: easy to install binary on all platforms, active development, active friendly community of contributors, native os base widgets on all platforms. Cons: hard to build from source on all platforms, everything but the kitchen sink comes with it, and some things are pretty buggy still or abandoned. PyQt: Pros: looks good on all platforms, easy to install and use. Cons: licensing issues require you to understand lots of specifics; owner-drawn widgets. PyGTK: Can't comment because I haven't used it. The major con in my mind is that (I think) you need the Gtk library to be installed on all platforms, so on OS X / Windows the widgets won't look platform-native. > All I am doing is prompting users for some data (listbox, radio > buttons, text box, ect...). Then I will have some text output, maybe > a scrolling text message as things are happening. I think each of the GUI libraries would be able to handle this easily. > I have some minor things I need to do, for example, if Checkbutton X > is clicked, I need to disable TextBox Y, and I would like to display > the scrolling text (output) Again, this is simply responding to events as they happen. You set up a callback function with your reactive code, and tell the GUI library to call that function when the event occurs. > Ultimately, is it worth downloading and learning some of the packages > avaiable for Python, or should I just stick to the Tkinter stuff that > is included. I think everyone should use wxPython, but I'm biased. > More specifically, has anyone used the Qt stuff for python, easy to > use? I've used it and it is easy, yes. Relative ease I can't answer though, because I find wxPython extremely easy due to depth of use over the years. Shameless plug: consider using Dabo on top of wxPython - we feel it makes wxPython even easier and more pythonic, but admittedly there's a bit of a learning curve there too. Even though Dabo is a full application framework originally meant for desktop database applications, it is modular and you can choose to only use the UI bits... http://dabodev.com -- pkm ~ http://paulmcnett.com From skip at pobox.com Thu May 31 10:13:27 2007 From: skip at pobox.com (skip at pobox.com) Date: Thu, 31 May 2007 09:13:27 -0500 Subject: Upgrading a largish group of packages w/ distutils Message-ID: <18014.55303.369800.765014@montanaro.dyndns.org> At work I need to upgrade numpy, scipy, ipython and matplotlib. They need to be done all at once. All have distutils setups but the new versions and the old versions are incompatible with one another as a group because numpy's apis changed. Ideally, I could just do something like cd ~/src cd numpy python setup.py install cd ../scipy python setup.py install cd ../matplotlib python setup.py install cd ../ipython python setup.py install however, even if nothing goes awry it leaves me with a fair chunk of time where the state of the collective system is inconsistent (new numpy, old everything else). I'm wondering... Can I stage the installs to a different directory tree like so: export PYTHONPATH=$HOME/local/lib/python-2.4/site-packages cd ~/src cd numpy python setup.py install --prefix=$PYTHONPATH cd ../scipy python setup.py install --prefix=$PYTHONPATH cd ../matplotlib python setup.py install --prefix=$PYTHONPATH cd ../ipython python setup.py install --prefix=$PYTHONPATH That would get them all built as a cohesive set. Then I'd repeat the installs without PYTHONPATH: unset PYTHONPATH cd ~/src cd numpy python setup.py install cd ../scipy python setup.py install cd ../matplotlib python setup.py install cd ../ipython python setup.py install Presumably the compilation (the time-consuming part) is all location-independent, so the second time the build_ext part should be fast. Can anyone comment on the feasibility of this approach? I guess what I'm wondering is what dependencies there are on the installation directory. Thx, Skip From kinch1967 at gmail.com Thu May 31 06:45:32 2007 From: kinch1967 at gmail.com (bullockbefriending bard) Date: 31 May 2007 03:45:32 -0700 Subject: speeding things up with C++ In-Reply-To: References: <1180171179.687276.77930@z28g2000prd.googlegroups.com> Message-ID: <1180608332.725330.306800@z28g2000prd.googlegroups.com> Thanks this is good news. I think my C/C++ background is sufficient to manage to figure things out if I RTFM carefully. Basically I want to pass in a Python list of integer tuples, create an STL container full of equivalent tuples, apply some processor- intensive algorithm to said list of tuples, and finally poke the results back into another Python list of integer tuples and return it to the calling Python environment. Data structures are well-defind and simple, and the most complex case would be 3-deep nested list, so I will seriously consider figuring out how to do it manually as you suggest. On May 31, 3:04 am, Jorgen Grahn wrote: > On 26 May 2007 02:19:39 -0700, bullockbefriending bard wrote: > ... > > > Essentially, I need to pass a list of 6-tuples containing only > > integers to my new sadly necessary super-fast compiled language > > function which i am not looking forward to writing: > > > input: [(1,2,3,4,5,6), (7,8,9,10,11,12),...] > > > and after much thrashing of processor resources, return data which > > looks like this to the Python calling environment: > > > output: [( (1, 2), (1,), (12,), (13), (1, 7, 11), (9,) ), ( another > > nested tuple like preceding one ), .... ] > ... > > However, I hope someone reading this will be able to tell me that I'm > > being a total pessimist and that in fact it isn't very difficult to do > > what I want to do using SWIG. > > You're talking about the actual conversion between Python data > structures and C or C++ data structures? That is easy to do even > manually, IMHO -- provided a decent C background. > > Have a look in the Python/C API Reference Manual, and the mapping > becomes clear. The PyListObject stuff for example, where there's a C > function for every basic operation on lists, and where the elements > have the C type PyObject. And so on. Mapping to C is just a matter of > walking a nested data structure, where you have a good idea what it is > supposed to look like (a list of six-tuples of some kind of numbers). > > /Jorgen > > -- > // Jorgen Grahn \X/ snipabacken.dyndns.org> R'lyeh wgah'nagl fhtagn! From mensanator at aol.com Thu May 17 19:56:57 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 17 May 2007 16:56:57 -0700 Subject: How to convert a number to binary? In-Reply-To: <1179445546.307017.275850@p77g2000hsh.googlegroups.com> References: <1179444832.775573.55830@y80g2000hsf.googlegroups.com> <1179445546.307017.275850@p77g2000hsh.googlegroups.com> Message-ID: <1179446217.435193.234070@l77g2000hsb.googlegroups.com> On May 17, 6:45 pm, Lyosha wrote: > On May 17, 4:40 pm, Michael Bentley wrote: > > > > > > > On May 17, 2007, at 6:33 PM, Lyosha wrote: > > > > Converting binary to base 10 is easy: > > >>>> int('11111111', 2) > > > 255 > > > > Converting base 10 number to hex or octal is easy: > > >>>> oct(100) > > > '0144' > > >>>> hex(100) > > > '0x64' > > > > Is there an *easy* way to convert a number to binary? > > > def to_base(number, base): > > 'converts base 10 integer to another base' > > > number = int(number) > > base = int(base) > > if base < 2 or base > 36: > > raise ValueError, "Base must be between 2 and 36" > > if not number: > > return 0 > > > symbols = string.digits + string.lowercase[:26] > > answer = [] > > while number: > > number, remainder = divmod(number, base) > > answer.append(symbols[remainder]) > > return ''.join(reversed(answer)) > > > Hope this helps, > > Michael > > That's way too complicated... Is there any way to convert it to a one- > liner so that I can remember it? Mine is quite ugly: > "".join(str((n/base**i) % base) for i in range(20) if n>=base**i) > [::-1].zfill(1)- Get the gmpy module (note inconsistencies involving octal and hex): >>> import gmpy >>> for base in xrange(2,37): print gmpy.digits(255,base) 11111111 100110 3333 2010 1103 513 0377 313 255 212 193 168 143 120 0xff f0 e3 d8 cf c3 bd b2 af a5 9l 9c 93 8n 8f 87 7v 7o 7h 7a 73 From jzgoda at o2.usun.pl Mon May 14 05:48:16 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Mon, 14 May 2007 11:48:16 +0200 Subject: Asyncore Help? In-Reply-To: References: <60e9f3330705132151q75f2bc2bt25aa04cff93f5b82@mail.gmail.com> Message-ID: Daniel Nogradi napisa?(a): > The twisted project might also be a good place for anything related to > python and networking: http://twistedmatrix.com/trac/ Twisted eats babies for breakfast, although it also kills all known germs(TM). ;) -- Jarek Zgoda "We read Knuth so you don't have to." From nufuhsus at gmail.com Fri May 11 17:07:51 2007 From: nufuhsus at gmail.com (nufuhsus at gmail.com) Date: 11 May 2007 14:07:51 -0700 Subject: Interesting list Validity (True/False) In-Reply-To: <1349km0g41b565@corp.supernews.com> References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> <1349ihg6j1e1k95@corp.supernews.com> <1349km0g41b565@corp.supernews.com> Message-ID: <1178917671.463649.102720@p77g2000hsh.googlegroups.com> On May 11, 4:32 pm, Grant Edwards wrote: > On Fri, May 11, 2007 at 01:20:44PM -0700, nufuh... at gmail.com > wrote: > > > On May 11, 3:55 pm, Grant Edwards wrote: > > > You got those results because that's what your program does. > > > > Were you intending it to do something else? If so, you're > > > going to have to explain what you wanted, because we can't > > According to my output, it seems that arg is False even when I > > give an option of '-o' which according to the book should be > > True. No? > > '-o' is not equal to True. However, that does not mean it > evaluates to false when tested by an if or while statement. > > > If arg == ['-o'] then shouldn't arg == True return True and > > skip the if? > > No. See the folloing link regarding the "truth value" of an > object: > > http://docs.python.org/lib/truth.html > > There are many objects other than True that evaluate to "true" > in the context of an if/while statement. Just because an > objecty has a "true" truth-value doesn't mean that it is equal > to the True object. > > -- > Grant Edwards grante Yow! Why don't you ever > at enter any CONTESTS, > visi.com Marvin?? Don't you know > your own ZIPCODE? OK. Then how would you differenciate between a call with an option versus one without (e.g. help.py -o (where arg == ['-o']) Vs. help.py (where arg == []))? From tjreedy at udel.edu Thu May 24 20:53:24 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 24 May 2007 20:53:24 -0400 Subject: Newsgroups and mailing lists (was Re: Slightly OT: Why all the spam?) References: <3bb44c6e0705220008y10f5deb7v86ed82d3f8241761@mail.gmail.com> Message-ID: "Aahz" wrote in message news:f34qpt$3oh$1 at panix3.panix.com... | First of all, if you're accessing python-list as comp.lang.python, you're | accessing a newsgroup, *not* a mailing list. Secondly, c.l.py is an | unmoderated group; there is no moderator and no control over who posts. | However, netnews (Usenet) has a mechanism for cancelling articles, and | cancelbots send out cancel messages for spam articles. This does not address the issue of spam passing thru python-list, which I believe is supposed to be somewhat moderated (by people who have rejected my help to catch spam) to gmane, where I read it. I presume this is the path for stuff injected via google. Or perhaps stuff flows the other way. I am not sure. Or perhaps it it injected independently in both or all three places. tjr From martin at v.loewis.de Thu May 17 15:08:33 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 17 May 2007 21:08:33 +0200 Subject: omissions in python docs? In-Reply-To: <1179427280.850561.72750@n59g2000hsh.googlegroups.com> References: <1179419983.750044.65030@n59g2000hsh.googlegroups.com> <464C9038.6000109@v.loewis.de> <1179427280.850561.72750@n59g2000hsh.googlegroups.com> Message-ID: <464CA831.4000106@v.loewis.de> memracom at yahoo.com schrieb: >> It often happened in the past that patches were admitted which don't >> simultaneously update the documentation, hence they diverge. These >> days, patches are regularly rejected for not providing proper >> documentation changes. > > Nevertheless, the docs *ARE* old and poorly maintained. I agree they are old, but they are *not* poorly maintained. There is a strict policy that changes to the code *must* be accompanied by documentation updates, and contributed documentation patches are quickly integrated (more quickly than code changes). So from a maintenance point of view, the documentation is at a better standing than the code. Regards, Martin From bscrivener42 at gmail.com Tue May 29 09:38:38 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: 29 May 2007 06:38:38 -0700 Subject: wxpython demo error on debian etch Message-ID: <1180445918.523446.133300@g4g2000hsf.googlegroups.com> If there is a wxPython on Debian user in the house? I am using the version of the demo that came with the apt-get download of wxPython. I thought I'd followed the instructions for installing and unpacking the wxPython demo program. It appears to run after a fashion, but I also get this at the commandline. Any help much appreciated. (python:5865): Gtk-CRITICAL **: gtk_window_realize_icon: assertion `info->icon_pixmap == NULL' failed Traceback (most recent call last): File "/usr/lib/python2.4/site-packages/wx-2.6-gtk2-unicode/wx/ _misc.py", line 1286, in Notify self.notify() File "/usr/lib/python2.4/site-packages/wx-2.6-gtk2-unicode/wx/ _core.py", line 13637, in Notify self.result = self.callable(*self.args, **self.kwargs) File "/home/rick/bin/wxPython/Main.py", line 1713, in ShowMain if self.fc.IsRunning(): File "/usr/lib/python2.4/site-packages/wx-2.6-gtk2-unicode/wx/ _core.py", line 13481, in __getattr__ raise PyDeadObjectError(self.attrStr % self._name) wx._core.PyDeadObjectError: The C++ part of the MySplashScreen object has been deleted, attribute access no longer allowed. Thanks, Rick From braindead at braindead.com Tue May 22 07:48:10 2007 From: braindead at braindead.com (enquiring mind) Date: Tue, 22 May 2007 11:48:10 GMT Subject: help - python can't find file References: <465194E3.FED4F65A@braindead.com> Message-ID: <4652D82F.60DA8FB7@braindead.com> darren, thanks for your explanation. I copied my paths and listed them in my code file #! /bin/user1/ python and python finds the file and interprets it so that will keep me going until my buddy returns to the city to explain my errors. It appears that my problem arose from taking lesson code out of text books and copying the pathing that is I guess slightly different than mine. Thanks ever so much. tk darren kirby wrote: > > quoth the enquiring mind: > > > - but now I get a error message 21 saying file or directory doesn't > > exist. > > You must be in the same directory (in konsole) as the python script for this > to work, else enter the relative path to the file: > > Assuming you are in your home directory (this is where a new konsole will > start you), and the py scripts are in a directory 'pythondir': > > $ cd pythondir > $ python myscript.py > > or: > > $ python pythondir/myscript.py > > You could also chmod the script to be executable and run it as a regular > command ...however... I don't mean this to sound like RTFM but I do think > that you could use some reading on Linux CLI usage. You say you have some > Linux books? > > I say this as my reading of your message indicates your problems lie with > misunderstanding the shell/paths etc, not with Python itself... > > -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 __peter__ at web.de Mon May 28 01:16:41 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 28 May 2007 07:16:41 +0200 Subject: os.path.walk not pruning descent tree (and I'm not happy with that behavior?) References: <1180316372.126765.213530@r19g2000prf.googlegroups.com> Message-ID: Joe Ardent wrote: > Good day, everybody! From what I can tell from the archives, this is > everyone's favorite method from the standard lib, and everyone loves > answering questions about it. Right? :) I don't know what to make of the smiley, so I'll be explicit: use os.walk() instead of os.path.walk(). > Anyway, my question regards the way that the visit callback modifies > the names list. Basically, my simple example is: > > ############################## > def listUndottedDirs( d ): > dots = re.compile( '\.' ) > > def visit( arg, dirname, names ): > for f in names: > if dots.match( f ): > i = names.index( f ) > del names[i] > else: > print "%s: %s" % ( dirname, f ) > > os.path.walk( d, visit, None ) > ############################### > > Basically, I don't want to visit any hidden subdirs (this is a unix > system), nor am I interested in dot-files. If I call the function > like, "listUndottedDirs( '/usr/home/ardent' )", however, EVEN THOUGH > IT IS REMOVING DOTTED DIRS AND FILES FROM names, it will recurse into > the dotted directories; eg, if I have ".kde3/" in that directory, it > will begin listing the contents of /usr/home/ardent/.kde3/ . Here's > what the documentation says about this method: > > "The visit function may modify names to influence the set of > directories visited below dirname, e.g. to avoid visiting certain > parts of the tree. (The object referred to by names must be modified > in place, using del or slice assignment.)" > > So... What am I missing? Any help would be greatly appreciated. Your problem is that you are deleting items from a list while iterating over it: # WRONG >>> names = [".alpha", ".beta", "gamma"] >>> for name in names: ... if name.startswith("."): ... del names[names.index(name)] ... >>> names ['.beta', 'gamma'] Here's one way to avoid that mess: >>> names = [".alpha", ".beta", "gamma"] >>> names[:] = [name for name in names if not name.startswith(".")] >>> names ['gamma'] The slice [:] on the left side is necessary to change the list in-place. Peter From steven at REMOVE.THIS.cybersource.com.au Tue May 8 00:33:51 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 08 May 2007 04:33:51 -0000 Subject: interesting exercise References: <1178595952.641173.76540@y80g2000hsf.googlegroups.com> Message-ID: On Tue, 08 May 2007 01:21:37 -0300, Gabriel Genellina wrote: > if not sorted(values): raise ValueError("unsorted values") sorted() doesn't return a flag telling if the values are sorted, it returns a new list containing values sorted. So this line will raise an exception only on an empty sequence. -- Steven. From robert.kern at gmail.com Wed May 9 17:01:02 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 09 May 2007 16:01:02 -0500 Subject: change of random state when pyc created?? In-Reply-To: References: <5ae25fF2oggbqU1@mid.uni-berlin.de> Message-ID: Alan G Isaac wrote: > Robert Kern wrote: >> http://docs.python.org/lib/typesmapping.html >> """ >> Keys and values are listed in an arbitrary order which is non-random, varies >> across Python implementations, and depends on the dictionary's history of >> insertions and deletions. >> """ > > Even this does not tell me that if I use a specified implementation > that my results can vary from run to run. That is, it still does > not communicate that rerunning an *unchanged* program with an > *unchanged* implementation can produce a change in results. The last clause does tell me that. -- 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 lanwrangler at gmail.com Tue May 1 09:01:45 2007 From: lanwrangler at gmail.com (lanwrangler at gmail.com) Date: 1 May 2007 06:01:45 -0700 Subject: Comparing bitmap images for differences? Message-ID: <1178024505.768505.262270@h2g2000hsg.googlegroups.com> I know it's a long shot but does anyone have any pointers to generic algorithms - or, even better, Python code - for comparing images and computing a value for the "difference" between them? What I want to do is to compare two bitmap images (taken from a webcam, so I'll likely be using PIL) and get some idea of the "difference" between them so I can tell if something in the image has changed, eg, a person has entered the field of view. I've had a look at the PIL documentation and all it really told me was how little I knew about image processing :-) and I couldn't see any recipes in the Python Cookbook that are aimed at this problem area. In a perfect world I'd love a method such as CompareImage(Img1, Img2) which would give a result of 255 if they're identical and 0 if not one pixel matches with a sliding scale inbetween but I know I'm probably asking for a lot there... Some ideas I've had is, maybe, increasing the contrast on both images (to take out variation in lighting etc), then compressing the results to get a hash value and comparing the hash, but that sounds likely to produce a lot of false positives. I note that PIL provides a histogram function for counting pixel colour values which sounds potentially useful and if no-one's got any better ideas I'll probably start working in that direction. Or, maybe, dump the bitmap data into a numpy array and do some kind of FFT on that but that feels very CPU- intensive. Those are my ideas so far but I thought it would be worth asking here first in case there are some known-good algorithms for doing this kind of thing rather than me trying to re-invent a wheel that ends up triangular... Thanks! Matthew. From wildemar at freakmail.de Mon May 21 15:34:36 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Mon, 21 May 2007 21:34:36 +0200 Subject: [Fwd: Re: managed lists?] Message-ID: <4651F44C.4040203@freakmail.de> I answered off list (because besically I'm an idiot). So if you like, read up the current news. :) -------- Original Message -------- Subject: Re: managed lists? Date: Mon, 21 May 2007 21:30:37 +0200 From: Jorgen Bodde To: Wildemar Wildenburger References: <11e49df10705211026s3e8f15b8nee32e0aa94b55ee6 at mail.gmail.com> <4651DFE1.7010109 at freakmail.de> Hi Wildemar, Thanks for the answer. I did make something myself after i could not find anything, just because it was fun to do :-) I did saw array but it was not for object, only for small types like int, char, etc to be used for quick but efficient buffers of raw data (at least it looks like that). The list I created uses a strong type check to make sure all objects in the list are of the same type, like ol = objlist.ObjList(class_name = SomeClass) Now only classes that are an instance of SomeClass are allowed in the array, ObjList mimics a normal list, it can index, iterate, find, delete, append items so it was basically a drop-in replacement for my _list = [] solution If you are interested i can send you the source. I created a py.test module as well to test every method intensively. Regards, - Jorgen On 5/21/07, Wildemar Wildenburger wrote: > Jorgen Bodde wrote: > > Right now i have a list in a class that I export as a member variable > > to the outside world, it is a standard list (e.g. [] ) but I wish to > > have a stronger type checking when adding objects, that only some > > objects are allowed and others are not. It was quite easy to create > > it, but I wonder if there is already a standard solution for lists > > that carry only objects of a single type? > > > > Don't have much time on me right now, so I'll just give you a hint: I > *think* python has an array-datatype somewhere in its STD-lib (that is: > in a module you have to import). Not sure, could have been only for > NumPy or so. A quick look into the docs should clarify that quickly. > > bye :) > W > From mad.vijay at gmail.com Fri May 4 02:20:35 2007 From: mad.vijay at gmail.com (SamG) Date: 3 May 2007 23:20:35 -0700 Subject: enable-shared Message-ID: <1178259635.955252.304000@n76g2000hsh.googlegroups.com> How we do if find that python that we are using is compiled with the -- enable-shared option. There is can actually be done using .... distutils.sysconfig module but this modules is ported only with python- devel but not with standard python install. Is there another way apart from checking the pyconfig.h file. Thanks in advance : )~ From jadestar at idiom.com Wed May 9 02:50:38 2007 From: jadestar at idiom.com (James T. Dennis) Date: Wed, 09 May 2007 06:50:38 -0000 Subject: Minor bug in tempfile module (possibly __doc__ error) Message-ID: <1178693438.689184@smirk> Tonight I discovered something odd in the __doc__ for tempfile as shipped with Python 2.4.4 and 2.5: it says: This module also provides some data items to the user: TMP_MAX - maximum number of names that will be tried before giving up. template - the default prefix for all temporary names. You may change this to control the default prefix. ... which would lead one to think that the following code would work: >>> import tempfile >>> tempfile.template = 'mytest' >>> tf = tempfile.NamedTemporaryFile() >>> tf.name '/tmp/mytest-XXXXXX' It doesn't. In fact I realized, after reading through tempfile.py in /usr/lib/... that the following also doesn't "work" like I'd expect: # foo.py tst = "foo" def getTst(arg): return "foo-%s" % arg # bar.py import foo foo.tst = "bar" print foo.getTst("testing") foo-testing <<<----- NOT "bar-testing" Now I would feel like a real idiot if I'd come across that in the foo/bar case here ... because I clearly don't understand quite *why* I can't "monkey patch" this value. I would ... but I don't. First, I wouldn't have written code like this foo/bar stuff; except to test my hypothesis about why changes to tempfile.template don't actually affect the values seen by functions in the tempfile namespace. Secondly, the author(s) of the tempfile module apparently didn't understand this either. And no one else even noticed that the __doc__ is wrong (or at least misleading -- since the only way I can see to change tempfile.template is to edit the .py file! So, I don't feel like an idiot. But I am curious ... ... why can't I change that value in that other namespace? Is it a closure? (Or like a closure?) Where is this particular aspect of the import/namespace semantics documented? -- Jim Dennis, Starshine: Signed, Sealed, Delivered From jstroud at mbi.ucla.edu Thu May 10 17:49:27 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 10 May 2007 14:49:27 -0700 Subject: SQLObject 0.9.0 In-Reply-To: <1178824322.008520.239540@y5g2000hsa.googlegroups.com> References: <1178824322.008520.239540@y5g2000hsa.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: > Why was this released 3 times with different version numbers in less > than an hour? > > Mike > For reasons others will know, there are different branches to the SQLObject project. I think, analogously, python still has an active 2.4 branch, if that helps make sense of maintaining branches based on versions. I'm not sure why the announcements aren't bundled into one because just about everyone who sees this for the first time asks the same question. James From ratchetgrid at googlemail.com Wed May 9 05:56:44 2007 From: ratchetgrid at googlemail.com (Nathan Harmston) Date: Wed, 9 May 2007 10:56:44 +0100 Subject: Using the CSV module In-Reply-To: <1068189.36314.BlRUCl8VTQA=.1178703613.squirrel@webmailer.hosteurope.de> References: <676224240705090140k2525224ch541a5740a19a6f3f@mail.gmail.com> <1068189.36314.BlRUCl8VTQA=.1178703613.squirrel@webmailer.hosteurope.de> Message-ID: <676224240705090256w48f682e4gbce49929022fa998@mail.gmail.com> I ve just finished writing one, I wanted to stay with the batteries included approach as much as possible though. Is there anyway I can request a change to the csv module? Thanks Nathan On 09/05/07, Stefan Sonnenberg-Carstens wrote: > Most of the time I found the CSV module not as useful as it might be - > due to the restrictions you describe. > > Why not write a simple parser class ? > > On Mi, 9.05.2007, 10:40, Nathan Harmston wrote: > > Hi, > > > > I ve been playing with the CSV module for parsing a few files. A row > > in a file looks like this: > > > > some_id\t|\tsome_data\t|t\some_more_data\t|\tlast_data\t\n > > > > so the lineterminator is \t\n and the delimiter is \t|\t, however when > > I subclass Dialect and try to set delimiter is "\t|\t" it says > > delimiter can only be a character. > > > > I know its an easy fix to just do .strip("\t") on the output I get, > > but I was wondering > > a) if theres a better way of doing this when the file is actually > > being parsed by the csv module > > b) Why are delimiters only allowed to be one character in length. > > > > Many Thanks in advance > > Nathan > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > > From kyosohma at gmail.com Thu May 31 15:15:48 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 31 May 2007 12:15:48 -0700 Subject: generating a tree-like structure In-Reply-To: References: Message-ID: <1180638948.157965.210260@q66g2000hsg.googlegroups.com> On May 31, 12:44 pm, Thorsten Kampe wrote: > Hi, > > This is a fairly general question: is there some kind of module or > framework that allows building a tree like structure from certain kind > of data? > > To be specific: I have a program that dumps the content of a LDAP > directory including all properties and values and groups the result > from the LDAP search by objClass. > > Now I was thinking: would it be possible to generate from the totally > unordered output that the LDAP server gives me, a tree like > representation that displays the hierarchy (omitting the values or > even properties if necessary)? > > It should be a textual representation of what you see in GUI programs > like "LDAP Administrator" but the output should be represented like > the "tree" program in Linux or Windows "tree.com". > > Any ideas appreciated... > > Thorsten I think you might be able to use ElementTree. The website for the module claims it can be used for hierarchical data structures: http://effbot.org/zone/element-index.htm Did you look at any of the Python LDAP tools? They might be useful too. See some of the links below: http://linuxjournal.com/article/6988 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303336 Hopefully they'll give some guidance. I've not used LDAP myself as of yet. Mike From wildemar at freakmail.de Wed May 30 07:31:01 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Wed, 30 May 2007 13:31:01 +0200 Subject: Python 2.5 and WXPython demo's In-Reply-To: <1180523448.993195.59180@q69g2000hsb.googlegroups.com> References: <1180523448.993195.59180@q69g2000hsb.googlegroups.com> Message-ID: <465D6075.7020903@freakmail.de> Andrew P wrote: > Hello, > > I am new (very) to Python and have just down loaded the latest version > of Python (2.5) and WXPython (2.8). > > For some reason I cannot get the WXPython demo to run at all. I run > windows XP and it can't find a program to run the demo. Any advice? > (apologies if this has been posted before). > > There *should* be a link in your startmenu in the wxPython group. I'm quite positive, but not 100% sure. I think it has the snake-icon. But if it's really not there (as you suggested), simply go the the folder you installed the demo to and run demo.py. Maybe there's a blunder in the installer for the 2.8 demo? Anyone? bye /W From maksim.kasimov at gmail.com Fri May 25 10:20:43 2007 From: maksim.kasimov at gmail.com (Maksim Kasimov) Date: Fri, 25 May 2007 17:20:43 +0300 Subject: just a bug In-Reply-To: <1180097871.265507.174720@p77g2000hsh.googlegroups.com> References: <1179841504.782279.86490@u36g2000prd.googlegroups.com> <1180082137.329142.45350@p77g2000hsh.googlegroups.com> <1180090985.066935.218250@h2g2000hsg.googlegroups.com> <1180097871.265507.174720@p77g2000hsh.googlegroups.com> Message-ID: harvey.thomas at informa.com : > You need to explicitly convert the string of UTF8 encoded bytes to a > Unicode string before parsing e.g. > unicodestring = unicode(encodedbytes, 'utf8') it is only a part of a string - not hole string, i've wrote it before. That meens that the content can not be converted to unicode until reciever program will get all parts of the utf-string from sender. the xml in iMessage is absolutely correct. Please read my previous posts. thanks. -- Maksim Kasimov From rrr at ronadam.com Fri May 25 13:52:16 2007 From: rrr at ronadam.com (Ron Adam) Date: Fri, 25 May 2007 12:52:16 -0500 Subject: webbrowser module bug? In-Reply-To: <465711B8.7070505@holdenweb.com> References: <1180106384.198363.14120@p47g2000hsd.googlegroups.com> <465711B8.7070505@holdenweb.com> Message-ID: Steve Holden wrote: > Ron Adam wrote: >> kyosohma at gmail.com wrote: >>> On May 24, 5:03 pm, Ron Adam wrote: >>>> Is anyone else having problems with the webbrowser module? >>>> >>>> Python 2.5.1c1 (release25-maint, Apr 12 2007, 21:00:25) >>>> [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 >>>> Type "help", "copyright", "credits" or "license" for more information. >>>> >>> import webbrowser >>>> >>> webbrowser.open('http://www.python.org') >>>> True >>>> >>> >>>> >>>> It opens firefox as expected, but the url is ... >>>> >>>> file:///home/ron/%22http://www.python.org%22 >>>> >>>> Which of course doesn't do what is expected. >>>> >>>> Any ideas? >>>> >>>> Ron >>> I don't know. This works for me with Python 2.4 on Windows XP SP2. The >>> docs don't say much (http://docs.python.org/lib/module- >>> webbrowser.html). Maybe it would be beneficial to read the module's >>> code? Or use the "register" command manually? >> It works for me on python 2.4 also, but not on later versions. >> >> Looks like I'll need to try to test the url at the point where it calls the >> browser from webbrowser.py. >> >> Can someone else test this on python 2.5? >> > On my Windows laptop it works on 2.4.1 and 2.5.1 native, but not on > 2.5.1 for Cygwin. Does it mangle the url in the same way? If so, then that would be enough to file a bug report. It's maybe not due to the webbrowser module it self, but maybe something else that's platform dependent? Can anyone else reproduce this? Ron From horpner at yahoo.com Mon May 21 08:39:23 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 21 May 2007 12:39:23 GMT Subject: converting strings to most their efficient types '1' --> 1, 'A' ---> 'A', '1.2'---> 1.2 References: <1179529661.555196.13070@k79g2000hse.googlegroups.com> <1179551680.283157.19000@y80g2000hsf.googlegroups.com> <464FA156.2070704@lexicon.net> Message-ID: On 2007-05-20, John Machin wrote: > On 19/05/2007 3:14 PM, Paddy wrote: >> On May 19, 12:07 am, py_genetic wrote: >>> Hello, >>> >>> I'm importing large text files of data using csv. I would like to add >>> some more auto sensing abilities. I'm considing sampling the data >>> file and doing some fuzzy logic scoring on the attributes (colls in a >>> data base/ csv file, eg. height weight income etc.) to determine the >>> most efficient 'type' to convert the attribute coll into for further >>> processing and efficient storage... >>> >>> Example row from sampled file data: [ ['8','2.33', 'A', 'BB', 'hello >>> there' '100,000,000,000'], [next row...] ....] >>> >>> Aside from a missing attribute designator, we can assume that the same >>> type of data continues through a coll. For example, a string, int8, >>> int16, float etc. >>> >>> 1. What is the most efficient way in python to test weather a string >>> can be converted into a given numeric type, or left alone if its >>> really a string like 'A' or 'hello'? Speed is key? Any thoughts? >>> >>> 2. Is there anything out there already which deals with this issue? >>> >>> Thanks, >>> Conor >> >> You might try investigating what can generate your data. With luck, >> it could turn out that the data generator is methodical and column >> data-types are consistent and easily determined by testing the >> first or second row. At worst, you will get to know how much you >> must check for human errors. >> > > Here you go, Paddy, the following has been generated very methodically; > what data type is the first column? What is the value in the first > column of the 6th row likely to be? > > "$39,082.00","$123,456.78" > "$39,113.00","$124,218.10" > "$39,141.00","$124,973.76" > "$39,172.00","$125,806.92" > "$39,202.00","$126,593.21" > > N.B. I've kindly given you five lines instead of one or two :-) My experience with Excel-related mistakes leads me to think that column one contains dates that got somehow misformatted on export. -- Neil Cerutti From gnewsg at gmail.com Thu May 17 13:46:35 2007 From: gnewsg at gmail.com (billiejoex) Date: 17 May 2007 10:46:35 -0700 Subject: Asyncore Help? In-Reply-To: References: Message-ID: <1179423995.947387.174790@p77g2000hsh.googlegroups.com> On 14 Mag, 06:51, "Paul Kozik" wrote: > I have trouble finding a solid example for what I need. Python.org and > other sites provide simple examples, but they appear more intended for > servers that simply send one peice of data to the client. Not a big deal. asynchat / asyncore are pretty easy-to-learn frameworks. Under the hoods they are extremely simpler if compared to Twisted. You shouldn't have problems in learning how the things works in a couple of days. Try to take a look at: http://effbot.org/zone/asyncore-ftp-client.htm http://effbot.org/librarybook/asynchat.htm > Besides this I am also stuck with dealing with TCP data streams. I can > receive and send the data (using threads, not yet with asynocore), but > I am unsure how to deal with the streamlike nature of TCP (and would > prefer to use TCP over UDP). If you really need speed UDP could be a better choice. > While basic socket work was rather easy to deal with, this has proved > significantly more difficult. Developing a bug-less network application by using the basic socket module instead of an high-level framework like asyncore it's surely a lot harder. Again: asyncore is really simple: it's just a matter of understanding the event-based approach that's very different from the thread-based one. From john at datavoiceint.com Mon May 14 18:04:54 2007 From: john at datavoiceint.com (HMS Surprise) Date: 14 May 2007 15:04:54 -0700 Subject: Time In-Reply-To: <134hdehnrd73bef@corp.supernews.com> References: <1178916216.893542.257320@y80g2000hsf.googlegroups.com> <1178916422.065108.312920@l77g2000hsb.googlegroups.com> <1178920014.621031.301860@n59g2000hsh.googlegroups.com> <1178927105.482975.174760@y5g2000hsa.googlegroups.com> <1179151205.987222.54910@k79g2000hse.googlegroups.com> <1179152573.315362.37040@u30g2000hsc.googlegroups.com> <1179152855.424498.274820@p77g2000hsh.googlegroups.com> <134hdehnrd73bef@corp.supernews.com> Message-ID: <1179180293.974361.226640@p77g2000hsh.googlegroups.com> > > Do you mean 12 Noon or 12 Midnight? 12AM and 12PM don't exist, > do they? > >>> t = (2007, 5, 14, 12, 0,0,0,0,0) >>> strftime('%p', t) 'PM' >>> t = (2007, 5, 14, 0,0,0,0,0,0) >>> strftime('%p', t) 'AM' >>> From stargaming at gmail.com Thu May 10 14:59:22 2007 From: stargaming at gmail.com (Stargaming) Date: Thu, 10 May 2007 20:59:22 +0200 Subject: which is more pythonic/faster append or +=[] In-Reply-To: <1hxuz03.husyup2cjk81N%aleax@mac.com> References: <1hxtelz.7f6rvnw4cyxmN%aleax@mac.com> <1178723595.516379.18180@u30g2000hsc.googlegroups.com> <1hxuz03.husyup2cjk81N%aleax@mac.com> Message-ID: Alex Martelli schrieb: > 7stud wrote: > ... > >>>.append - easy to measure, too: >>> >>>brain:~ alex$ python -mtimeit 'L=range(3); n=23' 'x=L[:]; x.append(n)' >>>1000000 loops, best of 3: 1.31 usec per loop >>> >>>brain:~ alex$ python -mtimeit 'L=range(3); n=23' 'x=L[:]; x+=[n]' >>>1000000 loops, best of 3: 1.52 usec per loop >>> >>>Alex >> >>Why is it necessary to copy L? > > > If you don't, then L gets longer and longer -- to over a million > elements by the end of the loop -- so we're measuring something that's > potentially very different from the problem under study, "what's the > best way to append one item to a 3-items list". > > That's important to consider for any microbenchmark of code that changes > some existing state: make sure you're measuring a piece of code that > _overall_ does NOT change said existing state in a cumulative way, > otherwise you may be measuring something very different from the issue > of interest. It's maybe the only important caveat about using "python > -mtimeit". > > > Alex > Cannot reproduce that. Consider the following: $ python -mtimeit "L=range(3)" "L.append(1); print len(L)" 4 4 [...] 4 1000 loops, best of 3: [...] Doesn't seem like copying is really neccessary. From rurpy at yahoo.com Tue May 15 17:33:52 2007 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 15 May 2007 14:33:52 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179236673.893122.28800@w5g2000hsg.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> Message-ID: <1179264832.815799.117420@n59g2000hsh.googlegroups.com> On May 15, 7:44 am, George Sakkis wrote: > After 175 replies (and counting), the only thing that is clear is the > controversy around this PEP. Most people are very strong for or > against it, with little middle ground in between. I'm not saying that > every change must meet 100% acceptance, but here there is definitely a > strong opposition to it. Accepting this PEP would upset lots of people > as it seems, and it's interesting that quite a few are not even native > english speakers. As I pointed out in a previous post, http://groups.google.com/group/comp.lang.python/msg/c911d6d249d327a6?hl=en& http://groups.google.com/group/comp.lang.python/msg/363fe742925623c4?hl=en& whether a person is or is not a native English speaker is irrelevant -- what is relevant is their current ability with English. And my impression is that neally all of posts from people not fluent in English (judging from grammar mistakes and such) are in favor of the PEP. From Pull up your pants, Speak english, Get a job, Sat May 12 11:02:17 2007 From: Pull up your pants, Speak english, Get a job, (Pull up your pants, Speak english, Get a job,) Date: Sat, 12 May 2007 10:02:17 -0500 Subject: OMG BRITNEYS AT IT AGAIN AGAIN!!!!!! In-Reply-To: <1178938167.288106.161280@o5g2000hsb.googlegroups.com> References: <1178920641.280005.221690@p77g2000hsh.googlegroups.com> <24edndmfSP6zddnbnZ2dnUVZ_oSdnZ2d@comcast.com> <1178938167.288106.161280@o5g2000hsb.googlegroups.com> Message-ID: <1178982207_12907@sp12lax.superfeed.net> On 2007-05-11, wise.of.clean789 at gmail.com >>wrote: >>http://britneyboobs.blogspot.com/2007/05/britney-spears-slips-up-again-exposes.html > > - Exclusive pics of Britney Spears...... > >Britneyboobs ....what?... you take pride in being on > >mykey wrote: > > > the queen of lip sync does it again! Why can't that ho git on dat private jet and fly to some fucking hillbilly resort and stay the fuck there. Take that Paris bitch too.. and give that BONEY ASS ho a CHEESE BURGER on da way. ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From nospam at noemailhere.nowhere Fri May 18 00:08:59 2007 From: nospam at noemailhere.nowhere (Anthony Irwin) Date: Fri, 18 May 2007 14:08:59 +1000 Subject: omissions in python docs? In-Reply-To: <1179452448.886371.169000@q75g2000hsh.googlegroups.com> References: <1179419983.750044.65030@n59g2000hsh.googlegroups.com> <1179451395.440662.127760@y80g2000hsf.googlegroups.com> <1179452448.886371.169000@q75g2000hsh.googlegroups.com> Message-ID: 7stud wrote: > On May 17, 7:23 pm, 7stud wrote: > > By the way, have the python doc keepers ever visited the php docs? In > my opinion, they are the best docs of any language I've encountered > because users can add posts to any page in the docs to correct them or > post code showing how to get around various idiosyncrasies when using > the functions. > Hi, I also like the php docs and love that you can type any function into the search at php.net and the documentation just comes up and there is example code and then user comments also. -- Kind Regards, Anthony Irwin http://www.irwinresources.com http://www.makehomebusiness.com email: anthony at above domains, - www. From bronger at physik.rwth-aachen.de Fri May 18 05:44:49 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Fri, 18 May 2007 11:44:49 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <464d6b22$0$25929$ba4acef3@news.orange.fr> Message-ID: <87d50ypisu.fsf@wilson.homeunix.com> Hall?chen! Laurent Pointal writes: > [...] > > Personnaly, even if the PEP goes (and its accepted), I'll continue > to use identifiers as currently. [...] Me too (mostly), although I do like the PEP. While many people have pointed out possible issues of the PEP, only few have tried to estimate its actual impact. I don't think that it will do harm to Python code because the programmers will know when it's appropriate to use it. The potential trouble is too obvious for being ignored accidentally. And in the case of a bad programmer, you have more serious problems than flawed identifier names, really. But for private utilities for example, such identifiers are really a nice thing to have. The same is true for teaching in some cases. And the small simulation program in my thesis would have been better with some ? and ?. At least, the program would be closer to the equations in the text then. > [...] > > * a possibility to specify for modules that they must *define* > only ascii-based names, like a from __futur__ import asciionly. To > be able to enforce this policy in projects which request it. Please don't. We're all adults. If a maintainer is really concerned about such a thing, he should write a trivial program that ensures it. After all, there are some other coding guidelines too that could be enforced this way but aren't, for good reason. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From nospam at noemailhere.nowhere Wed May 16 23:10:59 2007 From: nospam at noemailhere.nowhere (Anthony Irwin) Date: Thu, 17 May 2007 13:10:59 +1000 Subject: how do I count spaces at the beginning of a string? In-Reply-To: <1179367338.906430.97420@k79g2000hse.googlegroups.com> References: <1179367338.906430.97420@k79g2000hse.googlegroups.com> Message-ID: walterbyrd wrote: > The strings start with whitespace, and have a '*' or an alphanumeric > character. I need to know how many whitespace characters exist at the > beginning of the string. > Hi, I am new to python and just really learning but this is what I came up with. #!/usr/bin/env python def main(): s = " abc def ghi" count = 0 for i in s: if i == ' ': count += 1 else: break print count if __name__ == '__main__': main() -- Kind Regards, Anthony Irwin http://www.irwinresources.com http://www.makehomebusiness.com email: anthony at above domains, - www. From rene at korteklippe.de Tue May 15 08:57:45 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 15 May 2007 14:57:45 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <4649A429.3010406@web.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476081.7080609@web.de> <46498514$0$6402$9b4e6d93@newsspool2.arcor-online.net> <4649882E.3060005@web.de> <46499940$0$10199$9b4e6d93@newsspool4.arcor-online.net> <46499BF9.30209@web.de> <4649a2c1$0$10193$9b4e6d93@newsspool4.arcor-online.net> <4649A429.3010406@web.de> Message-ID: <4649ae4a$0$20289$9b4e6d93@newsspool3.arcor-online.net> Stefan Behnel schrieb: > You're not trying to suggest that writing code in a closed area project is a > bad habit, are you? I think that the idea that you know today, with 100% certainty, that all parts of your closed area project will stay closed forever is an illusion and thus a bad idea, yes. > What would be bad about allowing a project to decide about the best and > clearest way to name identifiers? That very same argument could be used to allow all sorts of "strange stuff" in Python like gotos and worse. What would be bad about allowing a project to decide about how to do flow control, especially if you never get in touch with it? > And: if it's not a project you will ever getin touch with - what do you care? I just fear that I *will* get in touch with identifiers using non-ASCII symbols if this PEP is implemented. -- Ren? From robin at reportlab.com Thu May 31 06:17:37 2007 From: robin at reportlab.com (Robin Becker) Date: Thu, 31 May 2007 11:17:37 +0100 Subject: non standard path characters Message-ID: <465EA0C1.9090400@chamonix.reportlab.co.uk> A kind user reports having problems running the reportlab tests because his path has non-ascii characters in it eg .....\Mes documents\Mes T?l?chargements\Firefox\... somewhere in the tests we look at the path and then try and convert to utf8 for display in pdf. Is there a standard way to do these path string conversions? Paths appear to come from all sorts of places and given the increasing use of zip file packaging it doesn't seem appropriate to rely on the current platform as a single choice for the default encoding. -- Robin Becker From nospam at noemailhere.nowhere Mon May 21 02:49:09 2007 From: nospam at noemailhere.nowhere (Anthony Irwin) Date: Mon, 21 May 2007 16:49:09 +1000 Subject: getting output from a command into a list to work with Message-ID: Hi All, I would like to run the command below and have each line from the output stored as an element in a list. find /some/path/ -maxdepth 1 -type f -size +100000k -exec ls -1 '{}' \ The reason for this is so I can then work on each file in the following manner var = command for i in var: # do stuff to file code here not sure the best way to get the output of the command so each line of output is one element in the list. -- Kind Regards, Anthony Irwin http://www.irwinresources.com http://www.makehomebusiness.com email: anthony at above domains, - www. From will_anne999 at yahoo.com Thu May 24 00:20:54 2007 From: will_anne999 at yahoo.com (william dy) Date: Wed, 23 May 2007 21:20:54 -0700 (PDT) Subject: Different methods with same name but different signature? Message-ID: <713634.7367.qm@web37902.mail.mud.yahoo.com> william dy christin de los santos lynor laxina --------------------------------- Take the Internet to Go: Yahoo!Go puts the Internet in your pocket: mail, news, photos & more. -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.wyburn at googlemail.com Tue May 22 08:08:47 2007 From: marc.wyburn at googlemail.com (marc.wyburn at googlemail.com) Date: 22 May 2007 05:08:47 -0700 Subject: NOOOOB In-Reply-To: <1179829763.464614.123920@a26g2000pre.googlegroups.com> References: <1179829763.464614.123920@a26g2000pre.googlegroups.com> Message-ID: <1179835727.142950.6030@r3g2000prh.googlegroups.com> On May 22, 11:29 am, jolly wrote: > Hey guys, > > I want to begin python. Does anyone know where a good starting point > is? > > Thanks, > Jem I went through the tutorial on python.org and found that really helpfull. If in a windows env the book by mark hammond is excellent. From bbxx789_05ss at yahoo.com Thu May 24 00:12:26 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 23 May 2007 21:12:26 -0700 Subject: read file to a dictionary In-Reply-To: References: <1179962203.201472.104500@q19g2000prn.googlegroups.com> Message-ID: <1179979945.950362.151820@o5g2000hsb.googlegroups.com> On May 23, 6:46 pm, James Stroud wrote: lol From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu May 17 07:30:08 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 17 May 2007 13:30:08 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de><1179160242.787344.48060@h2g2000hsg.googlegroups.com> <1179258692.237438.110860@p77g2000hsh.googlegroups.com> <464ad4a2$0$23143$9b4e6d93@newsspool1.arcor-online.net> <464C34DB.4010903@v.loewis.de> Message-ID: <5b2slsF2pri9cU1@mid.individual.net> "Martin v. L?wis" wrote: > I can't admit that, but I find that using German > class and method names is beautiful. The rest around > it (keywords and names from the standard library) > are not English - they are Python. > > (look me in the eye and tell me that "def" is > an English word, or that "getattr" is one) He's got a point (a small one though). For example: - self (can be changed though) - is - with - isinstance - try Regards, Bj?rn -- BOFH excuse #435: Internet shut down due to maintenance From grante at visi.com Tue May 15 14:31:27 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 15 May 2007 18:31:27 -0000 Subject: File record separators. References: <1179241525.667682.112220@y80g2000hsf.googlegroups.com> <1179249866.369812.167590@u30g2000hsc.googlegroups.com> Message-ID: <134jv3vbggd4u08@corp.supernews.com> On 2007-05-15, HMS Surprise wrote: > Would like to use pickle but it is apparently unavailable in the > package I am using, Jython 2.2. Odd. At least in 2.4, pickle.py seems to be Jython-aware. -- Grant Edwards grante Yow! does your DRESSING at ROOM have enough ASPARAGUS? visi.com From michael at jedimindworks.com Mon May 14 00:21:06 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Sun, 13 May 2007 23:21:06 -0500 Subject: How to do basic CRUD apps with Python In-Reply-To: <1179098458.333666.307750@e65g2000hsc.googlegroups.com> References: <1179098458.333666.307750@e65g2000hsc.googlegroups.com> Message-ID: On May 13, 2007, at 6:20 PM, walterbyrd wrote: > With PHP, libraries, apps, etc. to do basic CRUD are everywhere. Ajax > and non-Ajax solutions abound. > > With Python, finding such library, or apps. seems to be much more > difficult to find. > > I thought django might be a good way, but I can not seem to get an > answer on that board. > > I would like to put together a CRUD grid with editable/deletable/ > addable fields, click on the headers to sort. Something that would > sort-of looks like an online spreadsheet. It would be nice if the > fields could be edited in-line, but it's not entirely necessary. > > Are there any Python libraries to do that sort of thing? Can it be > done with django or cherrypy? > > Please, don't advertise your PHP/Ajax apps. You got answers on django-users! The best IMHO was the one from dballanc: "Django is good for providing the backend, but most of your functionality is probably going to be provided by ajax/javascript which django will happily communicate with, but does not provide." Django provides an ORM, but you don't have to use it. If you want, you can connect directly to your database just like you did with php. I've actually done that because something just "feels wrong" about using an ORM for CRUDy applications. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon May 14 10:49:31 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 14 May 2007 16:49:31 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46483740.4050406@web.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <4648252D.5020704@web.de> <46483740.4050406@web.de> Message-ID: <464876f8$0$27193$426a34cc@news.free.fr> Stefan Behnel a ?crit : > Eric Brunel wrote: >> On Mon, 14 May 2007 11:00:29 +0200, Stefan Behnel >>> Any chance there are still kanji-enabled programmes around that were >>> not hit >>> by the bomb in this scenario? They might still be able to help you get >>> the >>> code "public". >> Contrarily to what one might think seeing the great achievements of >> open-source software, people willing to maintain public code and/or make >> it evolve seem to be quite rare. If you add burdens on such people - >> such as being able to read and write the language of the original code >> writer, or forcing them to request a translation or transliteration from >> someone else -, the chances are that they will become even rarer... > > Ok, but then maybe that code just will not become Open Source. There's a > million reasons code cannot be made Open Source, licensing being one, lack of > resources being another, bad implementation and lack of documentation being > important also. > > But that won't change by keeping Unicode characters out of source code. Nope, but adding unicode glyphs support for identifiers will only make things worse, and we (free software authors/users/supporters) definitively *don't* need this. > Now that we're at it, badly named english identifiers chosen by non-english > native speakers, for example, are a sure way to keep people from understanding > the code and thus from being able to contribute resources. Broken English is certainly better than German or French or Italian when it comes to sharing code. > I'm far from saying that all code should start using non-ASCII characters. > There are *very* good reasons why a lot of projects are well off with ASCII > and should obey the good advice of sticking to plain ASCII. But those are > mainly projects that are developed in English and use English documentation, > so there is not much of a risk to stumble into problems anyway. > > I'm only saying that this shouldn't be a language restriction, as there > definitely *are* projects (I know some for my part) that can benefit from the > clarity of native language identifiers (just like English speaking projects > benefit from the English language). As far as I'm concerned, I find "frenglish" source code (code with identifiers in French) a total abomination. The fact is that all the language (keywords, builtins, stdlib) *is* in English. Unless you address that fact, your PEP is worthless (and even if you really plan to do something about this, I still find it a very bad idea for reasons already exposed). The fact is also that anyone at least half-serious wrt/ CS will learn technical English anyway. And, as other already pointed, learning technical English is certainly not the most difficult part when it comes to programming. > And yes, this includes spelling native > language identifiers in the native way to make them easy to read and fast to > grasp for those who maintain the code. Yes, fine. So we end up with a code that's a mix of English (keywords, builtins, stdlib, almost if not all third-part libs) and native language. So, while native speakers will still have to deal with English, non-native speakers won't be able to understand anything. Talk about a great idea... From nogradi at gmail.com Thu May 17 08:53:18 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Thu, 17 May 2007 14:53:18 +0200 Subject: Sending a JavaScript array to Python script? In-Reply-To: <1179405295.865954.241740@e65g2000hsc.googlegroups.com> References: <1179405295.865954.241740@e65g2000hsc.googlegroups.com> Message-ID: <5f56302b0705170553k73b700ddn5806a8103a220622@mail.gmail.com> > Just wondering if there is any way of sending a JavaScript array to a > Python cgi script? A quick Google search didn't turn up anything > useful. Simplejson is what you want: http://cheeseshop.python.org/pypi/simplejson HTH, Daniel From gh at gregor-horvath.com Tue May 15 23:44:00 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Wed, 16 May 2007 05:44:00 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464a25e9$0$10188$9b4e6d93@newsspool4.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649dd55$0$23144$9b4e6d93@newsspool1.arcor-online.net> <464a25e9$0$10188$9b4e6d93@newsspool4.arcor-online.net> Message-ID: Ren? Fleschenberg schrieb: > > We all know what the PEP is about (we can read). The point is: If we do > not *need* non-English/ASCII identifiers, we do not need the PEP. If the > PEP does not solve an actual *problem* and still introduces some > potential for *new* problems, it should be rejected. So far, the > "problem" seems to just not exist. The burden of proof is on those who > support the PEP. > A good product does not only react to problems but acts. Solving current problems is only one thing. Great products are exploring new ways, ideas and possibilities according to their underlying vision. Python has a vision of being easy even for newbies to programming. Making it easier for non native English speakers is a step forward in this regard. Gregor From mad.vijay at gmail.com Thu May 3 05:10:24 2007 From: mad.vijay at gmail.com (SamG) Date: 3 May 2007 02:10:24 -0700 Subject: 32 OS on 64-bit machine Message-ID: <1178183424.548438.303170@y80g2000hsf.googlegroups.com> If anyone has a x86_64 machine and is running a 32bit OS on top of that.... could you tell me what output would you get for the following program #====================== import platform print platform.processor() print platform.architecture() #====================== Thanks in advance : )~ From siona at chiark.greenend.org.uk Tue May 15 12:46:34 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 15 May 2007 17:46:34 +0100 (BST) Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179226183.215907.140450@q75g2000hsh.googlegroups.com> <4649AD7A.20202@web.de> Message-ID: Stefan Behnel wrote: >I don't think all identifiers in the stdlib are >a) well chosen >b) correct English words Never mind the standard library, by my count about 20% of keywords and builtins (excluding exception types) are either not correct English words ('elif', 'chr') or have some kind of mismatch between their meaning and the usual English usage ('hex', 'intern'). The discussion on readability and natural language identifiers reminds me of my first job in programming: looking after a pile of Fortran77 from the mid-80s. Case-insensitive, with different coders having different preferences (sometimes within the same module), and using more than four characters on an identifier considered shocking. Of course you got identifiers which were unintelligable, and it wasn't a great situation, but we coped and the whole thing didn't fall over in a complete heap. -- \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 steven at REMOVE.THIS.cybersource.com.au Tue May 15 05:22:22 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 15 May 2007 09:22:22 GMT Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <1hy2qg3.iqfvwnrvr9kjN%aleax@mac.com> Message-ID: On Sun, 13 May 2007 23:00:17 -0700, Alex Martelli wrote: > Aldo Cortesi wrote: > >> Thus spake Steven D'Aprano (steven at REMOVE.THIS.cybersource.com.au): >> >> > If you're relying on cursory visual inspection to recognize harmful >> > code, you're already vulnerable to trojans. >> >> What a daft thing to say. How do YOU recognize harmful code in a patch >> submission? Perhaps you blindly apply patches, and then run your test >> suite on a quarantined system, with an instrumented operating system to >> allow you to trace process execution, and then perform a few weeks >> worth of analysis on the data? >> >> Me, I try to understand a patch by reading it. Call me old-fashioned. > > I concur, Aldo. Indeed, if I _can't_ be sure I understand a patch, I > don't accept it -- I ask the submitter to make it clearer. Yes, but there is a huge gulf between what Aldo originally said he does ("visual inspection") and *reading and understanding the code*. If somebody submits a piece of code where all the variable names, functions, classes etc. are like a958323094, a498307913, etc. you're going to have a massive problem following the code despite being in ASCII. You would be sensible to reject the code. If you don't read Chinese, and somebody submits a patch in Chinese, you would be sensible to reject it, or at least have it vetted by somebody who does read Chinese. But is it really likely that somebody is going to submit a Chinese patch to your English or Italian project? I don't think so. > Homoglyphs would ensure I could _never_ be sure I understand a patch, > without at least running it through some transliteration tool. I don't > think the world of open source needs this extra hurdle in its path. If I've understood Martin's post, the PEP states that identifiers are converted to normal form. If two identifiers look the same, they will be the same. Except, probably, identifiers using ASCII O and 0, or I l and 1, or rn and m. Depending on your eyesight and your font, they look the same. The solution to that isn't to prohibit O and 0 in identifiers, but to use a font that makes them look different. But even if the homoglyphs was a problem, as hurdles go, it's hardly a big one. No doubt you already use automated tools for patch management, revision control, bug tracking, unit-testing, maybe even spell checking. Adding a transliteration tool to your arsenal is not really a disaster. -- Steven. From python at rcn.com Mon May 28 16:02:12 2007 From: python at rcn.com (Raymond Hettinger) Date: 28 May 2007 13:02:12 -0700 Subject: itertools.groupby In-Reply-To: References: <1180373388.112182.225700@i13g2000prf.googlegroups.com> Message-ID: <1180382532.846606.265100@q19g2000prn.googlegroups.com> > > That's not for everyone, so it isn't a loss if > > someone sticks > > with writing plain, clear everyday Python instead of > > an itertool. > > I know most of the module is fairly advanced, and that > average users can mostly avoid it, but this is a very > common-antipattern that groupby() solves: I think the OP would have been better-off with plain vanilla Python such as: See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/259173 Raymond From wdraxinger at darkstargames.de Thu May 31 14:43:17 2007 From: wdraxinger at darkstargames.de (Wolfgang Draxinger) Date: Thu, 31 May 2007 20:43:17 +0200 Subject: Webmail application for mod_python Message-ID: <5jh3j4-38a.ln1@darkstargames.dnsalias.net> I'm looking for a Squirrelmail* like webmail application, that I can hook up into mod_python. Is there anything ready to use or do I have to hack it myself? I don't like Squirrelmail, since I don't like PHP, and Squirrelmail depends on it. In the danger of getting my ears biten off in this NG: webmail apps for mod_perl or mod_ruby would be acceptable, too. Wolfgang Draxinger -- E-Mail address works, Jabber: hexarith at jabber.org, ICQ: 134682867 From __peter__ at web.de Fri May 4 12:43:05 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 04 May 2007 18:43:05 +0200 Subject: How safe is a set of floats? References: <1178288509.067493.5140@e65g2000hsc.googlegroups.com> <1hxkw5d.1ipc1zfocmqm9N%aleax@mac.com> <1178294650.738576.205690@q75g2000hsh.googlegroups.com> Message-ID: Paul McGuire wrote: > Does set membership test for equality ("==") or identity ("is")? As Alex said, equality: >>> a = 0.0 >>> b = -0.0 >>> a is b False >>> a == b True >>> set([a, b]) set([0.0]) Peter From stefan.sonnenberg at pythonmeister.com Sun May 6 03:08:42 2007 From: stefan.sonnenberg at pythonmeister.com (Stefan Sonnenberg-Carstens) Date: Sun, 06 May 2007 09:08:42 +0200 Subject: invoke user's standard mail client In-Reply-To: <463D7E30.8070307@pythonmeister.com> References: <1178266064.922925.125760@y80g2000hsf.googlegroups.com> <463D7E30.8070307@pythonmeister.com> Message-ID: <463D7EFA.1030207@pythonmeister.com> Stefan Sonnenberg-Carstens schrieb: > Gabriel Genellina schrieb: > >> En Fri, 04 May 2007 05:07:44 -0300, luc.saffre at gmail.com >> escribi?: >> >> >> >>> the simplest way to launch the user's standard mail client from a >>> Python program is by creating a mailto: URL and launching the >>> webbrowser: >>> But this method is limited: you cannot specify a file to be attached >>> to the mail. And I guess that there would be problems if the body text >>> is too complex. >>> Does somebody know about a better method? >>> It should be possible at least on Windows, since Acrobat Reader is >>> able to do it. >>> >>> >> On Windows you can use MAPI. >> >> >> > import win32api > win32api.ShellExecute(0,'open','mailto:',None,None,0) > For completeness import win32api win32api.ShellExecute(0,'open','mailto: guido at python.org',None,None,0) From rrogers82 at gmail.com Sun May 27 11:41:36 2007 From: rrogers82 at gmail.com (romiro) Date: 27 May 2007 08:41:36 -0700 Subject: PHP5 programmer learning Python Message-ID: <1180280496.946434.26760@q69g2000hsb.googlegroups.com> Hi all, I'm a PHP5 developer looking to "broaden my horizons" so to speak by learning a new language. I emphasize the 5 in PHP since I have fully engrossed myself in the full OOP of version 5 with my own ground-up projects as well as some work with PRADO (http://pradosoft.com) I've dabbled with a number of languages in the past, Python being no exception, but always ended up coming back to PHP due to being comfortable with it. Python has stuck to me as a language I _really_ think I should know more about. I've recently tried C#, a very short lived re-attempt at C++ and Java, and Ruby. None of those seemed "fun" except for Ruby, although from what I've seen the syntax between Ruby and Python are very similar to each other compared to the other languages. Anyway, my first question was if anyone knows of a tutorial that focuses on PHP -> Python learning, in such that there might be a block of PHP code alongside an example of how to do the same thing in Python. One example of something I've already mapped a comparison to thanks to standard tutorials is a PHP numeric indexed array being similar to a list and a PHP associative array being similar to a dictionary. Of course finding such of a tutorial isn't a deal breaker by any means, but I figured that having it available would be a boon for me to actually make some headway in my Python learning adventure. If there's anything else that could be said about the migration between the two languages, I'm all ears. I also don't really need to hear about how "disgusting" php is as a language...I am aware of the contained chaos that is PHP4, which is why I develop strictly in 5 using its OOP to the extent my feeble brain allows, a wariness toward the insecure pitfalls the language has begat in the past, and an attempt to produce as clean of a syntax as the language can allow. Thanks in advance for any help. From paul at boddie.org.uk Mon May 7 05:16:55 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 7 May 2007 02:16:55 -0700 Subject: invoke user's standard mail client In-Reply-To: References: <1178266064.922925.125760@y80g2000hsf.googlegroups.com> Message-ID: <1178529415.545317.131880@y5g2000hsa.googlegroups.com> On 4 Mai, 18:54, cla... at lairds.us (Cameron Laird) wrote: > . > Portland > is the best standardization of this problem we have under Linux. > > I'll address Windows in a subsequent follow-up. Portland [1] provides scripts (xdg-open, xdg-email...) which overlap with the functionality provided by the desktop module: http://www.python.org/pypi/desktop The desktop module should even work with Windows as well, but it seems that xdg-email has the edge in terms of providing the inquirer's desired support for composing e-mail messages (on Free Software desktops, anyway). Paul [1] http://portland.freedesktop.org/wiki/ From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon May 7 15:48:19 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 07 May 2007 21:48:19 +0200 Subject: Simulating simple electric circuits References: <5a9838F2nlbanU1@mid.individual.net> <1178565381.136800.250100@o5g2000hsb.googlegroups.com> Message-ID: <5a9e43F2nenc8U1@mid.individual.net> Arnaud Delobelle wrote: > On May 7, 7:05 pm, Bjoern Schliessmann > There is a master "current controller" object which tells >> the "source" object to start a "current" by calling its >> neighbour. The calls traverse the network until they reach a >> "ground" object. Specifically, the source passes a "telegram" >> instance with these calls, and everyone it passes through >> "registers" himself with it (telegrams are duplicated at joints). >> Then, the ground object calls back to the controller with all >> received telegrams. Like this I'm already able to get all >> possible ways through the network. > > Then you can get all 'potential' paths that depend on one or more > switches being on. Each path could know what switches it depends > on and be 'active' if and only if all those switches are on. And > each switch would know what paths depend on it. Similarly each > lightbulb would know what paths it depends on and be 'on' if at > least one path is active; and each path would know which > lightbulbs it powers In principle, I thought so too, but I didn't like the fact that this involves all possible circuits be determined only once. But it seems like there is no reasonable, different way. > When you turn a switch off, it would send a message to the paths > that depend on it (maybe via the controller?) so that they would > be deactivated. In turn the lightbulbs on these paths would be > informed that they are no longer active. > > When you turn a switch on, it would send a message to the paths > that depend on it so that those who do not have another off switch > would be activated. In turn the lightbulbs on these paths would > be informed that they have a new power source. Yep. Looks like I have to do extended "bookkeeping" for this. I was looking for a more dynamic, general way. > It seems to me that it would work well with the way you started it > out, but I may have misunderstood some aspects or overlooked some > problems ;) Thanks for your input. The biggest problem I got until now are the crummy interfaces for interconnection which quickly get inconcise. I've had a look at the NetworkX tutorial and it seems like this could simplify the code a bit. Regards, Bj?rn -- BOFH excuse #173: Recursive traversal of loopback mount points From carsten at uniqsys.com Tue May 8 07:55:02 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 8 May 2007 07:55:02 -0400 Subject: Getting a function name from string In-Reply-To: <390810050705080038p7f26d7b2maf9f6230178147ff@mail.gmail.com> References: <390810050705080038p7f26d7b2maf9f6230178147ff@mail.gmail.com> Message-ID: <20070508114911.M86003@uniqsys.com> On Tue, 8 May 2007 09:38:48 +0200, Cesar H?rdfeldt wrote > [...] ? > I now have 'module' and 'function' as strings and 'parms' normally as a list of strings. I can import the module by __import__(module) but is there another way to call: > module.function(parms) than using eval()? function_to_call = getattr(__import__(module), function) function_to_call(parms) Hope this helps, -- Carsten Haese http://informixdb.sourceforge.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Sat May 12 01:07:34 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 12 May 2007 02:07:34 -0300 Subject: py2exe LoadLibrary question References: <1178922172.944048.124430@y80g2000hsf.googlegroups.com> Message-ID: En Fri, 11 May 2007 19:22:53 -0300, escribi?: > Yep, it's the old LoadLibrary failed problem. > > I understand that python24.dll is required for the executable to run, > but I'm going to be building a few of these executables and I don't > want to have to bundle python24 along with each one. > We have python24.dll installed in c:/windows/system32, why is > loadlibrary not finding it? py2exe emulates LoadLibrary, does not use the Windows API function directly. In principle it might be possible to find python24.dll on the standard PATH, but it does not (currently). The dll is not so big, you could put it alongside your executable (as py2exe expects it to be). I used to install several small applications in a single directory, sharing the required dlls. Or switch to another tool like pyInstaller http://pyinstaller.python-hosting.com/wiki that apparently does not have this problem. -- Gabriel Genellina From steve at holdenweb.com Wed May 30 02:29:45 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 30 May 2007 02:29:45 -0400 Subject: RDFXML Parser For "qualified Dublin Core" Database File In-Reply-To: <465cff21.09da2647.3a75.ffffb942@mx.google.com> References: <465cff21.09da2647.3a75.ffffb942@mx.google.com> Message-ID: Brandon McGinty wrote: > Hi All, > > My goal is to be able to read the www.gutenberg.org > rdf catalog, parse it into a python > structure, and pull out data for each record. > > The catalog is a Dublin core RDF/XML catalog, divided into sections for > each book and details for that book. > > I have done a very large amount of research on this problem. > > I?ve tried tools such as pyrple, sax/dom/minidom, and some others both > standard and nonstandard to a python installation. > > None of the tools has been able to read this file successfully, and > those that can even see the data can take up to half an hour to load > with 2 gb of ram. > > So you all know what I?m talking about, the file is located at: > > http://www.gutenberg.org/feeds/catalog.rdf.bz2 > > Does anyone have suggestions for a parser or converter, so I?d be able > to view this file, and extract data? > > Any help is appreciated. > Well, have you tried xml.etree.cElementTree, a part of the standard library since 2.5? Well worth a go, as it seems to outperform many XML libraries. The iterparse function is your best bet, allowing you to iterate over the events as you parse the source, thus avoiding the need to build a huge in-memory data structure just to get the parsing done. The following program took about four minutes to run on my not-terribly up-to-date Windows laptop with 1.5 GB of memory with the pure Python version of ElementTree: import xml.etree.ElementTree as ET events = ET.iterparse(open("catalog.rdf")) count = 0 for e in events: count += 1 if count % 100000 == 0: print count print count, "total events" Here's an example output after I changed to using the extension module - by default, only the end-element events are reported. I think you'll be impressed by the timing. The only change was to the import staement, which now reads import xml.etree.cElementTree as ET sholden at bigboy ~/Projects/Python $ time python test19.py 100000 200000 300000 400000 500000 600000 700000 800000 900000 1000000 1100000 1200000 1300000 1400000 1469971 total events real 0m11.145s user 0m10.124s sys 0m0.580s Good luck! 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From grante at visi.com Tue May 8 13:46:48 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 08 May 2007 17:46:48 -0000 Subject: File Name Format References: <134147e2gsg6v35@corp.supernews.com> Message-ID: <1341ds8mtfvmn01@corp.supernews.com> On 2007-05-08, Marc 'BlackJack' Rintsch wrote: > In <134147e2gsg6v35 at corp.supernews.com>, Grant Edwards wrote: > >> On 2007-05-08, Anand wrote: >> >>> How do I convert programmatically the file names from WIN32 to UNIX format? >> >> You don't need to. AFAIK, all legal WIN32 filenames are legal >> UNIX file names. > > Doesn't this depend more on the file system than the operating system? Sort of. AFAIK, no matter which "Windows" filesystem you pick, the set of allowed filenames are legal for all of the common "Unix" filesystems (EXT3, XFS, Reiser, etc.). However, the OP hasn't offered any details about what it is he's actually wanting to do, so this is all just idle speculation... -- Grant Edwards grante Yow! I know how to do at SPECIAL EFFECTS!! visi.com From deepns7 at gmail.com Thu May 3 00:58:41 2007 From: deepns7 at gmail.com (pradeep nair) Date: 2 May 2007 21:58:41 -0700 Subject: FInd files with .so extension Message-ID: <1178168321.581307.284750@y5g2000hsa.googlegroups.com> HI, How do i find files with .so extension using python . From larry.bates at websafe.com Tue May 8 09:29:31 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 08 May 2007 08:29:31 -0500 Subject: changing a var by reference of a list In-Reply-To: References: Message-ID: Jorgen Bodde wrote: > Hi, > > I am trying to simplify my code, and want to automate the assigning of > variables I get back from a set. I was thinking of putting the > variables I want changed in a list: > > L = [self._varA, self._varB ] > > self._varA is a variable I want to change when I pass L to a function. > I know doing this; > > L[0] = 12 > > Will replace the entry self._varA with 12, but is there a way to > indirectly change the value of self._varA, through the list, something > like a by-reference in C++ or a pointer-pointer? > > With regards, > - Jorgen You can make self._varA and self._varB instances of a class and assign a value. Not tested. class _var: pass self._varA=_var() self._varB=_var() L=[self._varA, self._varB] then in function (or method of a class instance): L[0].value=12 Another way is to use a class to pass everything: class _vars: def __init__(self, vars=None): if vars is not None: for varname, value in vars.items(): setattr(self, varname, value) return vars=_vars({'_varA': 0, '_varB': 0}) Then you can access: vars._varA vars._varB -Larry l From thorsten at thorstenkampe.de Fri May 4 15:11:21 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Fri, 4 May 2007 20:11:21 +0100 Subject: My Python annoyances References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> <1178202431.147195.249790@u30g2000hsc.googlegroups.com> <7oqdnVScpod-qqbbnZ2dnUVZ_qmpnZ2d@scnresearch.com> Message-ID: * Ben Collver (Fri, 04 May 2007 06:40:50 -0700) > Thorsten Kampe wrote: > > He was using /Windows/ Python in Cygwin *chuckle*... Windows Python > > says Ctrl-Z because it doesn't know that it's been run from bash where > > Ctrl-Z is for job control. > > > > And the lesson we learn from that: if you're using Windows Python use > > a Windows shell. If you're using a Cygwin shell use Cygwin Python - > > unless you know what you're doing (which he wasn't). > > The reason I tried to do this: Cygwin python lacks _winreg, but I wanted > to SSH into Cygwin to run this script. > > I suppose the folks who know what they are doing probably stick to > wscript and WMI for this sort of stuff. No, they stick to Python and WMI for this sort of stuff: http://tgolden.sc.sabren.com/python/wmi.html From carsten at uniqsys.com Tue May 8 07:45:01 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 8 May 2007 07:45:01 -0400 Subject: replacing string in xml file In-Reply-To: <46405F73.3080501@web.de> References: <1178623414.092046.91120@y5g2000hsa.googlegroups.com> <46405F73.3080501@web.de> Message-ID: <20070508113718.M93616@uniqsys.com> On Tue, 08 May 2007 13:30:59 +0200, Stefan Behnel wrote > saif.shakeel at gmail.com schrieb: > [...] > > file_input = raw_input("Enter The ODX File Path:") > > input_xml = open(file_input,'r') > > This should say > > input_xml = open(file_input,'r').read() ...and then it still won't work because the OP's replace call assumes in-place operation despite the fact that strings aren't mutable. The OP needs something following this pattern: input_file = open(filename) xmlcontents = input_file.read() input_file.close() xmlcontents = xmlcontents.replace("spam", "eggs") output_file = open(filename,"w") output_file.write(xmlcontents) output_file.close() For extra credit, use a different file name for writing out the result and rename the file after it's written. That way you don't lose your file contents if a meteor hits your CPU just after it started to overwrite the file. Best regards, -- Carsten Haese http://informixdb.sourceforge.net From nyamatongwe+thunder at gmail.com Fri May 18 19:12:58 2007 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Fri, 18 May 2007 23:12:58 GMT Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179503525.018943.95740@u30g2000hsc.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <464C5382.6080403@v.loewis.de> <1179423799.254286.294930@w5g2000hsg.googlegroups.com> <1179503525.018943.95740@u30g2000hsc.googlegroups.com> Message-ID: <_pq3i.1390$wH4.1177@news-server.bigpond.net.au> Istvan Albert: > But you're making a strawman argument by using extended ASCII > characters that would work anyhow. How about debugging this (I wonder > will it even make it through?) : > > class ???????? > ??? = 0 > ?????? ?? ?=10 That would be invalid syntax since the third line is an assignment with target identifiers separated only by spaces. Neil From attn.steven.kuo at gmail.com Wed May 2 16:51:17 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 2 May 2007 13:51:17 -0700 Subject: How to check if a string is empty in python? In-Reply-To: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> References: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> Message-ID: <1178139077.864794.6590@q75g2000hsh.googlegroups.com> On May 2, 1:35 pm, noagbodjivic... at gmail.com wrote: > How to check if a string is empty in python? > if(s == "") ?? Empty strings and containers are false; so one can write if (not s): print "something..." -- Hope this helps, Steven From steve at holdenweb.com Thu May 17 10:32:51 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 17 May 2007 10:32:51 -0400 Subject: Python-URL! - weekly Python news and links (May 16) In-Reply-To: <1179408898.460231.292340@k79g2000hse.googlegroups.com> References: <1179408898.460231.292340@k79g2000hse.googlegroups.com> Message-ID: Beliavsky wrote: > On May 16, 2:45 pm, "Cameron Laird" wrote: >> QOTW: "Sometimes you just have to take the path of least distaste". - Grant >> Edwards >> >> "I want to choose my words carefully here, so I'm not misunderstood. > > > > I think Cameron Laird does a good job with the Python digest but > blundered here. Why did he highlight a foul comment having nothing to > do with Python? > In fact it *is* peripherally related, since Gartner are currently doing a "survey" on dynamic languages, and there was a considerable effort exerted just to make sure that most of the questions actually allowed sensible comparisons between the various languages. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From grante at visi.com Sat May 19 15:08:36 2007 From: grante at visi.com (Grant Edwards) Date: Sat, 19 May 2007 19:08:36 -0000 Subject: Python-URL! - weekly Python news and links (May 16) References: <1179408898.460231.292340@k79g2000hse.googlegroups.com> Message-ID: <134uipkdtaf7086@corp.supernews.com> On 2007-05-17, Beliavsky wrote: > >> QOTW: "Sometimes you just have to take the path of least >> distaste". - Grant Edwards >> >> "I want to choose my words carefully here, so I'm not misunderstood. > > > > I think Cameron Laird does a good job with the Python digest > but blundered here. Why did he highlight a foul comment having > nothing to do with Python? Having stumbled across this discussion in mid-thread, I was relieved to find out after following the thread upstream that that the "foul comment" in question wasn't mine. :) That said, I thought the other quote was rather amusing (both in style and content). I while I don't think that those "research" firms actually do anything useful, I wouldn't call them idiots. They seem to have figured out how to extract sizable amounts of money from corporate types by providing them with compilations of useless generalizations and meaningless pseudo-statistics. The people paying them are probably the ones more deserving of derision. -- Grant Edwards grante Yow! Thousands of days of at civilians ... have produced visi.com a ... feeling for the aesthetic modules -- From eiwot at hotmail.com Tue May 22 22:43:15 2007 From: eiwot at hotmail.com (Eiwot) Date: Wed, 23 May 2007 02:43:15 +0000 Subject: New Python articles blog Message-ID: Hi all, I created this blog --> http://pyarticles.blogspot.com to provide Python technique. Check it out please ! Cheers, _________________________________________________________________ Create the ultimate e-mail address book. Import your contacts to Windows Live Hotmail. www.windowslive-hotmail.com/learnmore/managemail2.html?locale=en-us&ocid=TXT_TAGLM_HMWL_reten_impcont_0507 -------------- next part -------------- An HTML attachment was scrubbed... URL: From ondrej.marsalek at gmail.com Tue May 1 12:19:42 2007 From: ondrej.marsalek at gmail.com (Ondrej Marsalek) Date: 1 May 2007 09:19:42 -0700 Subject: SWIG, STL & pickle Message-ID: <1178036382.828248.206050@o5g2000hsb.googlegroups.com> hello, i have the following problem/question: i have a c++ class i would like to wrap using swig, easy so far. i want to be able to pickle it as well and i understand that i need to implement the setstate and getstate methods to be able to do that. now the tricky part - my c++ class uses stl vectors (and possibly other stl containers). swig can handle that, except for the pickling. what should i do to be able to pickle the whole c++ object? i am not sure i would be able to dig into stl code and implement serialization for it by hand. thanks for any help. From rohitsethidce at gmail.com Tue May 22 14:57:15 2007 From: rohitsethidce at gmail.com (rohit) Date: 22 May 2007 11:57:15 -0700 Subject: too much memory use Message-ID: <1179860235.044137.295080@a26g2000pre.googlegroups.com> hi , i am making a program for desktop search. in order to make it more effective im implementing the records in the form of a tree(files starting with 'a','b','c'....have different trees ..so 26 trees in all) in memory and writing it down in file. the max size file has 16000 records...now to implement the tree in list i'm using line no as index ..and empty child nodes are represented as "\n" all this work is going on in the memory.. problem is the system eats up my 512 mb RAM +1gb virtual store n hangs cant think of an effective way to implement tree in memory(i can compact it on disk by writing just the index no..along with the record from which tree in memory can be reconstructed, but i have to implement tree as previous to implement random access) please help.. rohit sethi delhi college of engineering From gagsl-py2 at yahoo.com.ar Sun May 27 10:30:50 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 27 May 2007 11:30:50 -0300 Subject: Newbie question - better way to do this? References: <1180273441.455227.120170@g4g2000hsf.googlegroups.com> Message-ID: En Sun, 27 May 2007 10:44:01 -0300, Eric escribi?: > I have some working code, but I realized it is just the way I would > write it in C, which means there is probably a better (more pythonic) > way of doing it. > > Here's the section of code: > > accumulate = firstIsCaps = False > accumStart = i = 0 > while i < len(words): > firstIsCaps = firstIsCapitalized(words[i]) > if firstIsCaps and not accumulate: > accumStart, accumulate = i, True > elif accumulate and not firstIsCaps: > doSomething(words[accumStart : i]) > accumulate = False > i += 1 > > words is a big long array of strings. What I want to do is find > consecutive sequences of words that have the first letter capitalized, > and then call doSomething on them. (And you can ignore the fact that > it won't find a sequence at the very end of words, that is fine for my > purposes). Using groupby: py> from itertools import groupby py> py> words = "Este es un Ejemplo. Los Ejemplos usualmente son tontos. Yo siempre escribo tonterias.".split() py> py> for upper, group in groupby(words, str.istitle): ... if upper: ... print list(group) # doSomething(list(group)) ... ['Este'] ['Ejemplo.', 'Los', 'Ejemplos'] ['Yo'] You could replace your firstIsCapitalized function instead of the string method istitle(), but I think it's the same. See http://docs.python.org/lib/itertools-functions.html -- Gabriel Genellina From steven at REMOVE.THIS.cybersource.com.au Tue May 15 20:11:34 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 16 May 2007 00:11:34 GMT Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <46478694$0$1412$426a34cc@news.free.fr> <1hy252p.1anf7sr1p4yp12N%aleax@mac.com> <464988a4$0$20289$9b4e6d93@newsspool3.arcor-online.net> Message-ID: On Tue, 15 May 2007 12:17:09 +0200, Ren? Fleschenberg wrote: > Steven D'Aprano schrieb: >> How is that different from misreading "disk_burnt = True" as "disk_bumt >> = True"? In the right (or perhaps wrong) font, like the ever-popular >> Arial, the two can be visually indistinguishable. Or "call" versus >> "cal1"? > > That is the wrong question. The right question is: Why do you want to > introduce *more* possibilities to do such mistakes? Does this PEP solve > an actual problem, and if so, is that problem big enough to be worth the > introduction of these new risks and problems? But they aren't new risks and problems, that's the point. So far, every single objection raised ALREADY EXISTS in some form or another. There's all this hysteria about the problems the proposed change will cause, but those problems already exist. When was the last time a Black Hat tried to smuggle in bad code by changing an identifier from xyz0 to xyzO? > I think it is not. I think that the problem only really applies to very > isolated use-cases. Like the 5.5 billion people who speak no English. > So isolated that they do not justify a change to > mainline Python. If someone thinks that non-ASCII identifiers are really > needed, he could maintain a special Python branch that supports them. I > doubt that there would be alot of demand for it. Maybe so. But I guarantee with a shadow of a doubt that if the change were introduced, people would use it -- even if right now they say they don't want it. -- Steven. From davelist at mac.com Sun May 27 16:39:06 2007 From: davelist at mac.com (davelist at mac.com) Date: Sun, 27 May 2007 16:39:06 -0400 Subject: Why isn't this query working in python? In-Reply-To: References: <1180103946.552760.239200@p47g2000hsd.googlegroups.com> <6e42ec490705250751i89d3cf3v3a3062690d0284aa@mail.gmail.com> <1180207521.072958.322770@p47g2000hsd.googlegroups.com> <1180225290.235515.274000@q19g2000prn.googlegroups.com> <1180279833.131269.136770@w5g2000hsg.googlegroups.com> Message-ID: On May 27, 2007, at 4:01 PM, Steve Holden wrote: > erikcw wrote: >> On May 26, 8:21 pm, John Machin wrote: >>> On May 27, 5:25 am, erikcw wrote: >>> >>> >>> >>>> On May 25, 11:28 am, Carsten Haese wrote: >>>>> On Fri, 2007-05-25 at 09:51 -0500, Dave Borne wrote: >>>>>>> I'm trying to run the following query: >>>>>> ... >>>>>>> member_id=%s AND expire_date > NOW() AND completed=1 AND >>>>>>> (product_id >>>>>> Shouldn't you be using the bind variable '?' instead of '%s' ? >>>>> The parameter placeholder for MySQLdb is, indeed and >>>>> unfortunately, %s. >>>>> The OP is using parameter substitution correctly, though in an >>>>> obfuscated fashion. 'sql' is a misnamed tuple containing both >>>>> the query >>>>> string *and* the parameters, which is being unpacked with '*' >>>>> into two >>>>> arguments to the execute call. >>>>> The only problem I see is that the parameters should be a >>>>> sequence, i.e. >>>>> (self.uid,) instead of just (self.uid). >>>>> HTH, >>>>> -- >>>>> Carsten Haesehttp://informixdb.sourceforge.net >>>> I tried adding the comma to make it a sequence - but now change. >>>> ('SELECT payment_id FROM amember_payments WHERE member_id=%s AND >>>> expire_date > NOW() AND completed=1 AND (product_id >11 AND >>>> product_id >>>> <21)', (1608L,)) >>>> () >>>> What else could it be? >>> Possibly a type mismatch. How is member_id declared in the CREATE >>> TABLE? For diagnostic purposes, try passing in (1608,) and >>> ('1608',). >> >> Here is a copy of the table schema and the first 2 rows. >> >> -- phpMyAdmin SQL Dump >> -- version 2.9.0.2 >> -- http://www.phpmyadmin.net >> -- >> -- Host: localhost >> -- Generation Time: May 27, 2007 at 11:29 AM >> -- Server version: 5.0.27 >> -- PHP Version: 4.4.2 >> -- >> -- Database: `lybp_lybp` >> -- >> >> -- -------------------------------------------------------- >> >> -- >> -- Table structure for table `amember_payments` >> -- >> >> CREATE TABLE `amember_payments` ( >> `payment_id` int(11) NOT NULL auto_increment, >> `member_id` int(11) NOT NULL default '0', >> `product_id` int(11) NOT NULL default '0', >> `begin_date` date NOT NULL default '0000-00-00', >> `expire_date` date NOT NULL default '0000-00-00', >> `paysys_id` varchar(32) NOT NULL default '', >> `receipt_id` varchar(32) NOT NULL default '', >> `amount` decimal(12,2) NOT NULL default '0.00', >> `completed` smallint(6) default '0', >> `remote_addr` varchar(15) NOT NULL default '', >> `data` text, >> `time` timestamp NOT NULL default CURRENT_TIMESTAMP on update >> CURRENT_TIMESTAMP, >> `aff_id` int(11) NOT NULL default '0', >> `payer_id` varchar(255) NOT NULL default '', >> `coupon_id` int(11) NOT NULL default '0', >> `tm_added` datetime NOT NULL default '0000-00-00 00:00:00', >> `tm_completed` datetime default NULL, >> `tax_amount` decimal(12,2) NOT NULL default '0.00', >> PRIMARY KEY (`payment_id`), >> KEY `member_id` (`member_id`), >> KEY `payer_id` (`payer_id`), >> KEY `coupon_id` (`coupon_id`), >> KEY `tm_added` (`tm_added`,`product_id`), >> KEY `tm_completed` (`tm_completed`,`product_id`) >> ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=11020 ; >> >> -- >> -- Dumping data for table `amember_payments` >> -- >> >> INSERT INTO `amember_payments` VALUES (423, 107, 1, '2004-10-01', >> '2004-10-21', 'authorize_aim', '5687944', 3.95, 1, '', NULL, >> '2004-11-30 19:21:43', 0, '', 0, '2004-11-30 19:21:43', '2004-11-30 >> 19:21:43', 0.00); >> INSERT INTO `amember_payments` VALUES (422, 107, 1, '2004-10-22', >> '2004-11-21', 'authorize_aim', '5873225', 9.95, 1, '', NULL, >> '2004-11-30 19:22:18', 0, '', 0, '2004-11-30 19:20:13', '2004-11-30 >> 19:20:13', 0.00); >> >> Thanks for your help! >> Erik >> > I feel obliged to point out that there ARE no rows meeting the > criteria > you query specified! > > mysql> SELECT expire_date, NOW() FROM amember_payments; > +-------------+---------------------+ > | expire_date | NOW() | > +-------------+---------------------+ > | 2004-10-21 | 2007-05-27 15:59:21 | > | 2004-11-21 | 2007-05-27 15:59:21 | > +-------------+---------------------+ > 2 rows in set (0.02 sec) > > mysql> > > So I am not sure how you managed to get a manual query to work, but do > be sure that the Python query you mentioned at the start of the thread > > sql = """SELECT payment_id FROM amember_payments WHERE > member_id=%s AND expire_date > NOW() AND completed=1 AND (product_id >>> 11 AND product_id <21)""", (self.uid) > And doesn't the above comma, need to be a percent symbol? Dave > doesn't stand a chance of returning any results unless you use a time > machine to go back almost three years! > > regards > Steve From robert.kern at gmail.com Thu May 10 00:10:19 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 09 May 2007 23:10:19 -0500 Subject: change of random state when pyc created?? In-Reply-To: References: <5ae25fF2oggbqU1@mid.uni-berlin.de> Message-ID: Steven D'Aprano wrote: > On Wed, 09 May 2007 21:18:25 -0500, Robert Kern wrote: > >> Actually, the root cause of Peter's specific example is the fact that the >> default implementation of __hash__() and __eq__() rely on identity comparisons. >> Two separate invocations of the same script give different objects by identity >> and thus the "history of insertions and deletions" is different. > > The history is the same. The objects inserted are the same (by equality). No, they *were* different by equality (identity being the default implementation equality that was not overridden in either Peter's code nor Alan's). -- 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 bscrivener42 at gmail.com Tue May 29 13:33:09 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: 29 May 2007 10:33:09 -0700 Subject: wxpython demo error on debian etch In-Reply-To: <1180446704.521350.72450@k79g2000hse.googlegroups.com> References: <1180445918.523446.133300@g4g2000hsf.googlegroups.com> <1180446704.521350.72450@k79g2000hse.googlegroups.com> Message-ID: <1180459989.799593.243960@u30g2000hsc.googlegroups.com> On May 29, 8:51 am, kyoso... at gmail.com wrote: > The wxPython > website details how to get the latest version of wxPython (2.8.4) I'm fairly new to Linux, so I probably shouldn't mess with my stable Etch. I'll make do with this version of wxPython or go back to puzzling over Tkinter. Thanks, rick From steve at holdenweb.com Sat May 19 09:41:46 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 19 May 2007 09:41:46 -0400 Subject: RFC - n-puzzle.py In-Reply-To: <1179578316.956894.164140@y80g2000hsf.googlegroups.com> References: <1179530104.645902.135250@p77g2000hsh.googlegroups.com> <1179566627.583978.304810@n59g2000hsh.googlegroups.com> <1179578316.956894.164140@y80g2000hsf.googlegroups.com> Message-ID: Phoe6 wrote: > On May 19, 2:23 pm, Raymond Hettinger wrote: >> On May 18, 4:15 pm, Phoe6 wrote: >>> I would like to request a code and design review of one of my program. >>> n-puzzle.pyhttp://sarovar.org/snippet/detail.php?type=snippet&id=83 >> Nice job, this doesn't look like a beginner program at all. > > Thanks Raymond. :-) > >> For feedback, here's a few nits: > > Yes, I made changes in them all. Thanks for the list comprehension > pointer, I missed it. > >> Instead of: >> short_path = mdists[0] >> if mdists.count(short_path) > 1: >> write: >> short_path = mdists[0] >> if short_path in mdists[1:]: > > I would like to understand the difference between the two if > statements. > I had used count method, to signify the meaning that, if the least > distance occurs more then proceed with block. > How is 'in' with list[1:] an advantage? If it is. Because it can stop as soon as short_path is found, whereas the count method must examine all elements to determine whether they should increment the count beyond one. > >> Instead of: >> if node != 0: >> write: >> if node: > > Here again, I went by the meaning of non-zero value nodes and made > comparision with node != 0. Just in case, the n-states were > represented by '0', '1', '2', '3', I would have gone for node != '0' > sticking to the meaning. I think, I should aid it with a comment, > otherwise might get confused in the future. > This is a standard Python idiom. If you had used strings then the test *would* have had to explicitly compare against '0', but when evaluating for a test Python treats zeros, the empty string, the empty list, set or dictionary, None (and various other possibilties) as false. It's not a big deal, but it will be just a tad faster. > Thanks a lot, Raymond. :-) Channeling Raymond, he says you're welcome. :-) 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From grante at visi.com Thu May 24 17:01:06 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 24 May 2007 21:01:06 -0000 Subject: trouble converting c++ bitshift to python equivalent References: <1180037677.633613.30160@u30g2000hsc.googlegroups.com> <1180039195.148316.70100@o5g2000hsb.googlegroups.com> Message-ID: <135bv8ieao34d46@corp.supernews.com> On 2007-05-24, nanodust at gmail.com wrote: >> You should really use the struct module for that type of conversion, but >> you also need to know that indexing of lists and tuples starts at 0, not 1. > > indeed, i used to have temp = unpack('h', tBuf[1,3]) Which probably should have been temp = unpack('h', tBuf[1:3])[0] But that still doesn't do the same thing as your example which only used 7 bits from each byte. > but it was a hack (and as such a bit off ;) as i was having > troubles casting Python doesn't have "casting". -- Grant Edwards grante Yow! A can of ASPARAGUS, at 73 pigeons, some LIVE ammo, visi.com and a FROZEN DAQUIRI!! From victor.kryukov at gmail.com Wed May 16 13:06:20 2007 From: victor.kryukov at gmail.com (Victor Kryukov) Date: 16 May 2007 10:06:20 -0700 Subject: A bug in cPickle? Message-ID: <1179335180.786851.209900@y80g2000hsf.googlegroups.com> Hello list, The following behavior is completely unexpected. Is it a bug or a by- design feature? Regards, Victor. ----------------- from pickle import dumps from cPickle import dumps as cdumps print dumps('1001799')==dumps(str(1001799)) print cdumps('1001799')==cdumps(str(1001799)) >>>>output:>>>> True False vicbook:~ victor$ 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. >>> quit() vicbook:~ victor$ uname -a Darwin vicbook 8.9.1 Darwin Kernel Version 8.9.1: Thu Feb 22 20:55:00 PST 2007; root:xnu-792.18.15~1/RELEASE_I386 i386 i386 vicbook:~ victor$ From pyro.699 at gmail.com Mon May 21 15:32:06 2007 From: pyro.699 at gmail.com (Pyro) Date: Mon, 21 May 2007 16:32:06 -0300 Subject: py2exe compiling Message-ID: <562a25f0705211232g79c7a7acva40065addf3673ab@mail.gmail.com> Hello, I have just finished my script and am ready to distrabute it. I am having a little trouble using py2exe though. here is what i have at the top of my file for imports: import string, array, sgmllib, re, sys, cookielib, urllib2, random, ConfigParser, time from urllib2 import urlopen from ClientForm import ParseResponse from configobj import ConfigObj Now, there are some other file attributes i need a bit of help with. icon = nigel.ico file name = name file author = cody woolaver file version = 0.1.3 file comments = uhhh, a comment ^^ Thanks for your help ~Cody Woolaver -------------- next part -------------- An HTML attachment was scrubbed... URL: From bbxx789_05ss at yahoo.com Thu May 24 23:04:04 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 24 May 2007 20:04:04 -0700 Subject: sockets, gethostname() changing Message-ID: <1180062244.266857.300830@m36g2000hse.googlegroups.com> Hi, I'm experimenting with a basic socket program(from a book), and both the client and server programs are on my computer. In both programs, I call socket.gethostname(), but I discovered that when I am connected to the internet, both the client and server hang and nothing happens. I discovered that the hostname of my computer automatically changes to that of my isp when I'm connected to the internet, and presumably the server program on my computer cannot listen on my isp's address(host, port). Is there a way to make the hostname of my computer static, so that it doesn't change to my isp's hostname when I connect to the internet. I'm using mac os 10.4.7. Why does my computer's hostname dynamically change in the first place? server program: ------------------- import socket s = socket.socket() host = socket.gethostname() print host port = 1274 s.bind((host, port)) s.listen(5) while("Ctrl-C hasn't been entered"): c, addr = s.accept() #blocks and waits for client connection print "Got socket connection from", addr c.send("Thank you for connecting. Now get lost.") c.close() client program: ------------------- import socket s = socket.socket() host = socket.gethostname() port = 1274 s.connect((host, port)) print s.recv(1024) s.close() From collver at peak.org Fri May 4 09:09:11 2007 From: collver at peak.org (Ben Collver) Date: Fri, 04 May 2007 06:09:11 -0700 Subject: My Python annoyances In-Reply-To: <1178202431.147195.249790@u30g2000hsc.googlegroups.com> References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> <1178202431.147195.249790@u30g2000hsc.googlegroups.com> Message-ID: Paul Boddie wrote: > I'm sorry to hear about that. If by "macho" you mean people who insist > that things are good enough as they are, and that newcomers should > themselves adapt to whatever they may discover, instead of things > being improved so that they are more intuitive and reliable for > newcomers and experienced developers alike, then I'd certainly be > interested in undermining that culture. That was the sort of response I got on freenode #python, which I realize I should not take as representative of the whole community. Thank you for the thoughtful response. >> I tried to write portable Python code. The zlib CRC function returned >> different results on architectures between 32 bit and 64 bit >> architectures. I filed a bug report. It was closed, without a comment >> from the person who closed it. I get the unspoken message: bug reports >> are not welcome. > > Can you provide the bug identifier? Bug reports are generally welcome, > and despite complaints about patch reviews, I've found people > reviewing things I've submitted. It is problem report #1678102. I understand the problem: that a 32 bit number looks different in a 32 bit signed int than in a 64 bit signed int. However, the workaround of dropping a bit seems to defeat the purpose of using a CRC. > Yes, Ctrl-Z exits Python in the standard Windows edition. Since Cygwin > provides a POSIX-like environment, Ctrl-D should be used instead. If > the documentation is wrong, a bug report or patch should be filed > against the software. This morning I could not reproduce the problem. When the user types "quit" at the Python prompt, the Cygwin port instructs the user to press Control-D, which works. Even if you SSH in to Cygwin, and run the win32 port, it instructs the user to press Control-Z plus Return, which works. Maybe it was fixed after I had the problem. >> Between 2.4 and 2.5, tempfile returns a different type of object. My >> code cannot have a single test, it has check for type(obj) == file or >> obj.__class__ == tempfile._TemporaryFileWrapper. > > Try using isinstance or relying on "deeper" knowledge of how the > object will be used. Thank you for the hint. I just want my function to validate that one of its arguments is a file-like object. It isn't necessarily going to be a temporary file, but it might be. >>> import temporaryfile >>> t = tempfile.TemporaryFile() >>> isinstance(t, file) False > My opinions, already expressed, include the observation that the core > development community is more interested in extending the language > than in strengthening the standard library (and its documentation). It > should be noted that the proposed standard library reorganisation, > which is a very conservative affair, has actually been postponed until > after the release of Python 3.0a1 according to a message I read > recently. And yet, if you read people's lists about what they "hate" > about Python (amongst actual users of Python), guess which thing > almost always comes up? I guess you cannot blame folks for working on what they find interesting. Ben From sickcodemonkey at gmail.com Sun May 13 17:41:16 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Sun, 13 May 2007 17:41:16 -0400 Subject: file uploader In-Reply-To: <2adc542f0705091849t6c092ba0mf1cedd080da36960@mail.gmail.com> References: <2adc542f0705091849t6c092ba0mf1cedd080da36960@mail.gmail.com> Message-ID: <2adc542f0705131441h1aabda6cl8c30589fc2f5d9a2@mail.gmail.com> I never heard a response back concerning my previous question, so I decided to write my own function. If anyone has a simpler way of checking to see if a file already exists (prior to uploading to a server) and renaming it, please let me know. Here is the code that I am using (it runs exactly the same as the linux app 'arcgen'). <% import os,string filename = "whoa.mp3" dir_path = "/u01/" i = 0 while os.path.exists(dir_path+filename): #filename=string.replace(filename, ".-0",".-1") if i == 0: filename = "%s.-%s" % (filename,i) else: t = i-1 filename=string.replace(filename,".-%s" % (t),".-%s" % (i)) i += 1 req.write(filename) %> The directory contains the following files: "whoa.mp3" and "whoa.mp3.-0". This code will output "whoa.mp3.-1". On 5/9/07, Sick Monkey wrote: > > Hey guys. I wanted to write a little desktop application that would > upload files to an external server, to a specific directory. > > The desktop application is running on Mac OS X and I built a .psp script > that is running on a Red Hat server. > NOTE: This application is written for Python 2.5 (both py and psp) > > My code is giving me problems, in that it is overwriting files. I was > wondering if anyone knew of a module or a method that would overcome this > dilemma. I can adapt my program to search to see if the file existed > already in the directory and append a random string sequence to keep this > from occurring, but I do not want to reinvent the wheel (if such a thing > exists) and that would clutter up my program. :) > > Here is what I am currently using: > > fname = os.path.basename(uploadFile.filename) > dir_path = "/u01" > open(os.path.join(dir_path, fname), 'wb').write(uploadFile.file.read()) > > As always, any help is greatly appreciated. > > .dave > -------------- next part -------------- An HTML attachment was scrubbed... URL: From newsuser at stacom-software.de Tue May 29 06:58:30 2007 From: newsuser at stacom-software.de (Alexander Eisenhuth) Date: Tue, 29 May 2007 12:58:30 +0200 Subject: PyQt: Is signal / slot really working across threads? Message-ID: Hello pyqt users, i tried to use signal / slot across threads. With the following example I want to emit a signal when the thread loop is entered. The connected slot is never called. Why? Any help is very welcome ... Alexander import time import sys import PyQt4 from PyQt4.QtCore import (QObject, QThread) SIGNAL = PyQt4.QtCore.SIGNAL class CancelableQtThread_(QThread): def __init__(self): QThread.__init__(self) self.sigStarted = SIGNAL("sigStarted()") def run(self): print "Enter thread" self.emit(self.sigStarted) time.sleep(0.1) print "Leave thread" class TestSigSlot(QObject): def __init__(self): QObject.__init__(self) self._thread = CancelableQtThread_() self.connect(self._thread, self._thread.sigStarted, self.Called) self._thread.start() time.sleep(1.0) def Called(self): print "Called !" if __name__ == "__main__": obj = TestSigSlot() From arnodel at googlemail.com Tue May 1 03:02:36 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 1 May 2007 00:02:36 -0700 Subject: While we're talking about annoyances In-Reply-To: <1hxdhcd.v9sfz54elovkN%aleax@mac.com> References: <1177837565.317999.244420@c35g2000hsg.googlegroups.com> <1177857049.938363.166170@p77g2000hsh.googlegroups.com> <1hxchgp.7sw7efb72rh2N%aleax@mac.com> <1hxcm3o.19dhbys1wllx20N%aleax@mac.com> <1hxdhcd.v9sfz54elovkN%aleax@mac.com> Message-ID: <1178002955.984868.31560@y5g2000hsa.googlegroups.com> On Apr 30, 3:51 pm, a... at mac.com (Alex Martelli) wrote: > Michael Hoffman wrote: > > ... > > > >> Well, counting the index() function that is called in both cases, the > > >> original rank() had one sort, but my version has two sorts. > > > > That doesn't affet the big-O behavior -- O(N log N) holds whether you > > > have one sort, or three, or twentyseven. Again we're not talking about big-O: we're talking about which one is faster. > > I've taught programming classes before, and I would have had to fail > > anybody who misunderstood speed badly enough to claim that something > > repeating an O(N log N) algorithm 27 times was no faster than doing it > > once. ;-) > > As for me, I would fail somebody who thought they could compare speed > this way -- if the O(N log N) executed 27 times took (on a given > machine) 1 millisecond times N times log N, and the other one (on the > same machine) 1 second times N times log N (and in the big-O notation > you can NEVER infer what the multiplicative constant is), for example, > such a comparison would be totally of base. Of course you are right: this is basic asymptotic analysis. You also know very well that this is not what I or Michael were thinking of. He was simply saying that repeating the *same thing* 27 times takes more time than simply doing it once, as it was made clear by my earlier post that his solution involved repeating the same index() function twice. > > As Arnaud points out, asymptotic behavior is not the same as speed. His > > original statement that the more recently proposed definitions of rank() > > are slower than the OP's may be correct. And if it's not, it's not > > because they're all O(N log N). > > And if it is, it's not because of the "one sort" versus "two sorts": by > that sole criterion you just cannot guess (sensibly) at speed (measuring > is much better, though it has its own pitfalls). I'm afraid you can draw some conclusions in this case, precisely *because* one version has one sort less than the other (that is what I was hinting at in my first post). Let's say the time complexity of the first sort is: f(n) ~ Knlogn The time complexity of the second sort is: g(n) ~ Lnlogn The time complexity of the simple loop that can replace the second sort is: h(n) ~ Hn Now because the whole algorithm consists of doing one sort THEN the second thing(sort or loop), the time complexities of the two versions are as follow: Two sort version: f(n)+g(n) ~ Knlogn+Lnlogn ~ (K+L)nlogn One sort version: f(n)+h(n) ~ Knlogn + Hn ~ Knlogn(1+H/Klogn) ~ Knlogn So the two sort version is (K+L)/K times slower than the one-sort version asymptotically. (in practice I reckon K=L so that makes it twice slower) -- Arnaud "Errare humanum est, sed perseverare diabolicum" From epost2 at gmail.com Thu May 24 09:15:23 2007 From: epost2 at gmail.com (Bruce) Date: 24 May 2007 06:15:23 -0700 Subject: configobj - use of Message-ID: <1180012522.847219.278310@q69g2000hsb.googlegroups.com> I assume that you know the module configobj. I use it like this: I have a config_file : [sec1] [[subsec1]] a = 1 b = 2 [[subsec2]] a = 3 b = 1 .. ans so on Then in the code I have c = configobj.ConfigObj(path_to_config file) then I go like for instance for s in c['sec1']: print c['sec1'][s]['a'] Just think its awkward that its neccessary to use the c['sec1'] again inside the loop, guess I`d like it to be like print s.a instead Is this the right way to use configobj? From toby at tobiah.org Wed May 2 16:06:39 2007 From: toby at tobiah.org (Tobiah) Date: Wed, 02 May 2007 13:06:39 -0700 Subject: bitwise shift? In-Reply-To: <4638d8c5$0$16290$88260bb3@free.teranews.com> References: <462FEE8B.2030701@lexicon.net> <4638d8c5$0$16290$88260bb3@free.teranews.com> Message-ID: <4638e2bf$0$16368$88260bb3@free.teranews.com> Tobiah wrote: > John Machin wrote: >> On 26/04/2007 7:10 AM, Sherm Pendley wrote: >> >>> Shift left is *not* the same as multiplying by k. It is the same as >>> multi- >>> plying by 2^k. >> >> Where I come from, ^ is the exclusive-or operator. Of course YMMV in >> WV :-) > > desktops:toby:ga> bc > bc 1.06 > Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc. > This is free software with ABSOLUTELY NO WARRANTY. > For details type `warranty'. > 2^3 > 8 > Wow, thunderbird displayed this to me as a true exponent, even though it is an ascii message. anyone else get this? -- Posted via a free Usenet account from http://www.teranews.com From robin at reportlab.com Thu May 31 09:03:14 2007 From: robin at reportlab.com (Robin Becker) Date: Thu, 31 May 2007 14:03:14 +0100 Subject: non standard path characters In-Reply-To: <465ec26a$0$336$e4fe514c@news.xs4all.nl> References: <465ec26a$0$336$e4fe514c@news.xs4all.nl> Message-ID: <465EC792.7050305@chamonix.reportlab.co.uk> Tijs wrote: > Robin Becker wrote: ....... > Zip files contain a bit flag for the character encoding (cp430 or utf-8), > see the ZipInfo object in module zipfile and the link (on that page) to the > file format description. > But I think some zip programs just put the path in the zipfile, encoded in > the local code page, in which case you have no way of knowing. > thanks for that. I guess the problem is that when a path is obtained from such an object the code that gets the path usually has no way of knowing what the intended use is. That makes storage as simple bytes hard. I guess the correct way is to always convert to a standard (say utf8) and then always know the required encoding when the thing is to be used. -- Robin Becker From Eric_Dexter at msn.com Mon May 14 18:24:02 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 14 May 2007 15:24:02 -0700 Subject: deployment scripts In-Reply-To: <1179153152.824262.146460@k79g2000hse.googlegroups.com> References: <1179153152.824262.146460@k79g2000hse.googlegroups.com> Message-ID: <1179181442.240764.255860@e51g2000hsg.googlegroups.com> On May 14, 9:32 am, Erin wrote: > Does anyone have experience developing deployment scripts with Jython? csound blue is open source and uses jython, .. I don't have the url on me though http://www.stormpages.com/edexter/csound.html From jeff at taupro.com Mon May 14 07:12:46 2007 From: jeff at taupro.com (Jeff Rush) Date: Mon, 14 May 2007 06:12:46 -0500 Subject: Seeking Four Code Samples for Forrester Research Survey Message-ID: <4648442E.4020201@taupro.com> In working up a response to the survey being conducted by Forrester Research on dynamic languages, there is a section wherein they want to see code samples. The samples must include all code written for the example, and URLs to any frameworks or modules used. Their objective is to see how efficient/elegant the language is for developers. This is one area in which Python should excel. 1) Render a simple Web page containing text, data, and graphics, as specified in this wireframe mockup: http://dfwpython.org/uploads/Forrester/WireframeShot-1.jpg With the myriad number of web frameworks for Python, this is hard but let's pick those a few that are most expressive, as the person evaluating it may not be familiar with Python per se, but be looking for readability. 2) Invoke a simple Web service and format/display the results. This can be either web services or REST, whichever one looks cleanest. 3) Create a mash-up that overlays local temperature data onto a Google map. 4) Create a simple form for data submission with fields and drop down selects and a submit button, as specified in this wireframe mockup. At least one field should be validated. http://dfwpython.org/uploads/Forrester/WireframeShot-2.jpg To help our community's standing in the survey, and perhaps promotion of your favorite web framework, please consider picking one of these or providing a trimmed down example of existing code. Send it via private email to me, and I'll get it included in the survey response. Forrester's deadline to us is by the end of this week, May 18th. Thanks, Jeff Rush Python Advocacy Coordinator From bj_666 at gmx.net Tue May 15 09:15:47 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 15 May 2007 15:15:47 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> <4648294F.2000704@web.de> <46487a6c$0$2400$426a74cc@news.free.fr> <464977D3.6010703@web.de> <464993e7$0$23148$9b4e6d93@newsspool1.arcor-online.net> <464997E5.4050105@web.de> <46499f8f$0$20294$9b4e6d93@newsspool3.arcor-online.net> Message-ID: In <46499f8f$0$20294$9b4e6d93 at newsspool3.arcor-online.net>, Ren? Fleschenberg wrote: > Stefan Behnel schrieb: >> :) This is not about "technical" English, this is about domain specific >> English. How big is your knowledge about, say, biological terms or banking >> terms in English? Would you say you're capable of modelling an application >> from the domain of biology, well specified in a large German document, in >> perfect English terms? > > As I have said, I don't need to be able to do that (model the > application in perfect English terms). It is better to model it in > non-perfect English terms than to model it in perfect German terms. Yes, > I do sometimes use a dictionary to look up the correct English term for > a domain-specific German word when programming. It is rarely necessary, > but when it is, I usually prefer to take that effort over writing a > mixture of German and English. What about words that can't really be translated because they are not only domain specific but some "code" within the organization the project is written for? Wouldn't it be much easier for maintenance if the specification, the code, and the users of the program use the same terms for the same things or concepts instead of mixing this with some artificial translations? Maybe you don't need this. The field of programming is very broad and many domains can be translated and make sense in an international context, but e.g. software that should map the workflow of a local company with local laws and regulations and internal "names" for things and concepts looks strange in both, pure "english" and mixed local language and english. But the latter is easier to map to the specifications and language of the end users. Ciao, Marc 'BlackJack' Rintsch From jm.suresh at gmail.com Tue May 15 14:42:35 2007 From: jm.suresh at gmail.com (jm.suresh@no.spam.gmail.com) Date: 15 May 2007 11:42:35 -0700 Subject: Storing and searching nodes of a tree In-Reply-To: References: <1179233407.473173.259110@h2g2000hsg.googlegroups.com> <1179243655.596897.6450@e51g2000hsg.googlegroups.com> Message-ID: <1179254555.468676.190260@p77g2000hsh.googlegroups.com> On May 15, 9:25 pm, Marc 'BlackJack' Rintsch wrote: > In <1179243655.596897.6... at e51g2000hsg.googlegroups.com>, > > jm.sur... at no.spam.gmail.com wrote: > > If I have the tree in the dictionary, the code would like this, > > def search(tree, path): > > while path and not(tree.haskey(path)): > > path = path[:-1] > > if path: > > return tree[path] > > else: > > raise KeyError('path not on tree') > > > Another qn -- dict.haskey() takes logn time, am I right? > > No it's O(1). Dictionaries are implemented as hash tables. You may write > the condition as: > > while path and path not in tree: > > That's a little easier to read and a bit faster too as a method lookup is > spared. > > Ciao, > Marc 'BlackJack' Rintsch Wow :) , thanks. - Suresh From levicc00123 at gmail.com Sun May 6 13:02:07 2007 From: levicc00123 at gmail.com (Levi Campbell) Date: 6 May 2007 10:02:07 -0700 Subject: exporting a record from a database to a MS Word document. Message-ID: <1178470927.793357.204080@n76g2000hsh.googlegroups.com> Is there a way to export a record from a database kept with bsddb to MS Word, possibly with some type of formatting data? From sb at csse.unimelb.edu.au Sat May 26 00:21:25 2007 From: sb at csse.unimelb.edu.au (Steven Bird) Date: Sat, 26 May 2007 14:21:25 +1000 Subject: NLTK: Natural language processing in Python Message-ID: <97e4e62e0705252121t399e22feydde04e707e429b77@mail.gmail.com> NLTK ? the Natural Language Toolkit ? is a suite of open source Python modules, data sets and tutorials supporting research and development in natural language processing. It comes with 50k lines of code, 300Mb of datasets, and a 360 page book which teaches both Python and Natural Language Processing. NLTK has been adopted in at least 40 university courses. NLTK is hosted on sourceforge, and is ranked in the top 200 projects. http://nltk.sourceforge.net/ Quotes -- what users have said about NLTK: "... the quite remarkable Natural Language Toolkit (NLTK), a wonderful tool for teaching, and working in, computational linguistics using Python." http://www.ibm.com/developerworks/linux/library/l-cpnltk.html "Natural Language Toolkit (nltk) is an amazing library to play with natural language." http://www.biais.org/blog/index.php/2007/01/31/25-spelling-correction-using-the-python-natural-language-toolkit-nltk "... a wonderful lightweight framework that provides a wealth of NLP tools." http://harnly.net/2007/blog/geek/lang/ruby/nltks-ing-words-variations/ "A good place to start for those learning about NLP for the first time, this has been used in many academic situations. It is extremely well documented, with tutorials which not only explain the tool, but also give an overview of the subject (eg document clustering). I was able to go from downloading it for the first time, to creating and training a 2004 Task 1A system (bigram gene name tagger) in about and hour." http://compbio.uchsc.edu/corpora/bcresources.html "Students with no previous programming experience will be able to spend more of their time thinking about the logical steps involved in getting the computer to process language data, and less time mastering and using the arcana involved in getting the computer to do anything at all." http://linguistlist.org/issues/14/14-3165.html Steven Bird http://www.csse.unimelb.edu.au/~sb/ From showell30 at yahoo.com Sun May 27 15:14:54 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 27 May 2007 12:14:54 -0700 (PDT) Subject: unit testing In-Reply-To: Message-ID: <712447.67571.qm@web33503.mail.mud.yahoo.com> --- Steven Bethard wrote: > Have you tried py.test? > > http://codespeak.net/py/dist/test.html > > I've heard good things about it, but haven't gotten > around to trying it > yet. Here's a two-line test suite from the page > above: > > def test_answer(): > assert 42 == 43 > Changed the subject line. Nope, I haven't. I'm a tremendous advocate of unit testing, but I've never felt compelled to try out other libraries, because I work mostly on private code now, so the following-standard-practices-to-benefit-from-familiarity argument doesn't carry much weight with me, and also because I find it easy enough to do things on a roll-your-own basis. YMMV, of course. I have slowly introduced unit testing into my own work environment, with some success. We don't use a 3rd party testing framework, but here's my roll-your-own approach: 1) For flat-out failures, we just fail with a traceback right away. We don't bother to capture stats on how many tests failed. If one test fails, that's enough to clue in a developer that he/she broke something. 2) We don't use assertions very often, but rather just diff the output files to the GOLD files. This may eventually stop to scale, but it hasn't yet. 3)We have a little trickery to override imports, etc., as 99.99% of our code was never written with unit testing in mind, but I still want to regression test it. 4) We have quite a few mock-ish objects, mainly relating to simulating I/O situations. ____________________________________________________________________________________Pinpoint customers who are looking for what you sell. http://searchmarketing.yahoo.com/ From saif.shakeel at gmail.com Fri May 11 03:05:19 2007 From: saif.shakeel at gmail.com (saif.shakeel at gmail.com) Date: 11 May 2007 00:05:19 -0700 Subject: module error for elementtree Message-ID: <1178867119.666923.204000@h2g2000hsg.googlegroups.com> #!/usr/bin/env python from elementtree import ElementTree as Element tree = et.parse("testxml.xml") for t in tree.getiterator("SERVICEPARAMETER"): if t.get("Semantics") == "localId": t.set("Semantics", "dataPackageID") tree.write("output.xml") Hi, For the above code to work elementtree is imported in first line ,but when running it says : ImportError: No module named elementtree.ElementTree Does thie module exists as default or a patch is needed? Thanks From tbrkic at yahoo.com Tue May 29 13:35:21 2007 From: tbrkic at yahoo.com (glomde) Date: 29 May 2007 10:35:21 -0700 Subject: How to set a class inheritance at instance creation? In-Reply-To: <1180459645.803360.271750@r19g2000prf.googlegroups.com> References: <1180453971.556244.91370@q69g2000hsb.googlegroups.com> <1180459645.803360.271750@r19g2000prf.googlegroups.com> Message-ID: <1180460121.383133.35650@q69g2000hsb.googlegroups.com> On 29 Maj, 19:27, "shand... at gmail.com" wrote: > Why not just have Lang1 and Lang2 inherit from WriteStruct as well? This wont work I think since if add antoher Class: class WriteStruct(): def func1(self); print "Hello2" def Generate(self): self.func1() class WriteStruct2(WriteStruct): def func1(self); print "Hello" def Generate(self): self.func1() Den if Lang1, inherit both WriteStruct and WriteStruct2 I will get name clashes. In my real code I have very big Generate Method in WriteStruct that calls submethods. and thes submethods should be overriden by the subclasses. So I cant change the name on the submethods. > > On May 29, 8:52 am, glomde wrote: > > > Hi I wonder if you can set what subclass a class should > > have at instance creation. > > > The problem is that I have something like: > > > class CoreLang(): > > def AssignVar(self, var, value): > > pass > > > class Lang1(CoreLang): > > def AssignVar(self, var, value): > > return var, "=", value > > > class Lang2(CoreLang): > > def AssignVar(self, var, value): > > return var, "<=", value > > > class WriteStruct(): > > def Generate(self, vars): > > for var in vars: > > print self.AssignVar() > > > The problem is that I want WriteStruct to sometimes be a subclass of > > Lang1 and sometimes > > of Lang2. > > In the above example I could but the Generate Method in CoreLang. But > > in my real > > example I also want to able to subclass WriteStruct to be able to easy > > customize WriteStruct. > > Which I wouldnt be able to do if it was a method in CoreLang. > > > So in code I would like to write something like: > > > WriteStruct(Lang1).Generate(vars) > > > Even better would be that if I in the Lang1 class could > > just do WriteStruct().Generate(vars) and Lang1 class would > > magically make WriteStruct a subclass of itself. > > > Cheers, > > > /T From msurel at comcast.net Fri May 4 16:44:11 2007 From: msurel at comcast.net (Mike) Date: 4 May 2007 13:44:11 -0700 Subject: adding methods at runtime and lambda In-Reply-To: References: <1178221975.149008.192410@y5g2000hsa.googlegroups.com> <1178300759.455134.60560@n59g2000hsh.googlegroups.com> Message-ID: <1178311451.947716.231640@q75g2000hsh.googlegroups.com> On May 4, 2:05 pm, Peter Otten <__pete... at web.de> wrote: > Mike wrote: > > staticmethod makes the function available to the whole class according > > to the docs. What if I only want it to be available on a particular > > instance? Say I'm adding abilities to a character in a game and I want > > to give a particular character the ability to 'NukeEverybody'. I don't > > want all characters of that type to be able to wipe out the entire > > planet, just the particular character that got the powerup. > > Static methods are for specialists, you don't need them. But then, your > initial post looked like you were just exploring the possibilities... Yeah, I'm just poking around. > > You can > > - have the Character.nuke_everybody() method check a self._can_nuke_eb flag I don't like this one because it would require me to know every ability everybody might ever have up front. > - subclass the Character class with a NukingChar subclass and make only one > instance of that class A possibility, I guess, but does this then mean I would need a new class for every type of character? Probably not, but you would at least need types grouped by general class, kind of like D&D characters (Fighter, Magic User, etc.). It makes it harder for anybody to learn anything they want. > - add an instancemethod to one Character instance > > The simpler the approach you take the smarter you are ;) > > Peter I just realized in working with this more that the issues I was having with instancemethod and other things seems to be tied solely to builtins like dict or object. I remember at some point just doing something like: x.fn = myfnFunction and having it just work. If I do that with an instance of generic object however, I get an AttributeError. So: x = object() x.fn = myFn blows up. However, if I do class nc(object):pass x = nc() x.fn = myFn Then all is well. checking for an ability on somebody is as simple as 'fn' in dir(x) or hasattr(x, 'fn') I had thought this was a lot easier than I was making it out to be. What I don't know is why using an object derived from object allows you to dynamically add methods like this but the base object does not. At this point it is more of a curiosity than anything, but if somebody knows the answer off the top of their head, that would be great. Thanks. From deets at nospam.web.de Thu May 10 08:55:42 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 10 May 2007 14:55:42 +0200 Subject: Thread-safe dictionary In-Reply-To: References: Message-ID: <5agj2jF2n2uq3U2@mid.uni-berlin.de> Jean-Paul Calderone schrieb: > On 10 May 2007 05:45:24 -0700, tuom.larsen at gmail.com wrote: >> Hi, >> >> please consider the following code: >> >> >> from __future__ import with_statement >> >> class safe_dict(dict): >> def __init__(self, *args, **kw): >> self.lock = threading.Lock() >> dict.__init__(self, *args, **kw) >> def __getitem__(self, key): >> with self.lock: >> return dict.__getitem__(self, key) >> def __setitem__(self, key, value): >> with self.lock: >> dict.__setitem__(self, key, value) >> def __delitem__(self, key): >> with self.lock: >> dict.__delitem__(self, key) >> >> >> - would I need to override another methods e.g. update() or items() in >> order to remain thread-safe or is this enough? >> - in __getitem__, does it release the lock after returning the item? >> - wouldn't it be better to use threading.RLock, mutex, ... instead? >> > > The builtin dict type is already thread safe. Technically - yes. But you should mention that the reason for that is the GIL, which essentially ensures that python as whole is threadsafe on the level of assignments, collection manipulation and so forth. At the cost of not being able to have real concurrent threads except for C-code that explicitly releases the GIL. Diez From digimotif at gmail.com Tue May 29 21:24:24 2007 From: digimotif at gmail.com (digimotif) Date: 29 May 2007 18:24:24 -0700 Subject: need advice on building core code for python and PHP In-Reply-To: <1180047661.795384.295850@a26g2000pre.googlegroups.com> References: <1180025115.704410.250890@a35g2000prd.googlegroups.com> <1180028001.569139.317660@q66g2000hsg.googlegroups.com> <1180034698.387087.251590@o5g2000hsb.googlegroups.com> <1180047661.795384.295850@a26g2000pre.googlegroups.com> Message-ID: <1180488264.224155.281830@p77g2000hsh.googlegroups.com> On May 24, 5:01 pm, Graham Dumpleton wrote: > On May 25, 5:24 am, aspineux wrote: > > > > > On 24 mai, 19:33, Szabolcs Nagy wrote: > > > > > Is there a way I could code the base (core) code in Python and have > > > > PHP call it? I've really liked using SQLAlchemy and there are other > > > > * quick and dirty solution: > > > in a shell: > > > $ python yourscript.py pipe_out > > > in the php script: > > > fwrite(pipe_in, input_data); > > > results = fread(pipe_out, sizeof_results); > > > > * simple and nice solution: > > > do not ever use php > > > Write a CGI wrapper around your python script, and publish it using mod_python. > > And make the appropriate http requests from PHP. > > You do not need mod_python to host CGI scripts written in Python, they > are two separate things. > > Depending on the complexity of what you are doing, you might be better > off writing a backend server in Python that incorporates an XML-RPC > server. Your PHP script can then use XML-RPC client to communicate to > the backend Python server to do the real work. Over time you could > even transition your web pages to being done in Python instead. In > doing this your back end Python server doesn't have to change, you > just make XML-RPC calls from the Python code for the web pages in > place of where you would be doing it with PHP initially. You also > wouldn't be restricted to web based front ends, you could also use GUI > based front end as well. > > Graham This sounds more like the direction I should go. Is XML-RPC the only technology allowing this sort of setup? If I understand correctly, it would basically mean going to a three tiered application approach. I'd have the database, the python xml-rpc server, and the gui/web interfaces. I'd also want to make sure I'm implementing technology that will scale well. Brian From __peter__ at web.de Sat May 5 01:43:53 2007 From: __peter__ at web.de (Peter Otten) Date: Sat, 05 May 2007 07:43:53 +0200 Subject: Looping over lists References: Message-ID: Tommy Grav wrote: > I have a list: > > a = [1., 2., 3., 4., 5.] > > I want to loop over a and then > loop over the elements in a > that is to the right of the current > element of the first loop > > In C this would be equivalent to: > > for(i = 0; i < n; i++) { > for(j=i+1; j < n; j++) { > print a[i], a[j] > > and should yield: > 1. 2. > 1. 3. > 1. 4. > 1. 5. > 2. 3. > 2. 4. > 2. 5. > 3. 4. > 3. 5. > 4. 5. > > Can anyone help me with the right approach for this > in python? Two more options: def pop_combine(items): items = list(items) while items: a = items.pop(0) for b in items: print a, b def enumerate_combine(items): for i, a in enumerate(items): for b in items[i+1:]: print a, b Peter From broek at cc.umanitoba.ca Mon May 21 10:41:18 2007 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Mon, 21 May 2007 10:41:18 -0400 Subject: TIFF to PDF In-Reply-To: References: <1179687595.142454.23850@z24g2000prd.googlegroups.com> <1179744141.027494.60590@r3g2000prh.googlegroups.com> <4651A444.9040901@cc.umanitoba.ca> Message-ID: <4651AF8E.9010201@cc.umanitoba.ca> Gabriel Genellina said unto the world upon 05/21/2007 10:12 AM: > En Mon, 21 May 2007 10:53:08 -0300, Brian van den Broek > escribi?: > >> Gabriel Genellina said unto the world upon 05/21/2007 07:01 AM: >>> En Mon, 21 May 2007 07:42:21 -0300, revuesbio >>> escribi?: >>> >>>> os.system('"C:\Program Files\GnuWin32\bin\tiff2pdf.exe" -o C:\test.pdf >>>> C:\test.TIF') >>> \ is used as a escape character in strings. >>> Use either \\ or a raw string, that is: >>> >> Better still, use / as the path separator. That works fine on both >> windows and *nixes. > > But unfortunately / does not always work, specially for arguments to > internal commands: > > py> os.system("type c:/windows/win.ini") > La sintaxis del comando no es correcta. [invalid syntax] > 1 > py> os.system(r"type c:\windows\win.ini") > [Compatibility] > _3DPC=0x00400000 > _BNOTES=0x224000 > ... Thanks for the catch then, Gabriel. Windows is but a bitter memory for me, and / worked in every context in which I ever used it---I didn't know that the support was only partial. Best, Brian vdB From chris.cavalaria at free.fr Thu May 31 09:18:18 2007 From: chris.cavalaria at free.fr (Christophe) Date: Thu, 31 May 2007 15:18:18 +0200 Subject: Is PEP-8 a Code or More of a Guideline? In-Reply-To: References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <5c1jpkF2tl0ilU1@mid.individual.net> <1180539790.654176.26900@q75g2000hsh.googlegroups.com> <646aw86i.fsf@mail.com> Message-ID: <465ecb3c$0$29072$426a74cc@news.free.fr> Joe Riopel a ?crit : >> Each requires exactly the same number of key strokes when I do the >> math. (Too lazy to explain further...) > > foo_bar > f, o, o, shift + underscore, b, a, r = 8 > fooBar > f, o, o, shift + b, a, r = 7 f, o, o, _, b, a, r = 7 f, o, o, shift + b, a, r = 8 Also the shift+b is much more work than 2 keypresses IMHO. On the other hand, the underscore is done by pressing the 8 key without any other modifier which is very easy and accessible. Yeap, french layout rules for that naming convention :) From aleax at mac.com Sat May 5 22:12:56 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 5 May 2007 19:12:56 -0700 Subject: File names and file objects [was Re: My Python annoyances] References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> <1178202431.147195.249790@u30g2000hsc.googlegroups.com> <1hxkwj0.12jtj1v3b522bN%aleax@mac.com> Message-ID: <1hxnm89.reva1b1tgkzmvN%aleax@mac.com> Steven D'Aprano wrote: ... > What do people think about functions that accept either a file name or a > file object? > > def handle_file(obj): > if type(obj) == str: > need_to_close = True > obj = file(obj, 'r') > else: > need_to_close = False > do_something_with(obj.read()) > if need_to_close: > data.close() > > Good idea? Bad idea? Just a matter of personal preference? Acceptable as an idea, but a disaster in terms of this specific implementation (as coded, it would reject a Unicode string, or any other string-like object, for example). Also, if all you're going to do with the file is .read() it in one big gulp, there's no real advantage to this approach, either. Assuming the way you're going to use the file-like object is subtler (e.g., loop line by line so that huge files can be processed without overwhelming memory), then a better implementation may be warranted: def handle_file(file_or_path): try: f = open(file_or_path) finis = f.close except TypeError: f = file_or_path def finis(): pass try: for line in f: ... finally: finis() This version accepts anything that open is happy with, or else any sequence of lines, including but not limited to a file or file-like object open for reading. Now this, it seems to me, is a helpful approach to polymorphism. Alex From deets at nospam.web.de Thu May 24 09:15:57 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 24 May 2007 15:15:57 +0200 Subject: installing cx_Oracle. In-Reply-To: References: Message-ID: <5blhgjF2u4ii7U1@mid.uni-berlin.de> Carl K schrieb: > I am trying to use this: > http://python.net/crew/atuining/cx_Oracle/html/cx_Oracle.html > it is a real module, right? > > sudo easy_install cx_Oracle did not easy_install cx_Oracle. > > http://www.python.org/pypi/cx_Oracle/4.3.1 doesn't give me any clue. > > I got the source from > http://prdownloads.sourceforge.net/cx-oracle/cx_Oracle-4.3.1.tar.gz?download > > > carl at dell17:~/a/cx_Oracle-4.3.1$ python setup.py build > Traceback (most recent call last): > File "setup.py", line 36, in ? > oracleHome = os.environ["ORACLE_HOME"] > File "/usr/lib/python2.4/UserDict.py", line 17, in __getitem__ > def __getitem__(self, key): return self.data[key] > KeyError: 'ORACLE_HOME' yours. because you need the oracle OCI with libs and header files installed + the environment variable ORACLE_HOME pointing to the installation. I suggest you download the appropriat oracle instant client for your system. Diez From bbxx789_05ss at yahoo.com Tue May 15 18:28:06 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 15 May 2007 15:28:06 -0700 Subject: Python Newbie Suggestions In-Reply-To: <1179264515.958714.72880@l77g2000hsb.googlegroups.com> References: <1179264515.958714.72880@l77g2000hsb.googlegroups.com> Message-ID: <1179268086.322214.265360@e65g2000hsc.googlegroups.com> Not "Learning Python: From Novice to Professional". I've looked at "Learning Python 2nd Ed." to use as a reference for all the blunders in the first book I mentioned, and it's a lot better--plus it has exercises at the end of each chapter. From rene at korteklippe.de Wed May 16 04:32:10 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Wed, 16 May 2007 10:32:10 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464AB9F2.60906@web.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649dd55$0$23144$9b4e6d93@newsspool1.arcor-online.net> <464a25e9$0$10188$9b4e6d93@newsspool4.arcor-online.net> <1179291296.561359.286230@h2g2000hsg.googlegroups.com> <464ab64f$0$10185$9b4e6d93@newsspool4.arcor-online.net> <464AB9F2.60906@web.de> Message-ID: <464ac189$0$20297$9b4e6d93@newsspool3.arcor-online.net> Stefan Behnel schrieb: >>> - Non-english speakers can not create or understand >>> english identifiers hence can't create good code nor >>> easily grok existing code. >> I agree that this is a problem, but please understand that is problem is >> _not_ solved by allowing non-ASCII identifiers! > > Well, as I said before, there are three major differences between the stdlib > and keywords on one hand and identifiers on the other hand. Ignoring arguments > does not make them any less true. BTW: Please stop replying to my postings by E-Mail (in Thunderbird, use "Reply" in stead of "Reply to all"). I agree that keywords are a different matter in many respects, but the only difference between stdlib interfaces and other intefaces is that the stdlib interfaces are part of the stdlib. That's it. You are still ignoring the fact that, contrary to what has been suggested in this thread, it is _not_ possible to write "German" or "Chinese" Python without cluttering it up with many many English terms. It's not only the stdlib, but also many many third party libraries. Show me one real Python program that is feasibly written without throwing in tons of English terms. Now, very special environments (what I called "rare and isolated" earlier) like special learning environments for children are a different matter. It should be ok if you have to use a specially patched Python branch there, or have to use an interpreter option that enables the suggested behaviour. For general programming, it IMO is a bad idea. -- Ren? From mensanator at aol.com Thu May 3 13:31:18 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 3 May 2007 10:31:18 -0700 Subject: Library Naming In-Reply-To: <1178203288.888165.169130@y80g2000hsf.googlegroups.com> References: <1178203288.888165.169130@y80g2000hsf.googlegroups.com> Message-ID: <1178213478.128373.190420@e65g2000hsc.googlegroups.com> On May 3, 9:41 am, Trans wrote: > I'm taking a pole on how best to name programming library packages. Well, the Poles have been wrong before. > If you have a second, please have a look. > > http://7ranscode.blogspot.com/2007/05/library-poll.html > > Thanks, > T. From carsten at uniqsys.com Tue May 29 08:39:29 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 29 May 2007 08:39:29 -0400 Subject: itertools.groupby In-Reply-To: <1180420476.785936.322400@g37g2000prf.googlegroups.com> References: <1180286272.100790.131670@q75g2000hsh.googlegroups.com> <7xveecr5xx.fsf@ruckus.brouhaha.com> <6Y6dnb0mTLsaCsbbnZ2dnUVZ_hCdnZ2d@comcast.com> <1180420476.785936.322400@g37g2000prf.googlegroups.com> Message-ID: <1180442369.3373.26.camel@dot.uniqsys.com> On Mon, 2007-05-28 at 23:34 -0700, Raymond Hettinger wrote: > On May 28, 8:36 pm, "Carsten Haese" wrote: > > And while > > we're at it, it probably should be keyfunc(value), not key(value). > > No dice. The itertools.groupby() function is typically used > in conjunction with sorted(). It would be a mistake to call > it keyfunc in one place and not in the other. The mental > association is essential. The key= nomenclature is used > throughout Python -- see min(), max(), sorted(), list.sort(), > itertools.groupby(), heapq.nsmallest(), and heapq.nlargest(). Point taken, but in that case, the argument name in the function signature is technically incorrect. I don't really need this corrected, I was merely pointing out the discrepancy between the name 'keyfunc' in the signature and the call 'key(value)' in the description. For what it's worth, which is probably very little, help(sorted) correctly identifies the name of the key argument as 'key'. As an aside, while groupby() will indeed often be used in conjunction with sorted(), there is a significant class of use cases where that's not the case: I use groupby to produce grouped reports from the results of an SQL query. In such cases, I use ORDER BY to guarantee that the results are supplied in the correct order rather than using sorted(). Having said that, I'd like to expressly thank you for providing such a mindbogglingly useful feature. Writing reports would be much less enjoyable without groupby. Best regards, -- Carsten Haese http://informixdb.sourceforge.net From steve at REMOVE.THIS.cybersource.com.au Sun May 13 19:45:56 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 14 May 2007 09:45:56 +1000 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <20070513160046.GC29172@v.igoro.us> <7x646wa9wz.fsf@ruckus.brouhaha.com> Message-ID: On Sun, 13 May 2007 10:52:12 -0700, Paul Rubin wrote: > "Martin v. L?wis" writes: >> This is a commonly-raised objection, but I don't understand why people >> see it as a problem. The phishing issue surely won't apply, as you >> normally don't "click" on identifiers, but rather type them. In a >> phishing case, it is normally difficult to type the fake character >> (because the phishing relies on you mistaking the character for another >> one, so you would type the wrong identifier). > > It certainly does apply, if you're maintaining a program and someone > submits a patch. In that case you neither click nor type the > character. You'd normally just make sure the patched program passes > the existing test suite, and examine the patch on the screen to make > sure it looks reasonable. The phishing possibilities are obvious. Not to me, I'm afraid. Can you explain how it works? A phisher might be able to fool a casual reader, but how does he fool the compiler into executing the wrong code? As for project maintainers, surely a patch using some unexpected Unicode locale would fail the "looks reasonable" test? That could even be automated -- if the patch uses an unexpected "#-*- coding: blah" line, or includes characters outside of a pre-defined range, ring alarm bells. ("Why is somebody patching my Turkish module in Korean?") -- Steven From vinay_sajip at yahoo.co.uk Fri May 25 04:16:03 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 25 May 2007 01:16:03 -0700 Subject: stdlib doc for logger.findCaller() needs update. In-Reply-To: <1179918325.803451.76820@o5g2000hsb.googlegroups.com> References: <1179918325.803451.76820@o5g2000hsb.googlegroups.com> Message-ID: <1180080963.742418.170360@q75g2000hsh.googlegroups.com> On May 23, 12:05 pm, jitu... at hotmail.com wrote: > The logger objects findCaller() method is returning a "3" element > tuple instead of "2" two as > documented in the 2.4.4 Python Library Reference .DocString is showing > it correctly. I've updated the docs - the next 2.4.x release should have them. Thanks for the report. Vinay Sajip From nirnimesh at gmail.com Fri May 25 07:07:14 2007 From: nirnimesh at gmail.com (Nirnimesh) Date: 25 May 2007 04:07:14 -0700 Subject: optparse: list out entered values In-Reply-To: <1180087678.416600.316860@z28g2000prd.googlegroups.com> References: <1180087678.416600.316860@z28g2000prd.googlegroups.com> Message-ID: <1180091234.397739.262450@x35g2000prf.googlegroups.com> On May 25, 3:07 am, Nirnimesh wrote: > I'm using optparse.OptionParser for parsing command line arguments. > > parser = optparse.OptionParser() > parser.add_option("-x", "--xample", help="example", > default="nothing", > dest="ex") > options = parser.parse_args()[0] > > python example.py -x value > > I'm in search of a method to list out all the entered options along > with the values. something which gives me: > ex => value > help => example > version => blah blah.. > I expected such a method to be there already. > > I could use dir(options) but it's kinda ugly and would require > eliminating the "unwanted" variables. > > print dir(options) > > ['__doc__', '__eq__', '__init__', '__module__', '__ne__', '__repr__', > '__str__', '_update', '_update_careful', '_update_loose', > 'ensure_value', 'ex', 'read_file', 'read_module'] > > Any help would be greatly appreciated. > > Nirnimesh I dug around with the optparse module and got this: for key, val in parser.values.__dict__.iteritems(): print key, val From kirk at strauser.com Mon May 7 10:55:25 2007 From: kirk at strauser.com (Kirk Strauser) Date: Mon, 07 May 2007 09:55:25 -0500 Subject: Recommended validating XML parser? Message-ID: We're looking for a current, supported, validating XML parser. Since it seems like there are a few thousand out there, I though we'd see what everyone else is using. Bonus points if it can do something like: >>> foo = XMLParser(""" 3000 """, dtd=file('/etc/weightfile.dtd')) >>> print foo.weight 3000 ...or some variant on that theme. -- Kirk Strauser From steven.bethard at gmail.com Sun May 13 13:05:41 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 13 May 2007 11:05:41 -0600 Subject: Using "subprocess" without lists. . .? In-Reply-To: References: Message-ID: Michael Williams wrote: > Hi All, > > I've recently seen the "subprocess" module and am rather confused by > it's requirements. Is it not possible to execute an entire string > without having to break them up into a list of arguments? For instance, > I'd much rather do the following: > > > subprocess.call("ls -al | grep -i test") > > > . . .than to have to: > > > list = ["ls", "-a", "-l" ] . . . . . . and so on and so forth. > subprocess.call(list. . .) > > > What is the best way to go about executing a massively complex single > line command? You could always call "ls -al | grep -i test".split(). STeVe From stefan.behnel-n05pAM at web.de Tue May 8 13:00:37 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 08 May 2007 19:00:37 +0200 Subject: Python Binding In-Reply-To: <1178618848.423760.53420@p77g2000hsh.googlegroups.com> References: <1178618848.423760.53420@p77g2000hsh.googlegroups.com> Message-ID: <4640ACB5.6020507@web.de> STiAT wrote: > Why do you all suggest other things than the way suggested by python? Because going to Paris is not the only way to get french bread? Why would you want to write all that ugly glue code by hand that Pyrex generates for free? Module descriptors? Class descriptors? Method descriptors? Reference counting? That's what Pyrex saves you from. Honestly. >From what I read in your mail, that's exactly the kind of thing you're having trouble with. Wouldn't you prefer concentrating on your real code instead? > I havn't got a real problem writing the code in C, actually, it looked > as if it would give me several possibilities i wouldn't have with > pyrex (like binding more library functions to one provided python > function and so on). No idea what you mean in your parentheses, but I don't think there are many "possibilities" you "wouldn't have with Pyrex". We used Pyrex to write lxml, a wrapper around the huge API of libxml2 and libxslt. It's some 11000 lines of Pyrex code by now, but the generated C code is some 67000 lines in total. Even if it's somewhat verbose and generic in places, I wouldn't have wanted to write that by hand. Stefan From andre.roberge at gmail.com Sun May 13 13:51:02 2007 From: andre.roberge at gmail.com (=?utf-8?B?QW5kcsOp?=) Date: 13 May 2007 10:51:02 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <9TH1i.1773$mR2.1557@newssvr22.news.prodigy.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <9TH1i.1773$mR2.1557@newssvr22.news.prodigy.net> Message-ID: <1179078662.485697.61540@h2g2000hsg.googlegroups.com> On May 13, 2:30 pm, John Nagle wrote: > Martin v. L?wis wrote: > > PEP 1 specifies that PEP authors need to collect feedback from the > > community. As the author of PEP 3131, I'd like to encourage comments > > to the PEP included below, either here (comp.lang.python), or to > > python-3... at python.org > > > In summary, this PEP proposes to allow non-ASCII letters as > > identifiers in Python. If the PEP is accepted, the following > > identifiers would also become valid as class, function, or > > variable names: L?ffelstiel, chang?, ??????, or ??? > > (hoping that the latter one means "counter"). > > All identifiers are converted into the normal form NFC while parsing; > > comparison of identifiers is based on NFC. > > That may not be restrictive enough, because it permits multiple > different lexical representations of the same identifier in the same > text. Search and replace operations on source text might not find > all instances of the same identifier. Identifiers should be required > to be written in source text with a unique source text representation, > probably NFC, or be considered a syntax error. > > I'd suggest restricting identifiers under the rules of UTS-39, > profile 2, "Highly Restrictive". This limits mixing of scripts > in a single identifier; you can't mix Hebrew and ASCII, for example, > which prevents problems with mixing right to left and left to right > scripts. Domain names have similar restrictions. > > John Nagle Python keywords MUST be in ASCII ... so the above restriction can't work. Unless the restriction is removed (which would be a separate PEP). Andr? From stefan.behnel-n05pAM at web.de Wed May 16 05:53:38 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 16 May 2007 11:53:38 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de><1179160242.787344.48060@h2g2000hsg.googlegroups.com> <1179258692.237438.110860@p77g2000hsh.googlegroups.com> Message-ID: <464ad4a2$0$23143$9b4e6d93@newsspool1.arcor-online.net> Hendrik van Rooyen wrote: > "Beautiful is better than ugly" Good point. Today's transliteration of German words into ASCII identifiers definitely looks ugly. Time for this PEP to be accepted. Stefan From warren at muse.com Thu May 31 21:42:05 2007 From: warren at muse.com (Warren Stringer) Date: Thu, 31 May 2007 18:42:05 -0700 Subject: c[:]() Message-ID: <001b01c7a3ee$0fdceff0$240110ac@Muse> > > I did not hijack another thread > > You really did. In the first message you sent, we see the following > header: > > > In-Reply-To: <1180504773.374529.161740 at q66g2000hsg.googlegroups.com> ... Damn! I suck. Outlook as a newsreader sucks. I need to use something else. > I retyped the code you posted in the first post, and did not get the > same results as you. Specifically: > >>> def a: print 'a' > SyntaxError: invalid syntax > >>> def b: print 'b' > SyntaxError: invalid syntax > those obviously were not copied from working code. > > >>> c[:]() > TypeError: 'tuple' object is not callable > > this has the correct spelling of 'tuple' in it. Your post misspelled it. > > and finally, > >>> c[0]() > a > >>> c[:][0] > > > I don't know how you could have gotten c[:][0] to print 'a', but it > wasn't by running all of the code you presented to us. > > -- > Jerry They were copied from working code. Copied *badly*? Yes. Running python via: Windows -> start -> run -> python doesn't allow cut and paste Here is what I tested, now cut and past from visual studio IDE #-------------------- def a(): print 'a' def b(): print 'b' c = (a,b) c[:]() # typeError c[0]() # expected c[:][0]() # huh? [i() for i in c] # too long and ...huh? #-------------------------------------- Now, I'm extremely annoyed at my own original post, for misleading typos. Yeah, Mikael's example is really cool! And I followed his suggestion of making it cellphone friendly by shorting the name, like so: #-------------------------------------- class do(list): def __call__(self,*args,**kwargs): return [f(*args,**kwargs) for f in self] def a(): print 'a called' def b(): print 'b called' c = do() c = [a,b] do(c[:])() do(c)() #-------------------------------------- I prefer that last line, because [:] is very expensive to type from a cell phone. In summary: Sorry about the hijacked thread Sorry about the typos Outlook is an odd newsreader Mikael's solution works No PEP needed for this example Now, if I could only could do this: do(orchestra(conductor)).play() Cheers, \~/ From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu May 31 16:39:42 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 31 May 2007 22:39:42 +0200 Subject: strange PyLint configuration References: <1180613790.317480.314600@p47g2000hsd.googlegroups.com> <5c8glhF2tra7sU1@mid.individual.net> Message-ID: <5c8q4eF2vg743U1@mid.individual.net> Eduardo "EdCrypt" O. Padoan wrote: > No. Quoting PEP 8: > Functions: > """ > mixedCase is allowed only in contexts where that's already the > prevailing style (e.g. threading.py), to retain backwards > compatibility. > """ > Methods and instances: > """ > Use the function naming rules: lowercase with words separated by > underscores as necessary to improve readability. > """ Has this been updated recently? I could've sworn I had read that stuff like has_key was "old". Regards, Bj?rn -- BOFH excuse #432: Borg nanites have infested the server From dustin at v.igoro.us Thu May 3 13:40:33 2007 From: dustin at v.igoro.us (dustin at v.igoro.us) Date: Thu, 3 May 2007 12:40:33 -0500 Subject: _csv.Error: string with NUL bytes In-Reply-To: <1178213314.203450.167350@n76g2000hsh.googlegroups.com> References: <1178204593.280648.208040@c35g2000hsg.googlegroups.com> <1178209090.674787.202970@o5g2000hsb.googlegroups.com> <1178211458.634214.306500@o5g2000hsb.googlegroups.com> <1178213314.203450.167350@n76g2000hsh.googlegroups.com> Message-ID: <20070503174033.GC3560@v.igoro.us> On Thu, May 03, 2007 at 10:28:34AM -0700, IAmStarsky at gmail.com wrote: > On May 3, 10:12 am, dus... at v.igoro.us wrote: > > On Thu, May 03, 2007 at 09:57:38AM -0700, fscked wrote: > > > > As Larry said, this most likely means there are null bytes in the CSV file. > > > > > > Ciao, > > > > Marc 'BlackJack' Rintsch > > > > > How would I go about identifying where it is? > > > > A hex editor might be easiest. > > > > You could also use Python: > > > > print open("filewithnuls").read().replace("\0", ">>>NUL<<<") > > > > Dustin > > Hmm, interesting if I run: > > print open("test.csv").read().replace("\0", ">>>NUL<<<") > > every single character gets a >>>NUL<<< between them... > > What the heck does that mean? > > Example, here is the first field in the csv > > 89114608511, > > the above code produces: > >>>NUL<<<8>>>NUL<<<9>>>NUL<<<1>>>NUL<<<1>>>NUL<<<4>>>NUL<<<6>>>NUL<<<0>>>NUL<<<8>>>NUL<<<5>>>NUL<<<1>>>NUL<<<1>>>NUL<<<, I'm guessing that your file is in UTF-16, then -- Windows seems to do that a lot. It kind of makes it *not* a CSV file, but oh well. Try print open("test.csv").decode('utf-16').read().replace("\0", ">>>NUL<<<") I'm not terribly unicode-savvy, so I'll leave it to others to suggest a way to get the CSV reader to handle such encoding without reading in the whole file, decoding it, and setting up a StringIO file. Dustin From gagsl-py2 at yahoo.com.ar Thu May 17 21:16:28 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 17 May 2007 22:16:28 -0300 Subject: Creating a Python Type in C - tp_init and tp_new References: <1179429054.518950.240520@y80g2000hsf.googlegroups.com> Message-ID: En Thu, 17 May 2007 16:10:54 -0300, escribi?: > I'm creating a type in a C function as follows: > > static PyObject *Receive(PyObject *self, PyObject *args) { > pyMessageObject *msgobj = PyObject_New(pyMessageObject, > &pyMessageType); > return (PyObject *)msgobj; > } > > I have (some lines omitted): > > static PyTypeObject pyMessageType = > { > PyObject_HEAD_INIT(NULL) > ... > pyMessage_Init, /*tp_init*/ > 0, /*tp_alloc*/ > pyMessage_New, /*tp_new*/ > }; > > I have noticed that pyMessage_New and pyMessage_Init are not called. > However if the type is created in Python then they are called. Why is > this and how can I solve it? I think tp_new and tp_init are used when you create an instance by calling the type (in Python would be your_type()) At least it's in type's tp_call (type_call in typeobject.c) where __new__ and __init__ are checked and processed. So I think you should create your object using PyObject_CallObject(pyMessageType, NULL) but I'm not sure... just try and post your results! Or perhaps there is another way, I don't know. -- Gabriel Genellina From tedpottel at gmail.com Sat May 19 09:52:09 2007 From: tedpottel at gmail.com (tedpottel at gmail.com) Date: 19 May 2007 06:52:09 -0700 Subject: Creating a sub folder in the pythons LIB Directory Message-ID: <1179582729.526366.13130@p77g2000hsh.googlegroups.com> Hi, I am creating a library of functions. I would like to have them saved in a sub folder of pythons LIB folder, but I cannot get it to work. I have a script called test.py I stored it in LIB folder and typed Import test, work fine. I store the script in lib/ted Then type Import lib\ted I get a error that says invalid token, how do I do this???? From spamspam at spam.eggs Sun May 20 06:42:11 2007 From: spamspam at spam.eggs (Ben C) Date: Sun, 20 May 2007 05:42:11 -0500 Subject: questions about programming styles References: Message-ID: On 2007-05-20, fdu.xiaojf at gmail.com wrote: > Hi all, I'm not skilled at programming, so sorry for my ignorance. > My questions: > > (1) > which is the better way to calculate the value of attributes of a class ? > for example: > > (A) > def cal_attr(self, args): > #do some calculations > self.attr = calculated_value > and then if the vlue of attribute is needed, > self.cal_attr(args) > some_var = self.attr > or I can define cal_attr() as follows: > (B) > def cal_attr(self, args): > #do some calculations > return calculated_value > and then, if the value of attribute is needed, > self.attr = self.cal_attr(args) > some_var = self.attr It looks from your example like this attr depends on the args passed to cal_attr. Is it really then an "attribute" of the object, or just the result of a calculation that the object provides? If the latter, you might not want the variable self.attr at all, and just write some_var = self.cal_attr(args) Otherwise self.attr just ends up storing the result of the previous call to cal_attr. Is that useful? Does any other part of the program actually need that? If not don't store it. > (2) > when to use class methods and when to use functions ? I think you just mean methods (Python has something special called "class methods" which are for, er, well, you almost never need them). > In my opinion, both of class methods and functions have advantages and > disadvantages. I have to pass many arguments to a function, which is > annoying. When using class methods, the arguments can be stored as > attributes of the class, which is convenient for later use. But I have > to create an object in advance. That's about right. There's no hard and fast rule. If you need those values again it may be worth storing them, but be wary of storing computed values if there's a chance they're going to get out of date. > I have googled the web, but haven't found too much specific answers. > Can somebody kindly answer my questions or point me to the resources > available on the web ? You're asking good questions and they don't have easy answers. From paul at science.uva.nl Tue May 15 03:38:43 2007 From: paul at science.uva.nl (Paul Melis) Date: Tue, 15 May 2007 09:38:43 +0200 Subject: Trying to choose between python and java In-Reply-To: References: Message-ID: Anthony Irwin wrote: > Hi All, > > I am currently trying to decide between using python or java and have a > few quick questions about python that you may be able to help with. > > #1 Does python have something like javas .jar packages. A jar file > contains all the program files and you can execute the program with java > -jar program.jar > > I am sort of hoping python has something like this because I feel it > makes it easier to distribute between platforms e.g. linux, mac windows > etc. It depends on what you see as the benefit of jar's. If it is purely a matter of packing your whole application up into a single file that you can distribute then there are a number of tools to do that, each with their limits. Search for cx_freeze or py2exe (win32 only). > #2 What database do people recommend for using with python that is easy > to distribute across linux, mac, windows. You could use sqlite, which comes included with Python 2.5. The database files it creates are cross-platform usable and using sqlite saves you the trouble of having to set up a database server > #4 If I write a program a test it with python-wxgtk2.6 under linux are > the program windows likely to look right under windows and mac? Likely yes, but guaranteed no. You'll simply have to test to see how your program comes out on the other platforms. You could use a GUI toolkit that draws its own widgets instead of one that uses the native controls, like wxPython does. PyGTK comes to mind, not sure if it is available on the Mac. > #5 someone said that they used to use python but stopped because the > language changed or made stuff depreciated (I can fully remember which) > and old code stopped working. Is code written today likely to still work > in 5+ years or do they depreciate stuff and you have to update? The changes I can remember from the last couple of years seem to be mostly addition of new features to the language and more standard modules being included in the standard Python distribution. Of course, some things were deprecated, but I think actual code-breaking changes were not that common. But with Python 3.0 (still a long time to go) there will definitely be some incompatibilities, but a lot can probably be fixed automatically using an included conversion tool. Here's a description of the changes in the last 3 releases (2.5, 2.4, 2.3). These span a bit more than 3 years, as 2.3.0 was released on July 29th, 2003, with 2.5.0 on September 19th, 2006. Perhaps you can get a feel for the kind of changes from one release to the next. http://docs.python.org/whatsnew/whatsnew25.html http://www.python.org/doc/2.4/whatsnew/whatsnew24.html http://www.python.org/doc/2.3/whatsnew/ > Also does anyone else have any useful comments about python vs java > without starting a flame war. I guess it all depends on what you're going to use it for and what your goals and restrictions are. I've never seriously used Java (only a bit of C#), but I've been developing a GUI app with wxPython for the last couple of months and am pretty happy with it. Before that, I did lots of tooling with Python (conversion scripts, small computational stuff, etc) and was happy as well. So overall, I'm happy with Python :) It's pretty powerful for a wide variety of applications, comes with a large collection of modules for everything from networking to file compression to encryption to xml parsing to database handling to ... (see http://docs.python.org/lib/lib.html). I find code in Python to be more easily readable because of the absence of unneeded brackets and the fact that code that forms a block is always aligned properly (eeek, possible flame-war subject here). And it saves on the number of type strokes as well. Overall, great stuff! Paul From ptmcg at austin.rr.com Tue May 1 17:00:11 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 1 May 2007 14:00:11 -0700 Subject: I wish that [].append(x) returned [x] In-Reply-To: <46379a41$0$25252$88260bb3@free.teranews.com> References: <46379a41$0$25252$88260bb3@free.teranews.com> Message-ID: <1178053211.209905.154030@h2g2000hsg.googlegroups.com> On May 1, 3:45 pm, Tobiah wrote: > I wanted to do: > > query = "query text" % tuple(rec[1:-1].append(extra)) > > but the append() method returns none, so I did this: > > fields = rec[1:-1] > fields.append(extra) > query = "query text" % tuple(fields) > > -- > Posted via a free Usenet account fromhttp://www.teranews.com query = "query text" % tuple(rec[1:-1] + [extra]) should work. -- Paul From nejtak... Mon May 28 05:54:19 2007 From: nejtak... (Troels Thomsen) Date: Mon, 28 May 2007 11:54:19 +0200 Subject: stdout and threads Message-ID: <465aa6cc$0$52109$edfadb0f@dread11.news.tele.dk> Hello All I have trouble printing to stdout from a thread and main program. Not only will it look strange when they try to print at the same time, that is ok, but i think i see lock-ups. (strange exceptions in Tkinker etc) Or is it an issue with IDLE ? Should I implement a lock'ed / queued version and hook it into the sys.stdout ? (sorry if this has been answered recently in this group) using Python 2.5 (r25:51908 Idle 1.2 tpt From mail at microcorp.co.za Fri May 11 02:51:35 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 11 May 2007 08:51:35 +0200 Subject: Change serial timeout per read References: <1178754931.060029.135800@w5g2000hsg.googlegroups.com> <1178799405.221408.232080@o5g2000hsb.googlegroups.com> Message-ID: <016b01c793a1$c4c1c740$03000080@hendrik> wrote: > What I actually want to do is to respond immediately if the expected > string comes in, but not raise a timeout unless it takes longer than > the maximum time. So if the device I'm communicating with usually > responds in a second, but _can_ take up to 20 seconds, I don't want to > do a sleep(20) then read the port since this will slow everything down > a lot in an average world. I want to keep checking for the expected > string, and act upon it as soon as I've got it, only raising a timeout > if I haven't got it after 20 seconds. I guess to do this using non- > blocking calls I have to do something like: > timesofar = 0 > returnstring = port.read(1) > while len(returnstring) if timesofar >= timeout: > raise SerialException('Timeout') > time.sleep(checkportinterval) > timesofar += checkpointinterval > returnstring += port.read(1) > > This seems rather messy. What I've tried this morning is to produce a > modified version of uspp with a second optional timeout parameter in > its read() function. If this is present, the timeout given is sent to > the port using SetCommTimeouts(). If it's not present, the timeouts > specified when the port was opened are sent. At first sight, with > minimal testing on Windows, this seems to be working, and will leave > my application code a lot cleaner than the non-blocking plus sleep > approach. Of course I don't know whether my method will work on Linux, > and there may be problems I haven't found yet. If it works it works - no problem with that - fight the dragons as you meet them, one at a time. I normally put something like this in a read function (from memory, not tested): error = 0 k = '' try: k = port.read(1) except IoError: error = 1 return error,k For this to work, you have to first unblock the port using fcntl: def unblock(f): """given file f sets unblock flag to true""" fcntl.fcntl(f.fileno(),f.F_SETFL, os.O_NONBLOCK) Then you put a call to the read in a loop, and use time.time() to do your time out, resetting a start_time variable at the start, and every time you get a char, and using short sleeps (millisec or so) after unsuccessful calls to make it less of a busy loop. The side benefit of this is that once you have received a char, you can change gears and use a shorter time out to detect the end of message, in a protocol and state agnostic way. - when the device has stopped sending chars for a little while it has finished saying what it wants to say. - so its easy to write a get_a_reply routine with variable time out, moving the action from the char to the message level: start_time=time.time() s = '' while time.time()-start_time < time_out: error,k = get_a_char(port) if error: time.sleep(0.001) continue s += k # keep the first char start_time = time.time() while time.time() - start_time < 0.005: # inter char time out status,k = get_a_char(port) if error: time.sleep(0.001) continue s +=k start_time = time.time() break return s # return empty string or what was received Something similar works for me on Suse Linux - not sure if fcntl works on windows. And no it isn't pretty. - but then very little of what I write is... - Hendrik From ptmcg at austin.rr.com Thu May 17 19:59:04 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 17 May 2007 16:59:04 -0700 Subject: How to convert a number to binary? In-Reply-To: <1179445546.307017.275850@p77g2000hsh.googlegroups.com> References: <1179444832.775573.55830@y80g2000hsf.googlegroups.com> <1179445546.307017.275850@p77g2000hsh.googlegroups.com> Message-ID: <1179446343.856957.35050@q23g2000hsg.googlegroups.com> On May 17, 6:45 pm, Lyosha wrote: > That's way too complicated... Is there any way to convert it to a one- > liner so that I can remember it? Mine is quite ugly: > "".join(str((n/base**i) % base) for i in range(20) if n>=base**i)[::-1].zfill(1) > Howzis? "".join(map(str,[ int(bool(n & 2**i)) for i in range(20) if n>2**i ] [::-1])) Uses: - integer & to test for bit high or low, returns 2**i - bool(int) to evaluate boolean value of integers - zero -> False, nonzero -> True - int(bool) to convert True->1 and False->0 -- Paul From grante at visi.com Mon May 14 15:16:25 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 14 May 2007 19:16:25 -0000 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: Message-ID: <134hdc9qpdjhbaa@corp.supernews.com> On 2007-05-14, Michael Yanowitz wrote: > Let me guess - the next step will be to restrict the identifiers > to be at most 6 characters long. Of course. If they're any longer than that then you can't fit an entire identifier into a 26-bit CDC 6600 machine register so you can do a compare with a single machine instruction. -- Grant Edwards grante Yow! CHUBBY CHECKER just at had a CHICKEN SANDWICH in visi.com downtown DULUTH! From showell30 at yahoo.com Mon May 28 10:43:37 2007 From: showell30 at yahoo.com (Steve Howell) Date: Mon, 28 May 2007 07:43:37 -0700 (PDT) Subject: itertools.groupby In-Reply-To: <1180330198.466144.197620@j4g2000prf.googlegroups.com> Message-ID: <57139.57754.qm@web33514.mail.mud.yahoo.com> --- Raymond Hettinger wrote: > + The operation of \function{groupby()} is similar > to the \code{uniq} > filter > + in \UNIX{}. [...] Thanks! The comparison of groupby() to "uniq" really clicks with me. To the extent that others like the Unix command line analogy for understanding Python idioms, I compiled the following list, which includes a couple groupby examples from Raymond. >>> 'abacadabra'[:5] # head -5 abaca >>> 'abacadabra'[-5:] # tail -5 dabra >>> [word for word in 'aaa,abc,foo,zzz,cba'.split(',') if 'a' in word] # grep a ['aaa', 'abc', 'cba'] >>> sorted('abracadabra') # sort ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'r', 'r'] >>> list(reversed(sorted('abracadabra'))) # sort -r ['r', 'r', 'd', 'c', 'b', 'b', 'a', 'a', 'a', 'a', 'a'] >>> [k for k, g in groupby(sorted('abracadabra'))] # sort | uniq ['a', 'b', 'c', 'd', 'r'] >>> [(k, len(list(g))) for k, g in groupby(sorted('abracadabra'))] # sort | uniq -c [('a', 5), ('b', 2), ('c', 1), ('d', 1), ('r', 2)] >>> [k for k, g in groupby(sorted('abracadabra')) if len(list(g)) > 1] # sort | uniq -d ['a', 'b', 'r'] ____________________________________________________________________________________Get the Yahoo! toolbar and be alerted to new email wherever you're surfing. http://new.toolbar.yahoo.com/toolbar/features/mail/index.php From aleax at mac.com Mon May 7 23:00:57 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 7 May 2007 20:00:57 -0700 Subject: randomly write to a file References: <1178567497.042096.82940@w5g2000hsg.googlegroups.com> <1178574062.496137.11640@y5g2000hsa.googlegroups.com> Message-ID: <1hxre1l.15ydbuikdt4dsN%aleax@mac.com> Steven D'Aprano wrote: > On Mon, 07 May 2007 14:41:02 -0700, Nick Vatamaniuc wrote: > > > Rohit, > > > > Consider using an SQLite database. It comes with Python 2.5 and higher. > > SQLite will do a nice job keeping track of the index. You can easily > > find the line you need with a SQL query and your can write to it as > > well. When you have a file and you write to one line of the file, all of > > the rest of the lines will have to be shifted to accommodate, the > > potentially larger new line. > > > Using an database for tracking line number and byte position -- isn't > that a bit overkill? > > I would have thought something as simple as a list of line lengths would > do: > > offsets = [35, # first line is 35 bytes long > 19, # second line is 19 bytes long... > 45, 12, 108, 67] > > > To get to the nth line, you have to seek to byte position: > > sum(offsets[:n]) ...and then you STILL can't write there (without reading and rewriting all the succeeding part of the file) unless the line you're writing is always the same length as the one you're overwriting, which doesn't seem to be part of the constraints in the OP's original application. I'm with Nick in recommending SQlite for the purpose -- it _IS_ quite "lite", as its name suggests. BSD-DB (a DB that's much more complicated to use, being far lower-level, but by the same token affords you extremely fine-grained control of operations) might be an alternative IF, after first having coded the application with SQLite, you can indeed prove, profiler in hand, that it's a serious bottleneck. However, premature optimization is the root of all evil in programming. Alex From mensanator at aol.com Wed May 16 01:51:37 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 15 May 2007 22:51:37 -0700 Subject: Interesting list Validity (True/False) In-Reply-To: References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> <1178914190.166662.285410@p77g2000hsh.googlegroups.com> <1178915791.584216.293130@l77g2000hsb.googlegroups.com> <1178918808.091358.233740@o5g2000hsb.googlegroups.com> <1179017740.656323.209590@e51g2000hsg.googlegroups.com> <1179020634.130689.171960@o5g2000hsb.googlegroups.com> <1179031812.090768.248750@l77g2000hsb.googlegroups.com> <1179168081.603409.39970@e51g2000hsg.googlegroups.com> Message-ID: <1179294697.748669.165960@q75g2000hsh.googlegroups.com> On May 15, 9:23???pm, Steven D'Aprano wrote: > On Mon, 14 May 2007 11:41:21 -0700, mensana... at aol.com wrote: > > On May 13, 8:24 am, Steven D'Aprano > > wrote: > >> On Sat, 12 May 2007 21:50:12 -0700, mensana... at aol.com wrote: > > > I intended to reply to this yesterday, but circumstances (see timeit > > results) prevented it. > > >> >> > Actually, it's this statement that's non-sensical. > > >> >> > > >> >> > "if arg==True" tests whether the object known as arg is equal to > >> >> > the object known as True. > >> >> > > > >> >> Not at all, it makes perfect sense. X == Y always tests whether the > >> >> argument X is equal to the object Y regardless of what X and Y are. > > >> > Except for the exceptions, that's why the statement is wrong. > > >> But there are no exceptions. > > > > > Sec 2.2.3: > > Objects of different types, *--->except<---* different numeric types and > > different string types, never compare equal; > > Yes, and all swans are white, except for the black swans from Australia, > but we're not talking about swans, nor are we talking about objects of > different type comparing unequal, we're talking about whether X == Y > means X is equal to Y. > > THERE ARE NO EXCEPTIONS TO THIS, BECAUSE IT IS TRUE BY DEFINITION. > > In Python, the meaning of "equal" is nothing more and nothing less than > "does X == Y return True?". End of story, there is nothing more to > discuss. If it returns True, they are equal. If it doesn't, they aren't. > > If you want to drag in non-Python meanings of "equal", you are wrong to > do so. "Lizzie Windsor", "Queen Elizabeth the Second", "the Queen of > England" and "Her Royal Majesty, Queen Elizabeth II" are all equal in the > sense that they refer to the same person, but it would be crazy to expect > Python to compare those strings equal. > > If you want to complain that lists and tokens should compare equal if > their contents are the same, that's a different issue. I don't believe > you'll have much support for that. > > If you want to complain that numeric types shouldn't compare equal, so > that 1.0 != 1 != 1L != gmpy.mpz(1), that's also a different issue. I > believe you'll have even less support for that suggestion. > > [snip] > > >> > No, they are not "equal". > > >> Of course they are. It says so right there: "a equals d" is true. > > > Ok, but they are an exception to the rule "different types compare > > False". > > You are only quoting part of the rule. The rule says that numeric types > and strings are not included in the "different types" clause. If you > quote the full rule, you will see that it is not an exception to the > rule, it matches perfectly. Uh...ok, I get it...I think. I always thought that when someone said "all primes are odd except 2" it meant that 2 was was an exception. But since the rule specifically says 2 is an exception, it's not an exception. > > Although, the rule as given is actually incomplete, because it only > applies to built-in types. It does not apply to classes, because the > class designer has complete control over the behaviour of his class. If > the designer wants his class to compare equal to lists on Wednesdays and > unequal on other days, he can. (That would be a stupid thing to do, but > possible.) > > [snip] > > >> > The ints > >> > ALWAYS have to be coerced to mpzs to perform arithmetic and this > >> > takes time...LOTS of it. > > >> Really? Just how much time? > > > Can't say, had to abort the following. Returns the count of n/2 and 3n+1 > > operations [1531812, 854697]. > > Maybe you should use a test function that isn't so insane then. Honestly, > if you want to time something, time something that actually completes! > You don't gain any accuracy by running a program for twenty hours instead > of twenty minutes. Actually, I misunderstood the timeit tests, didn't quite realize the difference between .timeit() and .repeat(). And although that number may look insane, it's one I'm quite familiar with so I can tell that everything's working right. My Collatz research tends to be on the fringe, in places where angels fear to tread. > > [snip functions generating the Collatz sequence] > > >> timeit.Timer("x == y", "import gmpy; x = 1; y = gmpy.mpz(1)").repeat() > >> timeit.Timer("x == y", "x = 1; y = 1").repeat() > > >> I don't have gmpy installed here, > > > Good Lord! How do you solve a Linear Congruence? :-) > > In my head of course. Don't you? > > *wink* > > >> so I can't time it, but I look forward to seeing the results, if you > >> would be so kind. > > > I had a lot of trouble with this, but I think I finally got a handle on > > it. I had to abort the previous test after 20+ hours and abort a second > > test (once I figured out to do your example) on another machine after > > 14+ hours. I had forgotten just how significant the difference is. > > > import timeit > > > ## ? ?t = timeit.Timer("a == b", "a = 1; b = 1") ## ? ?u = > > timeit.Timer("c == d", "import gmpy; c = 1; d = gmpy.mpz(1)") > > ## ? ?t.repeat() > > ## ? ?[0.22317417437132372, 0.22519314605627253, 0.22474588250741367] ## > > ? ?u.repeat() > > ## ? ?[0.59943819675405763, 0.5962260566636246, 0.60122920650529466] > > Comparisons between ints take about 0.2 microseconds, compared to about > 0.6 microseconds for small gmpy.mpz values. That's an optimization worth > considering, but certainly not justifying your claim that one should > NEVER compare an int and a mpz "in a loop". If the rest of the loop takes > five milliseconds, who cares about a fraction of a microsecond difference? > > > Unfortunately, this is not a very useful test, since mpz coercion > > appears to vary ny the size of the number involved. > > No, it is a very useful test. It's not an EXHAUSTIVE test. > > (By the way, you're not testing coercion. You're testing the time it > takes to compare the two. There may or may not be any coercion involved.) But isn't the difference between t.repeat() and u.repeat() due to coercion? > > > Although changing t to > > > ## ? ?t = timeit.Timer("a == b", "a = 2**177149-1; b = 2**177149-1") > > > still produces tractable results > > ## ? ?t.repeat() > > ## ? ?[36.323597552202841, 34.727026758987506, 34.574566320579862] > > About 36 microseconds per comparison, for rather large longints. > > > the same can't be said for mpz coercion: > > > ## ? ?u = timeit.Timer("c == d", "import gmpy; c = 2**177149-1; d = > > gmpy.mpz(2**177149-1)") > > ## ? ?u.repeat() > > ## ? ?*ABORTED after 14 hours* > > This tells us that a comparison between large longints and large gmpz.mpz > vales take a minimum of 14 hours divided by three million, I thought it was 14 hours divided by 3. I said I didn't quite understand how timeit worked. > or roughly 17 > milliseconds each. That's horribly expensive if you have a lot of them. Yeah, and that will be the case for large numbers which is why I chose that insane number. In the Collatz test, that works out to about 1.7 million loop cycles. Run time is logarithmic to number size, so truly insane values still have tractable run times. Provided you don't mistakenly ask for 3 million tests thinking it's 3. > > It isn't clear _why_ the comparison takes so long. I'm thinking there may be something wrong. > > [snip] > > > And, just for laughs, I compared mpzs to mpzs, > > > ? ? s = 'import gmpy; a = gmpy.mpz(%d); b = gmpy.mpz(%d)' % (n,n) > > > which ended up faster than comparing ints to ints. > > I'm hardly surprised. If speed is critical, gmpy is likely to be faster > than anything you can do in pure Python. > > [snip] > > >> Even if it is terribly slow, that's just an implementation detail. What > >> happens when Python 2.7 comes out (or Python 3.0 or Python 99.78) and > >> coercion from int to mpz is lightning fast? Would you then say "Well, > >> int(1) and mpz(1) used to be unequal, but now they are equal?". > > > Are you saying I should be unconcerned about implementation details? > > That it's silly of me to be concerned about implementation side effects > > due to mis-matched types? > > Of course not. But the discussion isn't about optimization, that's just > an irrelevant side-track. > > >> Me, I'd say they always were equal, but previously it used to be slow > >> to coerce one to the other. > > > So, when you're giving advice to the OP you don't feel any need to point > > this out? That's all I'm trying to do, supply some "yes, but you should > > be aware of..." commentary. > > Why on Earth would I need to mention gmpy.mpz()? Does the OP even use > gmpy? You were the one who brought gmpy into the discussion, not him. Why > not give him a lecture about not repeatedly adding strings together, or > using << instead of multiplication by two, or any other completely > irrelevant optimization? My favorite, by the way, is that you can save > anything up to an hour of driving time by avoiding Hoddle Street during > peak hour and using the back-streets through Abbotsford, next to Yarra > Bend Park and going under the Eastern Freeway. Perhaps I should have > raised that as well? > > >> In any case, what you describe is a local optimization. Its probably a > >> good optimization, but in no way, shape or form does it imply that > >> mpz(1) is not equal to 1. > > > It's a different type. It is an exception to the "different types > > compare False" rule. > > What does this have to do with your ridiculous claim that mpz(1) is not > equal to 1? It clearly is equal. > > > That exception is not without cost, the type mis-match > > causes coercion. > > Any comparison has a cost. Sometimes its a lot, sometimes a little. That > has nothing to do with equality. > > >> There's nothing false about it. Ask any mathematician, does 1 equal > >> 1.0, and they will say "of course". > > > And if you ask any mathematician, he'll say that (1,) is equal to [1]. > > I'd like to find the mathematician who says that. The first thing he'd > say is "what is this (1,) notation you are using?" and the second thing > he'd ask is "equal in what sense?". > > Perhaps you should ask a mathematician if the set {1, 2} and the vector > [1, 2] are equal, and if either of them are equal to the coordinate pair > (1, 2). > > > That's the difference between a mathematician and a programmer. A > > programmer will say "of course not, the int has to be coered." > > A C programmer maybe. > > [snip] > > >> Numeric values are automatically coerced because that's more practical. > >> That's a design decision, and it works well. > > > And I'm not saying it shouldn't be that way. But when I wrote my Collatz > > Functions library, I wasn't aware of the performance issues when doing > > millions of loop cycles with numbers having millions of digits. I only > > found that out later. Would I have gotten a proper answer on this > > newgroup had I asked here? Sure doesn't look like it. > > If you had asked _what_? Unless you tell me what question you asked, how > can anyone guess what answer you would have received? > > If you had asked a question about optimization, you surely would have > received an answer about optimization. > > If you asked about string concatenation, you would have received a > question about string concatenation. > > If you had asked a question about inheritance, you would have received an > answer about inheritance. > > See the pattern? > > > BTW, in reviewing my Collatz Functions library, I noticed a coercion I > > had overlooked, so as a result of this discussion, my library is now > > slightly faster. So some good comes out of this argument after all. > > >> As for gmpy.mpz, since equality tests are completely under the control > >> of the class author, the gmpy authors obviously wanted mpz values to > >> compare equal with ints. > > > And they chose to do a silent coercion rather than raise a type > > exception. > > It says right in the gmpy documentation that this coercion will be > > performed. > > What it DOESN'T say is what the implications of this silent coercion > > are. > > OF COURSE a coercion takes time. This is Python, where everything is a > rich object, not some other language where a coercion merely tells the > compiler to consider bytes to be some other type. If you need your hand- > held to the point that you need somebody to tell you that operations take > time, maybe you need to think about changing professions. > > The right way to do this is to measure first, then worry about > optimizations. The wrong way is to try to guess the bottlenecks ahead of > time. The worse way is to expect other people to tell you were your > bottlenecks are ahead of time. > > > > >> >> Since both lists and tuples are containers, neither are strings or > >> >> numeric types, so the earlier rule applies: they are different > >> >> types, so they can't be equal. > > >> > But you can't trust a==d returning True to mean a and d are "equal". > > >> What does it mean then? > > > It means they are mathematically equivalent, which is not the same as > > being programatically equivalent. Mathematical equivalency is what most > > people want most of the time. > > I think that by "most people", you mean you. > > > Not all of the people all of the time, > > however. For example, I can calculate my Hailstone Function parameters > > using either a list or a tuple: > > >>>> import collatz_functions as cf > >>>> print cf.calc_xyz([1,2]) > > (mpz(8), mpz(9), mpz(5)) > >>>> print cf.calc_xyz((1,2)) > > (mpz(8), mpz(9), mpz(5)) > > > But [1,2]==(1,2) yields False, so although they are not equal, they ARE > > interchangeable in this application because they are mathematically > > equivalent. > > No, they aren't mathematically equivalent, because Python data structures > aren't mathematical entities. (They may be _similar to_ mathematical > entities, but they aren't the same. Just ask a mathematician about the > difference between a Real number and a float.) > > They are, however, both sequences, and so if your function expects any > sequence, they will both work. > > [snip] > > >> I never said that there was no efficiency differences. Comparing X with > >> Y might take 0.02ms or it could take 2ms depending on how much work > >> needs to be done. I just don't understand why you think that has a > >> bearing on whether they are equal or not. > > > The bearing it has matters when you're writing a function library that > > you want to execute efficiently. > > Which is true, but entirely irrelevant to the question in hand, which is > "are they equal?". Hey, here's an idea...let's forget the whole thing. > > -- > Steven. From jstroud at mbi.ucla.edu Wed May 23 20:46:26 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 23 May 2007 17:46:26 -0700 Subject: read file to a dictionary In-Reply-To: <1179962203.201472.104500@q19g2000prn.googlegroups.com> References: <1179962203.201472.104500@q19g2000prn.googlegroups.com> Message-ID: rohit wrote: > i want to implement a dictionary in python > the query is : > without explicitly doing the following steps > 1. reading from file to list > 2. processing list to dictionary > is there a module or a built in function that helps me "read" a file > directly into a dictionary > or any module that implements the above 2 steps > > thanks > rohit > No one can actually figure out exactly what you want because you speak in partial thoughts and vagaries. However, my amazing mind-reading abilities are picking up the following paranormal conveyances: ConfigParser cPickle shelve I leave it to you to interpret them as I am just a messenger. James From rurpy at yahoo.com Tue May 15 17:44:10 2007 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 15 May 2007 14:44:10 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649dd55$0$23144$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <1179265450.419865.180810@k79g2000hse.googlegroups.com> On May 15, 11:08 am, Carsten Haese wrote: snip > Once the students learn Python and realize that there are lots of Python > resources "out there" that are only in English, that will be a > motivation for them to learn English. Requiring all potential Python > programmers to learn English first (or assuming that they know English > already) is an unacceptable barrier of entry. One the big concerns seems to be a hypothesized negative impact on code sharing. Nobody has considered the positive impact resulting from making Python more accessible to non-English speakers, some of whom will go on to become wiling and able to contribute open "English python" code to the community. This positive impact may well outweigh the negative. From robin at alldunn.com Tue May 15 15:35:36 2007 From: robin at alldunn.com (Robin Dunn) Date: Tue, 15 May 2007 12:35:36 -0700 Subject: No subject Message-ID: <464A0B88.9050807@alldunn.com> Announcing ---------- The 2.8.4.0 release of wxPython is now available for download at http://wxpython.org/download.php. This release includes a number of bug fixes, updates to some contribs and other improvements. Source code is available, as well as binaries for both Python 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.4.0 ------------------ wxGTK: Make wx.NO_BORDER style work with wx.RadioBox (patch 1525406) Update to 1.0 of TreeMixin. wx.lib.customtreectrl: Patch from Andrea that fixes the following problems/issues: * ZeroDivisionError when using the Vista selection style and calling SelectItem; for some strange reason, sometimes the item rect is not initialized and that generates the ZeroDivisionError when painting the selection rectangle; * Added a DeleteWindow method to GenericTreeItem class, for items that hold a widget next to them; * Renamed CustomTreeCtrl method IsEnabled to IsItemEnabled, otherwise it conflicts with wx.Window.IsEnabled; * Now CustomTreeCtrl behaves correctly when the widget attached to an item is narrower (in height) than the item text; wx.lib.flatnotebook: Patch from Andrea that implements the following: * A new style FNB_FF2: my intentions were to make it like Firefox 2, however it turned out to be an hybrid between wxAUI notebook glose style & FF2 ...I still think it looks OK. The main purpose for making it more like wxAUI is to allow applications that uses both to have same look and feel (or as close as it can get...); * Changed the behavior of the left/right rotation arrows to rotate single tab at a time and not bulk of tabs; * Updated the demo module. XRCed now uses a wx.FileHistory object for managing the recent files menu. wx.DateSpan and wx.TimeSpan now use lower case property names in order to not conflict with the same named static methods that already existed. wx.aui.PyAuiDocArt and wx.aui.PyAuiTabArt can now be derived from in wxPython and plugged in to wx.AUI. XRCed has a new experimental feature to add controls by draging icons from the tool palette to the test window. Mouse position is tracked to highlight the future parent of the new item. Updates to MaskedEdit controls from Will Sadkin: maskededit.py: Added parameter option stopFieldChangeIfInvalid, which can be used to relax the validation rules for a control, but make best efforts to stop navigation out of that field should its current value be invalid. Note: this does not prevent the value from remaining invalid if focus for the control is lost, via mousing etc. numctrl.py, demo / MaskedNumCtrl.py: In response to user request, added limitOnFieldChange feature, so that out-of-bounds values can be temporarily added to the control, but should navigation be attempted out of an invalid field, it will not navigate, and if focus is lost on a control so limited with an invalid value, it will change the value to the nearest bound. combobox.py: Added handler for EVT_COMBOBOX to address apparently inconsistent behavior of control when the dropdown control is used to do a selection. textctrl.py Added support for ChangeValue() function, similar to that of the base control, added in wxPython 2.7.1.1. Update to latest FloatCanvas from Chris Barker. The pywxrc tool now properly supports generating classes for menus and menubars, and also creating attributes for menus, menubars and menu items. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From thomas.guest at gmail.com Tue May 22 04:44:41 2007 From: thomas.guest at gmail.com (tag) Date: 22 May 2007 01:44:41 -0700 Subject: doctest environment question In-Reply-To: References: <1179762737.153434.143030@b40g2000prd.googlegroups.com> <1179775483.685881.236940@x18g2000prd.googlegroups.com> <1179818466.394663.222390@k79g2000hse.googlegroups.com> Message-ID: <1179823481.228631.229790@w5g2000hsg.googlegroups.com> On 22 May, 08:59, Peter Otten <__pete... at web.de> wrote: [snip] > inspect.getmodule(f) returns None because f() is not defined in a module. OK. But there was a module when I ran interactively? > You can either move f() to a helper module and then > > from helper_module import f Yes. > or modify anouncement_function() to not rely on that non-existent module > > >>> def announce_function(f): > > ... " Rebind f within a module so that calls to f are announced. " > ... f.func_globals[f.__name__] = announce(f) > ... I think this is what I should be doing. Very nice! You're modifying f's own gloabl environment. > > > Let's give it a try. This next works fine in an interactive Python > > session but fails when doctested. > > >>>> def h(): pass > > ... > >>>> announce_function(h) > >>>> h() > > Calling h > > Even when it works, implicitly modifying global variables is bad style. I have to admit it didn't feel right, but I didn't come up with the idea you present. Thanks again for your help. From robert.rawlins at thinkbluemedia.co.uk Mon May 21 05:29:38 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Mon, 21 May 2007 10:29:38 +0100 Subject: Shared Memory Space - Accross Apps & Network Message-ID: <003a01c79b8a$8f1f8c30$ad5ea490$@rawlins@thinkbluemedia.co.uk> Hello Guys, I've got an application that runs on an embedded system, the application uses a whole bunch or dicts and other data types to store state and other important information. I'm looking to build a small network of these embedded systems, and I'd love to have them all share the same set or data. Is it possible to share the applications variables across multiple applications, so certain lists are like a 'pool' written to by the different systems? I'm sure I could cobble something together by writing the lists to shared files instead of keeping them in RAM, but that feels a little inefficient. I'd like to try and configure some form of master/slave relationship between my applications if possible. Thanks for any ideas you guys might have. Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From lokesh.jagasia at gmail.com Mon May 7 03:00:38 2007 From: lokesh.jagasia at gmail.com (lokesh.jagasia at gmail.com) Date: 7 May 2007 00:00:38 -0700 Subject: N00b question on Py modules Message-ID: <1178521238.333095.111370@h2g2000hsg.googlegroups.com> Hi. Sorry to sound like a noob but that's what I am when it comes to Python. I just wrote the below module and it behaves funny. My python module: _exitcode = 0 def setExitCode(): _exitcode = 1 if __name__ == '__main__': print _exitcode setExitCode() print _exitcode Actual O/P: 0 0 I expected to see an output of 0 followed by 1. But it turns out that the _exitcode variable is not changed at all. It seems that setExitCode() might be editing a local copy of the _exitcode variable. But then, how do I tell it to change the value of the module variable and not its local variable. I've been through the modules section of Python docs and a few ebooks as well, all suggest that it shouldn't be working this way. Please help out ppl. Thanks From jbmccrann at gmail.com Wed May 2 23:05:23 2007 From: jbmccrann at gmail.com (Midex) Date: 2 May 2007 20:05:23 -0700 Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? Message-ID: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> 100% EVIDENCE - SEE THE TRUTH FINALLY - ON THE GROUND VIDEO WITNESSES http://www.youtube.com/watch?v=YNN6apj5B2U In order to appreciate just what Truthers are talking about when they cry Treason over WTC7, you would want to see this History Channel documentary on what they claim happened to WTC7: http://www.youtube.com/watch?v=TVSxeJH_RCY Ben Chertoff can't get his story straight http://www.youtube.com/watch?v=9YND7XocMocj LIES LIES LIES LIES LIES 9/11 Truth Focoist Revolution. "When peaceful revolution is made impossible, violent revolution is inevitable" - Martin Luther King. How long shall they kill our prophets? Look up Focoism. Write about it. Spread the method. It will be how this revolution will take shape. From gagsl-py2 at yahoo.com.ar Tue May 29 15:08:34 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 29 May 2007 16:08:34 -0300 Subject: how to print the GREEK CAPITAL LETTER delta under utf-8 encoding References: <1180414659.066482.236370@i38g2000prf.googlegroups.com> <465BBB49.6000803@v.loewis.de> <1180421212.151587.118020@r19g2000prf.googlegroups.com> <465BD0AA.9080805@v.loewis.de> <1180462611.5376.13.camel@localhost> Message-ID: En Tue, 29 May 2007 15:16:52 -0300, Ragnar Ouchterlony escribi?: > If I for some reason can't open the object myself or needs encoding on > other file-like objects, I think the following wrapper function is of > use (it essentially does what codecs.open() does but takes a file-object > instead of a filename): > > def filewrapper(f, encoding=None, errors='strict'): > if encoding is None: > return f > > info = codecs.lookup(encoding) > srw = codecs.StreamReaderWriter(f, info.streamreader, > info.streamwriter, errors) > # Add attributes to simplify introspection > srw.encoding = encoding > return srw > > I find this especially useful for changing how stdout and friends does > it's encoding, e.g: > >>>> sys.stdout = filewrapper(sys.stdout, 'utf-8') >>>> print u"??? \N{GREEK CAPITAL LETTER DELTA}" > > Useful if you don't want to append .encode() to everything you print out > that potentially can contain non-ascii letters. Isn't the same as codecs.EncodedFile? -- Gabriel Genellina From revuesbio at gmail.com Sun May 6 17:44:07 2007 From: revuesbio at gmail.com (revuesbio) Date: 6 May 2007 14:44:07 -0700 Subject: msbin to ieee Message-ID: <1178487847.671199.108140@h2g2000hsg.googlegroups.com> Hi Does anyone have the python version of the conversion from msbin to ieee? Thank u From bbxx789_05ss at yahoo.com Wed May 23 15:31:58 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 23 May 2007 12:31:58 -0700 Subject: Namespace issue In-Reply-To: Message-ID: <1179948718.084531.262340@q75g2000hsh.googlegroups.com> On May 23, 12:20 pm, Ritesh Raj Sarraf wrote: > As per my understanding, the bad part is that on every call of the method > FetchData(), an import would be done. > > To not let that happen, I can put the import into __init__(). But when I put > in there, I get a NameError saying that my_module is not available even > though it got imported. > All I noticed is that the import has to be part of the method else I end up > getting a NameError. But always importing my_module is also not good. How about something like this: class Dog(object): myimport = None def __init__(self): if not Dog.myimport: print "importing..." import os Dog.myimport = os def test(self): print Dog.myimport.listdir("./") d = Dog() d.test() print print d2 = Dog() d2.test() --output:--- importing... [a bunch of files] [a bunch of files] From cai.haibin at gmail.com Mon May 28 02:01:32 2007 From: cai.haibin at gmail.com (james_027) Date: 27 May 2007 23:01:32 -0700 Subject: gui application on cross platform Message-ID: <1180332092.551838.258440@z28g2000prd.googlegroups.com> Hi, I am using delphi to develop gui application, and wish to make a shift to python. here are some of my question/concern... 1. is python develop gui application a cross platform? just like java swing? 2. delphi makes things easy for me like coding for a specific event on a specific component, could it be the same for python? 3. are there cool library of component like in delphi available for python that will make database application more usesable? 4. where do I start the learning curve? I did some research and I don't know which one to take among wxwdiget, pygtk, and etc. Thanks james From adrian_p_smith at yahoo.com Mon May 7 02:10:23 2007 From: adrian_p_smith at yahoo.com (Adrian Smith) Date: 6 May 2007 23:10:23 -0700 Subject: CGI python use "under a curse" In-Reply-To: References: <1178512216.246621.38960@p77g2000hsh.googlegroups.com> Message-ID: <1178518223.618267.325710@e51g2000hsg.googlegroups.com> On May 7, 2:30 pm, Steven D'Aprano wrote: > On Sun, 06 May 2007 21:30:16 -0700, Adrian Smith wrote: > It is NOT the same error. There are NO syntax errors in the script, there > is a runtime error. The so-called administrator is wrong: you can't use > Perl to test just any old CGI scripts. They have to be written in Perl. Well, I thought that, but you know what happens to newbies who come out with such opinions forcefully. Maybe they have special magic perl which parses python. > I see from the source code on your page that you have a line: > > > > You have two lines in your cgi script: > > form = cgi.FieldStorage() > print form["essay"].value > > Having never done cgi programming, I'm not sure what the problem is, but > after reading help(cgi) I'll take a stab in the dark and say try this: > > print form.value > > It might also help for you to try this: > > print form.keys() Both give me the same ISE, alas. > Good luck with the "admins" at your hosting company. Well, it *is* free, and there aren't that many free ones that offer Python. My paid-for host has sent me a message to say they're ruminating on my issues, though, so I live in hope. From mail at microcorp.co.za Wed May 16 02:22:17 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 16 May 2007 08:22:17 +0200 Subject: tkinter button state = DISABLED References: <1179163831.016938.79840@w5g2000hsg.googlegroups.com><1179175592.011635.103980@e51g2000hsg.googlegroups.com> Message-ID: <03f601c7979e$83559740$03000080@hendrik> "Gabriel Genellina" wrote: >Maybe there is a confusion here. You code above means that, when the event >"The leftmost MOUSE BUTTON was released" happens over your BUTTON WIDGET >b, your function will be called. I have never seen this working in Tkinter, unless the button was pressed on the widget in question - and worse, once you have clicked down on a ButtonRelease binding you can move the mouse pointer anywhere you like, even out of the application and when you release it, the bound function is called... Its either a bug or a feature, I don't know. - Hendrik From okyoon at stanford.edu Fri May 11 14:24:41 2007 From: okyoon at stanford.edu (OhKyu Yoon) Date: Fri, 11 May 2007 11:24:41 -0700 Subject: A newbie question about FileDialog in wxPython Message-ID: Hi! I am opening files using the wx.FileDialog in wxPython. I want to modify the FileDialog such that some information about a highlighted file is displayed before I decide to open the file. This is what I tried: class ModifiedFileDialog(wx.FileDialog): def __init__(self,parent,message,wildcard,style): wx.FileDialog(self,parent,message,"","",wildcard,style) width,height = self.GetSizeTuple() self.SetSizeWH(width,height+100) # and so on... I get an error when I try to change the size or make other changes. Could someone tell me how to make this work or direct me to some reference? Thank you. From http Tue May 1 01:51:23 2007 From: http (Paul Rubin) Date: 30 Apr 2007 22:51:23 -0700 Subject: re-importing modules References: <8%pZh.18192$Kd3.76@newssvr27.news.prodigy.net> <1177962288.575008.48490@q75g2000hsh.googlegroups.com> <1177967919.968338.3300@l77g2000hsb.googlegroups.com> <1177997329.701861.143290@e65g2000hsc.googlegroups.com> Message-ID: <7xejm1w0pw.fsf@ruckus.brouhaha.com> Graham Dumpleton writes: > That it doesn't reload a parent when a child changes may be fine in an > interactive debugger, but can cause problems if not done where > automatic reloading is being done in a long running web application > where you want to avoid server restarts. Oh that sounds horrid. If you really have to do something like that, it's time to consider adding serious hot-patching capability as I believe Erlang has done. Better is to start a new server process and transfer the live session data and active connections to it through IPC mechanisms. I've had an open RFE for many years (#814689) about ancillary messages on AF_UNIX sockets, which let you pass file descriptors (such as those attached to open TCP connections) between processes. It actually came up in conversation with someone about something I'm currently working on, so maybe I'll have reason to try coding it sometime soon (that's not at all definite though). From nick at craig-wood.com Fri May 11 04:30:03 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Fri, 11 May 2007 03:30:03 -0500 Subject: High resolution sleep (Linux) References: <1178274122.142071.91740@y5g2000hsa.googlegroups.com> <8l90i.911$UU.403@newssvr19.news.prodigy.net> <1178808104.915724.176100@n59g2000hsh.googlegroups.com> Message-ID: Bart wrote: > What about C module with usleep,nanosleep? Unlikely to help! It is an linux OS limit that the minimum sleep time is 1/HZ. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From dfabrizio at aviom.com Sat May 26 18:46:26 2007 From: dfabrizio at aviom.com (Dan Fabrizio) Date: Sat, 26 May 2007 18:46:26 -0400 Subject: Using python for a CAD program Message-ID: <000301c79fe7$b1e22c80$6501a8c0@corp.aviominc.com> Hello, I saw your post from last year about using python for a EE CAD program. What were your conclusions? I'm thinking about converting a Java CAD program I developed to Python with wxPython and C. I want to use C for the database storage and manipulation and wxPython for the GUI and user scriptable interface. I have also done something like with Tcl/Tk and C but think Python is much more modern and wxPython widgets look very professional and OO programming is very important to me. What did you decide to do? What language and what GUI libraries did you pick? I would appreciate any suggestions or advice. Regards, Dan Fabrizio ASIC Engineer Aviom Inc. 1157 Pheonixville Pike. West Chester, Pa. 19380 Phone 610 738 9005 ext. 292 Fax 610 738 9950 From iltchevi at gmail.com Wed May 2 19:35:36 2007 From: iltchevi at gmail.com (ici) Date: 2 May 2007 16:35:36 -0700 Subject: win32com.client Excel Color Porblem In-Reply-To: References: Message-ID: <1178148936.556908.189210@n59g2000hsh.googlegroups.com> On May 3, 1:37 am, Ray wrote: > Hi, > > I need to use cell's background color. > > when I record a macro from excel, it shows: > > Rows("7:7").Select > With Selection.Interior > .ColorIndex = 8 > .Pattern = xlSolid > > how do I run it from python win32com ? > xlApp.ActiveSheet.Rows("7:7").ColorIndex won't work. > > Thanks for any Help. > > Ray > > PS: where or how to find a win32com reference? My Excel Template :) + Rows # -*- encoding:utf-8 -*- import win32com.client try: import psyco; psyco.full() except ImportError: pass try: app = win32com.client.Dispatch("Excel.Application.11") # Excel 2003 except com_error: try: app = win32com.client.Dispatch("Excel.Application.10") # Excel XP except com_error: try: app = win32com.client.Dispatch("Excel.Application.9") # Excel 2000 except com_error: try: app = win32com.client.Dispatch("Excel.Application.8") # Excel 97 except com_error: app = win32com.client.Dispatch("Excel.Application") # Excel 5.0? # Or raise "No Office ..." app.Visible = True wbk = app.Workbooks.Add() app.DisplayAlerts = False while wbk.Worksheets.Count > 1: wbk.Worksheets[0].Delete() wbk.Worksheets[0].Name = "SHIT" sht = wbk.Worksheets[0] # Containers starts with 0! sht.Name += "$" # Rows rng = sht.Rows(7) rng.Interior.ColorIndex = 6 sht.Rows(8).Interior.ColorIndex = 8 # Rows End app.DisplayAlerts = True wbk.SaveAs(r"c:\temp\test.xls") app.Quit() From steve at holdenweb.com Fri May 25 22:14:21 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 25 May 2007 22:14:21 -0400 Subject: conditionally creating functions within a class? In-Reply-To: <163f0ce20705251744j5c728e9fn53585fe0c9250827@mail.gmail.com> References: <163f0ce20705251744j5c728e9fn53585fe0c9250827@mail.gmail.com> Message-ID: kaens wrote: > So, I have a class that has to retrieve some data from either xml or > an sql database. > This isn't a problem, but I was thinking "hey, it would be cool if I > could just not define the functions for say xml if I'm using sql", so > I did some fiddling around with the interpreter. > > First, I try conditionally creating a function, period: > > a = 'a' > > if(a == 'a') > def b: > print "hello" > else: > def c: > print "goodbye" > > this works fine. b is defined, c is not. change the value of a and b > gets defined and not c (sorry for the one-letter variables here, but > for these little examples I don't think they detract much) > > then I try doing this within a function: > > class test: > def __init__(self,which): > self.which = which > > if(self.which == 'a'): > def b: > print "hello" > else: > def c: > print "goodbye" > The problem here is that the "if" statement executes in class scope, which means at the same level at which the "def" statements define the methods. Unfortunately there is no "self" defined, as "self" is a method argument (whose value is provided automatically by the interpreter when a method call is made on a specific instance of the class). So it's out of scope. You could try to define the methods inside __init__, but that isn't really appropriate because __init__ runs each time a new instance requires initialization, and one of the primary ideas behind object orientation is that the class defines the same methods for all instances. You could override the methods in each instance, but this is all taking you further and further away from your relatively simple engineering goal. > tester = test('a') > tester.b() > > This doesn't "compile", says "Name 'self' is not defined". I assume > this is because of scope, something like it hasn't made the object > yet, so there is no self attribute. . . but I thought that python > wouldn't even bother reading that class statement until I tried to > make a test object, and that it would do the __init__ function before > anything else, so I'm a bit fuzzy here. > In Python the only non-executable statement is "global", so the class definition is executed when it's encountered. This is what give rise to the problems, which you have correctly diagnosed as being related to scoping issues. > Next I try creating the functions through functions: > > class test: > def __init__(self, which): > self.which = which > self.chooser() > > def chooser(self): > if( self.which == 'a'): > def b(self): > print "hello" > else: > def c(self): > print "goodbye" > > tester = test('a') > tester.b() > > this tells me "instance has no attribute b. > And it isn't lying. The problem is that "def b" is executed within the chooser() method, so it's local to that method and invisible to the class scope. > I'm pretty sure this is all a scoping error of some sort (I could be > wrong), but I don't have my head wrapped around it at all. Anyone with > more knowledge care to explain what's going on? > > Also, would there be a way to conditionally create functions in a > class? It doesn't really matter, but it'd be nice if I weren't > creating functions that I absolutely will not need for certain > instances at runtime Here I'd ask you to take a step back. What you really need is two parallel modules or classes, one of which handles SQL inputs and the other of which handles XML inputs. My own approach would be to define two modules with the same API and then import one or the other. Something like this: if intype == "a": import sqlmodule as myinmod # do SQL-specific stuff, if any else: import xmlmodule as myinmod # do XML-specific stuff, if any You can then call the functions and classes defined in the imported module as myinmod.func() and someinstance = myinmod.classname() Since you only import one module, you don't execute the definitions in the unused module at all, and as long as the APIs really are parallel you can write code that doesn't care which one it uses. There are other approaches you could take, but if this would answer your needs then I'd suggest you consider 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From aleax at mac.com Fri May 11 02:09:26 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 10 May 2007 23:09:26 -0700 Subject: which is more pythonic/faster append or +=[] References: <1hxtelz.7f6rvnw4cyxmN%aleax@mac.com> <1178723595.516379.18180@u30g2000hsc.googlegroups.com> <1hxuz03.husyup2cjk81N%aleax@mac.com> Message-ID: <1hxx6xj.avyhtu16rx0knN%aleax@mac.com> Peter Otten <__peter__ at web.de> wrote: > Note the -s before the initialization statement that Alex meant to add but > didn't. If that is missing Yep, sorry for erroneously skipping the -s! Alex From jstroud at mbi.ucla.edu Mon May 14 18:00:35 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 14 May 2007 15:00:35 -0700 Subject: customary way of keeping your own Python and module directory in $HOME In-Reply-To: <1179175513.896546.313500@y80g2000hsf.googlegroups.com> References: <1179175513.896546.313500@y80g2000hsf.googlegroups.com> Message-ID: jmg3000 at gmail.com wrote: > What's the customary way to keep your own local Python and package > directory? For example, when you're on a server where you don't have > root access, and everything must go in your home directory. > > * What directories do you create? > * What environment variables do you set? > * What config files do you keep? > * Does that setup work with distutils and setuptools? What special > options do you need to pass to these tools when installing modules for > everything to work right? > > Please, share your tips. > You can do more than you can imagine as non-root even if you have hyper-paranoid sysadmins who don't know how to protect infrastructure without shackling the users. I don't know about windoze (pro-windoze complainers: yep, I'm spelling it wrong on purpose, please complain elsewhere about my anti-windoze spelling :P -- If you want to be a pro-windoze speller, take the time to give your own answers instead of complaining all the time), but on *nix, you can compile python with the "--prefix=" option set to a directory in your home dir and install there. Because python is compiled with the prefix, you will not need to adjust the path if you add modules to the site-packages directory. If you have your own modules, but they aren't ready for site-packages, you can alter PYTHONPATH to point at your staging directory. I recommend having your own python install if you want a comprehensive approach. Sometimes you need to build your own Tcl/Tk and blt-wish if you have a linux version that predates the python dependency requirements, though. If you know the dependencies, its all very "configure --prefix= ; make ; make install", with proper settings of LD_LIBRARY path. Doesn't seem like hyper-paranoid sysadmining is all that efficient, does it? James From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri May 11 17:02:01 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 11 May 2007 23:02:01 +0200 Subject: Simulating simple electric circuits References: <5a9838F2nlbanU1@mid.individual.net> <5ae44aF2ku9rtU1@mid.individual.net> Message-ID: <5ak3u9F2odts2U1@mid.individual.net> Dave Baum wrote: > Sounds reasonable. Depending on the size of your network, I might > not worry too much about precomputing and saving information. Thanks. Yes, I'm actually testing it presently without any optimizations and it runs very well. > If your circuit has loops in it (where the output of a later relay > circles back to an earlier relay's coil), then it is possible for > the circuit to oscillate, so you might have to be careful about > this. That's no substancial problem, with real relay circuits this happens sometimes too :) (even in the systems I'm modelling) After all, I'm quite pleased now with how well the last approach I mentioned works. I've been able to model a medium complex switching sequence today, and it worked flawlessly. (The only problem I have now arises when I make relays react delayed, using Twisted's reactor.callLater. Sometimes, a relay gets current and loses it shortly after, but the event loop in rare cases executes the status change functions the other way round ("no current", then "current"). I've been trying to fix that by detection if a timer already runs. Anyhow, the inconsistencies only vanish if I let the relays react delayless again. I'm going to have to look into this further ...) Regards, Bj?rn P.S.: If anyone happens to be interested in details, just ask, I'll post some code. -- BOFH excuse #319: Your computer hasn't been returning all the bits it gets from the Internet. From rsa4046 at gmail.com Mon May 21 01:11:46 2007 From: rsa4046 at gmail.com (LokiDawg) Date: 20 May 2007 22:11:46 -0700 Subject: trouble with pyvtk In-Reply-To: <1179466886.812669.95170@w5g2000hsg.googlegroups.com> References: <1179462146.957576.193110@o5g2000hsb.googlegroups.com> <1179466886.812669.95170@w5g2000hsg.googlegroups.com> Message-ID: <1179724306.614416.166960@z24g2000prd.googlegroups.com> On May 18, 12:41 am, obau... at gmail.com wrote: > > This could be very well be a bug where infinite recursion happens, but > see if changing the recursion limit fixes this: > >>> import sys > >>> sys.getrecursionlimit() > 1000 > >>> sys.setrecursionlimit(10000) > Regards, > Ondrej Thanks for the tip, Ondrej. Unfortunately, this didn't do it, as pytvk still ends up at the same place: File "/usr/lib/python2.4/site-packages/pyvtk/common.py", line 149, in get_datatype r = self.get_datatype(o) File "/usr/lib/python2.4/site-packages/pyvtk/common.py", line 140, in get_datatype if is_int(obj): return self.default_int RuntimeError: maximum recursion depth exceeded I would be interested if anyone else has this difficulty with pyvtk-- Regards, Rolf From aaronwmail-usenet at yahoo.com Mon May 7 11:42:41 2007 From: aaronwmail-usenet at yahoo.com (aaronwmail-usenet at yahoo.com) Date: 7 May 2007 08:42:41 -0700 Subject: SkimpyGimpy PNG canvas w/ Javascript mouse tracking Message-ID: <1178552561.117926.143230@l77g2000hsb.googlegroups.com> ANN: SkimpyGimpy PNG canvas has Javascript mouse tracking The SkimpyGimpy PNG image canvas now can generate Javascript data structures which allow HTML pages to intelligently respond to mouse events over the image. Please read about the SkimpyGimpy Canvas and look at the mouse tracking example here: http://skimpygimpy.sourceforge.net/canvas.html The SkimpyGimpy main page is here: http://skimpygimpy.sourceforge.net/ BACKGROUND: SkimpyGimpy is a collection of tools for generating HTML visual, PNG image, and WAVE audio components for use in web based applications including CAPTCHA implementations (Completely Automated Public Turing test to tell Computers and Humans Apart) and PNG image creation tools with Javascript mouse tracking support. I hope you like. -- Aaron Watters === Sometimes say sometimes. From laurent.pointal at limsi.fr Wed May 2 09:35:27 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Wed, 02 May 2007 15:35:27 +0200 Subject: What do people use for code analysis. In-Reply-To: References: Message-ID: Steven W. Orr a ?crit : > Lots of code, calls to, calls by, inheritance, multiple tasks, etc. > > What do people use to figure out what's happening? > > TIA > I've collected some links over time: http://www.limsi.fr/Individu/pointal/python.html#liens-metaprog You may look at # depgraph - graphe de d?pendances entre modules # coverage - a Python module that measures code coverage during Python execution # pycover - a python coverage tool # pycount - m?trique de lignes sources Python # depgraph - generating python module dependency graphs # pycallgraph - g?n?ration du graphe d'appels pour les programmes Python (n?cessite GraphViz). From michael.forbes at gmail.com Fri May 4 16:14:42 2007 From: michael.forbes at gmail.com (Michael) Date: 4 May 2007 13:14:42 -0700 Subject: Why are functions atomic? In-Reply-To: <1178277194.559817.143360@o5g2000hsb.googlegroups.com> References: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> <1178044821.864741.235260@o5g2000hsb.googlegroups.com> <1178063341.779617.289690@o5g2000hsb.googlegroups.com> <1178065685.161372.81790@y80g2000hsf.googlegroups.com> <1178083318.404304.76100@q75g2000hsh.googlegroups.com> <1178260571.160570.299160@p77g2000hsh.googlegroups.com> <1178277194.559817.143360@o5g2000hsb.googlegroups.com> Message-ID: <1178309682.434461.291380@l77g2000hsb.googlegroups.com> On May 4, 4:13 am, Dustan wrote: > On May 4, 1:36 am, Michael wrote: > > ... def g(x=x): > > ... x = x + 1 > > ... return x > > ... return g > > >>> g = f(3) > > >>> g()> > > 4 > >>> g() > 4 > >>> g() > 4 > >>> g() # what is going on here???? > 4 Okay, so it is a bad design, but it illustrates the point. What is happening is that in the body of the function f, a new function is defined using the value of x passed as an argument to f. Thus, after the call g = f(3), the body of f is equivalent to def g(x=3): x = x + 1 return x This function is returned, so the call g() uses the default argument x=3, then computes x = x+1 = 3+1 = 4 and returns 4. Every call is equivalent to g() == g(3) = 4. Inside g, x is a local variable: it does not maintain state between function calls. (You might think that the first example would allow you to mutate the x in the closure, but this is dangerous and exactly what python is trying to prevent by making x a local variable when you make assignments in g. This is why the interpreter complains.) If you actually want to maintain state, you have to use a mutable object like a list. The following would do what you seem to expect. >>> def f(x0): ... def g(x=[x0]): ... x[0] = x[0] + 1 ... return x[0] ... return g ... >>> g = f(3) >>> g() 4 >>> g() 5 >>> h = f(0) >>> h() 1 >>> h() 2 >>> g() 6 From jm.suresh at gmail.com Fri May 4 02:08:33 2007 From: jm.suresh at gmail.com (jm.suresh@no.spam.gmail.com) Date: 3 May 2007 23:08:33 -0700 Subject: Getting some element from sets.Set Message-ID: <1178258913.095438.173020@h2g2000hsg.googlegroups.com> It is not possible to index set objects. That is OK. But, what if I want to find some element from the Set. from sets import Set s = Set( range(12 ) if I do pop, that particular element gets removed. I do not want to remove the element, but get some element from the Set. s.some_element() # Is not available Is there a way to do this. I am doing it like this: for x in s: break Now x is /some_element/ from s. - Suresh From bbxx789_05ss at yahoo.com Thu May 24 13:30:43 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 24 May 2007 10:30:43 -0700 Subject: How can I time a method of a class in python using Timeit In-Reply-To: <1180020970.039576.319230@m36g2000hse.googlegroups.com> References: <1180020970.039576.319230@m36g2000hse.googlegroups.com> Message-ID: <1180027843.322955.57280@q75g2000hsh.googlegroups.com> On May 24, 9:36 am, "silverburgh.me... at gmail.com" wrote: > Hi, > > I am using timeit to time a global function like this > > t = timeit.Timer("timeTest()","from __main__ import timeTest") > result = t.timeit(); > > But how can i use timeit to time a function in a class? > class FetchUrlThread(threading.Thread): > def aFunction(self): > # do something .... > > def run(self): > # how can I time how long does aFunction() take here? > aFunction(); > > Thank you. How about this: class Dog(object): def run(self): result = 10 * 20 + 3 import timeit t = timeit.Timer("d.run()", "from __main__ import Dog; d = Dog()") print t.timeit() From gagsl-py2 at yahoo.com.ar Tue May 22 17:53:39 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 22 May 2007 18:53:39 -0300 Subject: using google search api for python References: <465337A0.5080808@fmed.uba.ar> Message-ID: En Tue, 22 May 2007 15:34:08 -0300, Gerardo Herzig escribi?: > Hi all. Im looking for the pyGoogle for making google searchs y a python > script. The thing is, all im founding is an AJAX api, but the > application ill use is NOT a web app. So, someone know if there is a > pure python api that i can download and use? Unless you already have a key, you can't. See http://code.google.com/apis/soapsearch/ Either use the AJAX api, or a simple page request (and scrape it). -- Gabriel Genellina From jstroud at mbi.ucla.edu Thu May 3 23:59:30 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 03 May 2007 20:59:30 -0700 Subject: tkinter listboxes In-Reply-To: <1178249216.774940.141950@p77g2000hsh.googlegroups.com> References: <1178249216.774940.141950@p77g2000hsh.googlegroups.com> Message-ID: rahulnag22 at yahoo.com wrote: > I will give a simplified example of the problem at hand -- > > I have a case in which I have two listboxes - listbox1 and listbox2, > if I click on an item in listbox1 the item gets highlighted as > expected. Now if I click on an item in listbox2 the selected item in > listbox1 loses its highlight. My question is how do I keep the > listbox1 item from losing its highlight if I select an item in > listbox2 or to that matter any other widget. > > Thanks > Rahul > You will need to bind '' for each list box to something like: def button1(e): row = e.widget.lists[0].nearest(e.y) e.widget.selection_clear(0, END) e.widget.selection_set(row) return 'break' # how to bind alistbox.bind('', button1) The less than obvious thing here is that selections (highlighted here) are different than the active index (which is marked with an underline). You are probably using the active index and don't realize the difference. James From jadestar at idiom.com Mon May 14 18:03:09 2007 From: jadestar at idiom.com (James T. Dennis) Date: Mon, 14 May 2007 22:03:09 -0000 Subject: file uploader References: <2adc542f0705091849t6c092ba0mf1cedd080da36960@mail.gmail.com> <2adc542f0705131441h1aabda6cl8c30589fc2f5d9a2@mail.gmail.com> Message-ID: <1179180188.722184@smirk> Gabriel Genellina wrote: > En Sun, 13 May 2007 18:41:16 -0300, Sick Monkey > escribi?: >> If anyone has a simpler way of checking to see if >> a file already exists (prior to uploading to a server) and renaming it, >> please let me know. > I will ignore the "server" part... >> Here is the code that I am using (it runs exactly the same as the linux >> app >> 'arcgen'). >> [...] >> t = i-1 >> filename=string.replace(filename,".-%s" % (t),".-%s" % (i)) > If the original filename contained .-1 somewhere, you're modifying it. > This is safer and shorter: > import os,string > filename = "whoa.mp3" > dir_path = "/u01/" > ofilename = filename > i = 0 > while os.path.exists(dir_path+filename): > filename = "%s.-%s" % (ofilename,i) > i += 1 > req.write(filename) Is it really safer? Couldn't their still be a race condition (if some hostile process has write access to the directory in which this is being attempted)? Wouldn't it be safer to import tempfile, use the t=NamedTemporaryFile() function therein and then use try: os.link(t.name, ...) except OSError: to safely rename it? Something like: import os, tempfile tdir = "/u01/" tf = tempfile.NamedTemporaryFile(dir="/u01/" i = 0 while 1: try: os.link(tf.name, os.path.join(tdir, filename) except OSError: i += 1 filename = "%s.-%s" % (filename, i) else: break ...??? -- Jim Dennis, Starshine: Signed, Sealed, Delivered From gagsl-py2 at yahoo.com.ar Tue May 29 16:47:35 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 29 May 2007 17:47:35 -0300 Subject: embeded python progam into visual C++ application crash References: <1DC9064A1EB94845987C198ADF4E11201594A9@messagix.ISISTHIBAUD.local> Message-ID: En Tue, 29 May 2007 15:01:07 -0300, fabien.lyon escribi?: > hello, > The C++ application uses a python module which wraps commands set for CVS > management: > checkout, checkin and tag. > We used python2.5.1 and Visual C++ 6.0 2.5.1 is compiled with Visual Studio 2005 - I hope you had no problems with VC++ 6.0? > The problem we get is: > After a good import and definition of python functions we have a random > unhandled exception (from python25.dll) when calling python interface > function several times. > All the python module has been tested using the python IDLE. > > > This the C++ sequence code we used: > > Py_initialize() > Py_Import("moduleName") > cvs_init() // cvs view initialisation handled > by > python script init() > cvs_set_tag() // cvs commit and tag handled by python > script settag() > // the exception occured here Neither Py_initialize nor Py_Import functions exist - so please post actual code. -- Gabriel Genellina From hate at spam.com Sat May 12 07:36:20 2007 From: hate at spam.com (Jesse) Date: Sat, 12 May 2007 13:36:20 +0200 Subject: Popen and wget, problems Message-ID: <4645a6a6$0$8615$dbd49001@news.wanadoo.nl> Hi all, I have a problem using wget and Popen. I hope someone can help. -- Problem -- I want to use the command: wget -nv -O "dir/cpan.txt" "http://search.cpan.org" and capture all it's stdout+stderr. (Note that option -O requires 'dir' to be existing before wget is executed) Popen doesn't work, while os.system and shell do. Popen will give the error: dir/cpan.txt: No such file or directory While os.system and shell will give the correct result: 06:52:40 URL:http://search.cpan.org/ [3657/3657] -> "dir1/cpan.txt" [1] -- Background info about wget -- -Option -nv: -nv, --no-verbose turn off verboseness, without being quiet. -Option -O: -O, --output-document=FILE write documents to FILE. Note that wget requires any directories in the file-path of option -O to be existing before the wget command is executed. -- Python Code using Popen with cmd arg list -- # imports import os from subprocess import Popen, PIPE # vars and create dir cmd_set = ['wget', '-nv', '-O dir/cpan.txt', 'http://search.span.org'] cmd = ' '.join(cmd_set) print "cmd: " + cmd try: os.makedirs('dir') except: print 'dir already exists' # execute using Popen (does NOT work) proc = Popen(cmd_set, stdout=PIPE, stderr=PIPE) return_code = proc.wait() if return_code == 0: print "Success:\n%s" % (proc.stdout.read() + proc.stderr.read()) else: print "Failure %s:\n%s" % (return_code, proc.stderr.read() + proc.stdout.read()) # execute using os.system (does work) os.system(cmd) -- Python code output of Popen -- Failure 1: dir/cpan.txt: No such file or directory -- Question -- Why is Popen unable to correctly execute the wget, while os.system can? From aleax at mac.com Thu May 3 23:28:13 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 3 May 2007 20:28:13 -0700 Subject: [ANN] Update to Python Quick Reference Card (for Python 2.4) (v0.67) References: <4bnh33pb644j9qsvij3citqrpb2bmqlsu4@4ax.com> <4638e8a8$0$27396$ba4acef3@news.orange.fr> <1hxiay0.17x1upmcmvc46N%aleax@mac.com> <463a20cc$0$25950$ba4acef3@news.orange.fr> Message-ID: <1hxk0m6.1klg5pppnwj61N%aleax@mac.com> Laurent Pointal wrote: ... > > It's an excellent quick-reference card, BTW (though I don't quite > > understand why even-numbered pages are flipped upside-down). > > At work I print it on horizontal A4/USLetter, with recto-back, and with > binding (reliure in french) on small side of paper. Ah, that must be my problem -- I didn't set "binding" to the short side, but left it as I have it by default, on the long side. Thanks. Alex From stefan.sonnenberg at pythonmeister.com Mon May 7 02:31:09 2007 From: stefan.sonnenberg at pythonmeister.com (Stefan Sonnenberg-Carstens) Date: Mon, 7 May 2007 08:31:09 +0200 (CEST) Subject: Problem to Download ftp file In-Reply-To: <1D011717865DAE46B56AA1455F02CAC5C952DB@n1ex> References: <1D011717865DAE46B56AA1455F02CAC5C952DB@n1ex> Message-ID: <1068189.19772.BlRUCl8VTQA=.1178519469.squirrel@webmailer.hosteurope.de> Perhaps a problem with name resolution ? On Mo, 7.05.2007, 07:27, Shakil Ahmed wrote: > hi > Actually i need to know that how can i download a ftp file from ncbi by > using python module ftputil. > please help me. > > Thanks > regards, > Shakil > > import ftputil > > host = ftputil.FTPHost('ftp.ncbi.nih.gov/repository/OMIM/morbidmap', > 'anonymous', 'password') > > > > > > The Error message is: > > raise FTPOSError(ftp_error) > > FTPOSError: (11001, 'getaddrinfo failed') > > Debugging info: ftputil 2.2.2, Python 2.4.3 (win32) > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list From nagle at animats.com Thu May 3 17:54:27 2007 From: nagle at animats.com (John Nagle) Date: Thu, 03 May 2007 21:54:27 GMT Subject: My Python annoyances In-Reply-To: References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> Message-ID: Terry Reedy wrote: > "John Nagle" wrote in message > news:Eep_h.6829$2v1.1832 at newssvr14.news.prodigy.net... > | Ben Collver wrote: > || > from the person who closed it. I get the unspoken message: bug > reports > | > are not welcome. > > | Getting through the process requires a year or so. > > Ben got a respond in 3 days. He didn't actually need anything fixed. John Nagle From sjdevnull at yahoo.com Thu May 17 01:53:38 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 16 May 2007 22:53:38 -0700 Subject: Trying to choose between python and java In-Reply-To: References: Message-ID: <1179381218.041519.93220@u30g2000hsc.googlegroups.com> Cameron Laird wrote: > In article , > Terry Reedy wrote: > > > >"Anthony Irwin" wrote in message > >news:f2bghg$4q0$1 at news-01.bur.connect.com.au... > . > . > . > >| #5 someone said that they used to use python but stopped because the > >| language changed or made stuff depreciated (I can fully remember > >| which) and old code stopped working. Is code written today likely to > >| still work in 5+ years or do they depreciate stuff and you have to > >update? > > > >Most versions of Python are still available. You are free to use and > >distribute your copies indefinitely. Several older versions are still in > >use. > > > >Recent releases have added features but removed very little except bugs. > >Unfortunately, bug removal sometimes breaks code. And feature additions > >occasionally introduce bugs or otherwise break code, but that is why there > >are alpha, beta, and candidate releases before a final release. > > > >Python3 will remove many things at once. A conversion tool is being > >written. And there is no expectation that production code should be > >immediately converted, if ever. > . > . > . > I'll answer even more aggressively: Python's record of > backward compatibility is *better* than Java's. Although I objected earlier to the statement that Python has never had a release breaking backward compatibility, I agree 100% with this--the times that Python has broken backward compatibility have been preceded by several releases of deprecation warnings. Java on several occasions has simply broken working code in a new release with no warning. I wouldn't be shocked if Python has done the same, but I've never run into it in my code. From bbxx789_05ss at yahoo.com Sun May 27 13:17:52 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 27 May 2007 10:17:52 -0700 Subject: itertools.groupby Message-ID: <1180286272.100790.131670@q75g2000hsh.googlegroups.com> Bejeezus. The description of groupby in the docs is a poster child for why the docs need user comments. Can someone explain to me in what sense the name 'uniquekeys' is used this example: import itertools mylist = ['a', 1, 'b', 2, 3, 'c'] def isString(x): s = str(x) if s == x: return True else: return False uniquekeys = [] groups = [] for k, g in itertools.groupby(mylist, isString): uniquekeys.append(k) groups.append(list(g)) print uniquekeys print groups --output:-- [True, False, True, False, True] [['a'], [1], ['b'], [2, 3], ['c']] From bbxx789_05ss at yahoo.com Fri May 18 15:54:46 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 18 May 2007 12:54:46 -0700 Subject: namespace question In-Reply-To: <%fm3i.726$u56.355@newssvr22.news.prodigy.net> References: <%fm3i.726$u56.355@newssvr22.news.prodigy.net> Message-ID: <1179518086.531715.270890@l77g2000hsb.googlegroups.com> On May 18, 12:29 pm, "T. Crane" wrote: > If you put them at the top level, and suppose you saved it all in a file > called test.py, then when you type > > ln [1]: from test import myClass > > does it still load a,b,c and numpy into the namespace? > Yep. Easy to test: toBeImported.py ----------------- 1) Create a global variable: x = "red" 2) Create a function or a class with a method that prints out the value of x. yourProgram.py -------------- 1) Create a global variable with the same name, but with a different value: x = 100 2) Use from...import to import your class or function 3) Call the method or function that displays x. Which value for x was displayed? When things defined in a module travel around, they carry a snapshot of home with them. From joshua at eeinternet.com Tue May 8 17:18:49 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Tue, 08 May 2007 13:18:49 -0800 Subject: ANN: A login wrapper for DSPAM Message-ID: <4640dcf7$0$16346$88260bb3@free.teranews.com> I wanted it: http://www.mail-archive.com/dspam-users%40lists.nuclearelephant.com/msg00264.html So I wrote it. Annoucning DspamFrontend 1.0 DSPAM Frontend is a script written in Python designed to provide login facilities for DSPAM when HTTP basic auth is either undesireable or unavailable. dspamFrontend.py, along with some helper suid scripts, handles the authentication of the user (using an IMAP server), along with the invocation of the dspam scripts You can download it here: http://www.eeinternet.com/opensource.html No warranties are made, but this code has been in production for several weeks now, so is known to perform its assigned duties. Comments, questions, critiques welcome! j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE -- Posted via a free Usenet account from http://www.teranews.com From steven.bethard at gmail.com Sun May 27 18:58:59 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 27 May 2007 16:58:59 -0600 Subject: Error in optparse documentation In-Reply-To: <1180302882.090651.235860@q75g2000hsh.googlegroups.com> References: <1180302882.090651.235860@q75g2000hsh.googlegroups.com> Message-ID: <65GdnTx7IaGrkMfbnZ2dnUVZ_jadnZ2d@comcast.com> Shatadal wrote: > In the python documentation section 14.3.2.6 (http://docs.python.org/ > lib/optparse-generating-help.html) in the last line it is written > > "options that have a default value can include %default in the help > string--optparse will replace it with str() of the option's default > value. If an option has no default value (or the default value is > None), %default expands to none." > > However this is true only for python 2.4 and newer and not for older > versions. The optparse module is externally maintained. You should file a documentation bug at http://optik.sourceforge.net/ STeVe From duncan.booth at invalid.invalid Fri May 4 09:03:55 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 4 May 2007 13:03:55 GMT Subject: base64 and unicode References: Message-ID: EuGeNe Van den Bulke wrote: > Duncan Booth wrote: >> However, the decoded text looks as though it is utf16 encoded so it >> should be written as binary. i.e. the output mode should be "wb". > > Thanks for the "wb" tip that works (see bellow). I guess it is > experience based but how could you tell that it was utf16 encoded? I pasted the encoded form into idle and decoded it base 64. It ends with \r \x00\n\x00 and the nulls instantly suggest a 16 bit encoding. Scrolling to the beginning and it starts \xff\xfe which is the BOM for little-endian utf16. From kyosohma at gmail.com Fri May 11 15:43:35 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 11 May 2007 12:43:35 -0700 Subject: stealth screen scraping with python? In-Reply-To: <1178911975.308104.297380@n59g2000hsh.googlegroups.com> References: <1178911975.308104.297380@n59g2000hsh.googlegroups.com> Message-ID: <1178912614.940628.32470@y5g2000hsa.googlegroups.com> On May 11, 2:32 pm, different.eng... at gmail.com wrote: > Folks: > > I am screen scraping a large volume of data from Yahoo Finance each > evening, and parsing with Beautiful Soup. > > I was wondering if anyone could give me some pointers on how to make > it less obvious to Yahoo that this is what I am doing, as I fear that > they probably monitor for this type of activity, and will soon ban my > IP. > > -DE Depends on what you're doing exactly. I've done something like this and it only hits the page once: URL = 'http://quote.yahoo.com/d/quotes.csv?s=%s&f=sl1c1p2' TICKS = ('AMZN', 'AMD', 'EBAY', 'GOOG', 'MSFT', 'YHOO') u = urlopen(URL % ','.join(TICKS)) for data in u: tick, price, chg, per = data.split(',') # do something with data If you're grabbing all the data in one fell swoop (which is what you should aim for), then it's harder for Yahoo! to know what you're doing exactly. And I can't see why they'd care as that is all a browser does anyway. It's when you hit the site a bunch of times in a short period of time that sets off the alarms. Mike From grflanagan at yahoo.co.uk Wed May 16 09:13:37 2007 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 16 May 2007 06:13:37 -0700 Subject: Splitting a quoted string. In-Reply-To: <1179312169.045429.80960@e65g2000hsc.googlegroups.com> References: <1179312169.045429.80960@e65g2000hsc.googlegroups.com> Message-ID: <1179321217.083347.111260@h2g2000hsg.googlegroups.com> On May 16, 12:42 pm, mosscliffe wrote: > I am looking for a simple split function to create a list of entries > from a string which contains quoted elements. Like in 'google' > search. > > eg string = 'bob john "johnny cash" 234 june' > > and I want to have a list of ['bob', 'john, 'johnny cash', '234', > 'june'] > > I wondered about using the csv routines, but I thought I would ask the > experts first. > > There maybe a simple function, but as yet I have not found it. > See 'split' from 'shlex' module: >>> s = 'bob john "johnny cash" 234 june' >>> import shlex >>> shlex.split(s) ['bob', 'john', 'johnny cash', '234', 'june'] >>> From Wiseman1024 at gmail.com Sat May 5 21:47:39 2007 From: Wiseman1024 at gmail.com (Wiseman) Date: 5 May 2007 18:47:39 -0700 Subject: Python regular expressions just ain't PCRE In-Reply-To: <1178399197.942689.69390@e65g2000hsc.googlegroups.com> References: <1178323901.381993.47170@e65g2000hsc.googlegroups.com> <1178399197.942689.69390@e65g2000hsc.googlegroups.com> Message-ID: <1178416059.299809.82220@n76g2000hsh.googlegroups.com> On May 5, 10:06 pm, "sjdevn... at yahoo.com" wrote: > -1 on this from me. In the past 10 years as a professional > programmer, I've used the wierd extended "regex" features maybe 5 > times total, whether it be in Perl or Python. In contrast, I've had > to work around the slowness of PCRE-style engines by forking off a > grep() or something similar practically every other month. I use these complex features every month on my job, and performance is rarely an issue, at least for our particular application of PCRE. By the way, if you're concerned about performance, you should be interested on once-only subpatterns. From john at datavoiceint.com Fri May 11 11:21:28 2007 From: john at datavoiceint.com (HMS Surprise) Date: 11 May 2007 08:21:28 -0700 Subject: Better way to isolate string Message-ID: <1178896888.721679.207240@n59g2000hsh.googlegroups.com> Greetings. Given the string s below and using only python built-in capabilities, I am trying to isolate the substring G132153. This string may have any number of digits but the pieces around it will not change. I have accomplished this with split but there must be a more elegant and compact way to do this. >>> s ='G132153' >>> t = s.split('">') >>> u = t[-1].split('<') >>> v = u[0] >>> v 'G132153' Thanks, jvh From claird at lairds.us Sat May 19 21:52:38 2007 From: claird at lairds.us (Cameron Laird) Date: Sun, 20 May 2007 01:52:38 +0000 Subject: What is deployment? (was: A Few More Forrester Survey Questions) References: Message-ID: <68m4i4-9a4.ln1@lairds.us> In article , Jeff Rush wrote: . . . >2) How easy is it to install an application written in the language? > How is the application deployed? > > I'm having some trouble understanding the difference between > "deployment" and "installation". I suspect those words may > have a special meaning to Java developers (who designed the survey) > or to Big Corporate IT developers. Ideas? > > I can tell the story of distutils, python eggs and PyPI, and py2exe > and py2mumble for the Mac -- is there more to the story than that? . . . Oh, yes. As someone who often says "deploy", even in mixed company, and even writes about it on occasion, I feel obliged to respond. Meanings, in order of "frequency", for a sense of frequency I assert I can articulate: A. installation; B. installation, but we're trying to sound important, and "deployment" has an enterpris-y ring to it; C. something seriously different from installation. What might C. mean? Say I install a program, but I still have to worry about how I'm going to configure it within the cluster where I intend to use it, AND I need to co-ordinate its configuration with the central database on which it depends, AND I have to tie it in to our license- management system, AND there are issues with users sharing data and also protecting data from each other, AND ...--well, all those things that happen after narrow-sense installation are still part of "deployment". As it happens, I'm scheduled for a meeting Monday whose subject I'm willing to paraphrase as, "What does 'deployment' mean?". Let me know after reading what I've suggested above if you have an appetite for more. From gagsl-py2 at yahoo.com.ar Mon May 21 09:44:57 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 21 May 2007 10:44:57 -0300 Subject: Translating some Java to Python References: <1179692679.422164.27700@r3g2000prh.googlegroups.com> <1179738814.282655.192700@r3g2000prh.googlegroups.com> <465176ce$0$323$e4fe514c@news.xs4all.nl> <46518fec$0$339$e4fe514c@news.xs4all.nl> Message-ID: En Mon, 21 May 2007 09:26:19 -0300, Unknown escribi?: > One example that comes to mind is a class that is a proxy for a database > class, say Person. > The Person.Load(id) method doesn't use any instance or class data, it > instantiates a Person and populates it from the database. > It is clearly a part of the class's interface so for that I use a > @staticmethod. This is called a "factory method" and is usually implemented as a classmethod but a staticmethod is often OK. > *That* Pythonic I'm already ;-) Good! -- Gabriel Genellina From ceball at gmail.com Fri May 4 22:38:39 2007 From: ceball at gmail.com (Chris) Date: 4 May 2007 19:38:39 -0700 Subject: Strange terminal behavior after quitting Tkinter application In-Reply-To: References: <1178257164.415485.155290@q75g2000hsh.googlegroups.com> <1178290933.793501.110130@c35g2000hsg.googlegroups.com> Message-ID: <1178332719.691025.321370@p77g2000hsh.googlegroups.com> On May 5, 1:24 am, Dennis Lee Bieber wrote: > On 4 May 2007 08:02:13 -0700, Chris declaimed the > following in comp.lang.python: > > > Ah, sorry, I wasn't being precise. I meant the python commandline > > python interpreter. > > > So from aterminalI type (for example): > > python -i application.py > > > This launches the interpreter in myterminal. Then I can start the GUI > > (by typing "Application()", for example). If I use mainloop(), I can't > > interact with the interpreter from theterminaluntil I quit the GUI. > > Without mainloop(), I can continue to enter python commands. > > Which is to be expected... As the name implies, it is a loop. The > Python interpreter doesn't produce an interactive prompt until it runs > out of code to execute. Enter the following at an interactive prompt and > see what happens: > > while True: pass > > mainloop() is similar, though filled out with event dispatching logic: > > while True: > #get input event (keyboard, mouse clicks, mouse motion, etc.) > #call handler for that type of event > > All common GUI toolkits work this way (The AmigaOS was pretty much > the only exception, in that it did NOT natively rely upon binding > callbacks to events and then starting a library loop; one had to code > the dispatch loop by hand -- but this did mean that one could code a > subloop within an event handler if needed to restrict the available > events). Thanks, but I was just explaining why I don't want to call mainloop(). In my original example, I can type Application() at the interactive prompt and get a GUI (which seems to work apart from not quitting properly and leaving a messed-up terminal on some versions of linux) while still being able to use the interactive interpreter. I need to find out what cleanup is performed after mainloop() exists, I guess. Incidentally, I found the information in the thread http://thread.gmane.org/gmane.comp.python.scientific.user/4153 quite useful regarding mainloop() and being able to use python interactively from the prompt while still having a GUI. From walterbyrd at iname.com Wed May 16 22:16:37 2007 From: walterbyrd at iname.com (walterbyrd) Date: 16 May 2007 19:16:37 -0700 Subject: In a text file: how do I tell the EOF, from a blank line? Message-ID: <1179368197.929029.134400@p77g2000hsh.googlegroups.com> How do I test for the end of a file, in such a why that python can tell the EOF from a blank line? From claird at lairds.us Thu May 24 13:57:38 2007 From: claird at lairds.us (Cameron Laird) Date: Thu, 24 May 2007 17:57:38 +0000 Subject: need advice on building core code for python and PHP References: <1180025115.704410.250890@a35g2000prd.googlegroups.com> Message-ID: In article <1180025115.704410.250890 at a35g2000prd.googlegroups.com>, digimotif wrote: >All, >I'm currently working with a small development company on a PHP >application they already have. There are several processing tasks >that could be scripted in Python and run in the background to modify a >database, instead of the way they have it now, which waits for a >webpage to return from processing. > >There is also the possibility of building client gui applications that >work with the database as well, so I'm looking for a way I could >create a code base that enables us to use the same functions and >objects over and over again while building interfaces in Python, or >PHP, or whatever. > >Is there a way I could code the base (core) code in Python and have >PHP call it? I've really liked using SQLAlchemy and there are other >great things like Pylons I could integrate for various tasks, but I >first have to move some functionality out of PHP and into something >more "universal". What would you recommend? . . . "Yes", is the short answer. More details, later. From gagsl-py2 at yahoo.com.ar Sat May 12 01:25:51 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 12 May 2007 02:25:51 -0300 Subject: Recursion limit problems References: <1178921877.442519.165740@u30g2000hsc.googlegroups.com> Message-ID: En Fri, 11 May 2007 19:17:57 -0300, elventear escribi?: > I am runing into recursion limit problems. I have found that the > culprit was related to the __hash__ function that I had assigned to > the objects that were added to a set. As T. Reedy said, probably you have a recursive structure. These comments about __hash__, mutability and dict behavior are applicable to sets too : "The only required property is that objects which compare equal have the same hash value; it is advised to somehow mix together (e.g., using exclusive or) the hash values for the components of the object that also play a part in comparison of objects. If a class does not define a __cmp__() method it should not define a __hash__() operation either; if it defines __cmp__() or __eq__() but not __hash__(), its instances will not be usable as dictionary keys. If a class defines mutable objects and implements a __cmp__() or __eq__() method, it should not implement __hash__(), since the dictionary implementation requires that a key's hash value is immutable (if the object's hash value changes, it will be in the wrong hash bucket)." -- Gabriel Genellina From Thomas.Lenarz at netcologne.de Wed May 23 02:56:01 2007 From: Thomas.Lenarz at netcologne.de (Thomas Lenarz) Date: Wed, 23 May 2007 06:56:01 GMT Subject: Windows Debugging w/o MS References: Message-ID: <4653e21f.652003@news.netcologne.de> On Tue, 22 May 2007 18:49:04 -0700, "Christopher Anderson" wrote: >problem is, when I attempt to use it, I get a segfault. Now, I'm >pretty sure this segfault is just a bug in my C++ code. So of course, >I would like to debug this thing somehow. I tried using the mingw gdb >giving it my python.exe to run, but obviously this python has no debug >info, and wasn't even compiled with mingw. I was hoping it would still >somehow debug my extension module right, but when I do a backtrace >after it segfaults, I get nothing useful. I have no experience in writing python extension-modules. However, I would give the following scheme a try. It helped myself a lot while debugging segfaulting modules plugged into a framework, for which I haven't had the source-code. It is done easyly and quickly. If it doesn't work you won't lose a lot of time: 1. At the earliest stage of your own C++-Code, code an infinite loop depending on a single variable. e.g.: int i=0; for(;i==0;); 2. When you start your test now and it does not segfault before your code is reached, the process will be stuck in this loop. 3. Attach gdb to the process using the --pid option. (Unfortunately I did this only on Unix with dbx. Hope it works on windows and gdb as well. 4. Look if you are now able to see your source in gdb. 5. Set a breakpoint immediately after the infinite loop. 6. Free the loop by setting the variable i to a value different from 0. 7. You should be able to single step now. I am not sure if this will work. But it might be worth a try. Thomas From sjmachin at lexicon.net Thu May 17 19:12:53 2007 From: sjmachin at lexicon.net (John Machin) Date: 17 May 2007 16:12:53 -0700 Subject: Regexes: How to handle escaped characters In-Reply-To: <1179440203.534490.66510@u30g2000hsc.googlegroups.com> References: <87tzubqniq.fsf@wilson.homeunix.com> <87irarqkz7.fsf@wilson.homeunix.com> <1179435962.962404.191600@y80g2000hsf.googlegroups.com> <1179440203.534490.66510@u30g2000hsc.googlegroups.com> Message-ID: <1179443573.565202.217410@p77g2000hsh.googlegroups.com> On May 18, 8:16 am, Paul McGuire wrote: > On May 17, 4:06 pm, John Machin wrote: > > > > > On May 18, 6:00 am, Torsten Bronger > > wrote: > > > > Hall?chen! > > > > James Stroud writes: > > > > Torsten Bronger wrote: > > > > >> I need some help with finding matches in a string that has some > > > >> characters which are marked as escaped (in a separate list of > > > >> indices). Escaped means that they must not be part of any match. Note: "must not be *part of* any match" [my emphasis] [big snip] > > Here are two pyparsing-based routines, guardedSearch and > guardedSearchByColumn. The first uses a pyparsing parse action to > reject matches at a given string location Seems to be somewhat less like what the OP might have in mind ... While we're waiting for clarification from the OP, there's a chicken- and-egg thought that's been nagging me: if the OP knows so much about the searched string that he can specify offsets which search patterns should not span, why does he still need to search it? Cheers, John From sgeiger at ncee.net Wed May 30 20:48:31 2007 From: sgeiger at ncee.net (Shane Geiger) Date: Wed, 30 May 2007 19:48:31 -0500 Subject: Off Topic: What is the good book to learn Python ? In-Reply-To: <163f0ce20705301651r43a6c50et15a4bc621b74f328@mail.gmail.com> References: <1180549522.350380.276570@q66g2000hsg.googlegroups.com> <163f0ce20705301651r43a6c50et15a4bc621b74f328@mail.gmail.com> Message-ID: <465E1B5F.60305@ncee.net> Here are some excellent online books and tutorials to get started with: http://www.python.org/doc/tut/ http://www.ibiblio.org/obp/thinkCSpy/ http://www.python.org/topics/learn/prog.html http://www.python.org/topics/learn/non-prog.html http://docs.python.org/lib/ http://diveintopython.org/ http://gnosis.cx/TPiP/ http://rox.sourceforge.net/basic_python.html Here are some lists of books you can read online: http://www.techbooksforfree.com/perlpython.shtml http://en.wikibooks.org/wiki/Programming:Python http://wiki.python.org/moin/PythonBooks Some books: Byte of Python - online: http://www.byteofpython.info/files/120/byteofpython_120.pdf Quick Tour of Python - online: http://stsdas.stsci.edu/pyraf/doc/python_quick_tour/python_quick_tour.pdf Python in Nutshell - online: http://files.nixp.ru/books/programming/python/O%27Reilly%20--%20Python%20In%20A%20Nutshell.chm Python Standard Library - online: http://effbot.org/zone/librarybook-index.htm Python tutorial - online: http://www.ensta.fr/~enstar/doc/python/Python-Docs-2.4-PDF/tut.pdf kaens wrote: > On 30 May 2007 11:25:22 -0700, Katie Tam wrote: > >> I am new to this filed and begin to learn this langague. Can you tell >> me the good books to start with ? >> >> >> Katie Tam >> Network administrator >> http://www.linkwaves.com/main.asp >> http://www.linkwaves.com >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > > If you're experienced with other programming languages, I'd recommend > python in a nutshell, or perhaps programming python. I personally just > skimmed through the online tutorial, and kept the library and api > references handy. > > Orielly publishers almost always have excellent books on learning new > programming languages. > > I would also recommend to stay away from any "for dummies" or "in x > (hours/days)" books. They can be decent introductory material, but > unless you are really really new to programming, you probably wouldn't > be getting enough information to justify the cost of the book (and a > lot of times they have a lot of bad practices in them) > > Good luck! > -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy -------------- next part -------------- A non-text attachment was scrubbed... Name: sgeiger.vcf Type: text/x-vcard Size: 310 bytes Desc: not available URL: From jstroud at mbi.ucla.edu Mon May 7 23:26:29 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 07 May 2007 20:26:29 -0700 Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? In-Reply-To: References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> <08qk33t594ih0ulmjmev90d22lkfnotgoe@4ax.com> <463C2A3A.8332D211@hotmail.com> <0k8p33h90bp5tfajedb4bmd2eik8gfi2ho@4ax.com> Message-ID: quasi wrote: > On Mon, 7 May 2007 17:00:01 -0400, krw wrote: > > >>In article , >>quasi at null.set says... >> >>>On Mon, 7 May 2007 10:55:55 -0400, James Beck >>> wrote: >>> >>> >>>>In article <0k8p33h90bp5tfajedb4bmd2eik8gfi2ho at 4ax.com>, quasi at null.set >>>>says... >>>> >>>>>On Sat, 05 May 2007 07:54:50 +0100, Eeyore >>>>> wrote: >>>>> >>>>> >>>>>> >>>>>>quasi wrote: >>>>>> >>>>>> >>>>>>>Gib Bogle wrote: >>>>>>> >>>>>>> >>>>>>>>Ah, so the firefighters were in on the conspiracy! >>>>>>> >>>>>>>No, but the firefighters are very much aware that there is more to >>>>>>>9/11 than has been officially revealed. >>>>>>> >>>>>>>This is even more true at Pentagon. The firefighters there brought >>>>>>>dogs trained to search for survivors and/or remains >>>>>> >>>>>>Sounds like good practice. >>>>>> >>>>>> >>>>>> >>>>>>>and found nothing. >>>>>> >>>>>>And the significance of this is ? >>>>> >>>>>The plane was supposed to have passengers. >>>>> >>>>>quasi >>>>> >>>> >>>>Yep, and they found them all, therefore, there were none for the dogs to >>>>find. >>> >>>You pretty much made that up. >>> >>>They found nothing -- no bodies, no body parts, no blood, no bones, no >>>luggage, no rings (do gold rings melt at jet fuel temperatures?), no >>>jewelry (do diamonds melt at jet fuel temperatures?), no plane seats, >>>no silverware (ok, maybe they only had plastic). In other words, an >>>immediate mystery to the firefighters was the lack of any indication >>>that the plane had passengers. Even if you believe that most of the >>>passengers were essentially incinerated, it's not believable that all >>>of them were. Some of the bodies should have been recoverable right at >>>the scene. >> >>If none of the passenger's remains were ever found, why all the fuss >>last year when they found more. > > > That's news to me. We're talking about the Pentagon, not the WTC. > Besides, I didn't say that no remains were ever found. What I said was > that no passenger remains were found at the Pentagon on 9/11 by the > firefighters or their trained rescue dogs. > > At the WTC, no passenger remains were ever found, as far as I know. Of > course, that's not so surprising. What is surprising is the all too > convenient find of Mohammed Atta's undamaged passport in the WTC > rubble. It wasn't even buried. It was just sitting there, waiting to > be found. > > >>IOW, you're a liar. > > > That's way too strong. > > I'm not saying anything I know to be false. > > >>>Weeks later, parts of the wreckage were supposedly "analyzed" at a >>>government lab, and the official report claims they were able to >>>isolate DNA for many of the passengers. It doesn't ring true. >> >>...and a fool. > > > See if you can keep your argument from degenerating to the level of > personal attacks. > > quasi That is impossible for most people because this is an issue of religion for them. But then again, attacks are part of religion aren't they? From nis at superlativ.dk Mon May 28 04:16:14 2007 From: nis at superlativ.dk (=?ISO-8859-1?Q?Nis_J=F8rgensen?=) Date: Mon, 28 May 2007 10:16:14 +0200 Subject: Newbie question - better way to do this? In-Reply-To: References: Message-ID: <465a8fd2$0$90269$14726298@news.sunsite.dk> Steve Howell skrev: > def firstIsCapitalized(word): > return 'A' <= word[0] <= 'Z' For someone who is worried about the impact of non-ascii identifiers, you are making surprising assumptions about the contents of data. Nis From Wiseman1024 at gmail.com Sat May 5 12:00:17 2007 From: Wiseman1024 at gmail.com (Wiseman) Date: 5 May 2007 09:00:17 -0700 Subject: Python regular expressions just ain't PCRE In-Reply-To: References: <1178323901.381993.47170@e65g2000hsc.googlegroups.com> Message-ID: <1178380817.435469.11870@y80g2000hsf.googlegroups.com> On May 5, 7:19 am, Marc 'BlackJack' Rintsch wrote: > In <1178323901.381993.47... at e65g2000hsc.googlegroups.com>, Wiseman wrote: > > Note: I know there are LALR parser generators/parsers for Python, but > > the very reason why re exists is to provide a much simpler, more > > productive way to parse or validate simple languages and process text. > > (The pyparse/yappy/yapps/ > generator here> argument could have been used to skip regular > > expression support in the language, or to deprecate re. Would you want > > that? And following the same rule, why would we have Python when > > there's C?) > > I don't follow your reasoning here. `re` is useful for matching tokens > for a higher level parser and C is useful for writing parts that need > hardware access or "raw speed" where pure Python is too slow. > > Regular expressions can become very unreadable compared to Python source > code or EBNF grammars but modeling the tokens in EBNF or Python objects > isn't as compact and readable as simple regular expressions. So both `re` > and higher level parsers are useful together and don't supersede each > other. > > The same holds for C and Python. IMHO. > > Ciao, > Marc 'BlackJack' Rintsch Sure, they don't supersede each other and they don't need to. My point was that the more things you can do with regexes (not really regular expressions anymore), the better -as long as they are powerful enough for what you need to accomplish and they don't become a giant Perl- style hack, of course-, because regular expressions are a built-in, standard feature of Python, and they are much faster to use and write than Python code or some LALR parser definition, and they are more generally known and understood. You aren't going to parse a programming language with a regex, but you can save a lot of time if you can parse simple, but not so simple languages with them. Regular expressions offer a productive alternative to full-fledged parsers for the cases where you don't need them. So saying if you want feature X or feature Y in regular expressions you should use a Bison-like parser sounds a bit like an excuse, because the very reason why regular expressions like these exist is to avoid using big, complex parsers for simple cases. As an analogy, I mentioned Python vs. C: you want to develop high-level languages because they are simpler and more productive than working with C, even if you can do anything with the later. From jzgoda at o2.usun.pl Tue May 8 16:01:50 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Tue, 08 May 2007 22:01:50 +0200 Subject: chdir() In-Reply-To: <1178652809.436141.176900@u30g2000hsc.googlegroups.com> References: <1178652809.436141.176900@u30g2000hsc.googlegroups.com> Message-ID: HMS Surprise napisa?(a): > Tried executing os.chdir("c:\twill") from a python Tk shell and got > the error message: > > WindowsError: [Error 123] The filename, directory name, or volume > label syntax is incorrect: 'c:\twill'. > > I have the directory exists as I copied the name from the explorer > window that was open to it. > > What is wrong with the syntax? Unescaped '\' character. Try with raw string (r"c:\twill") or escape it ("c:\\twill"). -- Jarek Zgoda http://jpa.berlios.de/ From gagsl-py2 at yahoo.com.ar Thu May 3 09:14:01 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 03 May 2007 10:14:01 -0300 Subject: Handling Infinite Loops on Server Applications References: Message-ID: En Wed, 02 May 2007 21:38:52 -0300, Paul Kozik escribi?: > I'm working with a small server program I'm writing for a small video > game. The main class constructor starts a thread that handles socket > connections, which itself starts new threads for each user connection. And what's the purpose of the main thread then? > The actual server program itself however needs to wait in the > background, but continue looping as not to close the running threads. > The problem is, simply running a [while True: pass] main loop in this > style eats precious CPU cycles (and for nothing). If it waits for > input, such as a socket.accept() or raw_input(), this problem does not > occur (obviously because it's not constantly looping). Exactly. Use the network handling thread as the main thread, by example. > What would be the best way to handle this, perhaps in a fashion > similar to how most server programs are handled (with arguments such > as [apache start], [apache stop])? Any guides towards this type of > application development? See the asyncore module, or any of the predefined servers in the Python library. -- Gabriel Genellina From donn at u.washington.edu Tue May 29 14:16:51 2007 From: donn at u.washington.edu (Donn Cave) Date: Tue, 29 May 2007 11:16:51 -0700 Subject: 0 == False but [] != False? References: <1179982400.412340.178710@g4g2000hsf.googlegroups.com> <1179983482.452458.188690@q66g2000hsg.googlegroups.com> Message-ID: In article , Erik Max Francis wrote: > Donn Cave wrote: > > > Anyone who finds this surprising, might enjoy reading this > > article from the time several years ago when the feature > > was being considered. When you have some time - it's long, > > but interesting. The present confusion is more directly > > addressed towards the end. Yes, it's the Laura Creighton > > article again: > > > > http://groups.google.com/group/comp.lang.python/msg/2de5e1c8384c0360 > > If so, be sure to click "More options," then "View thread," and then > read the responses. There were many reasonable objections to her points. Not that it is of no historical interest to review all these reasonable arguments, but allow me to restore the context quote from my follow-up: In article <1179983482.452458.188690 at q66g2000hsg.googlegroups.com>, Paul McGuire wrote: > This has *got* to rank up there among the VFAQ's of them all, along > with the mysterious shared default empty list argument. I think this > particular question has been asked in one form or another at least > twice a week for the past month! Donn Cave, donn at u.washington.edu From rrr at ronadam.com Sat May 26 11:43:56 2007 From: rrr at ronadam.com (Ron Adam) Date: Sat, 26 May 2007 10:43:56 -0500 Subject: webbrowser module bug? In-Reply-To: <1180135131.139874.237560@w5g2000hsg.googlegroups.com> References: <1180118146.617722.300670@g4g2000hsf.googlegroups.com> <1180135131.139874.237560@w5g2000hsg.googlegroups.com> Message-ID: <465855BC.6040902@ronadam.com> Paul Boddie wrote: > Ron Adam wrote: >> Reseting the default browser with the gnome default application window >> confirmed this. The browser selection can either have the quotes around >> the args "%s" paremteter, or not depending on how and what sets it. >> >> Seems to me it should be quoted unless spaces in path names are never a >> problem in Linux. So this could be both a python bug and a Gnome desktop >> bug. Firefox probably does the right thing by putting the quotes around >> it, but that causes problems for webbrowser.py, which doesn't expect them. > > Quoting arguments in the way described is the safe, easy option (with > some potential problems with ' characters that can be worked around), > and I imagine that it's done precisely because other applications > could pass a path with spaces as the URL, and that such applications > would be invoking the command in a shell environment. Sadly, this > conflicts with any other precautionary measures, causing a degree of > "overquoting". > > Resetting the GNOME default is a workaround, but I'm not convinced > that it would be satisfactory. What happens if you try and open an > HTML file, in the file browser or some other application which uses > the desktop preferences, where the filename contains spaces? I'm not sure how to test this. Most things I can think of call the web browser directly. Maybe a link in an email? Yes, it is a work around. The webbrowser module needs to be smarter about quotes. As I said, this is fixed in 2.6 already. I emailed the module maintainer, and will probably file a bug report too. Ron From desertlinux at netscape.net Tue May 15 20:29:41 2007 From: desertlinux at netscape.net (Brian) Date: Tue, 15 May 2007 17:29:41 -0700 Subject: transparent images In-Reply-To: <1179275214.794050.199460@y80g2000hsf.googlegroups.com> References: <1179275214.794050.199460@y80g2000hsf.googlegroups.com> Message-ID: moishyyehuda at gmail.com wrote: > Does any one know how to make a transparent image with specifically > PIL, but any standard python library will do. I need a spacer, and it > has to be transparent. > > Thanks > Does this have to be done through Python? If not, you might enjoy GIMP (http://www.gimp.org), which can do this easily. Best of all, you can customize the size, etc. Dusty --- From mtobis at gmail.com Sat May 12 23:43:59 2007 From: mtobis at gmail.com (Michael Tobis) Date: 12 May 2007 20:43:59 -0700 Subject: How to cleanly pause/stop a long running function? In-Reply-To: <1179003065.771223.25600@e65g2000hsc.googlegroups.com> References: <1179003065.771223.25600@e65g2000hsc.googlegroups.com> Message-ID: <1179027839.401929.211180@q75g2000hsh.googlegroups.com> > Doing a Ctrl+C > interrupt would be a not-so-clean-way of performing such a thing, and > it would quit the application altogether. I'd rather have the function > return a status object of what it has accomplished thus far. Just in case you are unaware that you can explicitly handle ^C in your python code, look up the KeyboardInterrupt exception. mt From redtiger84 at googlemail.com Thu May 10 10:19:16 2007 From: redtiger84 at googlemail.com (Christoph Krammer) Date: 10 May 2007 07:19:16 -0700 Subject: Read binary data from MySQL database Message-ID: <1178806756.509611.192130@e51g2000hsg.googlegroups.com> Hello, I try to write a python application with wx that shows images from a MySQL database. I use the following code to connect and get data when some event was triggered: dbconn = MySQLdb.connect(host="localhost", user="...", passwd="...", db="images") dbcurs = dbconn.cursor() dbcurs.execute("""SELECT imgdata FROM images LIMIT 1""") imgstring = dbcurs.fetchone()[0] frame.showImage(imgstring) Within my frame, the following method is defined: def showImage(self, imgstring): imgdata = StringIO.StringIO() imgdata.write(imgstring) print imgdata.getvalue() wx.ImageFromStream(imgdata, wx.BITMAP_TYPE_GIF) panel = wx.Panel(self, -1) self.panel = panel But this does not work. The converter says that the data is not valid GIF. When I print the content of imgstring after the database select statement, it contains something like this: array('c', 'GIF89aL\x01=\x01\x85\x00\x00\x00\x00\x00\xff\xff\xff \x00\xff\xff\xff[...]\x00\x00;') When I try to print imgstring[1], the result is "I". So I don't quite get what this print result is about and why my input should not be valid. The data in the database is correct, I can restore the image with tools like the MySQL Query Browser. Thanks in advance, Christoph From sjmachin at lexicon.net Fri May 18 23:29:54 2007 From: sjmachin at lexicon.net (John Machin) Date: Sat, 19 May 2007 13:29:54 +1000 Subject: converting strings to most their efficient types '1' --> 1, 'A' ---> 'A', '1.2'---> 1.2 In-Reply-To: References: <1179529661.555196.13070@k79g2000hse.googlegroups.com> Message-ID: <464E6F32.7070200@lexicon.net> On 19/05/2007 10:04 AM, James Stroud wrote: > py_genetic wrote: >> Hello, >> >> I'm importing large text files of data using csv. I would like to add >> some more auto sensing abilities. I'm considing sampling the data >> file and doing some fuzzy logic scoring on the attributes (colls in a >> data base/ csv file, eg. height weight income etc.) to determine the >> most efficient 'type' to convert the attribute coll into for further >> processing and efficient storage... >> >> Example row from sampled file data: [ ['8','2.33', 'A', 'BB', 'hello >> there' '100,000,000,000'], [next row...] ....] >> >> Aside from a missing attribute designator, we can assume that the same >> type of data continues through a coll. For example, a string, int8, >> int16, float etc. >> >> 1. What is the most efficient way in python to test weather a string >> can be converted into a given numeric type, or left alone if its >> really a string like 'A' or 'hello'? Speed is key? Any thoughts? >> >> 2. Is there anything out there already which deals with this issue? >> >> Thanks, >> Conor >> > > This is untested, but here is an outline to do what you want. > > First convert rows to columns: > > > columns = zip(*rows) > > > Okay, that was a lot of typing. Now, you should run down the columns, > testing with the most restrictive type and working to less restrictive > types. You will also need to keep in mind the potential for commas in > your numbers--so you will need to write your own converters, determining > for yourself what literals map to what values. Only you can decide what > you really want here. Here is a minimal idea of how I would do it: > > > def make_int(astr): > if not astr: > return 0 > else: > return int(astr.replace(',', '')) > > def make_float(astr): > if not astr: > return 0.0 > else: > return float(astr.replace(',', '')) > > make_str = lambda s: s > > > Now you can put the converters in a list, remembering to order them. > > > converters = [make_int, make_float, make_str] > > > Now, go down the columns checking, moving to the next, less restrictive, > converter when a particular converter fails. We assume that the make_str > identity operator will never fail. We could leave it out and have a > flag, etc., for efficiency, but that is left as an exercise. > > > new_columns = [] > for column in columns: > for converter in converters: > try: > new_column = [converter(v) for v in column] > break > except: > continue > new_columns.append(new_column) > > > For no reason at all, convert back to rows: > > > new_rows = zip(*new_columns) > > > You must decide for yourself how to deal with ambiguities. For example, > will '1.0' be a float or an int? The above assumes you want all values > in a column to have the same type. Reordering the loops can give mixed > types in columns, but would not fulfill your stated requirements. Some > things are not as efficient as they might be (for example, eliminating > the clumsy make_str). But adding tests to improve efficiency would cloud > the logic. > [apologies in advance if this appears more than once] This approach is quite reasonable, IF: (1) the types involved follow a simple "ladder" hierarchy [ints pass the float test, floats pass the str test] (2) the supplier of the data has ensured that all values in a column are actually instances of the intended type. Constraint (1) falls apart if you need dates. Consider 31/12/99, 31/12/1999, 311299 [int?], 31121999 [int?], 31DEC99, ... and that's before you allow for dates in three different orders (dmy, mdy, ymd). Constraint (2) just falls apart -- with user-supplied data, there seem to be no rules but Rafferty's and no laws but Murphy's. The approach that I've adopted is to test the values in a column for all types, and choose the non-text type that has the highest success rate (provided the rate is greater than some threshold e.g. 90%, otherwise it's text). For large files, taking a 1/N sample can save a lot of time with little chance of misdiagnosis. Example: file of 1,079,000 records, with 15 columns, ultimately diagnosed as being 8 x text, 3 x int, 1 x float, 2 x date (dmy order), and [no kidding] 1 x date (ymd order). Using N==101 took about 15 seconds [Python 2.5.1, Win XP Pro SP2, 3.2GHz dual-core]; N==1 takes about 900 seconds. The "converter" function for dates is written in C. Cheers, John From gandalf at shopzeus.com Thu May 31 08:49:07 2007 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 31 May 2007 14:49:07 +0200 Subject: pexpect/termios error: Inappropriate ioctl for device Message-ID: <465EC443.3060107@shopzeus.com> Hi All, I have a python program that downloads database backups from a remote server, and tries to replace the local database with the downloaded backup. The database is a PostgreSQL server and my program calls the pg_restore command with the aid of the wonderful pexpect module. Everything works fine if I start this program from a tty. When I try to start the same program from cron, I get this nasty exception: Traceback (most recent call last): File "/root/restore_databases.py", line 82, in ? main() File "/root/restore_databases.py", line 79, in main restore_all() File "/root/restore_databases.py", line 73, in restore_all do_restore(os.path.join(BACKUPDIR,fname),database) File "/root/restore_databases.py", line 56, in do_restore dropdb(database) File "/root/restore_databases.py", line 44, in dropdb db.interact() File "/usr/local/lib/python2.4/site-packages/pexpect.py", line 1226, in interact mode = tty.tcgetattr(self.STDIN_FILENO) termios.error: (25, 'Inappropriate ioctl for device') What can I do to avoid this? Thanks, Laszlo From weinhand at unileoben.ac.at Wed May 30 08:22:46 2007 From: weinhand at unileoben.ac.at (Weinhandl Herbert) Date: Wed, 30 May 2007 14:22:46 +0200 Subject: calling Postgresql stored procedure In-Reply-To: <1180516688.022056.70220@q69g2000hsb.googlegroups.com> References: <1180516688.022056.70220@q69g2000hsb.googlegroups.com> Message-ID: <465d6c7c$0$11610$3b214f66@aconews.univie.ac.at> Alchemist schrieb: > I am using Python 2.4 and Postgresql 8.2 database server. > > On the database I have created a stored function, example, > CREATE OR REPLACE FUNCTION calculateaverage() > > I created a new python script and would like to call my database > stored function. > > How can I call a database stored function/procedure in python? > with : SELECT calculateaverage() FROM ... WHERE ... ; happy pythoning Herbert From S.Mientki-nospam at mailbox.kun.nl Thu May 24 16:41:40 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Thu, 24 May 2007 22:41:40 +0200 Subject: Python and GUI In-Reply-To: <135bs4dfpdl8q33@corp.supernews.com> References: <1179761984.704369.116310@b40g2000prd.googlegroups.com> <4651CDBC.1070508@ulmcnett.com> <5abb0$4655ee4c$d443bb3a$510@news.speedlinq.nl> <135bs4dfpdl8q33@corp.supernews.com> Message-ID: <8abbd$4655f7b0$d443bb3a$21589@news.speedlinq.nl> Grant Edwards wrote: > On 2007-05-24, Stef Mientki wrote: > >>> Finally, consider wax (http://zephyrfalcon.org/labs/wax.html). In my >>> view, this is *exactly* what python needs, and its not being maintained >>> anymore as far as I can tell. What I like about it is: >>> >>> 1) it is small...I can include the entire wax distribution in >>> my app with only a 780k footprint. >>> >>> 2) it is a very thin layer on wx, so when something doesn't quite work, >>> I can immediately fall back onto wx, mixing and matching wax and wx >>> objects. it's just that the wax objects have more pythonic calling and >>> use properties >> Sorry I don't know wax, but I wonder "a GUI designer without >> screenshots", is that Pythonic ;-) > > Uh, wha? > quote original message: "I am looking for a pythonic, professional looking GUI framework." > Who are you quoting about the screenshots? Sorry, maybe I'm not Pythonic enough, but talking about "GUI framework", the first thing I want to see are screenshots. cheers, Stef Mientki > > Wax isn't a "GUI designer", and I'm a bit lost as to what > screenshots have to do with the topic at hand. > From paddy3118 at googlemail.com Sun May 20 06:40:32 2007 From: paddy3118 at googlemail.com (Paddy) Date: 20 May 2007 03:40:32 -0700 Subject: Typed named groups in regular expression In-Reply-To: References: <1179552763.278347.163300@e65g2000hsc.googlegroups.com> <1179574798.034285.65120@o5g2000hsb.googlegroups.com> Message-ID: <1179657632.770570.248700@w5g2000hsg.googlegroups.com> On May 20, 2:27 am, "Hugo Ferreira" wrote: > Both Paddy (hackish) and McGuire (right tool for the job) ideas sound > very interesting ;-) I'll definitely research on them further. > > Thanks for the support... Hackis, hackISH! Sir, I would have you know that the idea proffered is a hack in the finest traditions of hackerdom. Why, the solution is guaranteed to work for the longest time with the smallest expenditure and be delivered in the quickest time and be good enough - but no more. So, promote the idea to a hack or its pistols at dawn! :-) - Paddy. From gagsl-py2 at yahoo.com.ar Mon May 7 23:14:50 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 08 May 2007 00:14:50 -0300 Subject: invoke user's standard mail client References: <1178266064.922925.125760@y80g2000hsf.googlegroups.com> <1178513538.133114.81940@p77g2000hsh.googlegroups.com> <1178571606.190151.233580@y5g2000hsa.googlegroups.com> Message-ID: En Mon, 07 May 2007 18:00:06 -0300, luc.saffre at gmail.com escribi?: > On May 7, 10:28 am, "Gabriel Genellina" > wrote: >> >> Get the pywin32 package (Python for Windows extensions) from >> sourceforge, >> install it, and look into the win32comext\mapi\demos directory. > > Thanks for the hint, Gabriel. > Wow, that's heavily spiced code! When I invoke mapisend.py I get: > > Traceback (most recent call last): > File "mapisend1.py", line 85, in > SendEMAPIMail(SendSubject, SendMessage, SendTo, > MAPIProfile=MAPIProfile) > File "mapisend1.py", line 23, in SendEMAPIMail > mapi.MAPIInitialize(None) > pywintypes.com_error: (-2147467259, 'Unspecified error', None, None) > > But what is a MAPI profile? I left this variable blank. You can register several profiles (or users, or accounts); leave it blank to use the default profile. > Do I need MS > Exchange Server to run this demo? No. But this simple example used to work fine for me, but not anymore :( . Perhaps it has to do with my Eudora configuration. I've never used Outlook nor OutlookExpress btw. You may find this thread interesting: http://mail.python.org/pipermail/python-win32/2005-November/003985.html -- Gabriel Genellina From hq4ever at gmail.com Fri May 4 08:05:46 2007 From: hq4ever at gmail.com (Maxim Veksler) Date: Fri, 4 May 2007 15:05:46 +0300 Subject: Non blocking sockets with select.poll() ? In-Reply-To: References: <20070504112137.19381.249713413.divmod.quotient.8262@ohm> Message-ID: On 5/4/07, Maxim Veksler wrote: > On 5/4/07, Jean-Paul Calderone wrote: > > On Fri, 4 May 2007 13:04:41 +0300, Maxim Veksler wrote: > > >Hi, > > > > > >I'm trying to write a non blocking socket port listener based on > > >poll() because select is limited to 1024 fd. > > > > > >Here is the code, it never gets to "I did not block" until I do a > > >telnet connection to port 10000. > > > > > > > What were you expecting? > > > > I'll try to explain. > I'm doing a little experiment: Capturing the whole tcp 1-65535 range > of the machine, allowing me to connect to the my service on the > machine on every port. I know that it's probably the most dumb thing > to do with TCP/IP communication please don't forget it's an > experiment. [snip] I think I got it working now :) """ #!/usr/bin/env python import socket import select class PollingSocket(socket.socket): def __init__(self, port_number): self.__poll = select.poll() self.tcp_port_number = port_number socket.socket.__init__(self, socket.AF_INET, socket.SOCK_STREAM) self.setblocking(0) self.bind(('0.0.0.0', self.tcp_port_number)) self.listen(5) self.__poll.register(self) def poll(self, timeout = 0): return self.__poll.poll(timeout) def debugPollingSocket(port_num): print "BIND TO PORT: ", port_num return PollingSocket(port_num) all_sockets = map(debugPollingSocket, xrange(10000, 19169)) print "We have this in stock:" for nb_active_socket in all_sockets: print nb_active_socket.tcp_port_number while 1: for nb_active_socket in all_sockets: print "Asking", nb_active_socket.tcp_port_number if nb_active_socket.poll(0): print "Found", nb_active_socket.tcp_port_number conn, addr = nb_active_socket.accept() while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close() """ -- Cheers, Maxim Veksler "Free as in Freedom" - Do u GNU ? From parvini_navid at yahoo.com Wed May 9 01:58:45 2007 From: parvini_navid at yahoo.com (Navid Parvini) Date: Tue, 8 May 2007 22:58:45 -0700 (PDT) Subject: CPU usage. Message-ID: <840961.69835.qm@web54514.mail.yahoo.com> Dear All, I want to get the CPU usage in my code. Is there any module in Python to get it? Also I want to get in on Windows and Linux. Thank you in advance. Navid --------------------------------- Ahhh...imagining that irresistible "new car" smell? Check outnew cars at Yahoo! Autos. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue May 15 04:44:24 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 15 May 2007 10:44:24 +0200 Subject: Trying to choose between python and java In-Reply-To: References: Message-ID: <464972dc$0$23728$426a74cc@news.free.fr> Steven Howe a ?crit : (snip) >> > Flame war? Here amongst all the reasonable adults programmers? It never > happens. > Lol ! +1 QOTW From quentel.pierre at wanadoo.fr Sun May 27 17:07:38 2007 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: 27 May 2007 14:07:38 -0700 Subject: Can python create a dictionary from a list comprehension? In-Reply-To: <1180299312.207986.4340@k79g2000hse.googlegroups.com> References: <1180299312.207986.4340@k79g2000hse.googlegroups.com> Message-ID: <1180300058.809976.156650@p77g2000hsh.googlegroups.com> On 27 mai, 22:55, erikcw wrote: > Hi, > > I'm trying to turn o list of objects into a dictionary using a list > comprehension. > > Something like > > entries = {} > [entries[int(d.date.strftime('%m'))] = d.id] for d in links] > > I keep getting errors when I try to do it. Is it possible? Do > dictionary objects have a method equivalent to [].append? Maybe a > lambda? > > Thanks for your help! > Erik entries = dict([ (int(d.date.strftime('%m')),d.id) for d in links] ) With Python2.4 and above you can use a "generator expression" entries = dict( (int(d.date.strftime('%m')),d.id) for d in links ) Regards, Pierre From bdesth.quelquechose at free.quelquepart.fr Wed May 9 16:42:16 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 09 May 2007 22:42:16 +0200 Subject: Parameter checking on an interfase In-Reply-To: <1178682591.359947.240390@y80g2000hsf.googlegroups.com> References: <1178682591.359947.240390@y80g2000hsf.googlegroups.com> Message-ID: <46422822$0$29857$426a74cc@news.free.fr> w.m.gardella.sambeth at gmail.com a ?crit : > Hi all, > I am more or less new to Python, and currently am making my > first "serious" program. The application is a Clinical History manager > (for my wife) which stores its data on a sqlite database. After > googling on this newsgroup, I have read several threads where is > stated that the LBYL way of testing parameters is not a pythonic way > to work, and that is preferable catch the exceptions generated trying > to use an invalid parameter passed to a function. > Although I am generally following this approach, the problem I > see is that sqlite docs states clearly that the engine does not check > that the data types passed to the SQL sentences matches the types > declared for the column, and lets any kind of information to be put in > any column of the table. When I code the "business objects" of the > application (don't know if this is the exact term for a layer that > will isolate the application from the raw database, letting me change > it in a future if necessary), business objects and databases are not necessarily related. And business objects are much more than a "database abstraction layer" - they are the "model" part of the MVC triad, and are the heart of your application's logic. As such, they are of course in charge of validating their own state wrt/ business rules. > I realize that if I pass arguments of > wrong type (say, a numeric ID instead of the patient name), the DB > engine will accept that gladly, and I will finish with data that could > not be consistently retrievable if I use the DB from another program > (no one right now, but I think of, perhaps, statistical trends on > diseases and treatments). > In this case, could be reasonable add type checking LBYL style > on the methods, so if passed data is of wrong type, it generates a > adequate exception to be catched by the caller? This is more a problem of validation/conversion of values than strictly a typing problem IMHO. As someone said : "be liberal about what you accept and strict about what you send". > In this way, the rest > of the app (mostly GUI) can be coded EAFP style. As programming > background, as you can guess, I have made some programming in C, VBA > and JavaScript (quite procedurally). > I hope that you can bring me some light about this kind of > design, so I can improve my coding and get the Python way faster. I strongly encourage you to have a look at SQLAlchemy (a hi-level RDBMS/python interface and an ORM) and Elixir (an ActiveRecord-like declarative layer on top of SQLAlchemy), and FormEncode (an in/out validation/conversion package). http://www.sqlalchemy.org/ http://elixir.ematia.de/ FWIW, I'm actually working on using the second to add validation/conversion to the first: http://groups.google.com/group/sqlelixir/browse_thread/thread/af7b2d0b87613482 From deets at nospam.web.de Wed May 16 05:08:35 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 16 May 2007 11:08:35 +0200 Subject: Quote aware split References: Message-ID: <5b000jF2qk8trU1@mid.uni-berlin.de> Ondrej Baudys wrote: > Hi, > > After trawling through the archives for a simple quote aware split > implementation (ie string.split-alike that only splits outside of > matching quote) and coming up short, I implemented a quick and dirty > function that suits my purposes. Maybe using the csv module together with cStringIO would be more straightforward. Diez From half.italian at gmail.com Wed May 16 04:40:56 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 16 May 2007 01:40:56 -0700 Subject: setting an attribute In-Reply-To: <1179300898.223314.76430@y80g2000hsf.googlegroups.com> References: <1179300898.223314.76430@y80g2000hsf.googlegroups.com> Message-ID: <1179304856.077195.75260@u30g2000hsc.googlegroups.com> On May 16, 12:34 am, 7stud wrote: > "When you bind (on either a class or an instance) an attribute whose > name is not special...you affect only the __dict__ entry for the > attribute(in the class or instance, respectively)." > > In light of that statement, how would one explain the output of this > code: > > class Test(object): > x = [1, 2] > > def __init__(self): > self.x[0] = 10 > > print Test.__dict__ #{.....'x':[1,2]....} > t = Test() > print t.x #[10, 2] > print t.__dict__ #{} > print Test.__dict__ #{.....'x':[10,2]...} > > It looks to me like self.x[0] is binding on an instance whose > attribute name is not special, yet it doesn't affect any __dict__ > entry for the attribute in the instance--instead it is affecting a > __dict__ entry for the attribute in the class. I think it's following scope rules. It can't find an attribute for self.x in the instance. It then checks the class for the var and finds it and sets it there. It would error otherwise... >>> class Test(object): ... def __init__(self): ... self.x[0] =7 ... >>> t = Test() Traceback (most recent call last): File "", line 1, in File "", line 3, in __init__ AttributeError: 'Test' object has no attribute 'x' ~Sean From showell30 at yahoo.com Tue May 29 19:53:38 2007 From: showell30 at yahoo.com (Steve Howell) Date: Tue, 29 May 2007 16:53:38 -0700 (PDT) Subject: SMTPAuthenticationError In-Reply-To: <1180469172.470577.185720@x35g2000prf.googlegroups.com> Message-ID: <742262.63753.qm@web33502.mail.mud.yahoo.com> --- Ramashish Baranwal wrote: > > Are you sure that your SMTP server uses this type > of authentication? > > Some SMTP servers use POP3 followed by SMTP to > authenticate instead. > > > > use telnet to verify, this link might help. > > > > > http://www.computerperformance.co.uk/exchange2003/exchange2003_SMTP_A... > > > > Hi Larry, > > Thanks for the reply. I have worked according to the > steps in the link > you provided. From that it seems my server accepts > base64 encoded > username and password. I am able to login this way. > How to give the > same in smtplib? > > Ram > To help debug this, you may want to try the following. 1) Copy smptlib.py into your local directory. On my box, you can find it here, or import sys; print sys.path to help find it on your box: /usr/local/lib/python2.3 2) Go the login() method, add some print statements there to see what's going on. I admit to not being an SMTP expert nor fully understanding the code at first glance, but here is some code iin smtplib.py that suggests you're close to getting this working, to the extent that your server wants base64 encoding: def encode_cram_md5(challenge, user, password): challenge = base64.decodestring(challenge) response = user + " " + hmac.HMAC(password, challenge).hexdigest() return encode_base64(response, eol="") Hope this helps. ____________________________________________________________________________________You snooze, you lose. Get messages ASAP with AutoCheck in the all-new Yahoo! Mail Beta. http://advision.webevents.yahoo.com/mailbeta/newmail_html.html From arnodel at googlemail.com Wed May 2 12:49:38 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 2 May 2007 09:49:38 -0700 Subject: I need help speeding up an app that reads football scores and generates rankings In-Reply-To: <1178118022.865173.266300@h2g2000hsg.googlegroups.com> References: <1178118022.865173.266300@h2g2000hsg.googlegroups.com> Message-ID: <1178124578.908184.320540@o5g2000hsb.googlegroups.com> On May 2, 4:00 pm, jocknerd wrote: > About 10 years ago, I wrote a C app that would read scores from > football games and calculate rankings based on the outcome of the > games. In fact, I still use this app. You can view my rankings athttp://members.cox.net/jocknerd/football. > > A couple of years ago, I got interested in Python and decided to > rewrite my app in Python. I got it to work but its painfully slow > compared to the C app. I have a file containing scores of over 1500 > high school football games for last season. With my Python app, it > takes about 3 minutes to process the rankings. With my C app, it > processes the rankings in less than 15 seconds. > > The biggest difference in my two apps is the C app uses linked lists. > I feel my Python app is doing too many lookups which is causing the > bottleneck. > > I'd love some feedback regarding how I can improve the app. I'd like > to drop the C app eventually. Its really ugly. My goal is to > eventually get the data stored in PostgreSQL and then have a Django > powered site to process and display my rankings. > > You can download the source code fromhttp://members.cox.net/jocknerd/downloads/fbratings.py > and the data file fromhttp://members.cox.net/jocknerd/downloads/vhsf2006.txt > > Thanks! A simple improvement is to change your list of teams('teamlist') to a dictionary of teams (call it say 'teamdict') mapping team names to teams. You have lots of #Some code for row in teamlist: if teamname == row['name']: #Do something with row These can all be replaced with: #Some code row = teamdict[teamname] #Do something with row (Although I wouldn't call it 'row' but rather 'team') That may speed up your code significantly. Moreover you can make the main loop (in calcTeamRatings) faster by avoiding looking up a team each time you need some info on it. Finally I would change your schedule list to a list of tuples rather than a list of dictionaries: each game in the schedule would be a tuple (team1, team2, ratio) and wouldn't include the actual team scores as you don't seem to use them in your calcTeamRatings function (that means moving the ratio calculation into the loop that creates the schedule) Disclaimer: I only looked at your code superficially and I don't claim to understand it ! HTH -- Arnaud From larry.bates at websafe.com Wed May 2 18:07:07 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 02 May 2007 17:07:07 -0500 Subject: Cannot execute Windows commands via Python in 64-bit In-Reply-To: <1178143060.952025.85520@h2g2000hsg.googlegroups.com> References: <1178143060.952025.85520@h2g2000hsg.googlegroups.com> Message-ID: nsjmetzger at gmail.com wrote: > I have a script that runs fine in Windows 2003 (32-bit). It basically > calls the Windows defrag command. When I try the exact same code on > Windows 2003 (64-bit) I get the following message: > > C:\Scripts>autodefrag.py > Starting defragment: defrag -v C: >>c:/Scripts/DEFRAG20070502.log > 'defrag' is not recognized as an internal or external command, > operable program or batch file. > > I have tried defrag.exe and even giving it the full path to > defrag.exe. Always the same result. Here is the python code that is > generating this error: > > cmd = "defrag -v C: >>c:/Scripts/DEFRAG20070502.log" > print "Starting defragment: ", cmd > errorlevel = os.system(cmd) > > > Anyone know what the heck is going on and how to fix it? This code > works fine on my 32-bit windows machines. > Thanks. > Sounds like system can't find defrag. Usually this is because of a path issue. Are you running the script in the foreground or scheduled? Can you open a command prompt and enter the command and have it work? If you give full path, this shouldn't be the problem. -Larry From basilisk96 at gmail.com Wed May 2 17:02:29 2007 From: basilisk96 at gmail.com (Basilisk96) Date: 2 May 2007 14:02:29 -0700 Subject: How to check if a string is empty in python? In-Reply-To: <1178139155.260722.153750@n59g2000hsh.googlegroups.com> References: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> <1178138964.503290.254060@o5g2000hsb.googlegroups.com> <1178139155.260722.153750@n59g2000hsh.googlegroups.com> Message-ID: <1178139749.693981.49760@n76g2000hsh.googlegroups.com> > How do you know that s is a string? It's a presumption based on the original problem statement. The example shown is a simple T/F check, which happens to determine the "emptiness" of strings. If type checking is absolutely necessary, one could use if isinstance(s, basestring): if s: print "not empty" else: print "empty" From sjmachin at lexicon.net Tue May 8 18:30:01 2007 From: sjmachin at lexicon.net (John Machin) Date: 8 May 2007 15:30:01 -0700 Subject: msbin to ieee In-Reply-To: <1178619341.882665.245470@e51g2000hsg.googlegroups.com> References: <1178487847.671199.108140@h2g2000hsg.googlegroups.com> <1178502738.104124.3840@h2g2000hsg.googlegroups.com> <1178525916.145819.264070@n59g2000hsh.googlegroups.com> <1178536910.566119.6650@o5g2000hsb.googlegroups.com> <1178539202.316506.199940@p77g2000hsh.googlegroups.com> <1178542593.668743.71500@u30g2000hsc.googlegroups.com> <1178545075.530201.180120@u30g2000hsc.googlegroups.com> <1178573895.164509.82270@u30g2000hsc.googlegroups.com> <1178619341.882665.245470@e51g2000hsg.googlegroups.com> Message-ID: <1178663401.061610.296340@e51g2000hsg.googlegroups.com> On May 8, 8:15 pm, revuesbio wrote: > On 7 mai, 23:38, John Machin wrote: > > > > > On May 7, 11:37 pm, revuesbio wrote: > > > > On 7 mai, 14:56, John Machin wrote: > > > > > On May 7, 10:00 pm, revuesbio wrote: > > > > > > On 7 mai, 13:21, John Machin wrote: > > > > > > > On May 7, 6:18 pm, revuesbio wrote: > > > > > > > > On 7 mai, 03:52, John Machin wrote: > > > > > > > > > On May 7, 7:44 am, revuesbio wrote: > > > > > > > > > > Hi > > > > > > > > > Does anyone have the python version of the conversion from msbin to > > > > > > > > > ieee? > > > > > > > > > Thank u > > > > > > > > > Yes, Google has it. Google is your friend. Ask Google. It will lead > > > > > > > > you to such as: > > > > > > > > >http://mail.python.org/pipermail/python-list/2005-August/337817.html > > > > > > > > > HTH, > > > > > > > > John > > > > > > > > Thank you, > > > > > > > > I've already read it but the problem is always present. this script is > > > > > > > for double precision MBF format ( 8 bytes). > > > > > > > It would have been somewhat more helpful had you said what you had > > > > > > done so far, even posted your code ... > > > > > > > > I try to adapt this script for single precision MBF format ( 4 bytes) > > > > > > > but i don't find the right float value. > > > > > > > > for example : 'P\xad\x02\x95' will return '0.00024924660101532936' > > > > > > > If you know what the *correct* value is, you might like to consider > > > > > > shifting left by log2(correct_value/erroneous_value) :-) > > > > > > > Do you have any known correct pairs of (mbf4 string, decimal_float > > > > > > value)? My attempt is below -- this is based on a couple of > > > > > > descriptive sources that my friend Google found, with no test data. I > > > > > > believe the correct answer for the above input is 1070506.0 i.e. you > > > > > > are out by a factor of 2 ** 32 > > > > > > > def mbf4_as_float(s): > > > > > > m0, m1, m2, m3 = [ord(c) for c in s] > > > > > > exponent = m3 > > > > > > if not exponent: > > > > > > return 0.0 > > > > > > sign = m2 & 0x80 > > > > > > m2 |= 0x80 > > > > > > mant = (((m2 << 8) | m1) << 8) | m0 > > > > > > adj = 24 + 128 > > > > > > num = mant * 2.0 ** (exponent - adj) > > > > > > if sign: > > > > > > return -num > > > > > > return num > > > > > > > HTH, > > > > > > John > > > > > > well done ! it's exactly what i'm waiting for !! > > > > > > my code was:>>> from struct import * > > > > > >>> x = list(unpack('BBBB','P\xad\x02\x95')) > > > > > >>> x > > > > > [80, 173, 2, 149] > > > > > >>> def conversion1(bytes): > > > > > > b=bytes[:] > > > > > sign = bytes[-2] & 0x80 > > > > > b[-2] |= 0x80 > > > > > exp = bytes[-1] - 0x80 - 56 > > > > > acc = 0L > > > > > for i,byte in enumerate(b[:-1]): > > > > > acc |= (long(byte)<<(i*8)) > > > > > return (float(acc)*2.0**exp)*((1.,-1.)[sign!=0]) > > > > > Apart from the 2**32 problem, the above doesn't handle *any* of the > > > > 2**24 different representations of zero. Try feeding \0\0\0\0' to it > > > > and see what you get. > > > > > > >>> conversion1(x) > > > > > > 0.00024924660101532936 > > > > > > this script come from google groups but i don't understand bit-string > > > > > manipulation (I'm a newbie). informations about bit-string > > > > > manipulation with python is too poor on the net. > > > > > The basic operations (and, or, exclusive-or, shift) are not specific > > > > to any language. Several languages share the same notation (& | ^ << > > > > > >>), having inherited it from C. > > > > > > thank you very much for your script. > > > > > Don't thank me, publish some known correct pairs of values so that we > > > > can verify that it's not just accidentally correct for 1 pair of > > > > values. > > > > pairs of values : > > > (bytes string, mbf4_as_float(s) result) right > > > float value > > > ('P\xad\x02\x95', 1070506.0) > > > 1070506.0 > > > ('\x00\x00\x00\x02', 5.8774717541114375e-039) 0.0 > > > There is no way that \x00\x00\x00\x02' could represent exactly zero. > > What makes you think it does? Rounding? > > > > ('\x00\x00\x00\x81', 1.0) > > > 1.0 > > > ('\x00\x00\x00\x82', 2.0) > > > 2.0 > > > ('\x00\x00@\x82', 3.0) > > > 3.0 > > > ('\x00\x00\x00\x83', 4.0) > > > 4.0 > > > ('\x00\x00 \x83', 5.0) > > > 5.0 > > > ('\xcd\xcc\x0c\x81', 1.1000000238418579) 1.1 > > > ('\xcd\xcc\x0c\x82', 2.2000000476837158) 2.2 > > > ('33S\x82', 3.2999999523162842) 3.3 > > > ('\xcd\xcc\x0c\x83', 4.4000000953674316) 4.4 > > > It is not apparent whether you regard the output from the function as > > correct or not. > > > 4.4 "converted" to mbf4 format is '\xcd\xcc\x0c\x83' which is > > 4.4000000953674316 which is the closest possible mbf4 representation > > of 4.4 (difference is 9.5e-008). > > > The next lower mbf4 value '\xcc\xcc\x0c\x83' is 4.3999996185302734 > > (difference is -3.8e-007). > > > Note that floating-point representation of many decimal fractions is > > inherently inexact. print repr(4.4) produces 4.4000000000000004 > > > Have you read this: > > http://docs.python.org/tut/node16.html > > ? > > > If you need decimal-fraction output that matches what somebody typed > > into the original software, or saw on the screen, you will need to > > know/guess the precision that was involved, and round the numbers > > accordingly -- just like the author of the original software would > > have needed to do. > > > >>> ['%.*f' % (decplaces, 4.4000000953674316) for decplaces in range(10)] > > > ['4', '4.4', '4.40', '4.400', '4.4000', '4.40000', '4.400000', > > '4.4000001', '4.40000010', '4.400000095'] > > > HTH, > > John > > another couples and round number corresponding to the right value > > ('\x00\x00\x00\x02', 5.8774717541114375e-039, '0.000') [snip] > all is ok. > thank u I have not yet found a comprehensive let alone authoritative description of the Microsoft binary floating format. However I've seen enough to form a view that in general converting '\x00\x00\x00\x02' to 0.0 would be a mistake, and that 5.8774717541114375e-039 is the correct answer. Why do I think so? There's a Borland/Inprise document on the wotsit.org website that gives C functions for conversion both ways between MBF and IEEE formats (both 32 bits and 64 bits). They are supposed to mimic functions that were in the MS C runtime library at one stage. The _fieeetomsbin (32 bits) function does NOT make a special case of IEEE 0.0; it passes it through the normal what is the exponent, what is the mantissa routine, and produces '\x00\x00\x00\x02' (ms exponent field == 2). The converse routine regards any MBF number with exponent 0 as being 0.0, and puts anything else through the normal cycle -- which is a nonsense with MBF exponent == 1, by the way (because of the offset of 2, the result in IEEE-32- bit is an exponent of -1 which becomes 255 which tags the result as infinity or NaN (not a number)). The lack of round-trip sameness for 0.0 is so astonishing that it this were true one would have expected it to be remarked on somewhere. So: It is probably sufficient for your application to round everything to 3 decimal places, but I thought I'd better leave this note to warn anyone else who might want to use the function. I am curious as to what software created your MBF-32-bit numbers ... care to divulge? Cheers, John From sutabi at gmail.com Tue May 29 08:48:27 2007 From: sutabi at gmail.com (Needless) Date: 29 May 2007 05:48:27 -0700 Subject: Video tutorials In-Reply-To: References: Message-ID: <1180442907.739691.205740@a26g2000pre.googlegroups.com> How much more complex? On May 28, 1:20 am, Laurentiu wrote: > Hello! > > i was searching the net for some video tutorials (free > and payed). > > i found some interesting stuff atwww.showmedo.combut > i want something more complex. > > can someone give me some address for video tutorials > or companies how made this tutorials, free or payed. > > i search at Lynda.com and vtc but i didn't find any > python references. > > thanks for all answers. > > Laurentiu > > ___________________________________________________________ > Yahoo! Mail is the world's favourite email. Don't settle for less, sign up for > your free account todayhttp://uk.rd.yahoo.com/evt=44106/*http://uk.docs.yahoo.com/mail/winte... From aspineux at gmail.com Thu May 31 07:38:51 2007 From: aspineux at gmail.com (aspineux) Date: 31 May 2007 04:38:51 -0700 Subject: replace the base class In-Reply-To: <1180563934.099612.244460@q19g2000prn.googlegroups.com> References: <1180557641.633245.189900@p77g2000hsh.googlegroups.com> <1180563934.099612.244460@q19g2000prn.googlegroups.com> Message-ID: <1180611531.370531.153160@g4g2000hsf.googlegroups.com> Larry: Using "as", I cannot use both Circle and ColorCircle or more like 3DCircle ... at the same time, only one of them. But this is a easy solution in some cases. On 31 mai, 00:25, Matimus wrote: Hi Martimus, your idea was a good one, I used it to meet my _particular_ needs. I was expecting something more complicate with metaclass, object introspection .... I used an interface (like in Java, a class with just method that must work in // with anoter class). Finally the "replacement" of the base class in done with a simple : class ColorCircle(ColorGraphInterface, Circle): graph_base_class=Circle Here is my full working test code class Graph: def plot(self): print 'Graph.plot' class Circle(Graph): def draw(self): print 'Circle.draw' self.plot() class Square(Graph): def draw(self): print 'Square.draw' self.plot() class ColorGraphInterface: graph_base_class=None def plot(self): print 'ColorGraphInterface.plot' self.graph_base_class.plot(self) def draw(self): print 'ColorGraphInterface.draw' self.graph_base_class.draw(self) class ColorCircle(ColorGraphInterface, Circle): graph_base_class=Circle class ColorCircle(ColorGraphInterface, Square): graph_base_class=Square cc=ColorCircle() cc.draw() > This is a rather simplistic example, but you may be able to use a > mixin class to achieve what you need. The idea is that you write a > class that overrides only what is needed to add the new functionality. > For you it would be Color. > > [code] > class Graph(object): > def _foo(self): > print "Graph._foo" > > class Color(object): > def _foo(self): > print "Color._foo" > > class Circle(Graph): > def bar(self): > self._foo() > > class ColorCircle(Color,Circle): # the order of parent classes is > important > pass > > if __name__ == "__main__": > c1 = Circle() > c2 = ColorCircle() > > c1.bar() #prints: Graph._foo > c2.bar() #pritns: Color._foo > [/code] > > You might not have to do anything already. Try this and see if it > works: > > [code] > > ColorCircle(ColorGraph,Circle): > pass > > [/code] > > Note that you will probably have to create an __init__ method, and > explicitly call the __init__ methods for the base classes. If the > __init__ for Circle ends up calling the __init__ method from Graph, > you may have issues. That is why the Color mixin that I created > inherited from object not Graph. It helps to avoid clashing __init__ > methods. Yes I know, super() do a great job for that :-) > > Matt From phil at riverbankcomputing.co.uk Thu May 31 04:19:54 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Thu, 31 May 2007 09:19:54 +0100 Subject: qt doevent In-Reply-To: <1180598645.635930.183950@o5g2000hsb.googlegroups.com> References: <1180598645.635930.183950@o5g2000hsb.googlegroups.com> Message-ID: <200705310919.54289.phil@riverbankcomputing.co.uk> On Thursday 31 May 2007 9:04 am, luca72 wrote: > Hello at all > I try to use qt , but i have problem, i don't find the command like > wx.Yield() in wx or doevent in vb. > Can you tell me the same command in qt QApplication.processEvents() Phil From adam at atlas.st Wed May 2 17:15:28 2007 From: adam at atlas.st (Adam Atlas) Date: 2 May 2007 14:15:28 -0700 Subject: Can I use Python instead of Joomla? In-Reply-To: <1178138925.498663.252920@o5g2000hsb.googlegroups.com> References: <1178138925.498663.252920@o5g2000hsb.googlegroups.com> Message-ID: <1178140528.005926.149590@h2g2000hsg.googlegroups.com> On May 2, 4:48 pm, walterbyrd wrote: > If I wanted to build a website with forums, news feeds, galleries, > event calander, document managment, etc. I do so in Joomla easily. > > But, I would perfer to use django/python, if that would be at all > practical. > > I suppose I could put python scripts into django, if those scripts > exist. Have you looked at Zope/Plone? It's not Django, but they're the de facto standards in the Python world for that sort of thing. From bj_666 at gmx.net Mon May 7 03:21:36 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 07 May 2007 09:21:36 +0200 Subject: Examples / Links needed References: <1178515847.621303.270280@o5g2000hsb.googlegroups.com> Message-ID: In <1178515847.621303.270280 at o5g2000hsb.googlegroups.com>, Andy wrote: > Gurus, I'm looking for definite examples (pardon me if I'm not clear > here) on Stack class...Somewhat like this : > > class Stack(object): > def __init__(self__) > self.__contents = [] I don't know what to tell you here without writing the thing for you. Ask yourself what operations a `Stack` needs and look at the documentation for `list` operations. It's pretty easy to map the stack operations to `list` ones. > and ad hoc implementation of a class based on number system like for > example somewhat like this > > > def __imult__(self, other): > self.__numerator *= other.__numerator > self.__denominator *= other.__denominator > . > . > return self So what exactly is your problem? Take a "number like", look at the methods it implements and do this for your "number like" class. > I'm not satisfied with Python Docs. Why? What does `Emulating numeric types`_ in the reference manual lack in your opinion? .. _Emulating numeric types: http://docs.python.org/ref/numeric-types.html Ciao, Marc 'BlackJack' Rintsch From waldemar.osuch at gmail.com Sun May 20 17:01:27 2007 From: waldemar.osuch at gmail.com (Waldemar Osuch) Date: 20 May 2007 14:01:27 -0700 Subject: pyExcelerator bug? In-Reply-To: <1179355368.793891.233240@u30g2000hsc.googlegroups.com> References: <1179355368.793891.233240@u30g2000hsc.googlegroups.com> Message-ID: <1179694886.941462.308560@b40g2000prd.googlegroups.com> On May 16, 4:42 pm, tkp... at hotmail.com wrote: > My program creates three lists: the first has dates expressed as > strings, the second has floats that are strictly positive, and the > third has floats that are strictly negative. I have no trouble writing > the data in these lists to a .csv file using the csv module using the > following code. > > outfile = file(fn + '.csv','wb') > writer = csv.writer(outfile) > for i in range(len(dateList)): > writer.writerow([dateList[i], posVals[i], negVals[i]]) > outfile.close() > > However, when I try to write to an Excel file usingpyExcelerator(see > code below), the third list is not always written correctly - my > program sometimes writes positive numbers into the third column of the > spreadsheet. Is this a known bug? if so, is there a workaround? IspyExceleratorbeing developed any longer? My attempts to reach the > developer have gone nowhere. > > w =pyExcelerator.Workbook() > ws = w.add_sheet(fn + p) > for i,d in enumerate(dateList): > ws.write(i+1, 0, dateList[i]) > ws.write(i+1, 1, posVals[i]) > ws.write(i+1, 2, negVals[i]) > w.save(fn+'.xls') > > Sincerely > > Thomas Philps Try using this patch on Cell.py and see if it fixes your problem: --- Cell.py (revision 4522) +++ Cell.py (revision 4523) @@ -101,6 +101,14 @@ def get_biff_data(self): + return BIFFRecords.NumberRecord(self.__parent.get_index(), self.__idx, self.__xf_idx, self.__number).get() + # Skipping all the logic below. + # From what I understand it tries to save space. + # Unfortunately it gets it wrong and produces false results. + # For example: + # 814289000 gets written out as -259452824 + From bbxx789_05ss at yahoo.com Sat May 19 12:45:09 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 19 May 2007 09:45:09 -0700 Subject: Beginner question: module organisation In-Reply-To: <1179148188.698342.317080@w5g2000hsg.googlegroups.com> References: <1179148188.698342.317080@w5g2000hsg.googlegroups.com> Message-ID: <1179593109.409934.193690@l77g2000hsb.googlegroups.com> On May 14, 7:09 am, Mail.To.Nathan... at gmail.com wrote: > Hello :) > > I am new to python and I don't have much expirience in object-oriented > technologies neither. > > The problem is the following: I have to create a simple python > template script that will always follow the same algorithm, let's say: > - read a mesh > - transform the mesh (let's say, refine) > > The last step should be a kind of a black box: > - the same input data format > - some algorithme inside > - the same output data format > > A number of different refine methods should be implemented. The end- > user must be able to write easily a new method and call it from the > base script without any major change. > > Something like this would be a solution (no classes created, no OO > programming): > - a module defining REFINE1(mesh), REFINE2(mesh), ... > - in the script: > from MODULE import REFINE2 as REFINE > REFINE(mesh) > > Is it a proper solution for this kind of problem? How would you > implement this kind of task? How about this: refineModule.py: --------------- def refine(userfunc, mesh): #process mesh func(mesh) aprogram.py: ------------ import refineModule def myRefine(mesh): print mesh refineModule.refine(myRefine, "hello world") From mangabasi at gmail.com Wed May 23 15:30:41 2007 From: mangabasi at gmail.com (Mangabasi) Date: 23 May 2007 12:30:41 -0700 Subject: Inheriting from Python list object(type?) In-Reply-To: <1179948261.685010.40300@a26g2000pre.googlegroups.com> Message-ID: <1179948641.489306.276890@k79g2000hse.googlegroups.com> On May 23, 2:24 pm, Lyosha wrote: > On May 23, 12:19 pm, Lyosha wrote: > > > > > On May 23, 12:07 pm, Mangabasi wrote: > > > > On May 23, 1:43 pm, "Jerry Hill" wrote: > > > > > On 23 May 2007 11:31:56 -0700, Mangabasi wrote: > > > > > > When I modified this to: > > > > > > class Point(list): > > > > > def __init__(self,x,y): > > > > > super(Point, self).__init__([x, y]) > > > > > self.x = x > > > > > self.y = y > > > > > > It worked. > > > > > Are you sure? > > > > > >>> p = Point(10, 20) > > > > >>> p > > > > [10, 20] > > > > >>> p.x > > > > 10 > > > > >>> p.x = 15 > > > > >>> p > > > > [10, 20] > > > > >>> p[0] > > > > 10 > > > > >>> p.x > > > > 15 > > > > > That doesn't look like what you were asking for in the original post. > > > > I'm afraid I don't know anything about numpy arrays or what special > > > > attributes an object may need to be put into a numpy array though. > > > > > -- > > > > Jerry > > > > This is the winner: > > > > class Point(list): > > > def __init__(self, x, y, z = 1): > > > super(Point, self).__init__([x, y, z]) > > > self.x = x > > > self.y = y > > > self.z = z > > > [...] > > >http://docs.python.org/dev/whatsnew/node3.htmlannouncesnamed tuples > > in python2.6. This is not what you want since tuples are immutable, > > but you might get some inspiration from their implementation. Or > > maybe not. > > Dude, google groups suck! They say "an error has occurred" and the > message is happily posted. Tell me about it! :) From aspineux at gmail.com Wed May 30 16:49:55 2007 From: aspineux at gmail.com (aspineux) Date: 30 May 2007 13:49:55 -0700 Subject: file / module / package - import problem In-Reply-To: References: Message-ID: <1180558195.130303.310160@k79g2000hse.googlegroups.com> The filename and its path is in global variable __file__ (that is different in any source file) try import os.path file=open(os.path.join(os.path.dirname(__file__), 'hauteur.yaml')) On 30 mai, 22:22, EuGeNe Van den Bulke wrote: > Hi there, > > I have a "problem" which could be a bad design on my behalf but I am not > sure so ... > > I have a package WMI which contains a module hauteur.py which, when > imported, load data from a file located in WMI/data/. In hauteur.py I > call open('data/hauteur.yaml'). > > test.py > WMI/ > hauteur.py > data/ > hauteur.yaml > lot.py > > It works well when hauteur is imported in lot.py but if I try import > WMI.hauteur in test.py it doesn't work because it looks for the > hauteur.yaml file in the "wrong" place. > > Is there a way to tell a module in a package to look for a file in a > specific place i.e. a within package location? > > Thanks, > > EuGeNe --http://www.3kwa.com From http Sun May 27 23:41:35 2007 From: http (Paul Rubin) Date: 27 May 2007 20:41:35 -0700 Subject: Newbie question - better way to do this? References: <1180273441.455227.120170@g4g2000hsf.googlegroups.com> Message-ID: <7x4plx398w.fsf@ruckus.brouhaha.com> Eric writes: > words is a big long array of strings. What I want to do is find > consecutive sequences of words that have the first letter capitalized, > and then call doSomething on them. (And you can ignore the fact that > it won't find a sequence at the very end of words, that is fine for my > purposes). As another poster suggested, use itertools.groupby: for cap,g in groupby(words, firstIsCapitalized): if cap: doSomething(list(g)) This will handle sequences at the the end words just like other sequences. From DPhillips at cybergroup.com Thu May 24 14:07:08 2007 From: DPhillips at cybergroup.com (Doug Phillips) Date: Thu, 24 May 2007 13:07:08 -0500 Subject: installing cx_Oracle. In-Reply-To: <1180028135.3395.25.camel@dot.uniqsys.com> Message-ID: <9A9D5186629F3D428E3C7CBA92A66E47C7A8FA@mail-26ps.atlarge.net> > It also works the other way around, at least on the non-empty > set of systems that contains my workstation. export simply > marks the variable name for automatic export to the > environment of subsequent commands. The value at that time > doesn't matter. What matters is the value that the name has > at the time the command is run: > > [carsten at dot ~]$ export FOOD > [carsten at dot ~]$ FOOD=spam > [carsten at dot ~]$ python -c "import os; print os.environ['FOOD']" > spam > [carsten at dot ~]$ FOOD=eggs > [carsten at dot ~]$ python -c "import os; print os.environ['FOOD']" > eggs Just tried on a FreeBSD 6.1 development box with stock /bin/sh and it works there too... ... And I just learned something new! -Doug From SuperM at ssiveBlackHoleAtTheCenterOfTheMilkyWayGalaxy.org Thu May 3 21:22:24 2007 From: SuperM at ssiveBlackHoleAtTheCenterOfTheMilkyWayGalaxy.org (The Great Attractor) Date: Thu, 03 May 2007 18:22:24 -0700 Subject: Firefighters at the site of WTC7 "Move away the building is going to blow up, get back the building is going to blow up." References: <1178161820.731367.264500@y80g2000hsf.googlegroups.com> <1178163974.007362.13870@c35g2000hsg.googlegroups.com> <1178172877.755445.101340@q75g2000hsh.googlegroups.com> <1178173090.238547.62190@o5g2000hsb.googlegroups.com> <1178207619.155007.129860@o5g2000hsb.googlegroups.com> Message-ID: On 3 May 2007 08:53:39 -0700, malibu wrote: >On May 3, 12:18 am, Eric Gisse wrote: >> On May 2, 10:14 pm, malibu wrote: >> >> > On May 2, 9:46 pm, Eric Gisse wrote: >> >> > > On May 2, 7:10 pm, Midex wrote: >> >> > > [...] >> >> > > I guess the explanation that people were looking at the building and >> > > watching its' structure deform is too rational. >> >> > Also, that was a Larry Silverstein impostor who >> > said they were going to 'pull it'. >> >> ...maybe if you read the context, it would make a little more rational >> sense. Fucking nutter. >> >> > And the only reason he took out huge amounts >> > of extra insurance on the buildings two months >> > before this happened was because of global >> > warming, because we all know a little bit of heat >> > will bring down steel buildings. >> >> A little heat and major structural damage. >> >> >> >> > John > >Gee, I'll bet all those explosions in the >subfloors of WTC1 + WTC2 did some >structural damage also! You're an idiot. > >Come to think of it. Slugs do not think. > >When the firefighters got there, all the glass >on the street floors was blown out. You're an idiot. >Shock wave from the plane hitting >80 floors up? You're a goddamned retard, boy. ARe you an islamic extremist by chance? > >Janitors and such coming up from the basement levels >bleeding and dazed. You're full of shit. > >Jet fuel trickling down the elevator shafts being ignited >by someone's roach? And exploding? You're an ifiot. >Severing the three-foot thick steel columns? >All 5 dozen of them? >(That's mighty fine primo, pardner!) The buildings collapsed WAY WAY UP on the floors where the planes hit, and fell from there down, taking floors out as the large top section of the building fell. You could be a bit more retarded, just not in this life. >Your brain got structural damage? No, but your never was right from the moment your retarded felon criminal mother shat you out of her ass and forgot to flush. >Dropped on your head as a kid? Got any more adolescent baby bullshit, little boy? >Don't put that fire iron too close >to the flames, honey. It'll melt >and deform! You're an idiot. There was a tanker crash in Oakland a couple days back (Sunday) that melted sections of the bridge it was on. Got Clue? You and Rosie are retarded. From chris at newcenturycomputers.net Thu May 24 10:41:17 2007 From: chris at newcenturycomputers.net (Chris Gonnerman) Date: Thu, 24 May 2007 09:41:17 -0500 Subject: Python on Vista installation issues In-Reply-To: <46544261.3030206@newcenturycomputers.net> References: <1179868315.458709.114000@p47g2000hsd.googlegroups.com> <46544261.3030206@newcenturycomputers.net> Message-ID: <4655A40D.3020108@newcenturycomputers.net> Okay, I've figured it out. It's easy (but stupid)... right click the extension installer program, and choose Run as Administrator. Just posting this so the next Google search for an answer might actually find one. -- ------------------------------------------------------------------------------- Chris Gonnerman Owner, New Century Computers Phone 660-213-3822 Fax 660-213-3339 From john at datavoiceint.com Mon May 14 10:22:53 2007 From: john at datavoiceint.com (HMS Surprise) Date: 14 May 2007 07:22:53 -0700 Subject: Time In-Reply-To: <1179151205.987222.54910@k79g2000hse.googlegroups.com> References: <1178916216.893542.257320@y80g2000hsf.googlegroups.com> <1178916422.065108.312920@l77g2000hsb.googlegroups.com> <1178920014.621031.301860@n59g2000hsh.googlegroups.com> <1178927105.482975.174760@y5g2000hsa.googlegroups.com> <1179151205.987222.54910@k79g2000hse.googlegroups.com> Message-ID: <1179152573.315362.37040@u30g2000hsc.googlegroups.com> > if t[2] == 'PM': > hrMn[0] = int(hrMn[0]) + 12 > Oops, should be: hrMn[0] = int(hrMn[0] if t[2] == 'PM': hrMn[0] += 12 From walterbyrd at iname.com Fri May 18 21:19:48 2007 From: walterbyrd at iname.com (walterbyrd) Date: 18 May 2007 18:19:48 -0700 Subject: No Python for Blackberry? Message-ID: <1179537588.505753.275200@q75g2000hsh.googlegroups.com> I could not find a version of Python that runs on a Blackberrry. I'm just amazed. A fairly popular platform, and no Python implementation? From jim at reallykillersystems.com Tue May 8 12:49:43 2007 From: jim at reallykillersystems.com (James Beck) Date: Tue, 8 May 2007 12:49:43 -0400 Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> <08qk33t594ih0ulmjmev90d22lkfnotgoe@4ax.com> <463C2A3A.8332D211@hotmail.com> <0k8p33h90bp5tfajedb4bmd2eik8gfi2ho@4ax.com> Message-ID: In article , quasi at null.set says... > On Mon, 7 May 2007 10:55:55 -0400, James Beck > wrote: > > >In article <0k8p33h90bp5tfajedb4bmd2eik8gfi2ho at 4ax.com>, quasi at null.set > >says... > >> On Sat, 05 May 2007 07:54:50 +0100, Eeyore > >> wrote: > >> > >> > > >> > > >> >quasi wrote: > >> > > >> >> Gib Bogle wrote: > >> >> > >> >> >Ah, so the firefighters were in on the conspiracy! > >> >> > >> >> No, but the firefighters are very much aware that there is more to > >> >> 9/11 than has been officially revealed. > >> >> > >> >> This is even more true at Pentagon. The firefighters there brought > >> >> dogs trained to search for survivors and/or remains > >> > > >> >Sounds like good practice. > >> > > >> > > >> >> and found nothing. > >> > > >> >And the significance of this is ? > >> > >> The plane was supposed to have passengers. > >> > >> quasi > >> > >Yep, and they found them all, therefore, there were none for the dogs to > >find. > > You pretty much made that up. > Yep, you must have access to better drugs than I do. You get to hallucinate your stuff up. Don't forget to adjust your tin beanie! Jim From castironpi at gmail.com Mon May 7 21:00:52 2007 From: castironpi at gmail.com (castironpi at gmail.com) Date: 7 May 2007 18:00:52 -0700 Subject: inspected console In-Reply-To: <1178585958.578959.149680@e65g2000hsc.googlegroups.com> References: <1178581950.683620.251980@y80g2000hsf.googlegroups.com> <1178585958.578959.149680@e65g2000hsc.googlegroups.com> Message-ID: <1178586052.774829.92620@y5g2000hsa.googlegroups.com> On May 7, 7:59 pm, castiro... at gmail.com wrote: > On May 7, 6:52 pm, castiro... at gmail.com wrote: > > > > > Presents a console permitting inspection. Input as well as output > > saved in Python-readable form. > > Python 2.5.1 memoryconsole4.py logging to My Documents\console.log>>> class A: > > > ... def f( self ): > > ... print 2 > > ...>>> a=A() > > >>> import inspect > > >>> inspect.getsource( a.f ) > > > '\tdef f( self ):\n\t\tprint 2\n' > > > This enabled by a log file, optionally set to console.log. Contents > > are: > > > #Mon May 07 2007 06:33:42 PM Python win32 2.5.1 in memoryconsole4.py > > class A: > > def f( self ): > > print 2 > > > a=A() > > import inspect > > inspect.getsource( a.f ) > > #fb: '\tdef f( self ):\n\t\tprint 2\n' > > > Line 10 Microsoft Win32 convenience binding; line 49 a little > > confusing. Give it a shot. > > > from code import InteractiveConsole > > import sys > > from os import environ > > from datetime import datetime > > from StringIO import StringIO > > from re import sub > > from os.path import join,split,abspath > > > class LoggedStdOut(StringIO): > > deflog= environ['USERPROFILE']+\ > > '\\My Documents\\console.log' > > def __init__( self, log=None ): > > StringIO.__init__( self ) > > self.stdout= None > > self.trip,self.head= True,'' > > self.logname= log or LoggedStdOut.deflog > > self.prettyname=join(split(split(abspath( > > self.logname))[0])[1],split(abspath(self.logname))[1]) > > for x,_ in enumerate( open( self.logname,'r' ) ): continue > > self._lineno= x #can use linecache > > self._log= open( self.logname,'a' ) > > def catch( self,head='#fb: ' ): > > self.stdout= sys.stdout > > sys.stdout= self > > self.head= head > > self.trip= True > > def throw( self ): > > sys.stdout= self.stdout > > self.stdout= None > > def getlineno( self ): > > return self._lineno > > def logwrite( self, data ): > > self._log.write( data ) > > self._lineno+= data.count('\n') > > def logflush( self ): > > self._log.flush() > > def write( self, data ): > > datal= sub( '\n([^$])','\n%s\\1'%self.head,data ) > > if self.trip: self.logwrite( self.head ) > > self.logwrite( datal ) > > self.trip= data.endswith('\n') > > return self.stdout.write( data ) > > def writelines( self, data ): > > raise 'Branch uncoded' > > > class LoggedInteractiveConsole(InteractiveConsole): > > def __init__( self,log=None,locals=None,filename=None ): > > self.out= LoggedStdOut( log ) > > if filename is None: filename= split(self.out.logname)[1] > > InteractiveConsole.__init__( self,locals,filename ) > > self.locals.update( __logname__= abspath( > > self.out.logname ) ) > > def push( self,line ): > > self.out.logwrite( '%s\n'%line ) > > self.out.logflush() > > self.out.catch() > > more= InteractiveConsole.push( self,line ) > > self.out.throw() > > return more > > def write( self,data ): > > return sys.stdout.write( data ) > > def interact( self,banner=None,*args ): > > self.out.logwrite( '\n#%s Python %s %s in %s\n'%\ > > ( datetime.now().strftime( > > '%a %b %d %Y %I:%M:%S %p' ), > > sys.platform,sys.version.split()[0], > > split(sys.argv[0])[1] ) ) > > if banner is None: banner=\ > > "Python %s %s logging to %s"%\ > > ( sys.version.split()[0],split(sys.argv[0])[1], > > self.out.prettyname ) > > return InteractiveConsole.interact( self,banner,*args ) > > > import compiler > > import linecache > > class NotatedConsole(LoggedInteractiveConsole): > > """-Code object- intercepted in runsource, and rerun with > > stored source before runsource. Built-in runsource > > does not modify source between call and runcode.""" > > def runsource( self,sc,filename='',*args ): > > self._runsourceargs= sc,filename > > return LoggedInteractiveConsole.runsource( self,sc, > > filename,*args ) > > def runcode( self,*args ): > > sc,filename= self._runsourceargs > > linecache.checkcache( filename ) > > #custom second compile (fourth actually) > > t= compiler.parse( sc ) > > compiler.misc.set_filename( filename,t ) > > def set_lineno( tree, initlineno ): > > worklist= [ tree ] > > while worklist: > > node= worklist.pop( 0 ) > > if node.lineno is not None: > > node.lineno+= initlineno > > worklist.extend( node.getChildNodes() ) > > set_lineno( t,self.out.getlineno()-len( self.buffer )+1 ) > > code= compiler.pycodegen.\ > > InteractiveCodeGenerator( t ).getCode() > > LoggedInteractiveConsole.runcode( self,code ) > > linecache.checkcache( filename ) > > > if __name__=='__main__': > > console= NotatedConsole() > > console.interact() > > Console-defined objects can be pickled as well. ">>>edit()" opens > console.log. Editor objects are pickled between statements. > > Python 2.5.1 furtherconsoles-display.py logging to My Documents > \console.log>>> class A: > > ... b=0 > ...>>> from pickle import loads,dumps > >>> loads(dumps(A)) > > >>> loads(dumps(A)).b > 0 > >>> edit() > > Loaded ok > > and the few lines from console.log: > #Mon May 07 2007 07:55:30 PM Python win32 2.5.1 in furtherconsoles- > display.py > class A: > b=0 > > from pickle import loads,dumps > loads(dumps(A)) > #fb: > loads(dumps(A)).b > #fb: 0 > edit() > > Hard coded paths on lines 24 and 67. Hope that's copy-and-pasteable > > import memoryconsole4 as memoryconsole > from os.path import join,exists,split,abspath > from os import environ > from sys import argv > import sys > import cPickle as pickle > from subprocess import Popen > from datetime import datetime,timedelta > > class Editors: > """Pickled after every statement.""" > def edit( self,filename=None ): > assert hasattr( self,'_cmdlinestr' ) and hasattr( self,'console' ) > if filename is None: filename= abspath( self.console.out.logname ) > parms= { 'filename': filename, 'loglen': self.console.out.getlineno() > +len(self.console.buffer)+1 } > Popen( self._cmdlinestr % parms ) > print >>sys.stderr, "Loaded ok" > def __repr__( self ): > return '<%s at %i: %s>'%(self.__class__,id(self),repr( [ x for x in > dir(self) if not x.startswith('__') ] )) > def __call__( self,*args ): > self.edit( *args )#what find default? > > class EditorsConsole(memoryconsole.NotatedConsole): > defdat= join( environ['USERPROFILE'],'My Documents\ > \consoleeditor.pickle' ) > def __init__( self,cmdlinestr,datname=None,*args,**kwargs ): > memoryconsole.NotatedConsole.__init__( self,*args,**kwargs ) > self._datname= datname or self.defdat > if exists( self._datname ): self.edit= > pickle.load( open( self._datname,'rb' ) ) > else: self.edit= Editors() > self.edit._cmdlinestr= cmdlinestr > self.locals.update( edit=self.edit ) > self.edit.console= self > self.lasttimestamp= datetime.now() > def push( self,*args ): > more= memoryconsole.NotatedConsole.push( self,*args ) > if not more and datetime.now()- self.lasttimestamp > > timedelta( minutes= 25 ): > self.lasttimestamp= datetime.now() > self.out.logwrite( '#%s in %s\n'%\ > ( self.lasttimestamp.strftime( '%a %b %d %Y %I:%M:%S > %p' ),split(argv[0])[1] ) ) > del self.edit.console > pickle.dump( self.edit,open( self._datname,'wb' ) ) #don't pickle me > self.edit.console= self > return more > def __repr__( self ): > return '<%s at %i: %s>'%(self.__class__,id(self),repr( [ x for x in > dir(self) if not x.startswith('__') ] )) > > import compiler as c > from memory import Memory > import imp > from sys import modules > > class ModuleConsole(EditorsConsole): > def __init__( self,log=None,locals=None,filename=None ): > EditorsConsole.__init__( self,log,locals,filename ) > self.workmodule= imp.new_module( 'workmodule' ) > self.workmodule.__file__= self.out.logname > modules[self.workmodule.__name__]= self.workmodule > self.locals.update( workmodule=self.workmodule, > __name__=self.workmodule.__name__ ) > self.locals.update( __file__=self.workmodule.__file__ )#may omit > __logname__ > del self.locals['__logname__'] > def runcode( self,*args ): > EditorsConsole.runcode( self,*args ) > for k,v in self.locals.iteritems(): > setattr( self.workmodule,k,v ) > > if __name__=='__main__': > editorscmdlinestr= '"%s" "%%(filename)s" -cursor %%(loglen)i: > 1'%join(environ['PROGRAMFILES'],'editplus 2\\editplus.exe') > console= ModuleConsole(editorscmdlinestr) > console.interact() whoops, that line 48 is extraneous. From aleax at mac.com Wed May 30 11:00:25 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 30 May 2007 08:00:25 -0700 Subject: New-style classes and special methods References: Message-ID: <1hyx204.jheiy0wwm7bN%aleax@mac.com> Raj B wrote: > Hi > > My question is about how special methods are stored internally in > Python objects. > Consider a new-style class which implements special methods such as > __call__ and __new__ > > class C(type): > def __call__(...): > > > class B: > __metaclass__ = C > > > b= B() > > The type of C is 'type', that of B is 'C'. When B is instantiated, > the __call__ method of C is first invoked, since C is the metaclass > for B. > > Internally, when a Python callable object 'obj' is called, the actual > function called seems to be > 'obj->ob_type->tp_call'. > > Does this that somehow the '__call__' method defined in C above is > assigned to the 'tp_call' slot in the object representing the class > C, instead of it just being stored in the dictionary like a normal > attribute? Where and how does this magic happen exactly? I'd > appreciate any level of detail. Yes, special methods populate the slots in the structures which Python uses to represent types. Objects/typeobject.c in the Python source distribution does the hard work, particularly in function type_new (line 1722 in my current SVN checkout). If you're not comfortable reading C code you may want to try looking at the "Python implemented in Python" project, pypy, or perhaps alternatives such as Jython (in Java) or better IronPython (in C#), but I am not familiar in detail with how they deal with the issue. Alex From tkpmep at hotmail.com Wed May 9 16:57:37 2007 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: 9 May 2007 13:57:37 -0700 Subject: Behavior of mutable class variables Message-ID: <1178744257.369030.95310@w5g2000hsg.googlegroups.com> I have written a program that runs portfolio simulations with different parameters and prints the output, but am mystified by the behavior of a mutable class variable. A simplified version of the program follows - would you kindly help me understand why it behaves the way it does. The function main() reads some data and then repeatedly calls simulation() with different parameter values. Each time the simulation runs, it creates a collection of stocks, simulates their behavior and prints the results. Here's what I expect to happen each time simulation( ) is called: the class variable NStocks for the class Stock is initialized to an empty list, and is then built up by __init__ as stocks are added to the portfolio. Unfortunately, ths is not what actuallly happens .NStocks is initialized to an empty list and then built up as I expect on the first call to simulation( ), but appears to persists between calls to simulation( ). Question: Why? Do I not create an entirely new list of stock objects each time I enter simulation()? I am aware that mutable items can behave in tricky ways, but am thoroughly mystified by the persistence of NStocks between calls to simulation() Sincerely Thomas Philips class Stock(object): NStocks = [] #Class variable, NStocks[i] = number of valid stocks at time i def __init__(self, id, returnHistory): self.id = id self.retHist = returnHistory for i in range(len(returnHistory)): if len(Stock.NStocks) <= i and retHist[i] != '': Stock.NStocks.append(1) elif len(Stock.NStocks) <= i and retHist[i] == '': Stock.NStocks.append(0) elif retHist[i] != '': Stock.NStocks[i] +=1 def simulation(N, par1, par2, idList, returnHistoryDir): port = [] for i in range(N): port.append( Stock(idList[i], returnHistoryDir[idList[i]] ) results = ...... print results. def main(): N, idList, returnHistoryDir= readData() for par1 in range(10): for par2 in range(10): simulation(N, par1, par2, idList, returnHistoryDir) From revuesbio at gmail.com Mon May 21 06:42:21 2007 From: revuesbio at gmail.com (revuesbio) Date: 21 May 2007 03:42:21 -0700 Subject: TIFF to PDF In-Reply-To: References: <1179687595.142454.23850@z24g2000prd.googlegroups.com> Message-ID: <1179744141.027494.60590@r3g2000prh.googlegroups.com> I'm trying to use tifflib but i have some problems : when i use direct command line : "C:\Program Files\GnuWin32\bin\tiff2pdf.exe" -o C:\test.pdf C: \test.TIF the pdf is ok. but when i try to launch command line via python the pdf file is not created. where is the problem ? import os os.system('"C:\Program Files\GnuWin32\bin\tiff2pdf.exe" -o C:\test.pdf C:\test.TIF') thank you From daniele.varrazzo at gmail.com Sun May 6 14:22:52 2007 From: daniele.varrazzo at gmail.com (Daniele Varrazzo) Date: 6 May 2007 11:22:52 -0700 Subject: problem with quoted strings while inserting into varchar field of database. In-Reply-To: References: Message-ID: <1178475772.423687.118800@e65g2000hsc.googlegroups.com> > I further discovered that the string variable that contains the > pickled object contains a lot of single quots "'" and this is what is > probably preventing the sql insert from succedding. can some one > suggest how to work around this problem? Every serious database driver has a complete and solid SQL escaping mechanism. This mechanism tipically involves putting placeholders in your SQL strings and passing python data in a separate tuple or dictionary. Kinda cur.execute("INSERT INTO datatable (data) VALUES (%s);", (pickled_data,)) instead of: cur.execute("INSERT INTO datatable (data) VALUES ('%s');" % (pickled_data,)) It is the driver responsibility to serialize the data (which usually involves adding enclosing quotes and escape odd charaters such as quotes themselves). What database/driver are you using? PostgreSQL+psycopg2 or any other wrong one? ;) In eiither case, read the driver documentation and the DBAPI documentation (http://www.python.org/dev/peps/pep-0249/) for further details. -- Daniele From mail at timgolden.me.uk Thu May 3 04:56:47 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 03 May 2007 09:56:47 +0100 Subject: how to use Dispatch to open an application in win32com.client In-Reply-To: <289998.57072.qm@web63401.mail.re1.yahoo.com> References: <289998.57072.qm@web63401.mail.re1.yahoo.com> Message-ID: <4639A3CF.4000500@timgolden.me.uk> Peter Fischer wrote: > Thank you for your answer. I just tried, but it didn't work. The reason seems to > be that Google Earth prevents a second instance to run on the same machine. > Maybe for licensing reasons (do you know whether it is legal to bypass this > and how to do this?). Don't know, but common sense tells me it's not a good idea! > However, now I will try to run the two instances on separate machines > and to synchronize them via network. Do you know how to start a second instance on a second machine over the network in python/COM (DCOM)? Is this possible directly with the win32com > package in python or do I have to install an additional package? Well, funnily enough, you use exactly the same call, but with a machine name on the end: import win32com.client xl = win32com.client.DispatchEx ( "Excel.Application", "other_machine" ) The trouble now is that, to use COM/DCOM effectively, you really need to know what to do, not just be a dabbler like me. On a recent thread, Alex Martelli recommended Don Box's "Essential COM" which I've noted down but haven't read: http://groups.google.com/group/comp.lang.python/msg/f95a2d51b6e84091?hl=en& That said, this is Python so even without using DCOM directly, you have a whole slew of across-the-network possibilities for interacting between apps on two machines. Just ask this list and sit back and wait for the variety of replies! TJG From duncan.booth at invalid.invalid Wed May 2 13:45:40 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 May 2007 17:45:40 GMT Subject: gpp (conditional compilation) References: <1178127460.046945.254100@y80g2000hsf.googlegroups.com> Message-ID: "maxwell at ldc.upenn.edu" wrote: > I'm trying to use the gpp utility (Gnu points to > http://en.nothingisreal.com/wiki/GPP) to do conditional compilation in > Python, and I'm running into a problem: the same '#' character > introduces Python comments and is used by default to introduce #ifdef > etc. lines. > > Here's an example of what I'm trying to do: > > #ifdef DEBUG > stderr.write("variable is...") #details of msg omitted > #endif > Why do you want conditional compilation. Is there anything wrong with: if __debug__: stderr.write("variable is...") #details of msg omitted If you run Python with the -O command line option the code protected by the if statement will be optimised out. For most other purposes where you might use conditional compilation just adding 'if' statements to execute at runtime (or try/except) will do the same purpose: if sys.platform=='win32': def foo(): ... something ... else: def foo(): .... something different ... From aleax at mac.com Sun May 13 18:35:15 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 13 May 2007 15:35:15 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <46478694$0$1412$426a34cc@news.free.fr> Message-ID: <1hy252p.1anf7sr1p4yp12N%aleax@mac.com> Bruno Desthuilliers wrote: > > Disallowing this does *not* guarantee in any way that > > identifiers are understandable for English native speakers. > > I'm not an English native speaker. And there's more than a subtle > distinction between "not garantying" and "encouraging". I agree with Bruno and the many others who have expressed disapproval for this idea -- and I am not an English native speaker, either (and neither, it seems to me, are many others who dislike this PEP). The mild pleasure of using accented letters in code "addressed strictly to Italian-speaking audiences and never intended to be of any use to anybody not speaking Italian" (should I ever desire to write such code) pales in comparison with the disadvantages, many of which have already been analyzed or at least mentioned. Homoglyphic characters _introduced by accident_ should not be discounted as a risk, as, it seems to me, was done early in this thread after the issue had been mentioned. In the past, it has happened to me to erroneously introduce such homoglyphs in a document I was preparing with a word processor, by a slight error in the use of the system- provided way for inserting characters not present on the keyboard; I found out when later I went looking for the name I _thought_ I had input (but I was looking for it spelled with the "right" glyph, not the one I had actually used which looked just the same) and just could not find it. On that occasion, suspecting I had mistyped in some way or other, I patiently tried looking for "pieces" of the word in question, eventually locating it with just a mild amount of aggravation when I finally tried a piece without the offending character. But when something similar happens to somebody using a sufficiently fancy text editor to input source in a programming language allowing arbitrary Unicode letters in identifiers, the damage (the sheer waste of developer time) can be much more substantial -- there will be two separate identifiers around, both looking exactly like each other but actually distinct, and unbounded amount of programmer time can be spent chasing after this extremely elusive and tricky bug -- why doesn't a rebinding appear to "take", etc. With some copy-and-paste during development and attempts at debugging, several copies of each distinct version of the identifier can be spread around the code, further hampering attempts at understanding. Alex From zedshaw at zedshaw.com Mon May 14 15:18:05 2007 From: zedshaw at zedshaw.com (Zed A. Shaw) Date: Mon, 14 May 2007 15:18:05 -0400 Subject: track cpu usage of linux application In-Reply-To: References: Message-ID: <20070514151805.8ca85904.zedshaw@zedshaw.com> On Mon, 14 May 2007 20:56:20 +0000 Fabian Braennstroem wrote: > Hi, > > I would like to track the cpu usage of a couple of > programs using python. Maybe it works somehow with > piping 'top' to python read the cpu load for a greped > application and clocking the the first and last > appearence. Is that a good approach or does anyone have > a more elegant way to do that? Look at the /proc filesystem instead. For example, you can do this: cat /proc/49595/status To get information about that process. Using this you can find out anything you need with just basic file operations. Use: man proc to find our more. -- Zed A. Shaw - Hate: http://savingtheinternetwithhate.com/ - Good: http://www.zedshaw.com/ - Evil: http://yearofevil.com/ From pyro.699 at gmail.com Thu May 17 19:36:39 2007 From: pyro.699 at gmail.com (Pyro) Date: Thu, 17 May 2007 20:36:39 -0300 Subject: Multi-Page login WITH Cookies (POST Data) Message-ID: <562a25f0705171636j6a1f70d8x7dff7aefc88b5f59@mail.gmail.com> Before i go into some detail i would like to start off by saying that this is NOT an advertising bot or anything like that. I am a web programmer designing a website in PHP and it requires users to login. I am building a program that will login as the administrator and browse the forums looking for any inappropriate activity. Here is how i have my login setup (it needs to be setup like this). http://pyro.allblizz.com/python/login1.php (Just Username) (username = 'thisname') http://pyro.allblizz.com/python/login2.php (Just Password) (password = 'whatpassword') http://pyro.allblizz.com/python/home.php (Home) (links are valid, and working submit system) Now, without cookies (just POST data) I am able to get this to work. [code] #!/usr/bin/python import sys from urllib2 import urlopen from ClientForm import ParseResponse forms = ParseResponse(urlopen("http://pyro.allblizz.com/login1.php"))[0] forms["username"] = "thisname" forms2 = ParseResponse(urlopen(forms.click()))[0] forms2["password"] = "whatpassword" print urlopen(forms2.click()).read() [/code] If you go and fill out the username and passwords using a web browser, you are able to login but, when i use this code it does not work. (Because the cookies are not being stored) After we are able to get a succussful login, i need a way that i can browse my site always including this cookie, like if i went to open up a page, it would use the cookie we got from logging in. Thanks alot guys ~Cody -------------- next part -------------- An HTML attachment was scrubbed... URL: From frank at chagford.com Tue May 29 01:22:45 2007 From: frank at chagford.com (Frank Millman) Date: 28 May 2007 22:22:45 -0700 Subject: DbiDate object In-Reply-To: <1180392704.580831.229190@q75g2000hsh.googlegroups.com> References: <1180392704.580831.229190@q75g2000hsh.googlegroups.com> Message-ID: <1180416165.039109.146000@w5g2000hsg.googlegroups.com> On May 29, 12:51 am, revuesbio wrote: > Hi all > > I am using odbc to connect to Microsoft Access DB. When I send a > request with a datetime column from the database, odbc returns > something called a DbiDate object. > ex :>>> x=data[0][2] > > >>> print x > > Fri Apr 20 07:27:45 2007 > > I would like to select columns where datetime ("DbiDate column") is > > yesterday date. > and i don't understand how to send request with this DbiDate. > > Could you help me ? > thank you I also use the odbc module, but I store dates in my system as datetime.datetime objects. I convert a DbiDate object to a datetime object like this - import datetime as dt date = dt.datetime.fromtimestamp(int(dbidate)) For selects, I use the datetime object directly - cur.execute('select * from table where date = ?',(date,)) I'm not sure how the odbc module handles that - maybe it converts date into str(date). In any case, it just works for me. HTH Frank Millman From kyosohma at gmail.com Mon May 14 10:09:40 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 14 May 2007 07:09:40 -0700 Subject: Time In-Reply-To: <1179151205.987222.54910@k79g2000hse.googlegroups.com> References: <1178916216.893542.257320@y80g2000hsf.googlegroups.com> <1178916422.065108.312920@l77g2000hsb.googlegroups.com> <1178920014.621031.301860@n59g2000hsh.googlegroups.com> <1178927105.482975.174760@y5g2000hsa.googlegroups.com> <1179151205.987222.54910@k79g2000hse.googlegroups.com> Message-ID: <1179151780.870236.208590@p77g2000hsh.googlegroups.com> On May 14, 9:00 am, HMS Surprise wrote: > Thanks for posting. I sure am sorry that I wasted your time. I should > have started the post stating I am using jython 2.2.3 and apparently > it has no datetime module. But I will keep datetime in mind for future > reference. > > Since I had no datetime I cobbled out the following. Seems to work > thus far. Posted here for the general amusement of the list. > > Regards, > > jvh > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > from time import * > s = '05/11/2007 1:23 PM' > t = s.split() > mdy = t[0].split('/') > > hrMn = t[1].split(':') > if t[2] == 'PM': > hrMn[0] = int(hrMn[0]) + 12 > > tuple =(int(mdy[2]), int(mdy[0]), int(mdy[1]), hrMn[0], int(hrMn[1]), > 0,0,0,0) > print tuple > > eTime = mktime(tuple) > print 'eTime', eTime Since jython works with Java, why not use Java's time/datetime modules? Various links abound. Here are a few: http://www.raditha.com/blog/archives/000552.html http://www.xmission.com/~goodhill/dates/deltaDates.html http://www.velocityreviews.com/forums/t149657-find-difference-in-datetime-variables.html Maybe those will give you some hints. Mike From sjdevnull at yahoo.com Wed May 16 00:19:27 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 15 May 2007 21:19:27 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <1179289167.723990.223890@u30g2000hsc.googlegroups.com> Steven D'Aprano wrote: > I've made various comments to other people's responses, so I guess it is > time to actually respond to the PEP itself. > > On Sun, 13 May 2007 17:44:39 +0200, Martin v. Lo:wis wrote: > > > PEP 1 specifies that PEP authors need to collect feedback from the > > community. As the author of PEP 3131, I'd like to encourage comments to > > the PEP included below, either here (comp.lang.python), or to > > python-3000 at python.org > > > > In summary, this PEP proposes to allow non-ASCII letters as identifiers > > in Python. If the PEP is accepted, the following identifiers would also > > become valid as class, function, or variable names: Lo:ffelstiel, change, > > oshibka, or ***ri*** (hoping that the latter one means "counter"). > > > > I believe this PEP differs from other Py3k PEPs in that it really > > requires feedback from people with different cultural background to > > evaluate it fully - most other PEPs are culture-neutral. > > > > So, please provide feedback, e.g. perhaps by answering these questions: > > - should non-ASCII identifiers be supported? why? - would you use them > > if it was possible to do so? in what cases? > > It seems to me that none of the objections to non-ASCII identifiers are > particularly strong. I've heard many accusations that they will introduce > "vulnerabilities", by analogy to unicode attacks in URLs, but I haven't > seen any credible explanations of how these vulnerabilities would work, > or how they are any different to existing threats. That's not to say that > there isn't a credible threat, but if there is, nobody has come close to > explaining it. > > I would find it useful to be able to use non-ASCII characters for heavily > mathematical programs. There would be a closer correspondence between the > code and the mathematical equations if one could write D(u*p) instead of > delta(mu*pi). Just as one risk here: When reading the above on Google groups, it showed up as "if one could write ?(u*p)..." When quoting it for response, it showed up as "could write D(u*p)". I'm sure that the symbol you used was neither a capital letter d nor a question mark. Using identifiers that are so prone to corruption when posting in a rather popular forum seems dangerous to me--and I'd guess that a lot of source code highlighters, email lists, etc have similar problems. I'd even be surprised if some programming tools didn't have similar problems. From vb at itechart.com Sun May 20 07:17:09 2007 From: vb at itechart.com (VB) Date: 20 May 2007 04:17:09 -0700 Subject: Custom Software Development Message-ID: <1179659829.212488.209440@e65g2000hsc.googlegroups.com> iTechArt Group - Custom Software Development and Offshore outsourcing Company http://www.itechart.com/ Offshore custom software development company iTechArt - Web site and Content Management Solutions development, CMS consulting: Ektron, Drupal and DotNetNuke iTechArt Group provides high quality custom software development services and offshore software development. On December 2006, iTechArt Group became an authorized Microsoft Certified Partner. This means that our company has been recognized by Microsoft for our vast expertise and authorized to custom software development; provide IT service consulting and custom business solutions. Custom Software Development and Offshore outsourcing Company iTechArt has worked together since 2003 to design build and deliver .NET Web Content Management software solutions that help clients meet their strategic objectives. We are agile oriented development partner able to consistently deliver solid results. iTechArt software development team assemblies specialists in the development of custom software applications and offshore software outsourcing services. Working concepts of our company are based on proven approaches and international standards used for custom software development such as Capability Maturity Model Integration for Software Engineering (CMMI- SW). In the same breath we have our own standpoint on software development process management which is fully effective and comprehensible for our clients. iTechArt offers software development in the next main directions: 1. Custom Software Development (Offshore outsourcing for worldwide based software development companies.) 2. Software Development for Digital Signage (Media content development and remote displays / information kiosks Web-based software application management.) 3. Web Site Development (E-commerce solutions, CMS/DotNetNuke/Ektron/ Drupal, Web 2.0/PHP/MySQL/AJAX, Flash/Action script/Flex and many more.) 4. Offshore Development Center (Dedicated development team of software developers. Our offshore development centers operate as an extension to clients' existing software engineering business.) Contact iTechArt ( http://www.itechart.com/ )about custom software development, end-to-end software solutions, outsourcing software development, custom DotNetNuke module development, DotNetNuke consulting, dotnetnuke hosting, first class Java and .Net developers, software application design, software testing, Quality Assurance, functionality testing and defect analysis, performance and stress testing, usability testing, Microsoft Media Services and Adobe Media Flash Server solutions, digital signage solutions and custom development, Ektron CMS400.NET developers, CMS, .NET Web Content Management software solutions Web: http://www.itechart.com/ http://www.itechart.com/Pages/ProductsServices/HowWeWork.aspx http://www.itechart.com/Pages/ProductsServices/BusinessModels.aspx http://www.itechart.com/Pages/ProductsServices/CustomSoftwareDevelopment.aspx http://www.itechart.com/Pages/ProductsServices/DotNetNukeModuleDevelopment.aspx From kinch1967 at gmail.com Sat May 26 05:19:39 2007 From: kinch1967 at gmail.com (bullockbefriending bard) Date: 26 May 2007 02:19:39 -0700 Subject: speeding things up with C++ Message-ID: <1180171179.687276.77930@z28g2000prd.googlegroups.com> I've done all the requisite profiling and thought fairly deeply about the efficiency of my python code, but am still going to have to speed up the innermost guts of what I am doing. Essentially, I need to pass a list of 6-tuples containing only integers to my new sadly necessary super-fast compiled language function which i am not looking forward to writing: input: [(1,2,3,4,5,6), (7,8,9,10,11,12),...] and after much thrashing of processor resources, return data which looks like this to the Python calling environment: output: [( (1, 2), (1,), (12,), (13), (1, 7, 11), (9,) ), ( another nested tuple like preceding one ), .... ] Each member of the returned list is a tuple containing 6 tuples, and each of those 6 tuples has at least one integer member. It would also be acceptable for the return values to be entirely nested lists instead of having the two innermost sequence types as tuples. I probably want to be using something like C++ because i'm going to need to use STL vectors and sets for what i'm doing in the algorithm i'm trying to speed up. IIRC Boost tuple is a bit painful for more than 10 elements + isn't really essential that I use a a non-mutable data type in what will be a small encapsulated bit of a much larger system. Anyway, I can probably very quickly figure out some hacked way to get the data into my function given that in the worst case I could take advantage of the knowledge that each input tuple always has 6 elements, and simply pass in a big array of ints. Yes, I know this is a bit retarded, but I'm talking worst case assuming on very tight schedule and no time to delve deeply into SWIG or whatever. Similarly it wouldn't be too difficult to return the result as the mother all of all strings which i could then parse fairly easily. However, I hope someone reading this will be able to tell me that I'm being a total pessimist and that in fact it isn't very difficult to do what I want to do using SWIG. I'm not asking for a complete solution, more like some general pointers from someone who has actually done something similar before. As an added bonus, I wouldn't if this is 'easily' doable using Ocaml as the guts instead of C++, I'd be happy to know about it. From sjmachin at lexicon.net Tue May 8 16:58:44 2007 From: sjmachin at lexicon.net (John Machin) Date: 8 May 2007 13:58:44 -0700 Subject: sys.path In-Reply-To: <1178638540.056691.161750@e65g2000hsc.googlegroups.com> References: <1178638540.056691.161750@e65g2000hsc.googlegroups.com> Message-ID: <1178657924.686609.112340@w5g2000hsg.googlegroups.com> On May 9, 1:35 am, HMS Surprise wrote: > Is sys.path setup differnently in jython vs python? I have environment > variables pythonpath and jythonpath set to include C:\python22 but the > initial printout indicates it is being ignored. Also when I used > sys.path.extend, the added pathname shows up as a series of single > characters. Have I misused .extend? > > Thanks, > > jh > > import sys > print sys.path > sys.path.extend("c:\python22") > print sys.path > import urllib > > ['.', 'C:\\maxq\\lib\\Lib', 'C:\\maxq\\jython'] Your sys.path looks stuffed already. You may have missed this in the flurry of posts and counter-posts, but I asked: have you been messing with the PYTHONHOME environment variable? This is what sys.path looks like after a normal installation, before any messing about: C:\junk>set PYTHONPATH Environment variable PYTHONPATH not defined C:\junk>set PYTHONHOME Environment variable PYTHONHOME not defined C:\junk>\python22\python Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.path ['', 'C:\\junk', 'C:\\python22\\DLLs', 'C:\\python22\\lib', 'C:\ \python22\\lib\\lib-tk', 'C:\\python22', 'C:\\python22\\lib\\site- packages'] >>> To get urllib to be imported from c:\python22\lib\urllib.py, you need c:\python22\lib (NOT c:\python22) to be in sys.path, and it should ALREADY be in sys.path (if you are running Python 2.2, of course). Please go to a dos-prompt, type in what I did above and paste the results into your next post. From bernhard.voigt at gmail.com Mon May 7 08:50:50 2007 From: bernhard.voigt at gmail.com (bernhard.voigt at gmail.com) Date: 7 May 2007 05:50:50 -0700 Subject: Plot with scipy In-Reply-To: <1178287027.434242.230170@h2g2000hsg.googlegroups.com> References: <1178283196.755609.241790@n59g2000hsh.googlegroups.com> <1178287027.434242.230170@h2g2000hsg.googlegroups.com> Message-ID: <1178542249.948480.270930@y5g2000hsa.googlegroups.com> On 4 Mai, 15:57, redcic wrote: > I've already got this package. I just wanted to try something new. > > However, since you talk about it, I've got a question regarding this > package. The execution of the code stops after the line: > pylab.show() > which is off course the last line of my code. My problem is that I > have to close the figure window in order to launch my program another > time. I'd like to be able to launch my program many times with > different parameters without having to close the figure windows before > each launch. > Just so you know, I'm using TkAgg backend. > > Any hint ? There's an option in your matplotlibrc file (personal lives in $HOME/.matplotlib, default in $PYTHONPATH/matplotlib/mpl-data): #### CONFIGURATION BEGINS HERE # the default backend; one of GTK GTKAgg GTKCairo FltkAgg QtAgg TkAgg # Agg Cairo GD GDK Paint PS PDF SVG Template backend : TkAgg numerix : numpy # numpy, Numeric or numarray interactive : True # see http://matplotlib.sourceforge.net/interactive.html ..... Take a look at the quoted webpage for details and troubleshooting. Bernhard From simon.murphy.nz at gmail.com Thu May 31 00:43:28 2007 From: simon.murphy.nz at gmail.com (simon.murphy.nz at gmail.com) Date: 30 May 2007 21:43:28 -0700 Subject: matplotlib Basemap help Message-ID: <1180586608.599197.91900@d30g2000prg.googlegroups.com> Hi everyone - I'm trying to move all of my MATLAB mapping scripts over to the Basemap toolbox of matplotlib. There are 2 things however that I still can't figure out: 1) When using the Mollweide projection I can't place meridian labels at all (presumably because they converge at the poles). In MATLAB one could explicity give a parallel to place the labels on, e.g. the equator. Is such a thing possible using Basemap? 2) All my latitude labels have pesky 'N' or 'S' after them, which is fine for geographic latitude but not for galactic latitude (I'm an astronomer) which denotes southern latitudes with a minus sign e.g. -45 deg. Any ideas? Thanks in advance, Simon Murphy From R.Brodie at rl.ac.uk Fri May 25 09:01:39 2007 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Fri, 25 May 2007 14:01:39 +0100 Subject: just a bug (was: xml.dom.minidom: how to preserve CRLF's inside CDATA?) References: <1179841504.782279.86490@u36g2000prd.googlegroups.com> <1180082137.329142.45350@p77g2000hsh.googlegroups.com> Message-ID: "Marc 'BlackJack' Rintsch" wrote in message news:pan.2007.05.25.09.45.22.373437 at gmx.net... > How did you verified that it is well formed? It appears to have a more fundamental problem, which is that it isn't correctly encoded (presumably because the CDATA is truncated in mid-character). I'm surprised Mozilla lets it slip by. From vatamane at gmail.com Mon May 7 17:41:02 2007 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 7 May 2007 14:41:02 -0700 Subject: randomly write to a file In-Reply-To: <1178567497.042096.82940@w5g2000hsg.googlegroups.com> References: <1178567497.042096.82940@w5g2000hsg.googlegroups.com> Message-ID: <1178574062.496137.11640@y5g2000hsa.googlegroups.com> Rohit, Consider using an SQLite database. It comes with Python 2.5 and higher. SQLite will do a nice job keeping track of the index. You can easily find the line you need with a SQL query and your can write to it as well. When you have a file and you write to one line of the file, all of the rest of the lines will have to be shifted to accommodate, the potentially larger new line. -Nick Vatamaniuc On May 7, 3:51 pm, rohit wrote: > hi, > i am developing a desktop search.For the index of the files i have > developed an algorithm with which > i should be able to read and write to a line if i know its line > number. > i can read a specified line by using the module linecache > but i am struck as to how to implement writing to the n(th) line in a > file EFFICIENTLY > which means i don't want to traverse the file sequentially to reach > the n(th) line > > Please help. > Regards > Rohit From aleax at mac.com Fri May 18 00:22:28 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 17 May 2007 21:22:28 -0700 Subject: Python Web Programming - looking for examples of solid high-traffic sites References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> Message-ID: <1hy9yf9.1nnsttj139za6bN%aleax@mac.com> Victor Kryukov wrote: ... > And although http://www.python.org/about/quotes/ lists many big names > and wonderful examples, be want more details. E.g. our understanding > is that Google uses python mostly for internal web-sites, and > performance is far from perfect their. YouTube is an interesting > example - anybody knows more details about that? Hmmm, I do, but exactly because I _do_ know a lot more details I cannot discuss them unless you're under the proper Non-Disclosure Agreement with Google, Inc. The best I can do otherwise is to point you to already existing webpages -- I'm not going to reveal Google-Confidential information, nor go to the substantial trouble to get such info cleared by Legal and all other Google stakeholders. For example, it HAS been published elsewhere that YouTube uses lighttpd, not Apache: . Fortunately, I managed to convince my YouTube colleagues to publically present many more details about the evolution of their architecture which had been discussed in Google-confidential talks and presentations -- and my wife Anna, who's on the program selection committee of OSCON, may have helped that talk get accepted (must not have been a hard job:-). See: I hope to see you (and anybody else interested in solid technical details about using Python for websites on YouTube's scale) in Portland, OR on July 26 -- that will also be your first and best chance to ask Mike Solomon specific questions that his talk might not directly address. Once that's done, maybe somebody can convince the YouTube guys to contribute a "Python Success Story" so that future querants about this can be easily pointed to a URL!-) I would also encourage anybody who's so keenly interested in Python to visit our jobs-listing web app, e.g., if within the US, at . Of course, one should *never* have the implementation language of a web-app show up in the URL, and I believe we've carefully avoided that error in other external-facing web-apps, such as (one I can reveal is indeed in Python, because that was mentioned at ) code.google.com. Etc, etc. Performance of web-apps (be they internal or external) depends more on the architecture than on the implementation language (as long as highly optimized C or C++, NOT Java or Python or whatever, is used for the few jobs that are extremely CPU-intensive, such as codecs, of course:-). So, if some Python-coded internal web-apps at Google perform badly (which may be the case as you say, though I can't think of any off-hand), it must be an issue of architecture. For example, a heavily used internal web-app at Google is Mondrian, , Guido van Rossum's web-app for code review -- it's got a good, solid architecture, and its performance is so good that many Googlers, me included, have switched to it for all the reviews we do (and, believe me, we do MANY -- _nothing_ is submitted to the global code repository until it's been OK'd in a code review). I can't mention other such apps because, AFAIK, they haven't been previously talked about in public and so they're Google Confidential by default until otherwise determined. Alex From aleax at mac.com Tue May 8 23:17:33 2007 From: aleax at mac.com (Alex Martelli) Date: Tue, 8 May 2007 20:17:33 -0700 Subject: 1.#QNAN Solution References: <10379999.post@talk.nabble.com> Message-ID: <1hxt9nq.4ah5i1klvlpuN%aleax@mac.com> Gabriel Genellina wrote: > En Tue, 08 May 2007 14:14:58 -0300, Greg Corradini > escribi?: > > > I'm running descriptive stats on mileages from a database (float numbers, > > about a million records). My sum returns 1.#QNAN, which I understand from > > searching this forum is an error. > > > > While I'm looking for help in solving this problem, I'm more interested > > in a > > general explanation about the cause of this problem. Any ideas? > > If you are summing a million floating point numbers, using a naive > algorithm may give you wrong results. > Look for "Kahan summation algorithm" (even discussed some weeks ago in > this group). Or, just check etc. I can't think offhand of a case where using the wrong/naive algorithm would give a NAN while Kahan's would converge, tho. Alex From stefan.behnel-n05pAM at web.de Sat May 26 02:00:15 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sat, 26 May 2007 08:00:15 +0200 Subject: Removing NS in ElementTree In-Reply-To: References: Message-ID: <4657CCEF.2080206@web.de> Sebastian Bassi wrote: > I would like to remove the namespace information from my elements and > have just the tag without this information. This > "{http://uniprot.org/uniprot}" is preapended into all my output. for el in root.getiterator(): if el.tag[0] == '{': el.tag = el.tag.split('}', 1)[1] That should do the job. Stefan From marc.wyburn at googlemail.com Tue May 22 08:16:30 2007 From: marc.wyburn at googlemail.com (marc wyburn) Date: 22 May 2007 05:16:30 -0700 Subject: NOOOOB In-Reply-To: <1179829763.464614.123920@a26g2000pre.googlegroups.com> References: <1179829763.464614.123920@a26g2000pre.googlegroups.com> Message-ID: <1179836189.980255.38810@a26g2000pre.googlegroups.com> On May 22, 11:29 am, jolly wrote: > Hey guys, > > I want to begin python. Does anyone know where a good starting point > is? > > Thanks, > Jem i went through the tutorials on the main site and then followed up with mark Hammonds book for windows stuff. I got a few other books as well to reference but I've found it easy enough to find info for almost everything on the net. From mensanator at aol.com Wed May 2 16:48:12 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 2 May 2007 13:48:12 -0700 Subject: bitwise shift? In-Reply-To: <4638d8c5$0$16290$88260bb3@free.teranews.com> References: <462FEE8B.2030701@lexicon.net> <4638d8c5$0$16290$88260bb3@free.teranews.com> Message-ID: <1178138892.055979.16540@p77g2000hsh.googlegroups.com> On May 2, 2:24 pm, Tobiah wrote: > John Machin wrote: > > On 26/04/2007 7:10 AM, Sherm Pendley wrote: > > >> Shift left is *not* the same as multiplying by k. It is the same as > >> multi- > >> plying by 2^k. > > > Where I come from, ^ is the exclusive-or operator. Of course YMMV in WV :-) > > desktops:toby:ga> bc > bc 1.06 > Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc. > This is free software with ABSOLUTELY NO WARRANTY. > For details type `warranty'. > 2^3 > 8 OTOH, IDLE 1.2c1 >>> 2^3 1 Guess which one is relevant to comp.lang.python? > > -- > Posted via a free Usenet account fromhttp://www.teranews.com From paul at boddie.org.uk Tue May 15 12:48:44 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 15 May 2007 09:48:44 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <4649D4A5.5060102@web.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649BC4C.10200@web.de> <1179238847.407605.4620@w5g2000hsg.googlegroups.com> <4649C63C.1030508@web.de> <1179242328.800088.246620@h2g2000hsg.googlegroups.com> <4649D4A5.5060102@web.de> Message-ID: <1179247724.234869.47310@l77g2000hsb.googlegroups.com> On 15 May, 17:41, Stefan Behnel wrote: > [javac -encoding Latin-1 Hallo.java] > From a Python perspective, I would rather call this behaviour broken. Do I > really have to pass the encoding as a command line option to the compiler? They presumably weighed up the alternatives and decided that the most convenient approach (albeit for the developers of Java) was to provide such a compiler option. Meanwhile, developers get to write their identifiers in the magic platform encoding, which isn't generally a great idea but probably works well enough for some people - their editor lets them write their programs in some writing system and the Java compiler happens to choose the same writing system when reading the file - although I wouldn't want to rely on such things myself. Alternatively, they can do what Python programmers do now and specify the encoding, albeit on the command line. However, what I want to see is how people deal with such issues when sharing their code: what are their experiences and what measures do they mandate to make it all work properly? You can see some discussions about various IDEs mandating UTF-8 as the default encoding, along with UTF-8 being the required encoding for various kinds of special Java configuration files. Is this because heterogeneous technical environments even within the same cultural environment cause too many problems? > I find Python's source encoding much cleaner here, and even more so when the > default encoding becomes UTF-8. Yes, it should reduce confusion at a technical level. But what about the tools, the editors, and so on? If every computing environment had decent UTF-8 support, wouldn't it be easier to say that everything has to be in UTF-8? Perhaps the developers of Java decided that the rules should be deliberately vague to accommodate people who don't want to think about encodings but still want to be able to use Windows Notepad (or whatever) to write software in their own writing system. And then, what about patterns of collaboration between groups who have been able to exchange software with "localised" identifiers for a number of years? Does it really happen, or do IBM's engineers in China or India (for example) have to write everything strictly in ASCII? Do people struggle with characters they don't understand or does copy/ paste work well enough when dealing with such code? Paul From gagsl-py2 at yahoo.com.ar Thu May 3 08:20:42 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 03 May 2007 09:20:42 -0300 Subject: passing an array of variant in vb to a python COM object = win32com bug ? References: <1178178883.246149.279780@c35g2000hsg.googlegroups.com> Message-ID: En Thu, 03 May 2007 04:54:43 -0300, vml escribi?: > I have a python com object which contains a method to inverse an array > in vb 6 the definition of the class is : > > class Fop: > _public_methods_ = [ 'SqVal' ] > def SqVal(self,*val): > #vol=(val[0][0],val[0][1]) > #mat1=mat((vol)) > #up=linalg.inv(mat1) > return str(val)#up > _reg_verprogid_ = "Python.Fop.3" > _reg_progid_ = "Python.Fop" > _reg_desc_ = "Python Fop" > _reg_clsid_ = "{30BD3490-2632-11cf-AD5B-524153480001}" > > I pass to this method an array of variant which is the matrix to > invert like that: > vb6 code : > > > Set obj = CreateObject("Python.Fop") > Dim ty(1, 1) As Variant > > ty(0, 0) = 1 > ty(1, 0) = 2 > ty(0, 1) = 3 > ty(1, 1) = 4 > > toto = obj.SqVal(ty) > > > when I dispaly toto as str(val) I obtain the following tuple "(((1, > 3), (2, 4)),)" which is not usable .... > > Do you have an idea to explain this strange behaviour ? This is the expected behaviour. Writing it completely in Python: py> def SqVal(*val): ... return str(val) ... py> ty=((1,3),(2,4)) py> SqVal(ty) '(((1, 3), (2, 4)),)' The *val parameter receives a tuple, whose elements are the positional arguments used when calling the function. As you call the function with a single argument, val receives a tuple with a single element. Perhaps you want to write it as: py> def SqVal(val): ... print val[0][0] ... print val[0][1] ... print val[1][0] ... print val[1][1] ... py> SqVal(ty) 1 3 2 4 (Of course, if used as a Fop method, dont forget the "self" parameter) -- Gabriel Genellina From aldo at nullcube.com Tue May 15 06:43:31 2007 From: aldo at nullcube.com (Aldo Cortesi) Date: Tue, 15 May 2007 20:43:31 +1000 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <1hy2qg3.iqfvwnrvr9kjN%aleax@mac.com> Message-ID: <20070515104331.GA16700@nullcube.com> Thus spake Steven D'Aprano (steven at REMOVE.THIS.cybersource.com.au): > >> Me, I try to understand a patch by reading it. Call me old-fashioned. > > > > I concur, Aldo. Indeed, if I _can't_ be sure I understand a patch, I > > don't accept it -- I ask the submitter to make it clearer. > > > Yes, but there is a huge gulf between what Aldo originally said he does > ("visual inspection") and *reading and understanding the code*. Let's set aside the fact that you're guilty of sloppy quoting here, since the phrase "visual inspection" is yours, not mine. Regardless, your interpretation of my words is just plain dumb. My phrasing was intended to draw attention to the fact that one needs to READ code in order to understand it. You know - with one's eyes. VISUALLY. And VISUAL INSPECTION of code becomes unreliable if this PEP passes. > If I've understood Martin's post, the PEP states that identifiers are > converted to normal form. If two identifiers look the same, they will be the > same. I'm sorry to have to tell you, but you understood Martin's post no better than you did mine. There is no general way to detect homoglyphs and "convert them to a normal form". Observe: import unicodedata print repr(unicodedata.normalize("NFC", u"\u2160")) print u"\u2160" print "I" So, a round 0 for reading comprehension this lesson, I'm afraid. Better luck next time. Regards, Aldo -- Aldo Cortesi aldo at nullcube.com http://www.nullcube.com Mob: 0419 492 863 From stefan.sonnenberg at pythonmeister.com Thu May 17 15:31:26 2007 From: stefan.sonnenberg at pythonmeister.com (Stefan Sonnenberg-Carstens) Date: Thu, 17 May 2007 21:31:26 +0200 Subject: Is wsgi ready for prime time? In-Reply-To: <1179426728.846565.51390@h2g2000hsg.googlegroups.com> References: <1179426728.846565.51390@h2g2000hsg.googlegroups.com> Message-ID: <464CAD8E.9080409@pythonmeister.com> Michele Simionato schrieb: > On May 17, 8:09 pm, Ron Garret wrote: > >> The wsgiref module in Python 2.5 seems to be empty: >> >> [ron at mickey:~/Sites/modpy]$ python >> Python 2.5 (r25:51908, Mar 1 2007, 10:09:05) >> [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin >> Type "help", "copyright", "credits" or "license" for more information.>>> import wsgiref >> >>>>> dir(wsgiref) >>>>> >> ['__builtins__', '__doc__', '__file__', '__name__', '__path__'] >> >> >> >> So... is wsgi considered ready for production use, or is it still on the >> bleeding edge? And if the former, which implementation should one use? >> >> rg >> > > > Try help(wsgiref). > > I would say that WSGI (the spec) is ready for production use whereas > wsgiref > (the implementation in the standard library) is intended for easy > development > and testing purposes, not for industrial strenght deployement. On the > other hand Zope 3 uses Twisted via WSGI as a business class server, > and I hear that mod_wsgi is slightly more performant than mod_python, > It is not only _slightly_ faster. It is a beast. > so those are the first options I would consider. But you could post on > the WSGI list for more. > > Michele Simionato > > IMHO WSGI is _only_ a new way of talking to webservers, like apache. It is as low-level as (f)cgi, so don't expect too much support at this stage - indeed a module like the cgi one in the std lib would be nice. As google uses it (mod_wsgi), I would suspect you can use it. From kay.schluehr at gmx.net Sun May 20 17:34:35 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 20 May 2007 14:34:35 -0700 Subject: ANN: EasyExtend 2.0 - beta1 Message-ID: <1179696875.057450.7310@a26g2000pre.googlegroups.com> Hi Pythonistas, EasyExtend is a grammar based preprocessor generator, code analysis and synthesis framework and metaprogramming system for Python written in Python. This is the first beta of EE 2.0. As always some novelties are implemented. This time it is Console Test an ultralightweight test facility based on recordings of interactive sessions: http://www.fiber-space.de/EasyExtend/doc/consoletest/consoletest.html You find EasyExtend on the projects homepage: http://www.fiber-space.de/EasyExtend/doc/EE.html The EasyExtend package is also uploaded to the cheeseshop: http://www.python.org/pypi/EasyExtend/2.0-beta1 To make yourself familiar with EE an introductory level tutorial is also present: http://www.fiber-space.de/EasyExtend/doc/tutorial/EETutorial.html Kay From andy.terrel at gmail.com Thu May 3 21:36:01 2007 From: andy.terrel at gmail.com (Andy Terrel) Date: 3 May 2007 18:36:01 -0700 Subject: How do I import a variable from another module? In-Reply-To: <1178242032.254096.316860@o5g2000hsb.googlegroups.com> References: <1178242032.254096.316860@o5g2000hsb.googlegroups.com> Message-ID: <1178242561.677032.4440@y80g2000hsf.googlegroups.com> are you sure your variable isn't in some code block that wouldn't be read on import? Such as: if __name__ == "__main___": actions = 1 From steve at REMOVE.THIS.cybersource.com.au Sun May 6 19:17:43 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 07 May 2007 09:17:43 +1000 Subject: howto make Python list from numpy.array? References: <1178480447.245977.293010@n59g2000hsh.googlegroups.com> <1178482016.071308.235520@l77g2000hsb.googlegroups.com> Message-ID: On Sun, 06 May 2007 13:06:56 -0700, dmitrey wrote: > Thanks all. > I tried all the approaches but they don't work in my situation > I have a variable x that can be > x = 1 > x = [1, 2, 3] > x = numpy.array([1,2,3]) > so all troubles are with 1st case And yet your question was about the third case: "howto make Python list from numpy.array?" You should have asked: How do I make a Python list from an int? And the answer would be: x = 1 lst = [x] Another answer would be: x = 1 lst = ["existing", "list"] lst.append(x) -- Steven. From martin at v.loewis.de Thu May 17 08:12:20 2007 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Thu, 17 May 2007 14:12:20 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46498cb1$0$6411$9b4e6d93@newsspool2.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <4648252D.5020704@web.de> <46483740.4050406@web.de> <46498cb1$0$6411$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <464C46A4.1060200@v.loewis.de> > IMO, the burden of proof is on you. If this PEP has the potential to > introduce another hindrance for code-sharing, the supporters of this PEP > should be required to provide a "damn good reason" for doing so. So far, > you have failed to do that, in my opinion. All you have presented are > vague notions of rare and isolated use-cases. The PEP explicitly states what the damn good reason is: "Such developers often desire to define classes and functions with names in their native languages, rather than having to come up with an (often incorrect) English translation of the concept they want to name." So the reason is that with this PEP, code clarity and readability will become better. It's the same reason as for many other features introduced into Python recently, e.g. the with statement. If you doubt the claim, please indicate which of these three aspects you doubt: 1. there are programmers which desire to defined classes and functions with names in their native language. 2. those developers find the code clearer and more maintainable than if they had to use English names. 3. code clarity and maintainability is important. Regards, Martin From napolpie at tin.it Thu May 3 05:08:55 2007 From: napolpie at tin.it (napolpie at tin.it) Date: Thu, 3 May 2007 10:08:55 +0100 (GMT+01:00) Subject: problem with meteo datas Message-ID: <1125132fe48.napolpie@tin.it> ----Messaggio originale---- Da: napolpie at tin.it Data: 3-mag-2007 10.02 A: Ogg: problem with meteo datas Hello, I'm Peter and I'm new in python codying and I'm using parsying to extract data from one meteo Arpege file. This file is long file and it's composed by word and number arguments like this: GRILLE EURAT5 Coin Nord-Ouest : 46.50/ 0.50 Coin Sud-Est : 44.50/ 2.50 MODELE PA PARAMETRE P NIVEAU MER 0 ECHEANCE 0.0 DATE 20020304000000 NB_POINTS 25 1020.91 1020.87 1020.91 1021.05 1021.13 1020.07 1020.27 1020.49 1020.91 1021.15 1019.37 1019.65 1019.79 1020.53 1020.77 1018.73 1018.89 1019.19 1019.83 1020.81 1018.05 1018.19 1018.75 1019.55 1020.27 NIVEAU MER 0 ECHEANCE 3.0 DATE 20020304000000 NB_POINTS 25 1019.80 1019.78 1019.92 1020.18 1020.34 1018.94 1019.24 1019.54 1020.08 1020.32 1018.24 1018.64 1018.94 1019.84 1019.98 1017.48 1017.88 1018.28 1018.98 1019.98 1016.62 1017.08 1017.66 1018.26 1018.34 NIVEAU MER 0 ECHEANCE 6.0 DATE 20020304000000 NB_POINTS 25 1019.37 1019.39 1019.57 ........ ........ ....... ......... ....... ....... ....... ....... ......... NIVEAU MER 0 ECHEANCE 48.0 DATE 20020304000000 NB_POINTS 25 1017.84 1017.46 1017.14 1016.86 1016.58 1017.28 1016.90 1016.46 1016.48 1016.34 1016.50 1016.06 1015.62 1015.90 1015.72 1015.94 1015.30 1014.78 1014.68 1014.86 1015.86 1015.10 1014.36 1014.00 1013.90 ............................. MODELE PA PARAMETRE T NIVEAU HAUTEUR 2 ECHEANCE 0.0 DATE 20020304000000 NB_POINTS 25 1.34 1.51 1.40 0.56 -0.36 1.73 1.43 0.89 -0.16 -0.99 2.06 1.39 1.14 -0.53 -0.99 2.12 2.22 2.15 0.76 -1.16 1.67 1.45 1.40 1.26 0.28 NIVEAU HAUTEUR 2 ECHEANCE 3.0 DATE 20020304000000 NB_POINTS 25 0.94 1.16 1.03 0.44 -0.41 0.95 0.61 0.22 ............................................. I'am at the begginning of computation and for the moment I write this code to extract only number data in form of a string: from pyparsing import * dec = Combine (Optional( "-" ) + delimitedList( Word( nums ), ".", combine=True )) datas = ZeroOrMore( dec ) f=file("arqal-Arpege.00", "r") g=file("out3", "w") for line in f: try: result = datas. parseString (line) add = result add1 = ";".join (add) print >> g,"(",add1,")" except ParseException, pe: print pe This is the output result in file g=file("out3", "w") ( ) ( ) ( ) ( 1020.91;1020.87;1020.91;1021.05;1021.13 ) ( 1020.07;1020.27; 1020.49;1020.91;1021.15 ) ( 1019.37;1019.65;1019.79; 1020.53;1020.77 ) ( 1018.73;1018.89;1019.19;1019.83;1020.81 ) ( 1018.05;1018.19;1018.75; 1019.55;1020.27 ) ( ) ( 1019.80;1019.78; 1019.92;1020.18;1020.34 ) ( 1018.94;1019.24;1019.54;1020.08;1020.32 ) ( 1018.24;1018.64;1018.94; 1019.84;1019.98 ) ( 1017.48;1017.88;1018.28; 1018.98;1019.98 ) ( 1016.62; 1017.08;1017.66;1018.26;1018.34 ) ( ) ( 1019.37;1019.39;1019.57; 1019.9;......; ........ .........; 1016.87) ( ) ( 1017.84; 1017.46;1017.14;1016.86;1016.58 ) ( 1017.28; 1016.90;1016.46;1016.48; 1016.34 ) ( 1016.50;1016.06;1015.62;1015.90; 1015.72 ) ( 1015.94;1015.30; 1014.78;1014.68;1014.86 ) ( 1015.86; 1015.10;1014.36;1014.00;1013.90 ) So I don't have any word but the problem is that Now I have to put in order this numerical datas in a type of NESTED matrix emulated by python like a nested dictionary : { 'P ' : { MER 0 : [ (1020.91; 1020.87;........;1020.27 ) ; (.........) ; ( 1019.80;1019.78;........; 1018.26;1018.34 ) ]; ......; SOL 0 : [ ( .......);.....;(........ ) ] } ; 'T' : { SOL 0 : [(.....;......) ; (ECHEANCE 3.0) ; (ECHEANCE 6.0) ; (.......;........) ]; HAUTEUR 2 : [(.......;......;......) ] } } ======>>>>>> { 'Parameter X' : { Level X : [ (predict step 3 hours from +0 to +48 hours ) ;]} } >>>>>> the bigger shell is fixed by Dictionary PARAMETER in the example is P= 'Pressure' but thre are many of this Temperature = T , Wind = U and V ecc... the second nested shell is setted by another Dictionary NIVEAU MER 0 in the example is MER 0 = sea level or SOL 0, but can be HAUTER 2,10 (HEIGHT 2,10 METERS) ecc..... (soil level , 1;0 meter from soil) ecc (from French language) and after every Level is associated with a LIST OF TUPLE: [(....); (....);(....)] to rappresented every step hours of prediction or expiration hours in French language: ECHEANCE XX.X = predicted hour +3. 0 +6.0 until 48H is setted of a list of tuple [(ECHEANCE 3.0); (ECHEANCE 6.0); (ECHEANCE XX.0);.........;(ECHEANCE 48.0)] like so: [1019.37; 1019.39;........;1020.27 );(.........);(1019.80; 1019.78;........; 1018.26;1018.34 )] where every list is at the end the is the datas grill: (5 x 5 points)= 25 datas 1020.91 1020.87 1020.91 1021.05 1021.13 1020.07 1020.27 1020.49 1020.91 1021.15 1019.37 1019.65 1019.79 1020.53 1020.77 1018.73 1018.89 1019.19 1019.83 1020.81 1018.05 1018.19 1018.75 1019.55 1020.27 So I ask you wich is the best way to begin to code the grammar parsying to make recognize him the 'word' inside of the data file and put the data in the form of nested dictionary and list of tuple illustrated before. In attached file there is one meteo arpege datas file and text of the message in open office file Thanks a lot for everyone can said me anything to solve this, big problem (for me)!!!! From s.mientki at id.umcn.nl Wed May 16 05:02:15 2007 From: s.mientki at id.umcn.nl (stef) Date: Wed, 16 May 2007 11:02:15 +0200 Subject: iteration doesn't seem to work ?? In-Reply-To: <1179305662.928436.215140@q75g2000hsh.googlegroups.com> References: <1179305662.928436.215140@q75g2000hsh.googlegroups.com> Message-ID: hello Sean, thanks very much for the explanation and solution. cheers, Stef Mientki half.italian at gmail.com wrote: > On May 16, 1:41 am, stef wrote: > >> hello, >> >> can someone tell me why the following iteration doesn't work, >> and >> how I should replace empty strings in a list with a default value. >> >> >>> v >> ['123', '345', '', '0.3'] >> >>> for items in v: >> ... if items=='': >> ... items='3' >> ... >> >>> >> >>> v >> ['123', '345', '', '0.3'] >> >>> >> >> thanks, >> Stef Mientki >> > > Inside the loop, 'items' is no longer referencing the list...its a > string. > > >>>> v = ['123', '4', '567', ''] >>>> for i in v: >>>> > ... print type(i) > ... > ... > > This works > > >>>> for j,i in enumerate(v): >>>> > ... if i=='': > ... v[j] = '3' > ... > >>>> v >>>> > ['123', '4', '567', '3'] > > > ~Sean > > From sjdevnull at yahoo.com Thu May 17 19:20:20 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 17 May 2007 16:20:20 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179355081.828574.241690@h2g2000hsg.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179289167.723990.223890@u30g2000hsc.googlegroups.com> <464abd12$0$23364$426a34cc@news.free.fr> <1179307776.953405.207680@l77g2000hsb.googlegroups.com> <464ad388$0$28786$426a34cc@news.free.fr> <1179337277.347833.237450@n59g2000hsh.googlegroups.com> <1179355081.828574.241690@h2g2000hsg.googlegroups.com> Message-ID: <1179442099.420374.122690@u30g2000hsc.googlegroups.com> On May 16, 6:38 pm, r... at yahoo.com wrote: > On May 16, 11:41 am, "sjdevn... at yahoo.com" > wrote: > > > Christophe wrote: > ....snip... > > > Who displays stack frames? Your code. Whose code includes unicode > > > identifiers? Your code. Whose fault is it to create a stack trace > > > display procedure that cannot handle unicode? You. > > > Thanks but no--I work with a _lot_ of code I didn't write, and looking > > through stack traces from 3rd party packages is not uncommon. > > Are you worried that some 3rd-party package you have > included in your software will have some non-ascii identifiers > buried in it somewhere? Surely that is easy to check for? > Far easier that checking that it doesn't have some trojan > code it it, it seems to me. What do you mean, "check for"? If, say, numeric starts using math characters (as has been suggested), I'm not exactly going to stop using numeric. It'll still be a lot better than nothing, just slightly less better than it used to be. > > And I'm often not creating a stack trace procedure, I'm using the > > built-in python procedure. > > > And I'm often dealing with mailing lists, Usenet, etc where I don't > > know ahead of time what the other end's display capabilities are, how > > to fix them if they don't display what I'm trying to send, whether > > intervening systems will mangle things, etc. > > I think we all are in this position. I always send plain > text mail to mailing lists, people I don't know etc. But > that doesn't mean that email software should be contrainted > to only 7-bit plain text, no attachements! I frequently use > such capabilities when they are appropriate. Sure. But when you're talking about maintaining code, there's a very high value to having all the existing tools work with it whether they're wide-character aware or not. > If your response is, "yes, but look at the problems html > email, virus infected, attachements etc cause", the situation > is not the same. You have little control over what kind of > email people send you but you do have control over what > code, libraries, patches, you choose to use in your > software. > > If you want to use ascii-only, do it! Nobody is making > you deal with non-ascii code if you don't want to. Yes. But it's not like this makes things so horribly awful that it's worth my time to reimplement large external libraries. I remain at -0 on the proposal; it'll cause some headaches for the majority of current Python programmers, but it may have some benefits to a sizeable minority and may help bring in new coders. And it's not going to cause flaming catastrophic death or anything. From tjreedy at udel.edu Tue May 15 02:37:47 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 15 May 2007 02:37:47 -0400 Subject: Sorting troubles References: <1179158708.433792.127150@h2g2000hsg.googlegroups.com><1179161396.220858.86150@q75g2000hsh.googlegroups.com> <1179204326.945346.38590@q75g2000hsh.googlegroups.com> Message-ID: wrote in message news:1179204326.945346.38590 at q75g2000hsh.googlegroups.com... | Teach said that the optimal threshold in hybrids is 14-16, but guess | he wasn't so right after all =\\ The overhead of using insertion sort | on a longer list turns out to be faster than just piling on | recursions, when confronted with bigger lists. The current list.sort (is C, of course, not Python) is a hybrid insert/merge sort with a threshhold, last I knew, of 64. I believe there are explanatory comments in the source. tjr From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed May 23 07:42:42 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 23 May 2007 13:42:42 +0200 Subject: Can I reference 1 instance of an object by more names ? rephrase In-Reply-To: References: Message-ID: <4654289a$0$2326$426a74cc@news.free.fr> stef a ?crit : > thanks Guys for your information, > > indeed you're all quit right, > but I think I've not correctly described my problem :-( > > I need to have 2 (or more) names, that references the same instance of > an object, > and in assigning a value to the object (or to some property in the object), > I need to do extra activities (like changing some global variables). Then you want a property (aka computed attribute). > Now if I use a "container type object", without actual using the index > of the container object, > I get things working OK. > But now I have to use a dummy index, if I use the object in assignments, > see program below. > Is there another way, without using the dummy index, to achieve the same > results ? > thanks, > Stef Mientki > > > class cpu_ports(object): > def __init__(self, value=0): > self._d = value > def __setitem__(self, index, value): > print 'vv' > self._d = value > def __getitem__(self, index): > return self._d > def __repr__(self): > return str(self._d) > > name1 = cpu_ports() # create an instance > name2 = name1 # refer with a second name to the same instance > print name1, name2 # test ok > > name1[0] = 25 # assign a value to the instance > print name1, name2 # both references are OK > > name2[0] = 26 # assign another value through the other name > print name1, name2 # both reference are OK > > name2[0] = name1[0] + 13 # use both names at either side of an assignment > print name1, name2 # both references still OK You can have something working the same way using a property, but that's how far you'll get - if you hoped to be able to automagically rebind name2 when rebinding name1, then too bad, because python wont let you do so. You have to understand that name = obj is totally different from name.attr = obj or name[index] = obj In the first case, this is *really* a binding, and that's one of the few things that Python won't let you mess with. In the two last cases, it's in fact a method call - as the use of __[get|set]item__ should make obvious. here's an example using a property: class cpu_ports(object): def __init__(self, value=0): self._d = value @apply def value(): def fset(self, value): print 'vv' self._d = value def fget(self): return self._d return property(**locals()) def __repr__(self): return str(self._d) name1 = cpu_ports() # create an instance name2 = name1 # refer with a second name to the same instance print name1, name2 # test ok name1.value = 25 # assign a value to the instance print name1, name2 # both references are OK name2.value = 26 # assign another value through the other name print name1, name2 # both reference are OK name2.value = name1.value + 13 print name1, name2 # both reference are OK And that's about as far as you can go (without rewriting Python I mean). From goon12 at gmail.com Thu May 31 08:25:56 2007 From: goon12 at gmail.com (Joe Riopel) Date: Thu, 31 May 2007 08:25:56 -0400 Subject: Is PEP-8 a Code or More of a Guideline? In-Reply-To: <646aw86i.fsf@mail.com> References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <5c1jpkF2tl0ilU1@mid.individual.net> <1180539790.654176.26900@q75g2000hsh.googlegroups.com> <646aw86i.fsf@mail.com> Message-ID: <6a2ccd190705310525gb51d794qa905d0c19621aa23@mail.gmail.com> > Each requires exactly the same number of key strokes when I do the > math. (Too lazy to explain further...) foo_bar f, o, o, shift + underscore, b, a, r = 8 fooBar f, o, o, shift + b, a, r = 7 From farri_88 at msn.com Fri May 18 08:54:44 2007 From: farri_88 at msn.com (Fazlyi Mustafa) Date: Fri, 18 May 2007 14:54:44 +0200 Subject: Naked Boobs! - Download for Free !!! In-Reply-To: <1179470215.915964.209640@w5g2000hsg.googlegroups.com> Message-ID: Pojedes bananu neka ti na cast majmine >From: penis.Mosely5 at gmail.com >To: python-list at python.org >Subject: Naked Boobs! - Download for Free !!! >Date: 17 May 2007 23:36:55 -0700 > >http://nudepicks.blogspot.com/ - Naked Boobie Downloads! > >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ Idolerna upptr?der p? MSN http://msnpresents.msn.com/hub/?mkt=sv-se From mcPas.De.Spam at mclaveauPas.De.Spam.com Mon May 14 17:19:30 2007 From: mcPas.De.Spam at mclaveauPas.De.Spam.com (Michel Claveau) Date: Mon, 14 May 2007 23:19:30 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: Message-ID: Hi! ;-))) In whitespace-programming-language, only three characters are used : Space - Tab - RC No parasitic characters in listings ; economy of ink ; ecological behavior ; LOL programming... Must, Python, follow this way? -- @-salutations Michel Claveau From roy at panix.com Wed May 2 21:19:54 2007 From: roy at panix.com (Roy Smith) Date: Wed, 02 May 2007 21:19:54 -0400 Subject: How to check if a string is empty in python? References: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> <1178154290.811928.208900@h2g2000hsg.googlegroups.com> Message-ID: In article <1178154290.811928.208900 at h2g2000hsg.googlegroups.com>, Dustan wrote: > On May 2, 5:50 pm, Steven D'Aprano > wrote: > > On Wed, 02 May 2007 13:35:47 -0700, noagbodjivictor wrote: > > > How to check if a string is empty in python? > > > if(s == "") ?? > > > > In no particular order, all of these methods will work: > > > > # test s is equal to another empty string > > if s == "": > > > > # assuming s is a string, test that it is empty > > if not s: > > > > # test s is a string and it is empty > > if isinstance(s, str) and not s: > > > > # test s has length 0 > > if len(s) == 0: > > > > # test the length of s evaluates as false > > if not len(s): > > > > # a long way to test the length of s > > if s.__len__() < 1: > > > > # a stupid way to test s is empty > > if bool(s) == False: > > > > # a REALLY stupid way to test s is empty > > if (bool(s) == False) == True: > > LOL > > > # test that appending s to itself is itself > > if s+s == s: > > > > # test that s has none of any character > > if not filter(None, [1 + s.find(chr(n)) for n in range(256)]): > > > > That last one is really only good for wasting CPU cycles. > > and the other ones are... ? > > > -- > > Steven. s.join("foo") == "foo" for c in s: raise "it's not empty" From alan.franzoni_invalid at geemail.invalid Sun May 13 18:41:01 2007 From: alan.franzoni_invalid at geemail.invalid (Alan Franzoni) Date: Mon, 14 May 2007 00:41:01 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <1u9kz7l2gcz1p.1e0kxqeikfp97.dlg@40tude.net> Il Sun, 13 May 2007 17:44:39 +0200, "Martin v. L?wis" ha scritto: [cut] I'm from Italy, and I can say that some thoughts by Martin v. L?wis are quite right. It's pretty easy to see code that uses "English" identifiers and comments, but they're not really english - many times, they're just "englishized" versions of the italian word. They might lure a real english reader into an error rather than help him understand what the name really stands for. It would be better to let the programmer pick the language he or she prefers, without restrictions. The patch problem doesn't seem a real issue to me, because it's the project admin the one who can pick the encoding, and he could easily refuse any patch that doesn't conform to the standards he wants. BTW, there're a couple of issues that should be solved; even though I could do with iso-8859-1, I usually pick utf-8 as the preferred encoding for my files, because I found it more portable and more compatible with different editors and IDE (I don't know if I just found some bugs in some specific software, but I had problems with accented characters when switching environment from Win to Linux, especially when reading/writing to and from non-native FS, e.g. reading files from a ntfs disk from linux, or reading an ext2 volume from Windows) on various platforms. By the way, I would highly dislike anybody submitting a patch that contains identifiers other than ASCII or iso-8859-1. Hence, I think there should be a way, a kind of directive or sth. like that, to constrain the identifiers charset to a 'subset' of the 'global' one. Also, there should be a way to convert source files in any 'exotic' encoding to a pseudo-intellegibile encoding for any reader, a kind of translittering (is that a proper english word) system out-of-the-box, not requiring any other tool that's not included in the Python distro. This will let people to retain their usual working environments even though they're dealing with source code with identifiers in a really different charset. -- Alan Franzoni - Togli .xyz dalla mia email per contattarmi. Remove .xyz from my address in order to contact me. - GPG Key Fingerprint (Key ID = FE068F3E): 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From basilisk96 at gmail.com Tue May 1 17:50:33 2007 From: basilisk96 at gmail.com (Basilisk96) Date: 1 May 2007 14:50:33 -0700 Subject: Removing the continous newline characters from the pythong string In-Reply-To: <1178055012.135278.104430@p77g2000hsh.googlegroups.com> References: <1178055012.135278.104430@p77g2000hsh.googlegroups.com> Message-ID: <1178056233.225222.163330@p77g2000hsh.googlegroups.com> why not use split: >>>s = " a\n\n\n\n\n\n\n\n\nsss\n\n\n\n\n\n\n\n\n\n\nvvvv\n\n\n\nvsa\n\n\n\nasf... \n\nafs" >>>s.split() ['a', 'sss', 'vvvv', 'vsa', 'asf...', 'afs'] From fsckedagain at gmail.com Thu May 10 18:04:30 2007 From: fsckedagain at gmail.com (fscked) Date: 10 May 2007 15:04:30 -0700 Subject: path stuff In-Reply-To: <1178829783.996168.48250@u30g2000hsc.googlegroups.com> References: <1178734266.858048.311740@y5g2000hsa.googlegroups.com> <1178818879.239014.152210@e65g2000hsc.googlegroups.com> <1178826330.282268.132350@p77g2000hsh.googlegroups.com> <1178829783.996168.48250@u30g2000hsc.googlegroups.com> Message-ID: <1178834670.518728.102920@e65g2000hsc.googlegroups.com> On May 10, 1:43 pm, fscked wrote: > On May 10, 12:45 pm, fscked wrote: > > > > > > > On May 10, 10:41 am, fscked wrote: > > > > On May 9, 7:02 pm, "Gabriel Genellina" wrote: > > > > > En Wed, 09 May 2007 15:11:06 -0300, fscked > > > > escribi?: > > > > > > I am walking some directories looking for a certain filename pattern. > > > > > This part works fine, but what if I want to exclude results from a > > > > > certain directory being printed? > > > > > Using os.walk you can skip undesired directories entirely: > > > > > for dirpath, dirnames, filenames in os.walk(starting_dir): > > > > if "archived" in dirnames: > > > > dirnames.remove("archived") > > > > # process filenames, typically: > > > > for filename in filenames: > > > > fullfn = os.path.join(dirpath, filename) > > > > ... > > > > > -- > > > > Gabriel Genellina > > > > OK, this is on Winbloze and it keeps giving me "The directory name is > > > invalid: u"blahblahblah" with double backslashies everywhere. I am > > > currently trying to figure out how to make those go away. I shall > > > check back in a bit. > > > > thanks for all the help so far. :)- Hide quoted text - > > > > - Show quoted text - > > > ok, got the backslashies fixed, not I want it to print just a single > > line for each matching filename and dirpath, but it prints 3... hmm...- Hide quoted text - > > > - Show quoted text - > > Nevermind, I am indentationally challenged. I was printing under the > for dirpath, dirname, filename part and had to unindent uno time. > > It works as desired now, thanks!- Hide quoted text - > > - Show quoted text - ok, I lied, it is still doing the archived folders. Here is the code: import os, sys from path import path myfile = open("boxids.txt", "r", 0) for line in myfile: d = 'D:\\Dir\\' + path(line.strip()) for f in d.walkfiles('*Config*.xml'): for dirpath, dirnames, filenames in os.walk(d): if "Archived" in dirnames: dirnames.remove("Archived") #skip this directory print f print 'Done' when it does the print f it still shows me the dirs i don't want to see. any more ideas? TIA From ptmcg at austin.rr.com Mon May 14 09:40:05 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 14 May 2007 06:40:05 -0700 Subject: Yet Another Software Challenge In-Reply-To: <1179148471.466017.156290@q75g2000hsh.googlegroups.com> References: <1179148471.466017.156290@q75g2000hsh.googlegroups.com> Message-ID: <1179150005.400863.256700@e51g2000hsg.googlegroups.com> On May 14, 8:14 am, Thierry wrote: > For those interested in programming riddles, I would like to > announce a new programming challenge I'm just launching athttp://software.challenge.googlepages.com > > This challenge is in its early stage and thus set to be continuously > improved. > > I would be especially interested in your comments and feedbacks about > this initiative and its relevance. > > Enjoy! > > Thierry More feedback: In Riddle 2, the "global" declarations are unnecessary, as you are only referencing the globally-defined vars for read. Also in Riddle 2, I would replace for s in alphabet: indices[s] = alphabet.index(s) with indices = dict( (s,i) for i,s in enumerate(alphabet) ) (I see part of your Python Challenge as giving new Pythoners something to cut their teeth on, and so this is an opportunity for giving examples of good style.) I do enjoy these challenges, they are quite addicting. :) -- Paul From nagle at animats.com Fri May 18 14:15:39 2007 From: nagle at animats.com (John Nagle) Date: Fri, 18 May 2007 11:15:39 -0700 Subject: Python Web Programming - looking for examples of solid high-traffic sites In-Reply-To: <1hyarxo.iqtdo1v9qpivN%aleax@mac.com> References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> <1hy9yf9.1nnsttj139za6bN%aleax@mac.com> <1hyarxo.iqtdo1v9qpivN%aleax@mac.com> Message-ID: Alex Martelli wrote: > Jarek Zgoda wrote: > > >>Daniel Nogradi napisa?(a): >> >> >>>>For example, it HAS been published elsewhere that YouTube uses lighttpd, >>>>not Apache: . >>> >>>How do you explain these, then: >>> >>>http://www.youtube.com/results.xxx >>>http://www.youtube.com/results.php >>>http://www.youtube.com/results.py >> >>Server signature is usually configurable. > > > Yeah, but I don't know why it's configured it that way. A good example > of a question that looks perfectly appropriate for YouTube's OSCON > session. YouTube's home page is PHP. Try "www.youtube.com/index.php". That works, while the obvious alternatives don't. If you look at the page HTML, you'll see things like Log In So there's definitely PHP inside YouTube. If you look at the HTML for YouTube pages, there seem to be two drastically different styles. Some pages begin with "", and have their CSS stored in external files. Those seem to be generated by PHP. Other pages start with "", with no "machine ID". It looks like the stuff associated with accounts and logging in is on the second system (Python?) while the search and view related functions are on the PHP system. Shortly after Google bought YouTube, they replaced YouTube's search engine (which was terrible) with one of their own. At that time, Google search syntax, like "-", started working. That's probably when the shift to PHP happened. John Nagle From cmpython at gmail.com Sat May 26 19:20:32 2007 From: cmpython at gmail.com (cmpython at gmail.com) Date: 26 May 2007 16:20:32 -0700 Subject: Newbie help understanding... In-Reply-To: <1180164211.934421.64420@i38g2000prf.googlegroups.com> References: <1180164211.934421.64420@i38g2000prf.googlegroups.com> Message-ID: <1180221632.893974.222790@q75g2000hsh.googlegroups.com> The problem is that in your function t is a string (one of the cards in the list called "cards") and strings don't have the ability to use the append method. But lists do. Therefore t.append is wrong but cards.append works fine. (Append means "take the list you have and add what is in the parenthesis to it...so cards.append("Ace") would append the string Ace to the list of cards). From q16941 at motorola.com Mon May 21 09:31:19 2007 From: q16941 at motorola.com (ashish) Date: Mon, 21 May 2007 19:01:19 +0530 Subject: GUI to python scripts Message-ID: <46519F27.2080700@motorola.com> Hi All, I need one help ,i started learning python few months back and i am comfortable with python now ,My intrest is, i want to genrate python scripts from GUI i.e. My GUI should be having macros or function of my intrest ,so if i select them it should generate corressponding python script for that.Can any one tell from where i will get such API or GUI application which will generate python scripts. Regards Ashish. From showell30 at yahoo.com Sun May 27 12:37:37 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 27 May 2007 09:37:37 -0700 (PDT) Subject: Why isn't this query working in python? In-Reply-To: <1180279833.131269.136770@w5g2000hsg.googlegroups.com> Message-ID: <37732.54938.qm@web33510.mail.mud.yahoo.com> --- erikcw wrote: > > > > > ('SELECT payment_id FROM amember_payments WHERE > member_id=%s AND > > > expire_date > NOW() AND completed=1 AND > (product_id >11 AND product_id > > > <21)', (1608L,)) > > > () > > > > Here is a copy of the table schema and the first 2 > rows. > Does your table actually contain any rows that meet the criteria that expire_date is in the future, completed is 1, product id is between 11 and 21, etc.? Have you tried debugging the SQL outside of Python? ____________________________________________________________________________________Ready for the edge of your seat? Check out tonight's top picks on Yahoo! TV. http://tv.yahoo.com/ From http Mon May 28 17:31:22 2007 From: http (Paul Rubin) Date: 28 May 2007 14:31:22 -0700 Subject: itertools.groupby References: <1180286272.100790.131670@q75g2000hsh.googlegroups.com> Message-ID: <7xveecr5xx.fsf@ruckus.brouhaha.com> Gordon Airporte writes: > This is my first exposure to this function, and I see that it does > have some uses in my code. I agree that it is confusing, however. > IMO the confusion could be lessened if the function with the current > behavior were renamed 'telescope' or 'compact' or 'collapse' or > something (since it collapses the iterable linearly over homogeneous > sequences.) It chops up the iterable into a bunch of smaller ones, but the total size ends up the same. "Telescope", "compact", "collapse" etc. make it sound like the output is going to end up smaller than the input. There is also a dirty secret involved , which is that the itertools functions (including groupby) are mostly patterned after similarly named functions in the Haskell Prelude, which do about the same thing. They are aimed at helping a similar style of programming, so staying with similar names IMO is a good thing. > A function named groupby could then have what I think is the clearly > implied behavior of creating just one iterator for each unique type of > thing in the input list, as categorized by the key function. But that is what groupby does, except its notion of uniqueness is limited to contiguous runs of elements having the same key. From showell30 at yahoo.com Mon May 28 17:45:26 2007 From: showell30 at yahoo.com (Steve Howell) Date: Mon, 28 May 2007 14:45:26 -0700 (PDT) Subject: ten small Python programs In-Reply-To: Message-ID: <407988.43697.qm@web33503.mail.mud.yahoo.com> --- Stef Mientki > > > I don't know MoinMoin, > but the answer is Yes (although maybe not for your > ten snippets). > First of all I think all programmers keep there own > collection of code snippets, > which much more valuable then "all the code code > snippets from everyone". Agreed. > Secondly, Python is nowadays not only used by > programmers, > but also by e.g. Scientific users (former MatLab > users), > who are not interested in the code itself, > but just in the results of that particular code. > For these people a lot of example programs, > for which they can easily see the results, > make some small changes and see the result again, > would be a wonderful addition. > In your own personal use, what are some libraries/techniques/etc. that you think could benefit from some kind of more organized presentation of example programs (or better way of showing how the examples work, etc.)? Are you part of the Scientific community? How new are you to Python? I do think newbies/intermediates/advanceds all have different needs. ____________________________________________________________________________________Building a website is a piece of cake. Yahoo! Small Business gives you all the tools to get online. http://smallbusiness.yahoo.com/webhosting From bscrivener42 at gmail.com Thu May 31 01:21:34 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: 30 May 2007 22:21:34 -0700 Subject: wxpython demo error on debian etch In-Reply-To: <1180462154.551455.83010@k79g2000hse.googlegroups.com> References: <1180445918.523446.133300@g4g2000hsf.googlegroups.com> <1180446704.521350.72450@k79g2000hse.googlegroups.com> <1180459989.799593.243960@u30g2000hsc.googlegroups.com> <1180462154.551455.83010@k79g2000hse.googlegroups.com> Message-ID: <1180588894.587378.276170@u30g2000hsc.googlegroups.com> On May 29, 1:09 pm, kyoso... at gmail.com wrote: > The newer versions of wxPython won't make your Debian crash or > anything. We run Debian at work and I've upgraded the Python to 2.4 > and the wxPython to its newest version. This has not affected the > server's stability in any way. Install like this? Debian stable is way behind the times, so you may find something appropriate in testing. Alternatively, the instructions below should work. apt-get install alien apt-get install libgtk2.0-dev freeglut3-dev python2.3-dev wget http://easynews.dl.sourceforge.net/wxpython/wxPython2.8-2.8.3.0-1.src.rpm rpmbuild --rebuild --define 'pyver 2.3' wxPython2.8-2.8.3.0-1.src.rpm cd rpmdir alien packagenames.rpm dpkg -i whatever alien called them > > This link explains the process the Debian team takes to implement new > versions of packages (like wxPython):http://en.wikipedia.org/wiki/Debian > > Basically, they test it for months before finally putting it in to the > "stable" category. However, since they have to do this for lots of > packages, one by one the packages get marked stable. So you could have > something like wxPython marked stable in March and 6 months later, the > rest of the packages are done so they're marked stable. And then after > additional testing, they release the new version. > > Hopefully that wasn't too confusing. > > Mike From larry.bates at websafe.com Thu May 10 12:38:20 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 10 May 2007 11:38:20 -0500 Subject: Newbie look at Python and OO In-Reply-To: <1178812734.860473.236370@y80g2000hsf.googlegroups.com> References: <1178812734.860473.236370@y80g2000hsf.googlegroups.com> Message-ID: walterbyrd wrote: > I learned to program with Pascal, way back when. Went into software > development for a while, then went into systems admin. Have programmed > in several languages, just learning Python. > > Some things I find odd: > > 1) 5/-2 == -3? > > 2) list assignment handling, pointing two vars to the same list: > > With simple data types: >>>> a = 5 >>>> b = a >>>> a = 3 >>>> a,b > (3, 5) > > Which is what I'd expect, since I have changed a, but not b. > > But with lists: >>>> a = list("1234") >>>> b = a >>>> a.append("5") >>>> a,b > (['1', '2', '3', '4', '5'], ['1', '2', '3', '4', '5']) > > b changes even though I have not touched b. I know why, but this is > not what I would ordinarilly expect, it does not seem intuitive. And, > IMO, it gets worse: > >>>> a = list("1234") >>>> b = a >>>> a = a + ['5'] >>>> a,b > (['1', '2', '3', '4', '5'], ['1', '2', '3', '4']) > > Sometimes changing a changes b, and sometimes not. You also have to > remember that subseqent changes to a will not change b - after some > operation but not others. To those who think in Python, I'm sure this > all seems normal. But, having programmed in about one dozen other > language, this seems downright bizare to me. I know why it works like > this, but it seems like an odd way to do things. > > 3) ambiguous use of the form: this.that() > > Sometimes, this.that() means module.funcion() as in: > >>>> os.dirlist(".") > > Other times, "this" is sort of like a parameter to the "that" > function: > >>>> a = list("1234") >>>> "_".join(a) > '1_2_3_4_5' > > And still other times, is seems that "this" is an object, acted upon > by "that" : > >>>> a = list("1234") >>>> b = "_".join(a) >>>> b.split("_") > ['1', '2', '3', '4', '5'] > > BTW: it seems a bit odd to that the positions of the string, and the > delimitor, are reversed between the complementory functions join(), > and split(). I suppose if it weren't for OO, we have something > terribly complicated, like: > > split(str, "_") > join(str, "_") > > Again, those who think in Python, will understand right away that: > > math.count(x) > > is counting the substring "x" in the "math" string. But can you see > where that might be confused to be a function called count() in the > math module? > > I'm not complaining. Python is a great language in many respects. But, > I would take some issue with those claiming Python is intuitive and > easy. IMO: there seems to be many ambiguous, unintuitve, and > confusing, aspects to Python. > Some of your confusion is because you have ingrained ideas about how "other" languages handle things and want Python to do it the same way. Give it some time and you will begin to understand (as many have) that there REALLY is method to the apparent madness... > Some things I find odd: > > 1) 5/-2 == -3? > > What do you except from integer arithmetic? The ONLY possible answers are -2, or -3. Python chooses to always return the floor (lower) of the two values in integer division. While this makes complete sense for positive integers, it seems odd for negative ones, but it is consistent. > With simple data types: >>>> a = 5 >>>> b = a >>>> a = 3 >>>> a,b > (3, 5) > Here you confuse Python's complete object orientation with other previously learned languages. a=5 In python means: make me a name 'a' in the local namespace that points to an object that holds a 5. It does not mean: create a memory area referred to by a and place a 5 in it (as many other languages do). b=a In python means: make me a name 'b' in the local namespace that points to object 'a'. A good way to see this is to do: id(a) id(b) you will see that they both point to the same object. > Which is what I'd expect, since I have changed a, but not b. > > But with lists: >>>> a = list("1234") >>>> b = a >>>> a.append("5") >>>> a,b > (['1', '2', '3', '4', '5'], ['1', '2', '3', '4', '5']) > > b changes even though I have not touched b. I know why, but this is > not what I would ordinarilly expect, it does not seem intuitive. And, > IMO, it gets worse: > Again this is because of objects not "containers" like Pascal or other languages. b=a In python means: create me an object 'b' that points the same place as object 'a'. a.append("5") modifies both variables because both variables point to the same place. >>>> a = list("1234") >>>> b = a >>>> a = a + ['5'] >>>> a,b > (['1', '2', '3', '4', '5'], ['1', '2', '3', '4']) > > Sometimes changing a changes b, and sometimes not. You also have to > remember that subseqent changes to a will not change b - after some > operation but not others. To those who think in Python, I'm sure this > all seems normal. But, having programmed in about one dozen other > language, this seems downright bizare to me. I know why it works like > this, but it seems like an odd way to do things. > do >>> id(a) 18192784 >>> id(b) 18192784 >>> a=a+['5'] In python means: create a new object a that is the old object a with a '5' appended to the list. Now look at the ids of the two variables: >>> id(a) 12993360 >>> id(b) 18192784 See 'a' and 'b' now point to different places. Append does in-place append, the a+['5'] makes a new object. > 3) ambiguous use of the form: this.that() > > Sometimes, this.that() means module.funcion() as in: > >>>> os.dirlist(".") > > Other times, "this" is sort of like a parameter to the "that" > function: > this.that() syntax always calls the that method of the object this. >>>> a = list("1234") >>>> "_".join(a) > '1_2_3_4_5' > "_" is a string object that has all the methods any other string object will have. Objects don't have to be named (via variables) to have methods. You could write: underline="_" underline.join(a) > And still other times, is seems that "this" is an object, acted upon > by "that" : > >>>> a = list("1234") >>>> b = "_".join(a) >>>> b.split("_") > ['1', '2', '3', '4', '5'] > Not really, you can write: underline="_" b=underline.join(a) c=b.split(underline) seems perfectly clear to me (but I have to admit it took me a while to see the beauty of python's syntax). > BTW: it seems a bit odd to that the positions of the string, and the > delimitor, are reversed between the complementory functions join(), > and split(). I suppose if it weren't for OO, we have something > terribly complicated, like: > > split(str, "_") > join(str, "_") > > Again, those who think in Python, will understand right away that: > > math.count(x) > > is counting the substring "x" in the "math" string. But can you see > where that might be confused to be a function called count() in the > math module? Actually it could be either. If you write your own class called math that has a count method this would work. If the math module had a count method (which it doesn't) and you import it, you might call that method of the math module this way. One thing you will come to appreciate is that you can replace virtually any module, function, etc. in Python with your own code. A mistake many new python programmers make is to shadow str, list, dict, etc. by using them as variable names. Then later they can't figure out why they can't do str(n). Hope the feedback helps. -Larry From afriere at yahoo.co.uk Wed May 23 03:23:50 2007 From: afriere at yahoo.co.uk (Asun Friere) Date: 23 May 2007 00:23:50 -0700 Subject: Unable to strip \n characters In-Reply-To: <1179779832.177031.210370@b40g2000prd.googlegroups.com> References: <1179658203.040541.220800@p77g2000hsh.googlegroups.com> <1179727531.061286.139560@x35g2000prf.googlegroups.com> <1179779832.177031.210370@b40g2000prd.googlegroups.com> Message-ID: <1179905030.538469.323680@u30g2000hsc.googlegroups.com> On May 22, 6:37 am, aiwarrior wrote: > On May 21, 7:05 am, Asun Friere wrote: > > > On May 20, 10:49 pm, Michael Bentley > > wrote: > > > > On May 20, 2007, at 7:41 AM, Michael Bentley wrote: > > > > > (upload.strip()) > > > > Oops: (upload.strip(),) or upload.strip() > > > Superfluous though the braces around your original were, it should > > still run ... > > ie. (a) == a > > When you mean superfluous you mean it makes a diffrence in run-time or > just code style? Hmm I thought I already answered, but it hasn't turned up so ... It is superfluous in both senses, ie it will (v. marginally) affect run-time performance, and it is generally considered good coding style not to include parentheses where they are not needed, (though one should not be absolute about this, there may be cases where superfluous parentheses greatly clarify the meaning of some code). From paul at boddie.org.uk Wed May 2 17:09:32 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 2 May 2007 14:09:32 -0700 Subject: Can I use Python instead of Joomla? In-Reply-To: <1178138925.498663.252920@o5g2000hsb.googlegroups.com> References: <1178138925.498663.252920@o5g2000hsb.googlegroups.com> Message-ID: <1178140172.082607.147450@e65g2000hsc.googlegroups.com> walterbyrd wrote: > If I wanted to build a website with forums, news feeds, galleries, > event calander, document managment, etc. I do so in Joomla easily. Yes, you can do this kind of thing with Python: http://wiki.python.org/moin/ContentManagementSystems > But, I would perfer to use django/python, if that would be at all > practical. Then you should be looking for a content management system (CMS) written using Django, although there are a number of other established open source solutions, particularly in the Zope universe, that are already widely deployed. Paul From half.italian at gmail.com Mon May 14 04:04:41 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 14 May 2007 01:04:41 -0700 Subject: Removing part of string In-Reply-To: <1179122203.691267.64200@o5g2000hsb.googlegroups.com> References: <1179122203.691267.64200@o5g2000hsb.googlegroups.com> Message-ID: <1179129881.435117.146890@e51g2000hsg.googlegroups.com> On May 13, 10:56 pm, saif.shak... at gmail.com wrote: > Hi, > I am parsing an xml file ,and one part of structure looks > something like this: > > - PhysicalLink="Infotainment_Control_Bus_CAN"> > Infotainment_Control_Bus_CAN_TIMEOUT_AX > Timeout N_As/N_Ar > Time from transmit request until a CAN frame transmit > confirmation is received. > > > In my code i am extracting the data within > ,which is Timeout N_As/N_Ar.These tags repeat and will have > different timer names..like > > - PhysicalLink="Infotainment_Control_Bus_CAN"> > Infotainment_Control_Bus_CAN_TIMEOUT_BS > Timeout N_Bs > Time that the transmitter of a multi-frame message > shall wait to receive a flow control (FC) frame before timing out with > a network layer error. > > > I need to remove the words Timeout from the data,and > take only the abbrevation..i.e.N_As/N_bs like that .In short i have to > remove the words which come with name Time,and also the space which > comes next to it. > and take only the abbreviation.Can someone help me in this. > Thanks Did you get elementtree working? From john at datavoiceint.com Fri May 11 16:47:02 2007 From: john at datavoiceint.com (HMS Surprise) Date: 11 May 2007 13:47:02 -0700 Subject: Time In-Reply-To: <1178916216.893542.257320@y80g2000hsf.googlegroups.com> References: <1178916216.893542.257320@y80g2000hsf.googlegroups.com> Message-ID: <1178916422.065108.312920@l77g2000hsb.googlegroups.com> > > Could you point to an example of a python time_t struct? > Or maybe that should be a tm struct??? From vinay_sajip at yahoo.co.uk Wed May 9 03:37:32 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 9 May 2007 00:37:32 -0700 Subject: RotatingFileHandler bugs/errors and a general logging question. In-Reply-To: <1178668334.588946.256490@e51g2000hsg.googlegroups.com> References: <1178668334.588946.256490@e51g2000hsg.googlegroups.com> Message-ID: <1178696252.753583.34150@q75g2000hsh.googlegroups.com> On May 9, 12:52 am, nicholas.petre... at gmail.com wrote: > The infrastructure in which I am work needs the ability to have log > files written to from multiple instances of the same script and > potentially from hundreds or more different machines. > > I know that the documentation suggests using a networkloggingserver > but I wanted to know if anyone had any other solutions to allow us to > build off of the current pythonloggingpackages. > Dennis is right - the logging system is threadsafe but not safe against multiple processes (separate Python instances) writing to the same file. It certainly sounds like you need a scalable solution - and having each script send the events to a network logging server seems a good way of handling the scalability requirement. The logger name used can include the script instance and machine name, e.g. by starting with hostname.scriptname.scriptpid... The socket server which receives the events can demultiplex them based on this information and write them to a central repository in any arrangement you care to implement (e.g. into one file or several). Given that the example in the docs is a (basic) working example, is there any particular reason why you don't want to follow the suggested approach? Regards, Vinay Sajip From Mattia.Gentilini_REMOVE_ at _REMOVE_CNAF.INFN.IT Fri May 25 10:04:52 2007 From: Mattia.Gentilini_REMOVE_ at _REMOVE_CNAF.INFN.IT (Mattia Gentilini) Date: Fri, 25 May 2007 16:04:52 +0200 Subject: How to do this in python with regular expressions In-Reply-To: References: <1180093895.743196.75510@b40g2000prd.googlegroups.com> Message-ID: Thorsten Kampe ha scritto: >> I'm trying to parsing html with re module. > Just don't. Use an HTML parser like BeautifulSoup Or HTMLParser/htmllib -- |\/|55: Mattia Gentilini e 55 = log2(che_palle_sta_storia) (by mezzo) |/_| ETICS project at CNAF, INFN, Bologna, Italy |\/| www.getfirefox.com www.getthunderbird.com * Using Mac OS X 10.4.9 powered by Cerebros (Core 2 Duo) * From larry.bates at websafe.com Fri May 25 18:37:42 2007 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 25 May 2007 17:37:42 -0500 Subject: Large Amount of Data In-Reply-To: References: Message-ID: Jack wrote: > Thanks for the replies! > > Database will be too slow for what I want to do. > > "Marc 'BlackJack' Rintsch" wrote in message > news:pan.2007.05.25.18.03.09.688008 at gmx.net... >> In , Jack wrote: >> >>> I need to process large amount of data. The data structure fits well >>> in a dictionary but the amount is large - close to or more than the size >>> of physical memory. I wonder what will happen if I try to load the data >>> into a dictionary. Will Python use swap memory or will it fail? >> What about putting the data into a database? If the keys are strings the >> `shelve` module might be a solution. >> >> Ciao, >> Marc 'BlackJack' Rintsch > > Purchase more memory. It is REALLY cheap these days. -Larry From claird at lairds.us Sun May 27 12:22:50 2007 From: claird at lairds.us (Cameron Laird) Date: Sun, 27 May 2007 16:22:50 +0000 Subject: PHP5 programmer learning Python References: <1180280496.946434.26760@q69g2000hsb.googlegroups.com> Message-ID: In article , Gabriel Genellina wrote: >En Sun, 27 May 2007 12:41:36 -0300, romiro escribi?: > >> Anyway, my first question was if anyone knows of a tutorial that >> focuses on PHP -> Python learning, in such that there might be a block >> of PHP code alongside an example of how to do the same thing in > >I don't know of a specific PHP->Python tutorial, but "Instant Python" >would give you a brief tour, and "Dive into Python" is a good book for >people with some previous programming background. Both should be easy to >find using Google. . . . Along with accurate advice others have already given you here ("Dive into Python" would be my preferred starting point), it occurs to me you might want at your side. Also, back in the PHP world, might interest you, if you're not already familiar with it. From msurel at comcast.net Thu May 3 15:52:55 2007 From: msurel at comcast.net (Mike) Date: 3 May 2007 12:52:55 -0700 Subject: adding methods at runtime and lambda Message-ID: <1178221975.149008.192410@y5g2000hsa.googlegroups.com> I was messing around with adding methods to a class instance at runtime and saw the usual code one finds online for this. All the examples I saw say, of course, to make sure that for your method that you have 'self' as the first parameter. I got to thinking and thought "I have a lot of arbitrary methods in several utility files that I might like to add to things. How would I do that?" And this is what I came up with: def AddMethod(currObject, method, name = None): if name is None: name = method.func_name class newclass(currObject.__class__):pass setattr(newclass, name, method) return newclass() And lets say I have a utility function that can check if a drive exists on my windows box called HasDrive. I can add that like this: superdict = addm(dict(), lambda self, d: myUtils.HasDrive(d), "hasdrive") and then I can call superdict.HasDrive('c') lambda makes it possible to add any random function because you can use it to set self as the first parameter. I've found several real uses for this already. My big question is, will something like this be possible in python 3000 if lambda really does go away? I've not heard much about lambda, reduce, etc. lately but I know Guido wanted them out of the language. Is there a better way to do this today than to use lambda? It seemed the simplest way to do this that I could find. From surekap at gmail.com Sun May 6 08:18:26 2007 From: surekap at gmail.com (Prateek) Date: 6 May 2007 05:18:26 -0700 Subject: MROW Locking Message-ID: <1178453906.895774.197280@l77g2000hsb.googlegroups.com> Can anyone direct me to a good resource on how to do MROW Locking efficiently in Python. The recipe at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413393 is actually quite inefficient (not sure if it is the code or MROW itself). I have a dictionary (a cache lets say or some sort of index) which needs to be accessed by multiple threads. Most of the time its just being read. Very rarely, I have to iterate over it (sometimes writing, mostly reading), sometimes I have to update a single entry or multiple entries (ala dict.update()). I'd like to know the best way to make this happen (i.e. is MROW really what I am looking for or is there something else?). Is there a good way to do this using the in-built Lock and RLock objects? This project is part of a commercial database product. Prateek From elliot at bentlogic.net Wed May 2 00:23:45 2007 From: elliot at bentlogic.net (Elliot Peele) Date: Wed, 02 May 2007 00:23:45 -0400 Subject: os.path.join In-Reply-To: <1178072869.844914.59010@u30g2000hsc.googlegroups.com> References: <1178072869.844914.59010@u30g2000hsc.googlegroups.com> Message-ID: <1178079825.3201.6.camel@localhost.localdomain> On Tue, 2007-05-01 at 19:27 -0700, 7stud wrote: > On May 1, 7:36 pm, Elliot Peele wrote: > > Why does os.path.join('/foo', '/bar') return '/bar' rather than > > '/foo/bar'? That just seems rather counter intuitive. > > > > Elliot > > join( path1[, path2[, ...]]) > Join one or more path components intelligently. If any component is an > absolute path, all previous components (on Windows, including the > previous drive letter, if there was one) are thrown away... Yes, but that still doesn't answer my question as to why os.path.join works that way. I understand that that is how it is written, but why? Elliot From steve at holdenweb.com Sat May 26 11:37:26 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 26 May 2007 11:37:26 -0400 Subject: conditionally creating functions within a class? In-Reply-To: <163f0ce20705251948p75adb3d2vaa2d2c70f6542d48@mail.gmail.com> References: <163f0ce20705251744j5c728e9fn53585fe0c9250827@mail.gmail.com> <163f0ce20705251948p75adb3d2vaa2d2c70f6542d48@mail.gmail.com> Message-ID: <46585436.2080405@holdenweb.com> kaens wrote: > Thanks a lot. What actually got me started on this whole thing was a > mention in pythons tutorial on classes that you could conditionally > create classes (which you can). > > Anyhow, yes this is cleared up. > > I'll probably go with using inheritance for this, as it makes sense > for my program overall, unless there's some huge disadvantage to using > it. Is there any way to make something like interfaces - or say > "objects that inherit from this class need to implement these > functions" in python? It's not really an issue for me, but if someone > else ends up wanting to extend my code it could be useful. > > I guess I could do something like > > class a: > def __init__(self): > raise NotImplementedError > def required_function: > raise NotImplementedError > > kinda mimicking abstract classes, unless there's a builtin way to do > this (looks like there's not but it may make it into python 3000) > > I'd rather not make seperate modules for these functions, as the class > that requires them does a good bit of other stuff as well (and will > definitely be using one type of data retrieval or another), and I > think this would make it easiest to extend in the future. > > If you think I'm on the wrong track here, let me know. > I have taken the liberty of copying this back to the list, since other people may have stringer opinions than I on your approach. Frankly, I wouldn't worry about the "expense" of declaring two classes. If you need SQL-handling and XML-handling code then just declare two classes (with inheritance from a common class if that makes sense) and stop worrying about cost. It really doesn't make sense to try and fiddle the class methods to accommodate the needs of a single instance. "Premature optimization is the root of all evil". regards Steve PS: Many people prefer it when newsgroup conversations read linearly, with the most recent contributions at the bottom. That way a reader can easily "pick up the story". > On 5/25/07, Steve Holden wrote: >> kaens wrote: >> > So, I have a class that has to retrieve some data from either xml or >> > an sql database. >> > This isn't a problem, but I was thinking "hey, it would be cool if I >> > could just not define the functions for say xml if I'm using sql", so >> > I did some fiddling around with the interpreter. >> > >> > First, I try conditionally creating a function, period: >> > >> > a = 'a' >> > >> > if(a == 'a') >> > def b: >> > print "hello" >> > else: >> > def c: >> > print "goodbye" >> > >> > this works fine. b is defined, c is not. change the value of a and b >> > gets defined and not c (sorry for the one-letter variables here, but >> > for these little examples I don't think they detract much) >> > >> > then I try doing this within a function: >> > >> > class test: >> > def __init__(self,which): >> > self.which = which >> > >> > if(self.which == 'a'): >> > def b: >> > print "hello" >> > else: >> > def c: >> > print "goodbye" >> > >> The problem here is that the "if" statement executes in class scope, >> which means at the same level at which the "def" statements define the >> methods. >> >> Unfortunately there is no "self" defined, as "self" is a method argument >> (whose value is provided automatically by the interpreter when a method >> call is made on a specific instance of the class). So it's out of scope. >> >> You could try to define the methods inside __init__, but that isn't >> really appropriate because __init__ runs each time a new instance >> requires initialization, and one of the primary ideas behind object >> orientation is that the class defines the same methods for all instances. >> >> You could override the methods in each instance, but this is all taking >> you further and further away from your relatively simple engineering >> goal. >> >> > tester = test('a') >> > tester.b() >> > >> > This doesn't "compile", says "Name 'self' is not defined". I assume >> > this is because of scope, something like it hasn't made the object >> > yet, so there is no self attribute. . . but I thought that python >> > wouldn't even bother reading that class statement until I tried to >> > make a test object, and that it would do the __init__ function before >> > anything else, so I'm a bit fuzzy here. >> > >> In Python the only non-executable statement is "global", so the class >> definition is executed when it's encountered. This is what give rise to >> the problems, which you have correctly diagnosed as being related to >> scoping issues. >> >> > Next I try creating the functions through functions: >> > >> > class test: >> > def __init__(self, which): >> > self.which = which >> > self.chooser() >> > >> > def chooser(self): >> > if( self.which == 'a'): >> > def b(self): >> > print "hello" >> > else: >> > def c(self): >> > print "goodbye" >> > >> > tester = test('a') >> > tester.b() >> > >> > this tells me "instance has no attribute b. >> > >> And it isn't lying. The problem is that "def b" is executed within the >> chooser() method, so it's local to that method and invisible to the >> class scope. >> >> > I'm pretty sure this is all a scoping error of some sort (I could be >> > wrong), but I don't have my head wrapped around it at all. Anyone with >> > more knowledge care to explain what's going on? >> > >> > Also, would there be a way to conditionally create functions in a >> > class? It doesn't really matter, but it'd be nice if I weren't >> > creating functions that I absolutely will not need for certain >> > instances at runtime >> >> Here I'd ask you to take a step back. What you really need is two >> parallel modules or classes, one of which handles SQL inputs and the >> other of which handles XML inputs. >> >> My own approach would be to define two modules with the same API and >> then import one or the other. Something like this: >> >> if intype == "a": >> import sqlmodule as myinmod >> # do SQL-specific stuff, if any >> else: >> import xmlmodule as myinmod >> # do XML-specific stuff, if any >> >> You can then call the functions and classes defined in the imported >> module as >> >> myinmod.func() >> >> and >> >> someinstance = myinmod.classname() >> >> Since you only import one module, you don't execute the definitions in >> the unused module at all, and as long as the APIs really are parallel >> you can write code that doesn't care which one it uses. >> >> There are other approaches you could take, but if this would answer your >> needs then I'd suggest you consider it. >> -- 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From jadestar at idiom.com Wed May 30 23:13:34 2007 From: jadestar at idiom.com (James T. Dennis) Date: Thu, 31 May 2007 03:13:34 -0000 Subject: Newbie question about string(passing by ref) References: <1178833397.076720.279940@l77g2000hsb.googlegroups.com> Message-ID: <1180581214.639353@smirk> Steven D'Aprano wrote: ... > Python does NOT support pass by reference. Nor does it do pass by value. > Both of those models might describe what other languages do, but they > don't describe what Python does. > Python's passing model is different from both pass by reference and pass > by value, and there are circumstances where Python seems to be acting as > if it were doing one or the other. But it isn't. The model Python uses is > often (but not often enough...) called "pass by object" or "call by > sharing". > http://effbot.org/zone/call-by-object.htm > Steven. Wouldn't it make sense to say that Python passes arguments by binding objects to parameter names? Thus, once you understand the concepts of "names" (vs. "variables") and "binding" (by contrast to "assignment") then you also understand the argument passing model in the same terms. Also, wouldn't it be fair to say that the class and def statements also bind names to objects (callable and class objects respectively). -- Jim Dennis, Starshine: Signed, Sealed, Delivered From gnewsg at gmail.com Thu May 17 13:53:54 2007 From: gnewsg at gmail.com (billiejoex) Date: 17 May 2007 10:53:54 -0700 Subject: Asyncore Help? In-Reply-To: <464BE894.5060208@sbcglobal.net> References: <464BE894.5060208@sbcglobal.net> Message-ID: <1179424434.428144.9180@o5g2000hsb.googlegroups.com> On 14 Mag, 06:51, "Paul Kozik" wrote: > I have trouble finding a solid example for what I need. Python.org and > other sites provide simple examples, but they appear more intended for > servers that simply send one peice of data to the client. Not a big deal. asynchat / asyncore are pretty easy-to-learn frameworks. Under the hoods they are extremely simpler if compared to Twisted. You shouldn't have problems in learning how the things works in a couple of days. Try to take a look at: http://effbot.org/zone/asyncore-ftp-client.htm http://effbot.org/librarybook/asynchat.htm > Besides this I am also stuck with dealing with TCP data streams. I can > receive and send the data (using threads, not yet with asynocore), but > I am unsure how to deal with the streamlike nature of TCP (and would > prefer to use TCP over UDP). If you really need speed UDP could be a better choice. > While basic socket work was rather easy to deal with, this has proved > significantly more difficult. Developing a bug-less network application by using the basic socket module instead of an high-level framework like asyncore it's surely a lot harder. Again: asyncore is really simple: it's just a matter of understanding the event-based approach that's very different from the thread-based one. From stefan.behnel-n05pAM at web.de Tue May 15 03:28:57 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 15 May 2007 09:28:57 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <7x4pmg716p.fsf@ruckus.brouhaha.com> <4648EC26.8020907@v.loewis.de> Message-ID: <46496139.1020101@web.de> Eric Brunel wrote: > On Tue, 15 May 2007 07:15:21 +0200, ZeD wrote: > >> Neil Hodgson wrote: >> >>> Ada 2005 allows Unicode identifiers and even includes the constant >>> '?' in Ada.Numerics. > ^^^ >> this. is. cool. > > Yeah, right... The problems begin... > > Joke aside, this just means that I won't ever be able to program math in > ADA, because I have absolutely no idea on how to do a 'pi' character on > my keyboard. Ah, you'll learn. :) Stefan From vinay_sajip at yahoo.co.uk Fri May 25 14:42:59 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 25 May 2007 11:42:59 -0700 Subject: stdlib doc for logger.findCaller() needs update. In-Reply-To: References: <1179918325.803451.76820@o5g2000hsb.googlegroups.com> <1180080963.742418.170360@q75g2000hsh.googlegroups.com> Message-ID: <1180118579.822437.84880@w5g2000hsg.googlegroups.com> On May 25, 12:27 pm, Steve Holden wrote: > > Is a further 2.4 release planned? > > I'd have thought that unless a security issue appears the answer is > likely to be "no". > You never know - and it didn't take long to commit the change to release24-maint, so why not?! Regards, Vinay From python at rcn.com Sun May 20 05:12:48 2007 From: python at rcn.com (Raymond Hettinger) Date: 20 May 2007 02:12:48 -0700 Subject: docs patch: dicts and sets In-Reply-To: <1179100338.610239.299180@k79g2000hse.googlegroups.com> References: <1178934092.773288.31830@o5g2000hsb.googlegroups.com> <1179100338.610239.299180@k79g2000hse.googlegroups.com> Message-ID: <1179652368.412078.303890@k79g2000hse.googlegroups.com> On May 13, 4:52 pm, r... at yahoo.com wrote: > Dismissing this as not a "real problem" is both wrong > and offensive to people taking the time to actually > propose improvements. I should have elaborated on what I meant by saying that there is not a real problem. Another way to put it is that the docs are sufficient when they say that set ordering is arbitrary. That should be a cue to not have *any* expectations about the internal ordering of sets and dicts. Any further documentation of behavior would be a mistake because it would of necessity expose implementation specific details. For instance, there is another intentionally undocumented observable behavior that sets and dicts change their internal order as new members are added. It is also intentional that Python makes almost no promises about the location of objects in memory. IIRC, the only guarantees made about object identity are that "a is a" is always true and None can be tested with "is". Raymond From python at hope.cz Thu May 3 10:27:44 2007 From: python at hope.cz (Johny) Date: 3 May 2007 07:27:44 -0700 Subject: How to replace the last (and only last) character in a string? Message-ID: <1178202464.201578.211150@c35g2000hsg.googlegroups.com> Let's suppose s='12345 4343 454' How can I replace the last '4' character? I tried string.replace(s,s[len(s)-1],'r') where 'r' should replace the last '4'. But it doesn't work. Can anyone explain why? Thanks L. From mykeymykey01 at yahoo.com Fri May 11 22:49:27 2007 From: mykeymykey01 at yahoo.com (mykey) Date: 11 May 2007 19:49:27 -0700 Subject: OMG BRITNEYS AT IT AGAIN AGAIN!!!!!! In-Reply-To: <24edndmfSP6zddnbnZ2dnUVZ_oSdnZ2d@comcast.com> References: <1178920641.280005.221690@p77g2000hsh.googlegroups.com> <24edndmfSP6zddnbnZ2dnUVZ_oSdnZ2d@comcast.com> Message-ID: <1178938167.288106.161280@o5g2000hsb.googlegroups.com> On May 11, 3:03 pm, notbob wrote: > On 2007-05-11, wise.of.clean... at gmail.com wrote: > > >http://britneyboobs.blogspot.com/2007/05/britney-spears-slips-up-agai... > > - Exclusive pics of Britney Spears...... > > Britneyboobs ....what?... you take pride in being one? > > nb the queen of lip sync does it again! From tjreedy at udel.edu Thu May 10 15:26:57 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 10 May 2007 15:26:57 -0400 Subject: append References: <1178816546.689849.255070@y5g2000hsa.googlegroups.com> Message-ID: "Neil Cerutti" wrote in message news:slrnf46nud.1hg.horpner at FIAD06.norwich.edu... | On 2007-05-10, HMS Surprise wrote: | > Trying not to be a whiner but I sure have trouble finding | > syntax in the reference material. I want to know about list | > operations such as append. Is there a pop type function? I | > looked in tutorial, language reference, and lib for list, | > append, sequence. Is there a place where us doofi ( who may not | > have our heads out in the sunlight) may find all related syntax | > grouped together? | | You need the material in the Python Manual in the astonishingly | useful Library Reference section 1.2.3: Built-In Types. The only | thing you'll look at nearly as much is 1.2.1: Built-In Functions. In the current version of the library reference, these are chapter 3 http://docs.python.org/lib/types.html and section 2.1 http://docs.python.org/lib/built-in-funcs.html A substantial number of newbie questions are answered therein. 'append' has several entries in the substantial lib ref index. tjr From noagbodjivictor at gmail.com Thu May 3 19:43:00 2007 From: noagbodjivictor at gmail.com (noagbodjivictor at gmail.com) Date: 3 May 2007 16:43:00 -0700 Subject: When does input() return an empty string? Message-ID: <1178235780.197074.161700@h2g2000hsg.googlegroups.com> I'm filling an array with user input, I want an empty string to be returned when nothing is entered; ie return key hit twice... How do I do that? From weinhand at unileoben.ac.at Mon May 7 08:27:57 2007 From: weinhand at unileoben.ac.at (WEINHANDL Herbert) Date: Mon, 07 May 2007 14:27:57 +0200 Subject: matplotlib: howto redraw figure automatically, without stop in show()/draw()? In-Reply-To: <1178532299.418643.267790@e51g2000hsg.googlegroups.com> References: <1178532299.418643.267790@e51g2000hsg.googlegroups.com> Message-ID: <463f1b6f$0$11094$3b214f66@aconews.univie.ac.at> dmitrey wrote: > Hi all, > here is a question already mentioned below, and I'm also interested in > that one very much. > unfortunatly, I can't write anything to matplotlib mailing lists > because I constantly get server internal error (500) > Does anyone knows the answer? maybe this is what you want ? http://matplotlib.sourceforge.net/faq.html#DYNAMIC happy pythoning herbert From michele.simionato at gmail.com Wed May 23 10:40:37 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 23 May 2007 07:40:37 -0700 Subject: Decorator question In-Reply-To: Message-ID: <1179931237.868045.124940@u30g2000hsc.googlegroups.com> If you are using Python 2.5, you can use functools.update_wrapper to simplify your life. For instance from functools import update_wrapper # requires Python 2.5 def trace(func): def wrapper(*args,**kw): print 'calling %s with args %s' % (func.__name__,args) return func(*args,**kw) return update_wrapper(wrapper,func) class P(object): @classmethod @trace def c(cls): print cls p =P() p.c() Also, you can have a look to my own decorator module: http://www.phyast.pitt.edu/~micheles/python/decorator.zip HTH, Michele Simionato From icmla at helios.cs.csubak.edu Fri May 25 14:23:39 2007 From: icmla at helios.cs.csubak.edu (icmla) Date: 25 May 2007 11:23:39 -0700 Subject: ICMLA 2007: CALL FOR PAPERS Message-ID: <1180117419.395094.283110@x18g2000prd.googlegroups.com> ICMLA 2007: CALL FOR PAPERS The Sixth International Conference on Machine Learning and Applications ICMLA 2007 December 13-15, 2007 Cincinnati, OH, USA http://www.icmla-conference.org/icmla07/ Co-Sponsored by: Association for Machine Learning and Applications California State University Bakersfield University of Louisville University of Cincinnati IEEE SMC (technical co-sponsorship) Conference Proceedings will be Published by:IEEE AIMS AND SCOPE ICMLA'07 aims to bring together researchers and practitioners to present the latest achievements andinnovations in the area of machine learning (ML). The conference provides a leading international forum for thedissemination of original research in ML, with emphasis on applications, novel algorithms, software andsystems. Following the success of previous ICMLA conferences, it attracts researchers and applicationdevelopers from a wide range of ML related areas such as statistical, probabilistic, fuzzy, evolutionary, inductive, and other kinds of learning, data mining, knowledge discovery, pattern recognition, knowledgeacquisition and retrieval,databases, data warehousing and visualization, knowledge-based systems and highperformance computing. The main goal of the conference is to advance the state-of-the-art in ML via promotionof high quality and novel research. Scope of the Conference: - multistrategy learning - statistical learning - neural network learning - learning through fuzzy logic - learning through evolution (evolutionary algorithms) - Bayesian network - case-based reasoning - evolutionary computation - reinforcement learning - machine learning of natural language - grammatical inference - knowledge acquisition and learning - multi lingual knowledge acquisition and representation - knowledge discovery in databases - knowledge intensive learning - knowledge representation and reasoning - information retrieval and learning - theories and models for plausible reasoning - cooperative learning - planning and learning - multi-agent learning - web navigation and mining - learning through mobile data mining - online and incremental learning - scalability of learning algorithms - learning through text and multimedia mining - distributed and parallel learning algorithms and applications - inductive learning - inductive logic programming - feature extraction and classification - support vector machines - computational learning theory - cognitive-modeling - hybrid algorithms - machine learning in game playing and problem solving intelligent virtual environments homeland security applications industrial applications science and engineering medicine bioinformatics computational biology Contributions describing applications of machine learning techniques to real-world problems, interdisciplinary research involving machine learning, experimental and/or theoretical studies yielding new insights into the design of ML systems, and papers describing development of new analytical frameworks that advance practical learning methods are especially encouraged. IMORTANT DATES Papers due: June 15, 2007 Notification of acceptance: September 1, 2007 Camera-ready papers & Pre-registration: October 1, 2007 The ICMLA Conference: December 13-15, 2007 All paper submissions will be handled electronically. Detailed instructions for submitting the papers are provided on the conference home page at http://www.icmla-conference.org/icmla07/ SUBMISSIONS High quality papers in all ML areas are solicited. Papers that present new directions will receive especially careful and supportive reviews. Authors are expected to ensure that their final manuscripts are original and are not appearing in the other publications. Paper should be limited to 4-6 pages and submitted in IEEE format (double column). Papers will be reviewed by the Program Committee on the basis of technical quality, originality, significance, and clarity. All submissions will be handled electronically. Accepted papers will be published in the conference proceedings, as a hardcopy. A selected number of accepted papers will be invited for possible inclusion, in an expanded and revised form, in a journal. ICMLA'07 Best Paper Awards will be conferred at the conference on the authors of the best research paper. Detailed instructions for submitting papers can be found at http://www.icmla-conference.org/icmla07/ For further information contact: Professor Mehmed Kantardzic, Email: mmkant01 at louisville.edu Conference Chair OR Dr. Tao Li, Email: taoli at cs.fiu.edu Dr. Ying Liu, Email: ying.liu at utdallas.edu Program co-Chairs SPECIAL SESSIONS, WORKSHOPS and TUTORIALS We invite submission of proposals for special sessions, workshops and tutorials. Proposals to organize suchsessions should include the following information: - name and address of the proposer(s) - title of the session/workshop/tutorial - description of the session/workshop/tutorial (see further details below) Each special session/workshop will have at least five paper presentations. The special session/workshop chairs will be responsible for soliciting the papers, reviewing, and making finaldecisions, in consultation with the conference chairs. The description of the session/worshop should includethe following information: - title of the session/workshop - scope - organizers and - committee members For further information contact: Professor Mehmed M. Kantardzic, Email mmkant01 at louisville.edu Conference Chair ORGANIZING BODIES Advisory Committee Jerome H. Friedman, Stanford University, USA Michalski Ryszard, George Mason University, USA Mitchell Tom, Carnegie Mellon University, USA VanLehn Kurt, University of Pittsburgh, USA David McAllester, Toyota Technological Institute at Chicago, USA Robert Schapire, Princeton University, USA Yao Xin, University of Birmingham, UK Lofti Zadeh, University of California Berkeley, USA Steering Committee Khurshid Ahmad, Trinity College, Dublin Hamid Arabnia, University of Georgia, USA Krzysztof Cios, University of Colorado at Denver, USA Khalid Hafeez, University of Bradford, UK Mehmed Kantardzic, University of Louisville, USA Lukasz Kurgan, University of Alberta, Canada Graham Kendall, University of Nottingham, UK Wei Li, California State University Bakersfield, USA Vasile Palade, Oxford University, UK Kevin Seppi, Brigham Young University, USA M. Arif Wani, California State University Bakersfield, USA Technical Meeting Committee General Chair M. Arif Wani California State University Bakersfield, USA Conference Chair Mehmed M. Kantardzic University of Louisville, USA Program co-Chairs Tao Li Florida International University, USA Ying Liu University of Texas at Dallas, USA Special Sessions Co-Chairs Visale Palade Oxford University, UK Lukasz Kurgan University of Alberta, Canada Sushmita Mitra Indian Statistical Institute, India Jieping Ye Arizona State University, USA Mitsunori Ogihara University of Rochester, USA Raj Bhatnagar University of Cincinnati, USA Seref Sagiroglu University of Gazi, Turkey Workshops Co-Chairs Xue-Wen Chen University of Kansas, USA Leif Peterson Methodist Hospital, USA Publicity Chair Khalid Hafeez University of Bradford, UK Registrations Chair Adel Elmaghraby University of Louisville, USA Awards Co-Chairs Hui Xiong, Rutgers University, USA Sponsorship Chair Ray R. Hashemi Armstrong Atlantic State University, USA Local Arrangements Chair University of Cincinnati, USA Raj Bhatnagar From necmettin.begiter at gmail.com Tue May 8 16:10:39 2007 From: necmettin.begiter at gmail.com (Necmettin Begiter) Date: Tue, 8 May 2007 23:10:39 +0300 Subject: Suggestions for how to approach this problem? In-Reply-To: <4640cba9$0$30544$c3e8da3@news.astraweb.com> References: <4640ca5b$0$23392$c3e8da3@news.astraweb.com> <4640cba9$0$30544$c3e8da3@news.astraweb.com> Message-ID: <200705082310.39615.necmettin.begiter@gmail.com> On Tuesday 08 May 2007 22:23:31 John Salerno wrote: > John Salerno wrote: > > typed, there are often line breaks at the end of each line > > Also, there are sometimes tabs used to indent the subsequent lines of > citation, but I assume with that I can just replace the tab with a space. Is this how the text looks like: 123 some information 124 some other information 126(tab here)something else If this is the case (the numbers are at the beginning, and after the numbers there is either a newline or a tab, the logic might be this simple: get the numbers at the beginning of the line. Check for \n and \t after the number, if either exists, remove them or replace them with a space or whatever you prefer, and there you have it. Also, how are the records seperated? By empty lines? If so, \n\n is an empty line in a string, like this: """ some text here\n \n some other text here\n """ From nomail at gmail.com Tue May 1 04:39:14 2007 From: nomail at gmail.com (Olivier Oost) Date: Tue, 01 May 2007 10:39:14 +0200 Subject: Log-in to forums (using cookielib)? In-Reply-To: References: <4636f011$0$329$e4fe514c@news.xs4all.nl> Message-ID: <4636fcb2$0$336$e4fe514c@news.xs4all.nl> Gabriel Genellina wrote: > En Tue, 01 May 2007 04:44:57 -0300, Olivier Oost > escribi?: > >> I need to login to a online forum, like a phpbb forum, and leave a >> message there. I figured I need to use cookielib, but the >> documentation of cookielib is not very clear to me. >> Can someone please tell me how I should log-in and leave a message on >> the board? > > Sure. But considering that this smells like an Automatic Spamming > Machine, I hope nobody will. > > --Gabriel Genellina No, it's not meant as a spamming machine. I only need to post a message and then (if that's possible) lock the topic (I'm admin on the forum where I need this). The program first needs to read the topic for certain words (that's already working), and then reply that those words aren't welcome. I hope I made myself clear. From steve at REMOVE.THIS.cybersource.com.au Mon May 28 09:28:56 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 28 May 2007 23:28:56 +1000 Subject: What's the best way to iniatilize a function References: <7NmdncRrFaG3WMTbnZ2dnUVZ_gWdnZ2d@comcast.com> Message-ID: On Sun, 27 May 2007 23:20:49 -0700, Jack wrote: > Thanks Steven, for the reply. Very helpful. I've got a lot to learn in > Python :) > > Some questions: > >> (1) Python can automatically free most data structures and close open >> files, but if your needs are more sophisticated, this approach may not be >> suitable. > > Since it's a wrapper of a DLL or .so file, I actually need to call > mylib_exit() > to do whatever cleanup the library needs to do. Well, there may be better ways, but I'd do something like this: # === mylib module === # Exception raised if library is not initiated class Uninitiated(Exception): pass def _init(): """Private set-up code.""" global DATA, _INITIALIZED DATA = range(100000) # or something more useful _INITIALIZED = True def _close(): """Private tear-down code.""" global DATA, _INITIALIZED del DATA, _INITIALIZED def isinited(): """Return True if the library is initialized, otherwise False.""" try: _INITIALIZED; return True except NameError: return False def init(): """Public set-up code.""" if not isinited(): _init() def close(): """Public tear-down code.""" if isinited(): _close() exit = close # alias for exit/close. def func(): if isinited(): return DATA[0] else: raise Uninitiated("Library is not initialized") All of the above can be modified to be in a class instead of a module. That's especially useful if you can have multiple instances, perhaps with different state. >>> 2. what's the right way to call mylib_exit()? I put it in __del__(self) >>> but it is not being called in my simple test. >> >> instance.__del__ is only called when there are no references to the >> instance. > > I didn't call del explicitly. I'm expecting Python to call it when > the program exits. I put a logging line in __del__() but I never > see that line printed. It seems that __del__() is not being called > even when the program exits. Any idea why? Python tries really really hard to call instance.__del__() but there are pathological cases where it just can't. Maybe you've found one of them. But I'm guessing that you may have defined a __del__ method, but not actually created an instance. If so, __del__ will never be called. This should work: class Foo(object): def __del__(self): print "All gone now" instance = Foo() When you exit, instance will be garbage collected and instance.__del__() will be called. But without the instance, __del__ is not called on the class directly. Hope this was some help, -- Steven. From mikeminer53 at hotmail.com Thu May 24 00:44:39 2007 From: mikeminer53 at hotmail.com (mkPyVS) Date: 23 May 2007 21:44:39 -0700 Subject: Resizing listbook's listview pane In-Reply-To: <1179949661.695477.167450@m36g2000hse.googlegroups.com> References: <1179939217.550237.300830@o5g2000hsb.googlegroups.com> <1179949661.695477.167450@m36g2000hse.googlegroups.com> Message-ID: <1179981879.346887.281620@r19g2000prf.googlegroups.com> On May 23, 1:47 pm, kyoso... at gmail.com wrote: > Wow! You sure like to post a lot! Sheesh! I subscribe to the wxPython > user's group and I don't see your post anywhere. Yeah sorry.. google groups was giving me repeated errors on post... frustration clicking took over and viola... 17 posts- my apologies. > > I can't find much documentation for this control either. The demo > seems to have a way to change the size of one of the panels using the > method "SetSize" though. I recommend trying the wxPython group again > though. > > Mike Neither can I. I've tried to use SetSize on the listview object but to no avail... I'm trying to down-size the content frame as it's min-size in the sizer may be what is causing the listview to be pushed to it's minsize. . Thx, Mike From istvan.albert at gmail.com Fri May 18 11:52:05 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: 18 May 2007 08:52:05 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <464C5382.6080403@v.loewis.de> <1179423799.254286.294930@w5g2000hsg.googlegroups.com> Message-ID: <1179503525.018943.95740@u30g2000hsc.googlegroups.com> On May 17, 2:30 pm, Gregor Horvath wrote: > Is there any difference for you in debugging this code snippets? > class T?rstock(object): Of course there is, how do I type the ? ? (I can copy/paste for example, but that gets old quick). But you're making a strawman argument by using extended ASCII characters that would work anyhow. How about debugging this (I wonder will it even make it through?) : class ???????? ??? = 0 ?????? ?? ?=10 (I don't know what it means, just copied over some words from a japanese news site, but the first thing it did it messed up my editor, would not type the colon anymore) i. From steve at REMOVE.THIS.cybersource.com.au Wed May 2 13:08:49 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 03 May 2007 03:08:49 +1000 Subject: Is it possible to determine what a function needs for parameters - References: <1178115727.932794.100390@h2g2000hsg.googlegroups.com> Message-ID: On Wed, 02 May 2007 07:22:07 -0700, rh0dium wrote: > Hi all, > > Below is a basic threading program. The basic I idea is that I have a > function which needs to be run using a queue of data. Early on I > specified my function needed to only accept basic parameters ( no > postional *args or *kwargs ) but now I am re-writing it and I want to > accept these. Is there anyway to determine what parameters are needed > by a given function and format the arguments given appropriately. Is this meant to be just a programming exercise to see how clever you can be? It's okay if it is, but if it is meant to be something useful, well, I can't imagine ever being in a situation where I know I have to pass arguments (say) 4, 5, "Hello", and None to a function, but not know whether they should be positional arguments or keyword arguments. Or, to put it another way... the usual procedure is for the developer (that's you) to read the function API to find out what arguments the function expects, and how it expects them, and then the developer modifies the parameters used accordingly. -- Steven. From Graham.Dumpleton at gmail.com Thu May 24 19:01:02 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: 24 May 2007 16:01:02 -0700 Subject: need advice on building core code for python and PHP In-Reply-To: <1180034698.387087.251590@o5g2000hsb.googlegroups.com> References: <1180025115.704410.250890@a35g2000prd.googlegroups.com> <1180028001.569139.317660@q66g2000hsg.googlegroups.com> <1180034698.387087.251590@o5g2000hsb.googlegroups.com> Message-ID: <1180047661.795384.295850@a26g2000pre.googlegroups.com> On May 25, 5:24 am, aspineux wrote: > On 24 mai, 19:33, Szabolcs Nagy wrote: > > > > Is there a way I could code the base (core) code in Python and have > > > PHP call it? I've really liked using SQLAlchemy and there are other > > > * quick and dirty solution: > > in a shell: > > $ python yourscript.py pipe_out > > in the php script: > > fwrite(pipe_in, input_data); > > results = fread(pipe_out, sizeof_results); > > > * simple and nice solution: > > do not ever use php > > Write a CGI wrapper around your python script, and publish it using mod_python. > And make the appropriate http requests from PHP. You do not need mod_python to host CGI scripts written in Python, they are two separate things. Depending on the complexity of what you are doing, you might be better off writing a backend server in Python that incorporates an XML-RPC server. Your PHP script can then use XML-RPC client to communicate to the backend Python server to do the real work. Over time you could even transition your web pages to being done in Python instead. In doing this your back end Python server doesn't have to change, you just make XML-RPC calls from the Python code for the web pages in place of where you would be doing it with PHP initially. You also wouldn't be restricted to web based front ends, you could also use GUI based front end as well. Graham From S.Mientki-nospam at mailbox.kun.nl Tue May 22 19:44:22 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Wed, 23 May 2007 01:44:22 +0200 Subject: Can I reference 1 instance of an object by more names ? Message-ID: hello, I'm trying to build a simple functional simulator for JAL (a Pascal-like language for PICs). My first action is to translate the JAL code into Python code. The reason for this approach is that it simplifies the simulator very much. In this translation I want to keep the JAL-syntax as much as possible intact, so anyone who can read JAL, can also understand the Python syntax. One of the problems is the alias statement, assigning a second name to an object. I've defined a class IO_port, and I create an instance of that port with the name port_D port_D = IO_port('D') Now I want to assign a more logical name to that port, (In JAL: "var byte My_New_Name IS port_D") Is that possible ? I think the answer is "no", because the object itself is not mutable. Am I right ? But I read: "An object can have any number of names, or no name at all." So am I wrong ? Sorry this has been discussed before, but I'm totally confused. thanks, Stef Mientki From nanodust at gmail.com Thu May 24 16:39:55 2007 From: nanodust at gmail.com (nanodust at gmail.com) Date: 24 May 2007 13:39:55 -0700 Subject: trouble converting c++ bitshift to python equivalent In-Reply-To: References: <1180037677.633613.30160@u30g2000hsc.googlegroups.com> Message-ID: <1180039195.148316.70100@o5g2000hsb.googlegroups.com> > You should really use the struct module for that type of conversion, but > you also need to know that indexing of lists and tuples starts at 0, not 1. indeed, i used to have temp = unpack('h', tBuf[1,3]) but it was a hack (and as such a bit off ;) as i was having troubles casting not quite used to python yet, will get there... thanks again !! From stefan.behnel-n05pAM at web.de Sun May 13 15:44:49 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sun, 13 May 2007 21:44:49 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <46476AB1.7010001@web.de> Jarek Zgoda schrieb: > Martin v. L?wis napisa?(a): Uuups, is that a non-ASCII character in there? Why don't you keep them out of an English speaking newsgroup? >> So, please provide feedback, e.g. perhaps by answering these >> questions: >> - should non-ASCII identifiers be supported? why? > > No, because "programs must be written for people to read, and only > incidentally for machines to execute". Using anything other than "lowest > common denominator" (ASCII) will restrict accessibility of code. No, but it would make it a lot easier for a lot of people to use descriptive names. Remember: we're all adults here, right? > While I can read the code with Hebrew, Russian or Greek names > transliterated to ASCII, I would not be able to read such code in native. Then maybe it was code that was not meant to be read by you? In the (not so small) place where I work, we tend to use descriptive names *in German* for the code we write, mainly for reasons of domain clarity. The *only* reason why we still use the (simple but ugly) ASCII-transcription (?->ue etc.) for identifiers is that we program in Java and Java lacks a /reliable/ way to support non-ASCII characters in source code. Thanks to PEP 263 and 3120, Python does not suffer from this problem, but it suffers from the bigger problem of not *allowing* non-ASCII characters in identifiers. And I believe that's a rather arbitrary decision. The more I think about it, the more I believe that this restriction should be lifted. 'Any' non-ASCII identifier should be allowed where developers decide that it makes sense. Stefan From Leisure.203 at gmail.com Mon May 21 04:00:05 2007 From: Leisure.203 at gmail.com (Leisure.203 at gmail.com) Date: 21 May 2007 01:00:05 -0700 Subject: (_Y_) Free PUSSY PICS! Message-ID: <1179734405.421063.96250@36g2000prm.googlegroups.com> http://nudepicks.blogspot.com/ - Free Booby Downloads From steven.bethard at gmail.com Sun May 27 19:14:20 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 27 May 2007 17:14:20 -0600 Subject: unit testing In-Reply-To: References: Message-ID: Steve Howell wrote: > --- Steven Bethard wrote: >> Have you tried py.test? >> >> http://codespeak.net/py/dist/test.html >> >> I've heard good things about it, but haven't gotten >> around to trying it >> yet. Here's a two-line test suite from the page >> above: >> >> def test_answer(): >> assert 42 == 43 >> > > Changed the subject line. > > Nope, I haven't. I'm a tremendous advocate of unit > testing, but I've never felt compelled to try out > other libraries, because I work mostly on private code > now, so the > following-standard-practices-to-benefit-from-familiarity > argument doesn't carry much weight with me, and also > because I find it easy enough to do things on a > roll-your-own basis. YMMV, of course. My view is generally that if I can get someone else to maintain parts of my code for me, that's a good thing. ;-) > 1) For flat-out failures, we just fail with a > traceback right away. Looks like that's the -x/--exitfirst option in py.test. > 2) We don't use assertions very often, but rather > just diff the output files to the GOLD files. This > may eventually stop to scale, but it hasn't yet. I guess I don't do enough stuff with file input and file output for this to make sense for me. > 3)We have a little trickery to override imports, > etc., as 99.99% of our code was never written with > unit testing in mind, but I still want to regression > test it. > > 4) We have quite a few mock-ish objects, mainly > relating to simulating I/O situations. You might look into the Python Mock module: http://python-mock.sourceforge.net/ STeVe From tartifola at gmail.com Fri May 25 03:18:29 2007 From: tartifola at gmail.com (Tartifola) Date: Fri, 25 May 2007 09:18:29 +0200 Subject: No file from stdin References: <20070524184811.6e439221.tartifola@gmail.com> <1180035653.188189.210480@q19g2000prn.googlegroups.com> Message-ID: <20070525091829.a8c9e780.tartifola@gmail.com> Hi, > On May 24, 9:48 am, Tartifola wrote: > > Hi, > > suppose a script of python is waiting for a file from the stdin and none > > is given. How can I make the script to stop and, for example, print an > > error message? > > > > Sorry for the n00b question and thanks > > I'm not exactly sure what you mean. This assumes that you intended the > contents of the file be piped in from the command line. > [code] > import sys > > if sys.stdin.isatty(): > print >>sys.stderr, "expected input from stdin" > sys.exit(1) That's exactly what I was looking for. I did not know about isatty() thanks From stefan.behnel-n05pAM at web.de Sun May 13 15:31:19 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sun, 13 May 2007 21:31:19 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <7xabw8aa22.fsf@ruckus.brouhaha.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <7xabw8aa22.fsf@ruckus.brouhaha.com> Message-ID: <46476787$0$20286$9b4e6d93@newsspool3.arcor-online.net> Paul Rubin wrote: > "Martin v. L?wis" writes: >> - would you use them if it was possible to do so? in what cases? > > I would never insert them into a program. In existing programs where > they were used, I would remove them everywhere I could. Luckily, you will never be able to touch every program in the world. Stefan From maric at aristote.info Mon May 28 04:25:18 2007 From: maric at aristote.info (Maric Michaud) Date: Mon, 28 May 2007 10:25:18 +0200 Subject: os.path.walk not pruning descent tree (and I'm not happy with that behavior?) In-Reply-To: References: <1180316372.126765.213530@r19g2000prf.googlegroups.com> Message-ID: <465A91EE.5020402@aristote.info> I'm really sorry, for all that private mails, thunderbird is awfully stupid dealing with mailing lists folder. Gabriel Genellina a ?crit : > En Sun, 27 May 2007 22:39:32 -0300, Joe Ardent escribi?: > > > - iterate backwards: > > for i in range(len(names)-1, -1, -1): > fname = names[i] > if fname[:1]=='.': > names.remove(fname) > This is not about iterating backward, this is about iterating over the index of each element instead of iterating over the element (which must be done begining by the end). In fact this code is both inefficient and contains a subtle bug. If two objects compare equals in the list, you will remove the wrong one. It should be : for i in range(len(names)-1, -1, -1): if names[i][:1]=='.': del names[i] > - filter and reassign in place Seems the best here. > (the [:] is important): Not so. Unless "names" is referenced in another namespace, simple assignment is enough. > names[:] = [fname for fname in names if fname[:1]!='.'] > > (Notice that I haven't used a regular expression, and the remove method) > From alan.franzoni_invalid at geemail.invalid Wed May 23 12:31:52 2007 From: alan.franzoni_invalid at geemail.invalid (Alan Franzoni) Date: Wed, 23 May 2007 18:31:52 +0200 Subject: Basic Class/Instance Question References: <1179921235.622391.230150@h2g2000hsg.googlegroups.com> Message-ID: Il 23 May 2007 04:53:55 -0700, Siah ha scritto: [cut] No. It's because the *body* of the function gets evaluated every time the function is called, while the *definition* of the function gets evaluated just once, when the function is 'declared'. Your issue arises when the default value of the function (which is part of the definition, not of the body) is a mutable object, because it's the very same default value that gets modified at each time. -- Alan Franzoni - Togli .xyz dalla mia email per contattarmi. Remove .xyz from my address in order to contact me. - GPG Key Fingerprint (Key ID = FE068F3E): 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From tiarno at sas.com Fri May 25 12:03:54 2007 From: tiarno at sas.com (Tim Arnold) Date: Fri, 25 May 2007 12:03:54 -0400 Subject: extra xml header with ElementTree? References: <1180107283.591686.48190@u30g2000hsc.googlegroups.com> Message-ID: "Gerard Flanagan" wrote in message news:1180107283.591686.48190 at u30g2000hsc.googlegroups.com... > On May 25, 3:55 pm, "Tim Arnold" wrote: >> Hi, I'm using ElementTree which is wonderful. I have a need now to write >> out >> an XML file with these two headers: >> >> >> >> My elements have the root named tocbody and I'm using: >> newtree = ET.ElementTree(tocbody) >> newtree.write(fname) >> >> I assume if I add the encoding arg I'll get the xml header: >> newtree = ET.ElementTree(tocbody) >> newtree.write(fname,encoding='utf-8') >> >> but how can I get the into the tree? >> >> python2.4.1,hpux10,ElementTree1.2.6 >> > > #This import is for 2.5, change for 2.4 > from xml.etree import cElementTree as ET > > tocbody = 'onetwo' > > doc = ET.ElementTree(ET.fromstring(tocbody)) > > outfile = open('\\working\\tmp\\toctest.xml', 'w') > > outfile.write('') > > outfile.write('') > > doc._write(outfile, doc._root, 'utf-8', {}) > > outfile.close() > > ----------------- > > > > > one > two > > thanks, this works well. After looking at the ET code, I just used the 'write' method straight since it calls _write in turn. thanks again, --Tim From bj_666 at gmx.net Mon May 14 03:37:13 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 14 May 2007 09:37:13 +0200 Subject: Removing part of string References: <1179122203.691267.64200@o5g2000hsb.googlegroups.com> Message-ID: In <1179122203.691267.64200 at o5g2000hsb.googlegroups.com>, saif.shakeel wrote: > Hi, > I am parsing an xml file ,and one part of structure looks > something like this: > > - PhysicalLink="Infotainment_Control_Bus_CAN"> > Infotainment_Control_Bus_CAN_TIMEOUT_AX > Timeout N_As/N_Ar > Time from transmit request until a CAN frame transmit > confirmation is received. > > > In my code i am extracting the data within > ,which is Timeout N_As/N_Ar.These tags repeat and will have > different timer names..like > > - PhysicalLink="Infotainment_Control_Bus_CAN"> > Infotainment_Control_Bus_CAN_TIMEOUT_BS > Timeout N_Bs > Time that the transmitter of a multi-frame message > shall wait to receive a flow control (FC) frame before timing out with > a network layer error. > > > I need to remove the words Timeout from the data,and > take only the abbrevation..i.e.N_As/N_bs like that .In short i have to > remove the words which come with name Time,and also the space which > comes next to it. > and take only the abbreviation.Can someone help me in this. You can test for the prefix with the `startswith()` method and use string slicing to create a new string without the prefix: In [3]: prefix = 'Timeout ' In [4]: longname = 'Timeout N_Bs' In [5]: longname.startswith(prefix) Out[5]: True In [6]: longname = longname[len(prefix):] In [7]: longname Out[7]: 'N_Bs' Ciao, Marc 'BlackJack' Rintsch From tjreedy at udel.edu Fri May 11 14:35:45 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 11 May 2007 14:35:45 -0400 Subject: Towards faster Python implementations - theory References: <1210i.7468$2v1.2505@newssvr14.news.prodigy.net><1178804728.527486.196400@y80g2000hsf.googlegroups.com> <1178895563.144837.176310@e65g2000hsc.googlegroups.com> Message-ID: "sturlamolden" wrote in message news:1178895563.144837.176310 at e65g2000hsc.googlegroups.com... | On May 10, 4:02 pm, Tim Golden wrote: | I know, I know. But that doesn't stop me from envying what the Lisp | community has achieved. But do not let your envy stop you from noticing and appreciating what the Python commnunity has achieved. | Python still sucks if we are using it for scientific simulations, Not if you use extensions compiled from C or Fortran. Doing so is not cheating, any more than using the C-coded methods of the builtin types. Leveraging existing code and compilers was part of Python's design. With the Numeric extensions, produced by people at the US nuke labs. scientific simulations were, I think, Python's first killer ap. | Sure it is only 150-200 times slower than C for these tasks, As a general statement, nonsense. A LinPack inversion of a 10k x 10k matrix takes the same time whether called from Python or a C program. The miniscule extra overhead of Python is more than made up for by the ability to call LinPack and other functions interactively. The extended buffer protocol, championed by Travis Oliphant and slated for 3.0, will make cooperation between extensions much easier. Terry Jan Reedy From edreamleo at charter.net Fri May 4 15:31:22 2007 From: edreamleo at charter.net (Edward K Ream) Date: Fri, 4 May 2007 14:31:22 -0500 Subject: Where are the strings in gc.get_objects? References: Message-ID: The following script dumps all objects allocated since the last time it was called. It suppresses the dump if more than 200 new objects were allocated. g.app.idDict is a dict whose keys are id(obj) and whose values are obj. (g.app.idDict will persist between invocations of the script). This allows us to determine whether an object has already been allocated. It's not a perfect test,but perfection is not required. As expected, this stresses the gc a lot. The isLargeItem function is important: it returns True if repr(obj) would be too big. It tries to avoid actually generating repr(obj). Even so, sometimes the script appears to hang while isLargeItem cranks. I thought it would be clever to call isLargeItem for dict values, but that overflowed the stack. Anyway, here is the script: import gc,types def isLargeItem (obj): ....if ( ........type(obj) == types.CodeType or ........type(obj) == types.ListType and len(obj) > 500 or ........type(obj) == types.TupleType and len(obj) > 500 ....): ........return True ....if type(obj) == types.DictType: ........n = 0 ; keys = obj.keys() ........if len(keys) > 100: return True ........for key in keys: ............val = obj.get(key) ............# if isLargeItem(val): return True ............n += len(repr(key)) ............n += len(repr(val)) ............if n > 1000: return True ........return False ............ ....return len(repr(obj)) > 1000 try: d = g.app.idDict except AttributeError: d = g.app.idDict = {} new = {} for obj in gc.get_objects(): ....oldObj = d.get(id(obj)) ....if oldObj is None: ........new[id(obj)] = obj ........ keys = new.keys() print '----- %d new objects' % len(keys) if len(keys) < 200: ....keys.sort() ....n = 0 ....for key in keys: ........n += 1 ........obj = new.get(key) ........print '%3d' % (n),key,type(obj), ........if isLargeItem(obj): ............print '***** large item' ........else: ............print repr(obj) ....print '=====' for key in keys: ....d[key] = new.get(key) And here is some example output: ----- 70129 new objects [first run of script: nothing printed] ----- 118 new objects [second run of script] 1 13723776 2 17053392 3 20219840 4 21927208 5 23088536 ('5780', '??', '??', '??', '66', '4', '4522765', '??', '115', '174', '\x02', '-1', 'b', '98', '.232818 72.23282192.23282432.23282472.23282592.23282672.24029064.24051224.canvas', '2', '524', '412', '66') 6 23248088 ('gc', 'types', 'isLargeItem', 'g', 'app', 'idDict', 'd', 'AttributeError', 'new', 'get_objects', 'obj ', 'get', 'id', 'oldObj', 'None', 'keys', 'len', 'sort', 'n', 'key', 'type', 'repr') 7 23293152 (<_Pmw.Pmw_1_2.lib.PmwBase.__TkinterCallWrapper instance at 0x0175AB20>, '5780', '??', '??', '??', '66 ', '4', '4522765', '??', '115', '174', '\x02', '-1', 'b', '98', '.23281872.23282192.23282432.23282472.23282592.23282672.24029064.2 4051224.canvas', '2', '524', '412', '66') 8 23562680 9 24069264 [] 10 24116944 {'stack': [], 'v': } 11 24117936 ['black', 'blue'] 12 24118016 > 13 24953360 ('type', 'obj', 'types', 'CodeType', 'ListType', 'len', 'TupleType', 'True', 'DictType', 'n', 'keys', 'key', 'get', 'val', 'repr', 'False') 14 24959216 (('command', None), ('insert', None), ('overwrite', None), ('button', None), ('body', 'body'), ('text' , 'head'), ('tree', 'head'), ('tree', 'canvas'), ('log', 'log'), ('text', 'log'), ('text', None), ('all', None)) 15 25585536 ('obj', 'd', 'oldObj', 'isLargeItem', 'n', 'keys', 'gc', 'key', 'new', 'types') 16 26717792 17 27405776 18 27405808 19 27405840 20 27405872 21 27405968 22 27406000 23 27406032 24 27406064 25 27406096 26 27406128 27 27406160 28 27406192 29 27406224 30 27406256 31 27406320 32 27564784 33 27571824 ***** large item 34 27572704 ['black', 'red', 'blue', 'purple'] 35 27608960 {'c': Commander 23254680: u'C:\\prog\\tigris-cvs\\leo\\test\\test.leo', 'widget': , 'actualEvent': , 'char': '\x02', 'w': , 'y': 174, 'x': 115, 'keysym': 'b'} 36 27621536 {'subst': None, 'widget': , 'func': } 37 27622976 {} 38 27647312 (, (), , ['24118016call it']) 39 27647408 (None, 500, 0, 100, 1000) 40 27647456 ('obj', 'val', 'keys', 'n', 'key') 41 43151120 42 43368936 [] 43 43369296 [] 44 43369376 (,) 45 43369496 [] 46 43369696 ['24118016callit'] 47 43369736 [] 48 43369816 [] 49 43369856 [] 50 43369896 (leoTkTextWidget id: 25544304 name: head-6, 27) 51 43370096 (, 8) 52 43370216 ('\x02', u'Ctrl+b') 53 43370296 tkGui.leoKeyEvent: char: '\x02', keysym: 'b' 54 43370496 (, (,)) 55 43370616 [] 56 43370656 (leoTkTextWidget id: 27572864 name: head-10, 44) 57 43370696 (, 8) 58 43370776 (, 8) 59 43370856 (, 8) 60 43370936 61 43370976 [41, 46, 50, 51, 56, 1, 6, 11, 16, 21, 25, 29, 33] 62 43371016 <_Pmw.Pmw_1_2.lib.PmwBase.__TkinterCallWrapper instance at 0x0295CA08> 63 43371056 [7, 12, 17, 42, 52] 64 43371096 [36, 40, 45, 49, 55, 5, 10, 15, 20, 24, 28] 65 43371136 [] 66 43371176 [34, 38, 43, 47, 53, 3, 8, 13, 18, 22, 26] 67 43371216 [] 68 43371256 [] 69 43371296 [] 70 43371336 [] 71 43371576 (leoTkTextWidget id: 25544784 name: head-8, 35) 72 43371696 [] 73 43371736 (, 8) 74 43372016 (leoTkTextWidget id: 25542984 name: head-2, 9) 75 43372136 [] 76 43372176 (leoTkTextWidget id: 27572984 name: head-11, 48) 77 43372376 (, 8) 78 43372592 {'stack': [], 'v': } 79 43372736 {'keysym_num': 98, 'widget': , 'x_root': 524, 'type': '2', 'delt a': 66, 'y_root': 412, 'height': '??', 'char': '\x02', 'width': '??', 'state': 4, 'num': '??', 'time': 4522765, 'y': 174, 'x': 115 , 'serial': 5780, 'keysym': 'b', 'keycode': 66} 80 43373168 {'27563248:5.': (leoTkTextWidget id: 25543504 name: head-3, 14), '27563376:6.': (leoTkTextWidget id: 25 544544 name: head-7, 31), '27563632:9.': (leoTkTextWidget id: 27572424 name: head-5, 23), '27563440:7.': (leoTkTextWidget id: 2757 2024 name: head-1, 4), '25508048:0.': (leoTkTextWidget id: 27572864 name: head-10, 44), '27513232:2.': (leoTkTextWidget id: 255447 84 name: head-8, 35), '27562704:3.': (leoTkTextWidget id: 25542984 name: head-2, 9), '27563152:4.': (leoTkTextWidget id: 27572984 name: head-11, 48), '26446064:1.': (leoTkTextWidget id: 25544304 name: head-6, 27), '27563536:8.': (leoTkTextWidget id: 25543704 n ame: head-4, 19), '27563728:0.': (leoTkTextWidget id: 27627608 name: head-12, 54)} 81 43373312 ***** large item 82 43373456 {'stack': [], 'v': None} 83 43373600 {'stack': [], 'v': } 84 43373744 ***** large item 85 43373888 {'stack': [], 'v': } 86 43374032 {34: (, 8), 3: (, 8), 38: (, 8), 8: (, 8), 43: (, 8), 13: (< pos 27406256 lvl: 0 [0] byte-code tests>, 8), 47: (, 8), 18: (, 8), 53: (, 8), 22: (, 8), 26: (, 8)} 87 43374176 {'stack': [], 'v': } 88 43374464 {'stack': [], 'v': } 89 43374608 {'stack': [], 'v': } 90 43374752 {'stack': [], 'v': } 91 43374896 {'stack': [], 'v': } 92 43375040 {'stack': [], 'v': } 93 43375184 {'stack': [], 'v': } 94 43375328 {'stack': [], 'v': } 95 43375472 {'stack': [], 'v': } 96 43375616 {'stack': [], 'v': } 97 43376192 {'stack': [], 'v': } 98 43380784 [] 99 43380824 (leoTkTextWidget id: 25543504 name: head-3, 14) 100 43381024 (, 8) 101 43381184 [] 102 43381224 (leoTkTextWidget id: 25544544 name: head-7, 31) 103 43381424 (, 8) 104 43381584 [] 105 43381624 (leoTkTextWidget id: 27572024 name: head-1, 4) 106 43381824 (, 8) 107 43382024 (leoTkTextWidget id: 25543704 name: head-4, 19) 108 43382224 (, 8) 109 43382424 (, 8) 110 43382704 (leoTkTextWidget id: 27572424 name: head-5, 23) 111 43382824 [] 112 43382864 (leoTkTextWidget id: 27627608 name: head-12, 54) 113 43383384 ***** large item 114 43384912 115 43425840 116 43426032 117 43426224 (None, , '----- %d new objects', 200, 0, 1, '%3d', '***** large item', '=====') 118 43442512 ***** large item ===== I think this answers the question about where the strings are: they are enclosed in tuples. My guess is that the tuples are the way that Python's bytecode accesses the strings. For example, there is a LOAD_CONST i bytecode whose argument i is an index into the stack frame (or is it the code objects). Anyway, my guess is that strings seldom (never?) exist outside the tuple by which they are referenced. So I think this answers the mystery, mostly. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From manatlan at gmail.com Sat May 12 10:54:37 2007 From: manatlan at gmail.com (manatlan) Date: 12 May 2007 07:54:37 -0700 Subject: Dynamic subclassing ? In-Reply-To: <4645cc78$0$20196$426a74cc@news.free.fr> References: <1178976888.443891.116090@y80g2000hsf.googlegroups.com> <4645cc78$0$20196$426a74cc@news.free.fr> Message-ID: <1178981677.003637.292860@y80g2000hsf.googlegroups.com> On 12 mai, 17:00, Bruno Desthuilliers wrote: > manatlan a ?crit : > > > I've got an instance of a class, ex : > > > b=gtk.Button() > > > I'd like to add methods and attributes to my instance "b". > > I know it's possible by hacking "b" with setattr() methods. > > You don't even need setattr() here, you can set the attributes directly. > > > > > But i'd > > like to do it with inheritance, a kind of "dynamic subclassing", > > without subclassing the class, only this instance "b" ! > > > In fact, i've got my instance "b", and another class "MoreMethods" > > > class MoreMethods: > > def sayHello(self): > > print "hello" > You don't necessarily need subclassing here. What you want is a typical > use case of the Decorator pattern: > > class MoreMethods(object): > def __init__(self, button): > self._button = button > > def sayHello(self): > print "hello" > > def __getattr__(self, name): > return getattr(self._button, name) > > def __setattr__(self, name, value): > if name in dir(self._button): > setattr(self._button, name, value) > else: > object.__setattr__(self, name, value) > > b = MoreMethods(gtk.Button()) > b.set_label("k") > b.say_hello() except that "b" is not anymore a "gtk.Button", but a "MoreMethods" instance ... i'd like that "b" stay a "gtk.Button" ... From nikbaer at gmail.com Wed May 2 13:20:29 2007 From: nikbaer at gmail.com (nik) Date: 2 May 2007 10:20:29 -0700 Subject: ScrolledText? In-Reply-To: <1178086650.307817.285720@p77g2000hsh.googlegroups.com> References: <1178057529.486757.154860@y5g2000hsa.googlegroups.com> <1178086650.307817.285720@p77g2000hsh.googlegroups.com> Message-ID: <1178126429.502174.242550@e65g2000hsc.googlegroups.com> Great thank you for the help, we got it working. From jadestar at idiom.com Thu May 10 02:41:16 2007 From: jadestar at idiom.com (James T. Dennis) Date: Thu, 10 May 2007 06:41:16 -0000 Subject: Minor bug in tempfile module (possibly __doc__ error) References: <1178693438.689184@smirk> Message-ID: <1178779275.833420@smirk> Dennis Lee Bieber wrote: > On Wed, 09 May 2007 06:50:38 -0000, "James T. Dennis" > declaimed the following in comp.lang.python: >> In fact I realized, after reading through tempfile.py in /usr/lib/... >> that the following also doesn't "work" like I'd expect: >> > No idea of the tempfile problem, but... > >> # foo.py >> tst = "foo" >> def getTst(arg): >> return "foo-%s" % arg > This return is using a literal "foo-". Change it to > return "%s-%s" % (tst, arg) Sorry that was a retyping bug in my posting ... not in my sample code which was on another system. > and try again. Try it yourself. As I said ... the value of tst in your name space will be changed, but the value returned by functions in the imported module will still use the old value! -- Jim Dennis, Starshine: Signed, Sealed, Delivered From michael at jedimindworks.com Tue May 1 17:16:40 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Tue, 1 May 2007 16:16:40 -0500 Subject: How can I get the ascii code of a charter in python? In-Reply-To: <1178053581.390873.65850@n76g2000hsh.googlegroups.com> References: <1178053581.390873.65850@n76g2000hsh.googlegroups.com> Message-ID: <2D8E6F10-7467-4867-A378-B1399260C8B9@jedimindworks.com> On May 1, 2007, at 4:06 PM, tedpottel at gmail.com wrote: > Hi, > a python newbe needs some help, > > I read the python doc at > http://docs.python.org/lib/module-curses.ascii.html > > I tried > Import curses.asciicurses.ascii > Print ascii('a') > > I get an error saying module curses.ascii8 does not exsist. > > How can I get the ascii code of a charter in python? Do you mean ord()? From fruels at gmail.com Fri May 4 05:46:44 2007 From: fruels at gmail.com (whitewave) Date: 4 May 2007 02:46:44 -0700 Subject: DiffLib Question In-Reply-To: References: <1178095577.190066.158960@y80g2000hsf.googlegroups.com> <1178097127.286181.216520@y80g2000hsf.googlegroups.com> <1178097973.516943.248720@y80g2000hsf.googlegroups.com> Message-ID: <1178272004.263635.146300@n59g2000hsh.googlegroups.com> > Usually, Differ receives two sequences of lines, being each line a > sequence of characters (strings). It uses a SequenceMatcher to compare > lines; the linejunk argument is used to ignore certain lines. For each > pair of similar lines, it uses another SequenceMatcher to compare > characters inside lines; the charjunk is used to ignore characters. > As you are feeding Differ with a single string (not a list of text lines), > the "lines" it sees are just characters. To ignore whitespace and > newlines, in this case one should use the linejunk argument: > > def ignore_ws_nl(c): > return c in " \t\n\r" > > a =difflib.Differ(linejunk=ignore_ws_nl).compare(d1,d2) > dif = list(a) > print ''.join(dif) > > I n a d d i t i o n , t h e c o n s i d e > r e > d p r o b l e m d o e s n o t h a v e > a m > e a n i n g f u l t r a d i t i o n a l t y > p e > o f- + > a d j o i n t- > + p r o b l e m e v e n f o r t h e s i > m p > l e f o r m s o f t h e d i f f e r e n t > i a > l e q u a t i o n a n d t h e n o n l o > c a l > c o n d i t i o n s . D u e- + > t o t h e s e f a c t s , s o m e s e r > i o > u s d i f f i c u l t i e s a r i s e i n > t h > e a p p l i c a t i o n o f t h e c l a > s s i > c a l m e t h o d s t o s u c h a- + > p r o b l e m .+ > Thanks! It works fine but I was wondering why the result isn't consistent. I am comparing two huge documents with several paragraphs in it. Some parts in the paragraph returns the diff perfectly but others aren't. I am confused. Thanks. Jen From steve at REMOVE.THIS.cybersource.com.au Tue May 8 11:31:22 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 09 May 2007 01:31:22 +1000 Subject: interesting exercise References: <1178595952.641173.76540@y80g2000hsf.googlegroups.com> <1178601624.812907.23550@u30g2000hsc.googlegroups.com> Message-ID: On Tue, 08 May 2007 10:22:05 +0000, James Stroud wrote: > This takes annoying past annoying to some new level of hell to which > even satan himself wouldn't venture. And thank you for sharing that piece of spam with us again. It was so much less enjoyable to see it the second time. Seriously James, with more and more people using automated spam filters, it might not be such a wise idea to keep having your name associated with spam content. -- Steven. From duncan.booth at invalid.invalid Thu May 24 08:59:29 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 24 May 2007 12:59:29 GMT Subject: Lists vs tuples (newbie) References: Message-ID: "Hendrik van Rooyen" wrote: > "Duncan Booth" wrote: >> "Hendrik van Rooyen" wrote: >> >> > Aside from the hashing issue, there is nothing that a tuple can do >> > that can't be done as well or better by a list. >> >> There are a few other cases where you have to use a tuple, for >> example in a try..except statement the exception specification must >> be an exception to be caught or a tuple of exception specifications: >> a list won't work to catch multiple exceptions. > > Esoteric - But I stand corrected... > > any other "must use a tuple's " ? > > Seems they all fall into a class that can be described as required by > the language - I was thinking data. > There used to be several other situations where a tuple was required but I can't think of any others which still exist. So far as data is concerned, the same reason that exceptions require tuples could arise in your own code: If you look at the definition of the except clause expression (simplified to remove the deprecated string option): > An object is compatible with an exception if it is the class or a base > class of the exception object or a tuple containing an item compatible > with the exception you'll see that it is impossible for this structure to contain any loops. An equivalent structure using lists instead of tuples could contain loops and any code which searched it for a match would have to account for this somehow. So, anywhere you want a tree structure with a guarantee that it does not contain any loops it may be appropriate to use tuples to represent the structure. From kyosohma at gmail.com Thu May 31 09:58:36 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 31 May 2007 06:58:36 -0700 Subject: Examples of high-quality python code? In-Reply-To: References: Message-ID: <1180619916.951795.110180@g4g2000hsf.googlegroups.com> On May 31, 8:38 am, Larry Bates wrote: > kaens wrote: > > Hey everyone, I'm relatively new to python - I actually picked it up > > to see how quickly I could start building non-trivial apps with it. > > > Needless to say, I was quite pleased. > > > Anyhow, I'm looking to expand my understanding of python, and I feel > > that one of the best ways to do that is looking at other peoples code. > > > Unfortunately, I don't feel like I grok the python mindset quite well > > enough to fully distinguish between awesome, average, and not-pythony > > code, so I was hoping some of the more experienced python people could > > point me to some (preferably FOSS) non-trivial apps written in python > > that are examples of great python code. > > > I realize this may be a bit ambiguous - basically I don't want to go > > randomly downloading other people's source and end up assimilating > > techniques that aren't . . . well . . . pythonistic. > > > So, who wants to hook me up? > > You should consider picking up a copy of Python Cookbook. Alex and > others have reviewed the code it contains and IMHO it is well written. > > I've also learned quite a lot from: > > Python on Win32 (book by Mark Hammond/Andy Robinson) > Reading source code to standard library > Reading ReportLab source (www.reportlab.org) > Reading PIL source (www.effbot.org) > Reading wxPython source (www.wxpython.org) > Monitoring this list on a daily basis > > -Larry Also "Python Programming" by Lutz has some great code to learn from as it also explains most of it. Mike From steven.klass at gmail.com Wed May 2 12:36:05 2007 From: steven.klass at gmail.com (rh0dium) Date: 2 May 2007 09:36:05 -0700 Subject: Is it possible to determine what a function needs for parameters - In-Reply-To: <4638a4eb$0$2033$426a74cc@news.free.fr> References: <1178115727.932794.100390@h2g2000hsg.googlegroups.com> <4638a4eb$0$2033$426a74cc@news.free.fr> Message-ID: <1178123765.763358.276570@p77g2000hsh.googlegroups.com> On May 2, 7:49 am, Bruno Desthuilliers wrote: > Yes - using inspect.getargspec. I don't have example code at hand yet, > but it's not really complicated. Viola!! Hey this works!! Now I have modified my code to do this - way cool (still kind of a mess though) args, varargs, varkw, defs = inspect.getargspec(self.function) # Deal with just some args if varargs is None and varkw is None: result=self.function(input) # Deal with *args if varkw is None and varargs is not None and len(args) > 0: result=self.function(input[0:-1], *input[-1]) if varkw is None and varargs is not None and len(args)==0: result=self.function(*input[0]) # Deal with *kwargs if varkw is not None and varargs is not None and len(args) > 0: result=self.function(input[0:-2], *input[-2], **input[-1]) if varkw is not None and varargs is not None and len(args)==0: result=self.function(*input[-2], **input[-1]) if varkw is not None and varargs is None and len(args) > 0: result=self.function(input[0:-1], **input[-1]) if varkw is not None and varargs is None and len(args) == 0: result=self.function(**input[0]) Now this worked until I threw a function which looked like this def func5( input1, input2, input3 ) pass So it barfed because of this.. if varargs is None and varkw is None: result=self.function(input) but all of the parameters were lumped as a list so input1 contained them all... A small tweak turned into this.. if varargs is None and varkw is None: if isinstance(input, tuple): result=self.function(*input) else: result=self.function(input) But now I suppose I need to do this for all of them but that will break my other logic... Yuck - I have to be missing something here. From jstroud at mbi.ucla.edu Thu May 3 15:31:43 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 03 May 2007 12:31:43 -0700 Subject: Responding to Trolls [was Re: ignorance and intolerance in computing communties] In-Reply-To: References: <1178120019.271716.299590@e65g2000hsc.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Wed, 02 May 2007 21:23:13 -0700, James Stroud wrote: > > >>Xah Lee wrote: >> >>>Today, a motherfucker Christophe Rhodes (aka Xof in irc://chat.freenode.net/lisp >>>) kicked banned me. >> >>Are you aware that you are a troll? Have you considered that this has >>anything to do with your being kick-banned? Why do 99.999999 % of the >>people on the web not get treated like you? Answer: you are a troll and >>they are not. > > > Sometimes I dream of a world, a wonderful, far away world, where nobody > was allowed to post to Usenet until they can correctly answer the > following multiple-choice question: > > Q Verbally abusing trolls ... > 1. gives them the attention they crave > 2. fails to discourage their trollish behaviour > 3. annoys the people who otherwise wouldn't have seen the troll's post > 4. all of the above If you say so, but I honestly can not fathom such twisted psychology. James From __peter__ at web.de Thu May 3 15:00:15 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 03 May 2007 21:00:15 +0200 Subject: _csv.Error: string with NUL bytes References: <1178204593.280648.208040@c35g2000hsg.googlegroups.com> <1178209090.674787.202970@o5g2000hsb.googlegroups.com> <1178211458.634214.306500@o5g2000hsb.googlegroups.com> <1178213314.203450.167350@n76g2000hsh.googlegroups.com> Message-ID: dustin at v.igoro.us wrote: > I'm guessing that your file is in UTF-16, then -- Windows seems to do > that a lot. It kind of makes it *not* a CSV file, but oh well. Try > > print open("test.csv").decode('utf-16').read().replace("\0", > ">>>NUL<<<") > > I'm not terribly unicode-savvy, so I'll leave it to others to suggest a > way to get the CSV reader to handle such encoding without reading in the > whole file, decoding it, and setting up a StringIO file. Not pretty, but seems to work: from __future__ import with_statement import csv import codecs def recoding_reader(stream, from_encoding, args=(), kw={}): intermediate_encoding = "utf8" efrom = codecs.lookup(from_encoding) einter = codecs.lookup(intermediate_encoding) rstream = codecs.StreamRecoder(stream, einter.encode, efrom.decode, efrom.streamreader, einter.streamwriter) for row in csv.reader(rstream, *args, **kw): yield [unicode(column, intermediate_encoding) for column in row] def main(): file_encoding = "utf16" # generate sample data: data = u"\xe4hnlich,\xfcblich\r\nalpha,beta\r\ngamma,delta\r\n" with open("tmp.txt", "wb") as f: f.write(data.encode(file_encoding)) # read it with open("tmp.txt", "rb") as f: for row in recoding_reader(f, file_encoding): print u" | ".join(row) if __name__ == "__main__": main() Data from the file is recoded to UTF-8, then passed to a csv.reader() whose output is decoded to unicode. Peter From pc at p-cos.net Tue May 1 14:13:33 2007 From: pc at p-cos.net (Pascal Costanza) Date: Tue, 01 May 2007 20:13:33 +0200 Subject: Lisp-like macros in Python? In-Reply-To: <1178042354.689281.182070@h2g2000hsg.googlegroups.com> References: <1178035825.193334.184250@o5g2000hsb.googlegroups.com> <1178042354.689281.182070@h2g2000hsg.googlegroups.com> Message-ID: <59peadF2l8bruU1@mid.individual.net> Converge is a Python-style language with a macro facility. See http://convergepl.org/ Pascal -- My website: http://p-cos.net Common Lisp Document Repository: http://cdr.eurolisp.org Closer to MOP & ContextL: http://common-lisp.net/project/closer/ From mccredie at gmail.com Fri May 25 13:54:55 2007 From: mccredie at gmail.com (Matimus) Date: 25 May 2007 10:54:55 -0700 Subject: Large Amount of Data In-Reply-To: References: Message-ID: <1180115695.539641.8110@r3g2000prh.googlegroups.com> On May 25, 10:50 am, "Jack" wrote: > I need to process large amount of data. The data structure fits well > in a dictionary but the amount is large - close to or more than the size > of physical memory. I wonder what will happen if I try to load the data > into a dictionary. Will Python use swap memory or will it fail? > > Thanks. The OS will take care of memory swapping. It might get slow, but I don't think it should fail. Matt From tkapoor at wscm.net Thu May 17 16:26:28 2007 From: tkapoor at wscm.net (Tarun Kapoor) Date: Thu, 17 May 2007 15:26:28 -0500 Subject: Error on FTP Upload .. No such file or directory Message-ID: <9E0CC1A9D55BE54CAD39E562649F1716038DA37E@wscmmail.wscm.corp> ------- Code ------ remotepath = "/incoming" f = FTP(host) f.login(username,password) f.cwd(remotepath) localfile ="C:\\test.txt" fd = open(localfile,'rb') path,filename = os.path.split(localfile) f.storbinary('STOR %s' % filename,fd) fd.close() f.quit() -------- Error -------- Traceback (most recent call last): File "P:\Working\Python code\temp.py", line 21, in ? uploadFile("C:\\test.txt") File "P:\Working\Python code\temp.py", line 16, in uploadFile f.storbinary('STOR %s' % filename,fd) File "C:\Python23\lib\ftplib.py", line 415, in storbinary conn = self.transfercmd(cmd) File "C:\Python23\lib\ftplib.py", line 345, in transfercmd return self.ntransfercmd(cmd, rest)[0] File "C:\Python23\lib\ftplib.py", line 327, in ntransfercmd resp = self.sendcmd(cmd) File "C:\Python23\lib\ftplib.py", line 241, in sendcmd return self.getresp() File "C:\Python23\lib\ftplib.py", line 214, in getresp raise error_perm, resp ftplib.error_perm: 553 test.txt: No such file or directory. Disclaimer This e-mail and any attachments is confidential and intended solely for the use of the individual(s) to whom it is addressed. Any views or opinions presented are solely those of the author and do not necessarily represent those of Waterstone Capital Management, L.P and affiliates. If you are not the intended recipient, be advised that you have received this e-mail in error and that any use, dissemination, printing, forwarding or copying of this email is strictly prohibited. Please contact the sender if you have received this e-mail in error. You should also be aware that e-mails are susceptible to interference and you should not assume that the contents of this e-mail originated from the sender above or that they have been accurately reproduced in their original form. Waterstone Capital Management, L.P. and affiliates accepts no responsibility for information, or errors or omissions in this e-mail or use or misuse thereof. If in doubt, please verify the authenticity with the sender. From ai.nature at gmail.com Thu May 31 10:47:04 2007 From: ai.nature at gmail.com (ai) Date: 31 May 2007 07:47:04 -0700 Subject: How to clean a module? Message-ID: <1180622824.836459.222090@q19g2000prn.googlegroups.com> It assumes that there is a module A which have two global variables X and Y. If I run "import A" in the IDLE shell, then I can use A.X and A.Y correctly. But if I want to change the module A and then delete the variable Y, I find I can use A.Y just the same as before! In fact, I have tried all the following methods but can't remove the A.Y: execute "import A" again "reload(A)" "del A; import A" Yes, if you use "del A.Y", it works. But it is stupid since there are probably many names. In my thought, if no one references objects in A, "del A" will release all memory about A. But it seems that the fact is not. So I can not refresh the namespace to follow changes of a module easily and I will worry about the memory if I del a module. I want to know if there is a way to clear a module entirely. From python.leojay at gmail.com Fri May 4 03:01:40 2007 From: python.leojay at gmail.com (Leo Jay) Date: Fri, 4 May 2007 15:01:40 +0800 Subject: default config has no md5 module? Message-ID: <4e307e0f0705040001t69300dabw5df37c2799201787@mail.gmail.com> i want to compile a python by myself, but after configure and make, it seems that md5 is not built by default. what should i do to compile md5 as an module? -- Best Regards, Leo Jay From mail at microcorp.co.za Thu May 17 02:33:28 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 17 May 2007 08:33:28 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de><1179160242.787344.48060@h2g2000hsg.googlegroups.com> <1179258692.237438.110860@p77g2000hsh.googlegroups.com> Message-ID: <019501c79856$8502a160$03000080@hendrik> "Gregor Horvath" wrote: > Hendrik van Rooyen schrieb: > > > It is not so much for technical reasons as for aesthetic > > ones - I find reading a mix of languages horrible, and I am > > kind of surprised by the strength of my own reaction. > > This is a matter of taste. I agree - and about perceptions of quality. Of what is good, and not good. - If you havent yet, read Robert Pfirsig's book: "Zen and the art of motorcycle maintenance" > In some programs I use German identifiers (not unicode). I and others > like the mix. My customers can understand the code better. (They are > only reading it) > I can sympathise a little bit with a customer who tries to read code. Why that should be necessary, I cannot understand - does the stuff not work to the extent that the customer feels he has to help you? You do not talk as if you are incompetent, so I see no reason why the customer should want to meddle in what you have written, unless he is paying you to train him to program, and as Eric Brunel has pointed out, this mixing of languages is all right in a training environment. > > > > "Beautiful is better than ugly" > > Correct. > But why do you think you should enforce your taste to all of us? You misjudge me - the OP asked if I would use the feature, and I am speaking for myself when I explain why I would not use it. > > With this logic you should all drive Alfa Romeos! > Actually no - this is not about logic - my post clearly stated that I was talking about feelings. And the only logic that applies to feelings is the incontrovertible fact that they exist, and that it makes good logical sense to acknowledge them, and to take that into account in one's actions. And as far as Alfa's go - we have found here that they are rather soft - our dirt roads destroy them in no time. : - ( - Hendrik From apatheticagnostic at gmail.com Wed May 30 08:19:13 2007 From: apatheticagnostic at gmail.com (kaens) Date: Wed, 30 May 2007 08:19:13 -0400 Subject: Key Listeners In-Reply-To: <465d64c4$0$7452$426a74cc@news.free.fr> References: <1180491273.446164.281990@q75g2000hsh.googlegroups.com> <1180510259.914953.225420@h2g2000hsg.googlegroups.com> <465d64c4$0$7452$426a74cc@news.free.fr> Message-ID: <163f0ce20705300519m4404bc22m75f31549252c702@mail.gmail.com> On 5/30/07, Bruno Desthuilliers wrote: > Benedict Verheyen a ?crit : > > bruno.desthuilliers at gmail.com schreef: > >> On 30 mai, 04:14, Mike wrote: > >>> Are there key listeners for Python? Either built in or third party? > >> > >> What is a "key listener" ? > >> > (snip) > > In google, the first link is a link to the java sun home page. > > The first sentence on that page: "Key events indicate when the user is > > typing at the keyboard." > > I do know what's a "key listener" in Java, thanks !-) > > My question was supposed to have side effects - like the OP asking > himself if he was really asking the right question. > > Regards too. > -- > http://mail.python.org/mailman/listinfo/python-list > What, he wants to know if there's a way in python to capture keystrokes, and do something with them depending on what they are. I mean, it's very unlikely that you would ask for something called a "key listener" if you didn't want to do something like: if keypress == 'a': do somem right? Even if you're looking to do it the java way, all of the listener functionality more or less boils down to "wait for and report keys being pressed". He could have been less ambiguous, but I don't think that he was asking the wrong question per se. Not to mention asking the OP "what's a key listener" isn't going to make them think about the question they asked - it makes it seem like you don't know what a key listener is (and frankly, I think that if you have done any work with doing stuff on different keystrokes, you'll figure out what is meant by key listener pretty quickly, even if you haven't heard the term before) From zdenekmaxa at yahoo.co.uk Wed May 30 03:50:33 2007 From: zdenekmaxa at yahoo.co.uk (Zdenek Maxa) Date: Wed, 30 May 2007 09:50:33 +0200 Subject: multiline regular expression (replace) In-Reply-To: References: <1180432000.953227.144690@i13g2000prf.googlegroups.com> Message-ID: <465D2CC9.4000108@yahoo.co.uk> Hi, Thanks a lot for useful hints to all of you who replied to my question. I could easily do now what I wanted. Cheers, Zdenek Holger Berger wrote: > Hi, > > yes: > > import re > > a=""" > I Am > Multiline > but short anyhow""" > > b="(I[\s\S]*line)" > > print re.search(b, a,re.MULTILINE).group(1) > > > gives > > I Am > Multiline > > Be aware that . matches NO newlines!!! > May be this caused your problems? > > regards > Holger > > > Zdenek Maxa wrote: > > >> half.italian at gmail.com wrote: >> >>> On May 29, 2:03 am, Zdenek Maxa wrote: >>> >>> >>>> Hi all, >>>> >>>> I would like to perform regular expression replace (e.g. removing >>>> everything from within tags in a XML file) with multiple-line pattern. >>>> How can I do this? >>>> >>>> where = open("filename").read() >>>> multilinePattern = "^ .... <\/tag>$" >>>> re.search(multilinePattern, where, re.MULTILINE) >>>> >>>> Thanks greatly, >>>> Zdenek >>>> >>>> >>> Why not use an xml package for working with xml files? I'm sure >>> they'll handle your multiline tags. >>> >>> http://effbot.org/zone/element-index.htm >>> http://codespeak.net/lxml/ >>> >>> ~Sean >>> >>> >>> >> Hi, >> >> that was merely an example of what I would like to achieve. However, in >> general, is there a way for handling multiline regular expressions in >> Python, using presumably only modules from distribution like re? >> >> Thanks, >> Zdenek >> > > From rene at korteklippe.de Sat May 19 15:03:48 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Sat, 19 May 2007 21:03:48 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464C5936.5020003@v.loewis.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649dd55$0$23144$9b4e6d93@newsspool1.arcor-online.net> <464a25e9$0$10188$9b4e6d93@newsspool4.arcor-online.net> <1179291296.561359.286230@h2g2000hsg.googlegroups.com> <464ab64f$0$10185$9b4e6d93@newsspool4.arcor-online.net> <464AB9F2.60906@web.de> <464ac189$0$20297$9b4e6d93@newsspool3.arcor-online.net> <464ac493$0$6394$9b4e6d93@newsspool2.arcor-online.net> <464add30$0$6401$9b4e6d93@newsspool2.arcor-online.net> <464C5936.5020003@v.loewis.de> Message-ID: <464f4a14$0$10193$9b4e6d93@newsspool4.arcor-online.net> Martin v. L?wis schrieb: > I've reported this before, but happily do it again: I have lived many > years without knowing what a "hub" is, and what "to pass" means if > it's not the opposite of "to fail". Yet, I have used their technical > meanings correctly all these years. I was not speaking of the more general (non-technical) meanings, but of the technical ones. The claim which I challenged was that people learn just the "use" (syntax) but not the "meaning" (semantics) of these terms. I think you are actually supporting my argument ;) -- Ren? From wildemar at freakmail.de Wed May 30 07:24:33 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Wed, 30 May 2007 13:24:33 +0200 Subject: Rats! vararg assignments don't work In-Reply-To: <1180496542.955320.5430@m36g2000hse.googlegroups.com> References: <1180496033.608791.35840@g37g2000prf.googlegroups.com> <1180496542.955320.5430@m36g2000hse.googlegroups.com> Message-ID: <465D5EF1.3000401@freakmail.de> George Sakkis wrote: > The time machine did it again: http://www.python.org/dev/peps/pep-3132/. > > Uhm, John Swartzwelder, right? :D /W From half.italian at gmail.com Wed May 23 15:43:53 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 23 May 2007 12:43:53 -0700 Subject: Parallel/distributed generator In-Reply-To: <1179943256.575473.62610@q66g2000hsg.googlegroups.com> Message-ID: <1179949433.482419.177540@r19g2000prf.googlegroups.com> On May 23, 11:00 am, George Sakkis wrote: > I'm looking for any existing packages or ideas on how to implement the > equivalent of a generator (in the Python sense, i.e.http://www.python.org/dev/peps/pep-0255/) in a parallel/distributed > way. As a use case, imagine a function that generates a range of > primes. I'd like to be able to do something along the following lines: > > def iterprimes(start=1, end=None): > # ... > yield prime > > # rpc-related initialization > ... > rpc_proxy = some_rpc_lib(iterprimes, start=1e6, end=1e12) > for prime in proxy: > print prime > > Is there any module out there that does anything close to this ? > > George Parellel Python? http://www.parallelpython.com/content/view/17/31/#SUM_PRIMES I've never used it, but looks like it does what you are looking for. ~Sean From gagsl-py2 at yahoo.com.ar Wed May 16 15:38:39 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 16 May 2007 16:38:39 -0300 Subject: zipfile stupidly broken References: Message-ID: En Wed, 16 May 2007 12:18:35 -0300, Martin Maney escribi?: > So the author knows that there's a hard limit of 64K on the comment > size, but feels it's more important to fail a little more quickly when > fed something that's not a zipfile - or a perfectly legitimate zipfile > that doesn't observe his ad-hoc 4K limitation. I don't have time to > find a gentler way to say it because I have to find a work around for > this arbitrary limit (1): this is stupid. This is not a good place for reporting bugs - use http://sourceforge.net/bugs/?group_id=5470 -- Gabriel Genellina From nospam at nospam.com Tue May 1 14:15:42 2007 From: nospam at nospam.com (3c273) Date: Tue, 1 May 2007 11:15:42 -0700 Subject: Comparing bitmap images for differences? References: <1178024505.768505.262270@h2g2000hsg.googlegroups.com> Message-ID: > Those are my ideas so far but I thought it would be worth asking here > first in case there are some known-good algorithms for doing this kind > of thing rather than me trying to re-invent a wheel that ends up > triangular... > > Thanks! > Matthew. > This might get you started. http://tinyurl.com/7qexl Louis From collver at peak.org Fri May 4 09:36:05 2007 From: collver at peak.org (Ben Collver) Date: Fri, 04 May 2007 06:36:05 -0700 Subject: My Python annoyances In-Reply-To: References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> Message-ID: Terry Reedy wrote: > Three days after you posted, 'gagenellina' explained that he thought your > complaint was invalid. > "py> -531560245 & 0xffffffff > 3763407051L > > It's the same number (actually, the same bit pattern). ..." > > A few weeks later, noticing that you had not challenged his explanation, I > closed after changing the Resolution box to Invalid. THAT WAS MY COMMENT. > > A month later, I notice that you still have not directly challenged G's > claim of invalidity. Instead, you ignored it and simply repeated your > claim here. WHO IS IGNORING WHO? > ... > Real bug reports are quite welcome, as any honest person could determine by > looking thru the tracker. Hi Terry, I understand and agree that the number was the same bit pattern. I don't remember being asked to challenge this. I must have missed the status change notification. I do wonder whether the diagnosis is accurate: is the sparc64 port actually using an unsigned int where the i386 port is using a signed int? Either way, I don't see how it reflects on the validity of the report. I reported that the resulting numbers were different. To me that seems a trap for the unwary. All I saw was a comment on what might cause my problem, and then I saw that the problem report was closed. Now I am told that I didn't even file a real bug report. I don't know whether to take that as "this is a trivial problem not worth reporting" or "this is a poorly filed bug report". I am an honest person, honestly! Ben From david.colliver.NEWS at revilloc.REMOVETHIS.com Tue May 1 11:01:17 2007 From: david.colliver.NEWS at revilloc.REMOVETHIS.com (David) Date: Tue, 1 May 2007 16:01:17 +0100 Subject: SEO - Search Engine Optimization - Seo Consulting References: <1177808356.681710.42980@n76g2000hsh.googlegroups.com> Message-ID: <#O8fXGAjHHA.3700@TK2MSFTNGP06.phx.gbl> I am not going to join the argument, except to say that as you can see, I top post. In outlook express, you can see the messages as a thread, so you read the initial message, come to the reply and you read the response without having to scroll. Bottom posting would be fine if the previous message that promted the response was removed from the server, but it isn't, therefore, top posting is very logical. -- Best regards, Dave Colliver. http://www.AshfieldFOCUS.com ~~ http://www.FOCUSPortals.com - Local franchises available "Sebastian Kaliszewski" wrote in message news:f17b4j$iah$1 at bozon2.softax.pl... > Bob Phillips wrote: >> You bottom posters really are a bunch of supercilious, self-righteous >> bigots. > > Whatever. When reading answers to some statements normal people like first > to see the statement then the response, not the other way around. Just > because you're using broken tool (Outlook Express) it does not excuse you > of being rude. > > Besides, reposting that spamming site address is idiotic by itself, > regardless of top posting or not. > > [...] >> And regardless of his response, Mr Bruney IS an MVP, he is clearly >> knowledgeable in his subject, and his book is well enough thought of to >> make me consider buying it. > > > Regardless of who Mr Bruney is, this if completely offtopic on > comp.lang.python, misc.writing, alt.consumers.uk-discounts.and.bargains > and uk.people.consumers.ebay > > Just notice that you're posting to *more than one* group. Just please > learn to use the damn reader! Even Outlook Express allows to set > Followup-To: header and limit the polution. > EOT From C.delete_this.Sanders at BoM.GOv.AU Thu May 3 00:22:02 2007 From: C.delete_this.Sanders at BoM.GOv.AU (Charles Sanders) Date: Thu, 03 May 2007 14:22:02 +1000 Subject: Lazy evaluation: overloading the assignment operator? In-Reply-To: <59scumF2lqg76U1@mid.uni-berlin.de> References: <1178133344.415521.118710@n76g2000hsh.googlegroups.com> <59scumF2lqg76U1@mid.uni-berlin.de> Message-ID: <4639636b$0$14016$c30e37c6@lon-reader.news.telstra.net> Diez B. Roggisch wrote: > I fail to see where laziness has anything to do with this. > In C++, this problem can be remedied with the so called > temporary base class idiom. I have seen this referred to as lazy evaluation in C++, so I suspect that Diez and Sturia are using "Lazy evaluation" in different contexts with different meaning. > But this has nothing to do with laziness, which does not > reduce the amount of code to execute, but instead defers the > point of execution of that code. But that is precisely what Sturia is suggesting, defer (for a few nanoseconds) the evaluation of the multiplications and addition until the assignment occurs. Admittedly a big difference to the lazy evaluation implied by python's yield statement, but still a version of lazy evaluation and (at least sometimes) referred to as such in a C++ context. I am a python newbie (about one month) but I think some of what Sturia wants could be achieved by partially following what is usually done in C++ to achieve what he wants. It would involve a replacement array class (possibly derived from NumPy's arrays) and a proxy class. + Addition, multiplication, etc of arrays and proxy arrays does not return the result array, but returns a proxy which stores the arguments and the operation. + Array indexing of the proxy objects results in the indexing methods of the arguments being called and the operation being carried out and returned. In C++ this is normally very efficient as the operations are all defined inline and expanded by the compiler. + If necessary, define an additional method to evaluate the entire array and return it. I think this would allow code like (if the new array type is XArray) a = Xarray(...) b = Xarray(...) c = Xarray(...) d = Xarray(...) y = a*b+c*d # Returns a proxy object x = y[4] # Computes x = a[4]*b[4] + c[4]*d[4] v = y.eval() # Evaluates all elements, returning Xarray z = ((a+b)*(c+d)).eval() # Also evaluates all elements Whether it would be any faster is doubtful, but it would eliminate the temporaries. Charles From tbrkic at yahoo.com Tue May 29 17:14:12 2007 From: tbrkic at yahoo.com (glomde) Date: 29 May 2007 14:14:12 -0700 Subject: How to set a class inheritance at instance creation? In-Reply-To: References: <1180453971.556244.91370@q69g2000hsb.googlegroups.com> Message-ID: <1180473252.831877.200170@h2g2000hsg.googlegroups.com> On 29 Maj, 22:45, Steve Holden wrote: > glomde wrote: > > Hi I wonder if you can set what subclass a class should > > have at instance creation. > > > The problem is that I have something like: > > > class CoreLang(): > > def AssignVar(self, var, value): > > pass > > > class Lang1(CoreLang): > > def AssignVar(self, var, value): > > return var, "=", value > > > class Lang2(CoreLang): > > def AssignVar(self, var, value): > > return var, "<=", value > > > class WriteStruct(): > > def Generate(self, vars): > > for var in vars: > > print self.AssignVar() > > > The problem is that I want WriteStruct to sometimes be a subclass of > > Lang1 and sometimes > > of Lang2. > > In the above example I could but the Generate Method in CoreLang. But > > in my real > > example I also want to able to subclass WriteStruct to be able to easy > > customize WriteStruct. > > Which I wouldnt be able to do if it was a method in CoreLang. > > > So in code I would like to write something like: > > > WriteStruct(Lang1).Generate(vars) > > > Even better would be that if I in the Lang1 class could > > just do WriteStruct().Generate(vars) and Lang1 class would > > magically make WriteStruct a subclass of itself. > > You should rethink your program design. > > It seems that when you create a WriteStruct you should really be passing > its __init__() method the class that you want it to be a "subclass" of, > creating an instance of that class, and then using generic delegation to > that subclass (using a modified __getattr__()) to handle methods that > aren't found in the WriteStruct. This is what I am going to do. For some reason I got stuck to think I needed to solve it with inheritance. Didnt think of the possibility to modify getattr to make the delegation be much nicer. Thanks for the tip > > I can see there are circumstances in which this might not work, but I > believe your current ugly intentions reveal a design smell that you > really need to get rid of if you want a clean program. > > 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 your way to fame!! > holdenweb.blogspot.com squidoo.com/pythonology > tagged items: del.icio.us/steve.holden/python > All these services currently offer free registration! > -------------- Thank You for Reading ---------------- From gagsl-py2 at yahoo.com.ar Mon May 28 14:47:22 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 28 May 2007 15:47:22 -0300 Subject: Why isn't this query working in python? References: <1180103946.552760.239200@p47g2000hsd.googlegroups.com> <6e42ec490705250751i89d3cf3v3a3062690d0284aa@mail.gmail.com> <1180207521.072958.322770@p47g2000hsd.googlegroups.com> <1180225290.235515.274000@q19g2000prn.googlegroups.com> <1180279833.131269.136770@w5g2000hsg.googlegroups.com> Message-ID: En Mon, 28 May 2007 14:53:57 -0300, Dennis Lee Bieber escribi?: > On Sun, 27 May 2007 20:35:28 -0400, Carsten Haese > declaimed the following in comp.lang.python: > >> On Sun, 2007-05-27 at 16:39 -0400, davelist at mac.com wrote: >> > > sql = """SELECT payment_id FROM amember_payments WHERE >> > > member_id=%s AND expire_date > NOW() AND completed=1 AND (product_id >> > >>> 11 AND product_id <21)""", (self.uid) > > It's confusing, as the example shown is not the common form for > parameter passing on the .execute() call -- without the .execute() it is > unclear. I presume the .execute() is using *sql to unpack the tuple... Yes, the original message said self.amember_cursor.execute(*sql) It IS confusing... -- Gabriel Genellina From rocky at panix.com Sun May 6 20:37:52 2007 From: rocky at panix.com (R. Bernstein) Date: 06 May 2007 20:37:52 -0400 Subject: Emacs and pdb after upgrading to Ubuntu Feisty References: <1178426788.614637.209400@w5g2000hsg.googlegroups.com> Message-ID: levander writes: > I've been using pdb under emacs on an Ubuntu box to debug python > programs. I just upgraded from Ubuntu Edgy to Feisty and this combo > has stopped working. Python is at 2.5.1 now, and emacs is at 21.41.1. If I had to take a guess the big change would be in Python 2.5.1 and the Emacs pdb package has not kept up with that. Edgy was running Python 2.4.x. The emacs version is about the same. (And I agree with Alexander Schmolck that emacs 23 alpha is much much nicer). If you were to report a problem, my guess then would be the Debian maintainer for the Emacs pdb package. More info below. > It used to be I could just "M-x pdb RET pdb RET" and be > presented with a prompt where I could debug my script, as well as an > arrow in another source code buffer indicating where I am in the > source code. > > Now however, when I do "M-x pdb RET pdb ~/grabbers/npr-grabber.py -s > WESUN", I get this is in a buffer called *gud*: > > Current directory is /home/levander/grabbers/ > > No prompt or anything follows it, just that one line. It doesn't pop > up an arrow in the other buffer either. None of the regular commands > like 'n', 's', or 'l' do anything here. So, I did a 'Ctrl-C' and got: > > > /home/levander/grabbers/npr-grabber.py(24)() > -> """ > (Pdb) > /home/levander/grabbers/npr-grabber.py(30)() > -> import getopt > (Pdb) Traceback (most recent call last): > File "/usr/bin/pdb", line 1213, in main > pdb._runscript(mainpyfile) > File "/usr/bin/pdb", line 1138, in _runscript > self.run(statement, globals=globals_, locals=locals_) > File "bdb.py", line 366, in run > exec cmd in globals, locals > File "", line 1, in > File "/home/levander/grabbers/npr-grabber.py", line 30, in > import getopt > File "/home/levander/grabbers/npr-grabber.py", line 30, in > import getopt > File "bdb.py", line 48, in trace_dispatch > return self.dispatch_line(frame) > File "bdb.py", line 66, in dispatch_line > self.user_line(frame) > File "/usr/bin/pdb", line 144, in user_line > self.interaction(frame, None) > File "/usr/bin/pdb", line 187, in interaction > self.cmdloop() > File "cmd.py", line 130, in cmdloop > line = raw_input(self.prompt) > KeyboardInterrupt > Uncaught exception. Entering post mortem debugging > Running 'cont' or 'step' will restart the program > > /home/levander/grabbers/cmd.py(151)cmdloop() > -> pass > (Pdb) > > It's wierd because at the bottom of that call stack, it does look like > it's wating for input, but no input works... And, after I hit Ctrl-C > I do get a prompt as you see at the bottom of that listing just > above. Now I type "quit" and get: Yes, it looks like it is in its input look reading debugger commands. If you've tried commands that produce output (e.g. "list", "where", "print") and you are getting nothing then, yes, that's weird. Emacs however will gobble up and hide what it thinks is location information from the debugger. So if you were running "step" or "next" or "continue" I could see how output would be disappearing. In any event a guess for some of the problem is that the Emacs isn't parsing the output correctly. I've noticed subtle changes in reporting the where you are between Python 2.4 and 2.5 such as giving a module name when that's known. The emacs regular expressions no doubt haven't been updated for knowing this and matching the location is and probably needs to be a little bit fussy. > > Post mortem debugger finished. The /home/cponder/grabbers/npr- > grabber.py will be restarted > > Anybody can tell me who to get pdb working under emacs on Ubuntu > Feisty? I haven't tried pdb, but another Alex, Oleksandr Moskale, has a Debian package for pydb which gets filtered down to Edgy and Feisty, and I've used that and it works. ;-) And it also works with ipython in the way that 'as mentioned too. From rridge at caffeine.csclub.uwaterloo.ca Thu May 10 08:29:52 2007 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Thu, 10 May 2007 08:29:52 -0400 Subject: Single precision floating point calcs? References: <1343v0emvdjr545@corp.supernews.com> <1344t3gauu8b486@corp.supernews.com> Message-ID: Grant Edwards wrote: >In the C implementations, the algorithms will be done >implemented in single precision, so doing my Python prototyping >in as close to single precision as possible would be "a good >thing". Something like numpy might give you reproducable IEEE 32-bit floating point arithmetic, but you may find it difficult to get that out of a IA-32 C compiler. IA-32 compilers either set the x87 FPU's precision to either 64-bits or 80-bits and only round results down to 32-bits when storing values in memory. If you can target CPUs that support SSE, then compiler can use SSE math to do most single precision operations in single precision, although the compiler may not set the required SSE flags for full IEEE complaince. In other words, since you're probably going to have to allow for some small differences in results anyways, it may not be worth the trouble of trying to get Python to use 32-bit floats. (You might also want to consider whether you want to using single precision in your C code to begin with, on IA-32 CPUs it seldom makes a difference in performance.) Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From gagsl-py2 at yahoo.com.ar Mon May 14 14:35:25 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 14 May 2007 15:35:25 -0300 Subject: Time References: <1178916216.893542.257320@y80g2000hsf.googlegroups.com> <1178916422.065108.312920@l77g2000hsb.googlegroups.com> <1178920014.621031.301860@n59g2000hsh.googlegroups.com> <1178927105.482975.174760@y5g2000hsa.googlegroups.com> <1179151205.987222.54910@k79g2000hse.googlegroups.com> <1179152573.315362.37040@u30g2000hsc.googlegroups.com> <1179152855.424498.274820@p77g2000hsh.googlegroups.com> Message-ID: En Mon, 14 May 2007 11:27:35 -0300, HMS Surprise escribi?: > On May 14, 9:22 am, HMS Surprise wrote: > > Oops +=1, should be: > hrMn[0] = int(hrMn[0] > if t[2] == 'PM': > hrMn[0] += 12 > > Need more starter fluid, coffee please!!! Still won't work for 12 AM nor 12 PM... -- Gabriel Genellina From mcl.office at googlemail.com Sat May 5 04:52:25 2007 From: mcl.office at googlemail.com (mosscliffe) Date: 5 May 2007 01:52:25 -0700 Subject: Newbie and Page Re-Loading In-Reply-To: <1hxltav.y0wenquohjqeN%aleax@mac.com> References: <1178275290.158007.248180@h2g2000hsg.googlegroups.com> <463b6678$0$10433$426a34cc@news.free.fr> <1178302555.479739.227920@o5g2000hsb.googlegroups.com> <1178313011.279170.292200@u30g2000hsc.googlegroups.com> <1hxltav.y0wenquohjqeN%aleax@mac.com> Message-ID: <1178355145.800007.22940@l77g2000hsb.googlegroups.com> Alex, Thanks for the help. Richard On May 5, 3:42 am, a... at mac.com (Alex Martelli) wrote: > Miki wrote: > > ... > > > > Is there a lightweight Https Server I could run locally (WINXP), which > > > would run .py scripts, without lots of installation modifications ? > >http://lighttpd.net. > > Make sure "mod_cgi" is uncommented, set your document root and set > > right python interpreter in cgi.assign > > For https, you do need to do substantial homework, though -- no two ways > about it, since you'll need to get SSL certificates, etc etc. There are > reasonably simple instructions for the purpose at > ration.html>, but they're for Linux -- I don't know how they change when > you want to serve https on Xp. > > Alex From joncle at googlemail.com Wed May 2 11:05:34 2007 From: joncle at googlemail.com (Jon Clements) Date: 2 May 2007 08:05:34 -0700 Subject: Writing a nice formatted csv file In-Reply-To: <1178115244.446071.317250@n76g2000hsh.googlegroups.com> References: <1178115244.446071.317250@n76g2000hsh.googlegroups.com> Message-ID: <1178118334.323808.49530@o5g2000hsb.googlegroups.com> On 2 May, 15:14, redcic wrote: > Hi all, > > I use the csv module of Python to write a file. My code is of the > form : > > cw = csv.writer(open("out.txt", "wb")) > cw.writerow([1,2,3]) > cw.writerow([10,20,30]) > > And i get an out.txt file looking like: > 1,2,3 > 10,20,30 > > Whereas what I'd like to get is: > 1, 2, 3, > 10, 20, 30 > > which is more readable. > > Can anybody help me to do so ? How about pre-formatting the columns before hand before using something like: # List of formatting to apply to each column (change this to suit) format = ['%03d', '%10s', '%10s'] data = [1, 10, 100] print [fmt % d for fmt,d in zip(format,data)] Results in: ['001', ' 10', ' 100'] Then write that using the CSV module. hth Jon. From whamil1 at entergy.com Fri May 4 14:31:51 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Fri, 4 May 2007 13:31:51 -0500 Subject: How to check if a string is empty in python? In-Reply-To: <1178302751.544971.281270@y5g2000hsa.googlegroups.com> Message-ID: <588D53831C701746A2DF46E365C018CE01D2CA8E@LITEXETSP001.etrsouth.corp.entergy.com> > -----Original Message----- > From: mensanator at aol.com > > On May 4, 5:02 am, Jaswant wrote: > > This is a simple way to do it i think > > > > s=hello > > > > >>> if(len(s)==0): > > > > ... print "Empty" > > ... else: > > ... print s > > ... > > hello > > But you are still making the assumption that s is a string. > (BTW, you need quotes around your example.) > > For example: > > >>> print a,b > 11 11 > > Can you tell which one is the string? I.e., which one had quotes > around it? > > If you correctly assume that it was b, then yes, your example works. > > >>> print len(b) > 2 > > If you incorrectly assume it was a, then the example doesn't work. > > >>> print len(a) > Traceback (most recent call last): > File "", line 1, in > print len(a) > TypeError: object of type 'int' has no len() > > You have to know that a variable is a string before you try to do a > len(). > > Dynamic typing is a feature, but that doesn't relieve you of the > necessary tests. Your point would be important if the question were "How can I tell if x is an empty string?" On the other hand, "How to check if a string is empty?" implies that the OP already knows it is a string. Maybe he's been using string methods on it, maybe he got it from a function that he knows provides a string. Maybe he's checked its type. It doesn't really matter, if he's aware it is a string he doesn't have to test it for stringness. --- -Bill Hamilton From larry.bates at websafe.com Tue May 1 09:52:03 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 01 May 2007 08:52:03 -0500 Subject: Want to build a binary header block In-Reply-To: References: Message-ID: <46374603.2080102@websafe.com> Bob Greschke wrote: > This is the idea > > Block = pack("240s", "") > Block[0:4] = pack(">H", W) > Block[4:8] = pack(">H", X) > Block[8:12] = pack(">B", Y) > Block[12:16] = pack(">H", Z)) > > but, of course, Block, a str, can't be sliced. The real use of this is a > bit more complicated such that I can't just fill in all of the "fields" > within Block in one giant pack(). I need to build it on the fly. For > example the pack(">H", X) may be completely skipped some times through the > function. There are many more fields in Block than in this example and they > are all kinds of types not just H's and B's. What I really want is a C > struct union. :) > > How would I do this? > > Thanks! > > Bob > > When I have something like this I normally write a class for it and make its __str__ method return the packed output. Example (not tested, but you should get the drift): import struct class blockStruct: def __init__(self): self.hstring=240*" " self.W=None self.X=None self.Y=None self.Z=None return def __str__(self): rtnvals=[] rtnvals.append(struct.pack("240s", self.hstring) rtnvals.append(struct.pack(">H", W)) . . . return ''.join(rtnvals) Then in your main program bS=blockStruct() bs.hstring='this is a test'.ljust(240, ' ') bs.W=12 bs.X=17 bs.Y=1 bs.Z=0 print bS Seemed to be a good way that made debugging and understanding easy for me. -Larry From elventear at gmail.com Mon May 14 15:05:15 2007 From: elventear at gmail.com (elventear) Date: 14 May 2007 12:05:15 -0700 Subject: Recursion limit problems In-Reply-To: References: <1178921877.442519.165740@u30g2000hsc.googlegroups.com> <1179156916.706892.144770@y80g2000hsf.googlegroups.com> Message-ID: <1179169515.850123.54190@y80g2000hsf.googlegroups.com> On May 14, 1:20 pm, "Terry Reedy" wrote: > > Dicts first compare hashes and if they are equal, then check equality. If > two unequal strings have the same hash value, as is possible of course > (given only 2**32 possible hashes and many more possible strings), both can > still be used as different keys. Ditto for unequal numbers. Or for a > number and string with equal hashes. And so on. The first quoted > sentence, about mixing, is directed at minimizing such hash collisions. Now my question is, since the definition mentions __cmp__ explicity. Is that the only function it uses? What if __ne__, __eq__ are defined, but not __cmp__? Finally I am still confused about the inequality. Does dict only care about the __cmp__ ouput being 0 and ignore the rest, or does it make use of -1,1 as well? Could I just say that 0 defines equality in my object and 1 otherwise, without regard of it being less than or greater than? Thanks! From robert.rawlins at thinkbluemedia.co.uk Tue May 1 22:21:09 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Wed, 2 May 2007 03:21:09 +0100 Subject: Killing Threads Message-ID: <000d01c78c60$8c0056d0$a4010470$@rawlins@thinkbluemedia.co.uk> Hello Guys, I've got an application which I've fearfully placed a couple of threads into however when these threads are running it seems as if I try and quite the application from the bash prompt it just seems to freeze the SSH client. I've also seen that if I have my app running in the background on the system then my 'reboot' no longer works, it just hangs after saying it's going to shut down. Is there anything specific i should be doing to kill my threads? Thanks, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From snewman18 at gmail.com Thu May 31 09:54:49 2007 From: snewman18 at gmail.com (snewman18 at gmail.com) Date: 31 May 2007 06:54:49 -0700 Subject: How do I Extract Attachment from Newsgroup Message Message-ID: <1180619689.128854.29180@q75g2000hsh.googlegroups.com> I'm parsing NNTP messages that have XML file attachments. How can I extract the encoded text back into a file? I looked for a solution with mimetools (the way I'd approach it for email) but found nothing. Here's a long snippet of the message: >>> n.article('116431') ('220 116431 article', '116431', '', ['MIME-Version: 1.0', 'Message-ID: ', 'Content-Type: Multipart/Mixed;', ' boundary="------------Boundary-00=_A5NJCP3FX6Y5BI3BH890"', 'Date: Thu, 24 May 2007 07:41:34 -0400 (EDT)', 'From: Newsclip ', 'Path: newsclip.ap.org!flounder.ap.org!flounder', 'Newsgroups: ap.spanish.online,ap.spanish.online.business', 'Keywords: MUN ECO PETROLEO PRECIOS', 'Subject: MUN ECO PETROLEO PRECIOS', 'Summary: ', 'Lines: 108', 'Xref: newsclip.ap.org ap.spanish.online:938298 ap.spanish.online.business:116431', '', '', '-------------- Boundary-00=_A5NJCP3FX6Y5BI3BH890', 'Content-Type: Text/Plain', 'Content-Transfer-Encoding: 8bit', 'Content-Description: text, unencoded', '', '(AP) Precios del crudo se mueven sin rumbo claro', 'Por GEORGE JAHN', 'VIENA', 'Los precios ... (truncated for length) ... '', '___', '', 'Editores: Derrick Ho, periodista de la AP en Singapur, contribuy\xf3 con esta informaci\xf3n.', '', '', '-------------- Boundary-00=_A5NJCP3FX6Y5BI3BH890', 'Content-Type: Text/Xml', 'Content- Transfer-Encoding: base64', 'Content-Description: text, base64 encoded', '', 'PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPCFET0NUWVBFIG5pdGYgU1lT', 'VEVNICJuaXRmLmR0ZCI+CjxuaXRmPgogPGhlYWQ +CiAgPG1ldGEgbmFtZT0iYXAtdHJhbnNyZWYi', 'IGNvbnRlbnQ9IlNQMTQ3MiIvPgogIDxtZXRhIG5hbWU9ImFwLW9yaWdpbiIgY29udGVudD0ic3Bh', 'bm9sIi8+CiAgPG1ldGEgbmFtZT0iYXAtc2VsZWN0b3IiIGNvbn From revuesbio at gmail.com Mon May 7 04:18:36 2007 From: revuesbio at gmail.com (revuesbio) Date: 7 May 2007 01:18:36 -0700 Subject: msbin to ieee In-Reply-To: <1178502738.104124.3840@h2g2000hsg.googlegroups.com> References: <1178487847.671199.108140@h2g2000hsg.googlegroups.com> <1178502738.104124.3840@h2g2000hsg.googlegroups.com> Message-ID: <1178525916.145819.264070@n59g2000hsh.googlegroups.com> On 7 mai, 03:52, John Machin wrote: > On May 7, 7:44 am, revuesbio wrote: > > > Hi > > Does anyone have the python version of the conversion from msbin to > > ieee? > > Thank u > > Yes, Google has it. Google is your friend. Ask Google. It will lead > you to such as: > > http://mail.python.org/pipermail/python-list/2005-August/337817.html > > HTH, > John Thank you, I've already read it but the problem is always present. this script is for double precision MBF format ( 8 bytes). I try to adapt this script for single precision MBF format ( 4 bytes) but i don't find the right float value. for example : 'P\xad\x02\x95' will return '0.00024924660101532936' From "ruili_gc(NO_SPAM)" at earthlink.net Tue May 1 23:03:28 2007 From: "ruili_gc(NO_SPAM)" at earthlink.net (NO_SPAM) Date: Wed, 02 May 2007 03:03:28 GMT Subject: python win32com excel problem In-Reply-To: <4KQZh.214$o47.98@newsfe12.lga> References: <4KQZh.214$o47.98@newsfe12.lga> Message-ID: <4cTZh.10756$3P3.9860@newsread3.news.pas.earthlink.net> Bart Willems wrote: > Ray wrote: >> Hi, >> I tried to call "xlApp.Columns.AutoFit=1" the whole program will crash, >> but without xlApp.Columns.AutoFit=1, everything just fine. > > Autofit is a method. Also, columns are a method of a worksheet - try: > xlApp.Worksheets.Columns("C:K").Autofit() > (or whatever columns you need of course) > >> 2. How do I set a rows format? I need to set row "F" to "Text", >> "o","p" to general, and >> "Q", "R", to currency. > > Same story: you will need to define the range first. > xlApp.Worksheets.Rows("10:200").Numberformat = "General" > I think that you actually mean columns, and not rows - columns have > character designators, rows have numbers. In that case, try something > like xlApp.Activesheet.Columns("F") = "@" (text format), or the other > appropiate codes for number formatting as required. I usually pick > "#,##0.00" to display numbers with two decimals and thousands seperators. > > Cheers, > Bart Thanks a lot!! Ray From bj_666 at gmx.net Tue May 8 12:37:26 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 08 May 2007 18:37:26 +0200 Subject: Atttribute error References: <1178641784.974581.14000@p77g2000hsh.googlegroups.com> Message-ID: In <1178641784.974581.14000 at p77g2000hsh.googlegroups.com>, HMS Surprise wrote: > The snippet below causes an attribute error. > > AttributeError: module 'urllib' has no attribute 'urlopen' > > I am using python 2.2.3. According to the documentation at C: > \Python22\Doc\lib urllib has a function called urlopen. Do you have a file called `urllib.py` in the current directory? Then this gets imported instead of the module in the standard library. Add this directly after the ``import`` to see what's happening: print urllib.__file__ print dir(urllib) Ciao, Marc 'BlackJack' Rintsch From jgodoy at gmail.com Thu May 3 10:17:19 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Thu, 03 May 2007 11:17:19 -0300 Subject: SQLObject 0.8.3 References: Message-ID: <874pmu3sb4.fsf@gmail.com> Oleg Broytmann writes: > * Fixed sqlbuilder - .startswith(), .endswith() and .contains() assumed > their parameter must be a string; now you can pass an SQLExpression: > Table.q.name.contains(func.upper('a')), for example. Oleg, this made me think: is it possible to call a function in a schema other than public in PostgreSQL? For example if I had myschema.myfunction and wanted to use it I can't do "func.myschema.myfunction"... Is there something like a "dbName" for func? :-) -- Jorge Godoy From mattheww at chiark.greenend.org.uk Tue May 15 20:12:17 2007 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 16 May 2007 01:12:17 +0100 (BST) Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <4649a561$0$10187$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <9cA*ymPKr@news.chiark.greenend.org.uk> Thorsten Kampe wrote: >* Ren? Fleschenberg (Tue, 15 May 2007 14:35:33 +0200) >> I am talking about the stdlib, not about the very few keywords Python >> has. Are you going to re-write the standard library in your native >> language so you can have a consistent use of natural language among your >> code? > Why would I want to do that? It's not my code. Identifier names are > mine. If I use modules from standard library I use some "foreign > words". There's no problem in that. It could even be an advantage. I sometimes find that I have to use a 'second best' name myself because I want to avoid the possible confusion caused if I choose a name which has a well-known existing use. -M- From grante at visi.com Thu May 24 16:28:25 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 24 May 2007 20:28:25 -0000 Subject: trouble converting c++ bitshift to python equivalent References: <1180037677.633613.30160@u30g2000hsc.googlegroups.com> Message-ID: <135btb97ttsf975@corp.supernews.com> On 2007-05-24, nanodust at gmail.com wrote: > hello all > > i am relatively new to python, catching on, but getting stuck on > simple thing: > > i have two string bytes i need to push into a single (short) int, like > so in c: > > temp = strBuf[2]; > > temp = (temp<<7)+(strBuf[1]); (ord(strBuf[2])<<7) + ord(strBuf[1]) -- Grant Edwards grante Yow! This PORCUPINE knows at his ZIPCODE ... And he has visi.com "VISA"!! From google at mrabarnett.plus.com Mon May 7 18:23:57 2007 From: google at mrabarnett.plus.com (MRAB) Date: 7 May 2007 15:23:57 -0700 Subject: is for reliable? In-Reply-To: References: Message-ID: <1178576637.508646.262670@q75g2000hsh.googlegroups.com> On May 7, 8:46 pm, "pablo... at giochinternet.com" wrote: > Hi to all I have a question about the for statement of python. I have the > following piece of code where cachefilesSet is a set that contains the > names of 1398 html files cached on my hard disk > > for fn in cachefilesSet: > > fObj = codecs.open( baseDir + fn + '-header.html', 'r', 'iso-8859-1' ) > u = fObj.read() > > v = u.lower() > rows = v.split('\x0a') > > contentType = '' > > for r in rows: > if r.find('content-type') != -1: > y = r.find(':') > if y != -1: > z = r.find(';', y) > if z != -1: > contentType = r[y+1:z].strip() > cE = r[z+1:].strip() > characterEncoding = cE.strip('charset = ') > else: > contenType = r[y+1:].strip() > characterEncoding = '' > break > > if contentType == 'text/html': > processHTMLfile( baseDir + fn + '-body.html', characterEncoding, cardinalita ) > > fileCnt += 1 > if fileCnt % 100 == 0: print fileCnt > [snip] I'd like to point out what look like 2 errors in the code: 1. You have "contenType" instead of "contentType" in "contenType = r[y +1:].strip()". 2. The string method "strip(...)" treats its string argument as a _set_ of characters to strip, so "cE.strip('charset = ')" will strip any leading and trailing "c", "h", "a", etc., which isn't what I think you intended. From rene at korteklippe.de Tue May 15 06:34:25 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 15 May 2007 12:34:25 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46483740.4050406@web.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <4648252D.5020704@web.de> <46483740.4050406@web.de> Message-ID: <46498cb1$0$6411$9b4e6d93@newsspool2.arcor-online.net> Stefan Behnel schrieb: > Ok, but then maybe that code just will not become Open Source. There's a > million reasons code cannot be made Open Source, licensing being one, lack of > resources being another, bad implementation and lack of documentation being > important also. > > But that won't change by keeping Unicode characters out of source code. Allowing non-ASCII identifiers will not change existing hindrances for code-sharing, but it might add a new one. IMO, the burden of proof is on you. If this PEP has the potential to introduce another hindrance for code-sharing, the supporters of this PEP should be required to provide a "damn good reason" for doing so. So far, you have failed to do that, in my opinion. All you have presented are vague notions of rare and isolated use-cases. > I'm only saying that this shouldn't be a language restriction, as there > definitely *are* projects (I know some for my part) that can benefit from the > clarity of native language identifiers (just like English speaking projects > benefit from the English language). And yes, this includes spelling native > language identifiers in the native way to make them easy to read and fast to > grasp for those who maintain the code. If a maintenance programmer does not understand enough English to be able to easily cope with ASCII-only identifiers, he will have a problem anyway, since it will be very hard to use the standard library, the documentation, and so on. -- Ren? From mikeminer53 at hotmail.com Thu May 24 01:41:38 2007 From: mikeminer53 at hotmail.com (mkPyVS) Date: 23 May 2007 22:41:38 -0700 Subject: Resizing listbook's listview pane In-Reply-To: <1179981879.346887.281620@r19g2000prf.googlegroups.com> References: <1179939217.550237.300830@o5g2000hsb.googlegroups.com> <1179949661.695477.167450@m36g2000hse.googlegroups.com> <1179981879.346887.281620@r19g2000prf.googlegroups.com> Message-ID: <1179985298.360208.309740@q19g2000prn.googlegroups.com> On May 23, 10:44 pm, mkPyVS wrote: So the issue was that the min-size of the content panel actually limits the size of the listview control. Once the minsize attribute is modified in the listbook panels the listview can then be resized to be wider on callback or with a custom sizer... Now on to figure out how to change the displayed text width. Thanks, Mike From duncan-news at grisby.org Tue May 22 04:48:07 2007 From: duncan-news at grisby.org (Duncan Grisby) Date: Tue, 22 May 2007 08:48:07 GMT Subject: Components for a client/server architecture References: <5bd99qF2s85heU1@mid.uni-berlin.de> Message-ID: In article , Samuel wrote: [...] >> Sounds like CORBA to me. CORBA has a very mature and good implementation >> for Python called OmniORB, and interoperability with other orbs (the >> ones available for e.g. Java) is very good - as CORBA as standard is >> mature. > >I have worked with Bonobo (an implementation of CORBA) before, though not >on the network - it is fairly complex. But I did not think of using it >for this purpose, it might actually make sense. I'll have to look into >the transport protocol more. To be clear, Bonobo is not an implementation of CORBA. It is a (somewhat byzantine) implementation of a component model on top of CORBA. CORBA certainly has some complex corners, but for many of the most common application requirements it is pretty simple, and buys you a lot in terms of cross-platform compatibility and clarity of interfaces. Cheers, Duncan. -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- From joshua at eeinternet.com Tue May 8 17:19:07 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Tue, 08 May 2007 13:19:07 -0800 Subject: ANN: vuLookup.py, a TCP lookup server for Postfix Message-ID: <4640dcf7$1$16346$88260bb3@free.teranews.com> We needed it, so we wrote it. Announcing vuLookup.py 1.0 vuLookup.py is a TCP lookup table server for Postfix, written in Python. It reads an ini file and uses the values therein to answer requests for virtual users, as well as virtual domains. You can download it here: http://www.eeinternet.com/opensource.html No warranties are made, but this code has been in production for several weeks now, so is known to perform its assigned duties. Comments, questions, critiques welcome! >From a comment on a mailing list: > I think you should explain the value if this. the basic thing is the > value compared to a hash map. but depending on how it works, comparison > with mysql/ldap may be good too. The main motivation for this was less overhead vs. a database or ldap solution. The INI file is very simple, and it is easy for even non-technical users to understand. Changes made to the ini file are seen at the reload interval, no postmap (as root) command required if the ini file is in a group that has edit permissions. We are a small shop (about 10 clients, maybe 80 e-mail accounts) and a database or ldap solution would have been too much work, especially if we went and made an interface for editing the aliases. Also, since we are using dspam, we wanted to "resolve" all the aliases before the messages were sent to dspam (we're using postfix -> dspam -> postfix) and since the virtualusertable didn't take file arguments for expansion, it wasn't going to work to put all the entries directly in the virtualusertable map. I this system, we've moved pretty much everything (even stuff that used to be in the "aliases" file) into the virtualusertable.ini file. Hope that answers some questions. If you have any more, feel free to ask! j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE -- Posted via a free Usenet account from http://www.teranews.com From http Sun May 27 15:46:18 2007 From: http (Paul Rubin) Date: 27 May 2007 12:46:18 -0700 Subject: Is PEP-8 a Code or More of a Guideline? References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <87myzqpstb.fsf@benfinney.id.au> <1180282164.427316.51710@p47g2000hsd.googlegroups.com> Message-ID: <7xk5uu2gol.fsf@ruckus.brouhaha.com> Paul McGuire writes: > code about once/year. But it does mean that additions to the external > API to the std lib will contain method calls such as get_files, > send_message, delete_record, etc. I think this just promotes a > perception of Python as "so last century." I think you've got it backwards; the godawful MixedCase style goes back to Smalltalk, which couldn't use underscores in identifiers because it had assigned some other purpose to that character. That it was picked up by Java is not evidence of anything other than Java's Vogon-like tastelessness, and of course C# uses it since C# is basically a Java dialect. From roger.miller at nova-sol.com Fri May 4 21:03:58 2007 From: roger.miller at nova-sol.com (Roger Miller) Date: 4 May 2007 18:03:58 -0700 Subject: behavior difference for mutable and immutable variable in function definition In-Reply-To: <1178318341.669871.294390@n76g2000hsh.googlegroups.com> References: <1178314206.701824.291560@n59g2000hsh.googlegroups.com> <1178318341.669871.294390@n76g2000hsh.googlegroups.com> Message-ID: <1178327038.494994.164260@w5g2000hsg.googlegroups.com> On May 4, 12:39 pm, 7stud wrote: > On May 4, 3:30 pm, jianbing.c... at gmail.com wrote: > > > > > Hi, > > > Can anyone explain the following: > > > Python 2.5 (r25:51908, Apr 9 2007, 11:27:23) > > [GCC 4.1.1 20060525 (Red Hat 4.1.1-1)] on linux2 > > Type "help", "copyright", "credits" or "license" for more information.>>> def foo(): > > > ... x = 2 > > ...>>> foo() > > >>> def bar(): > > > ... x[2] = 2 > > ... > > > >>> bar() > > > Traceback (most recent call last): > > File "", line 1, in > > File "", line 2, in bar > > NameError: global name 'x' is not defined > > > Thanks, > > Jianbing > > The first function is completely irrelevant unless you expect this to > work: > > x = 2 > x[2] = 2 > > Traceback (most recent call last): > File "test1.py", line 2, in ? > x[2] = 2 > TypeError: object does not support item assignment > > So that leaves you with: > > > >>> def bar(): > > > ... x[2] = 2 > > ... > > > >>> bar() > > Would you expect this to work: > > x[2] = 2 > print x I will sympathize with the OP to the extent that the message "global name 'x' is not defined" is a bit misleading. All that the interpreter really knows is that 'x' is not defined, locally or globally, and it should probably not presume to guess the coder's intention. From xi at gamma.dn.ua Sat May 12 18:37:58 2007 From: xi at gamma.dn.ua (Kirill Simonov) Date: Sun, 13 May 2007 01:37:58 +0300 Subject: [ANN] PyYAML-3.05: YAML parser and emitter for Python Message-ID: <200705130137.58248.xi@gamma.dn.ua> ======================== Announcing PyYAML-3.05 ======================== A new bug fix release of PyYAML is now available: http://pyyaml.org/wiki/PyYAML Changes ======= * Windows binary packages were built with LibYAML trunk. * Fixed a bug that prevent processing a live stream of YAML documents in timely manner (Thanks edward(at)sweetbytes(dot)net). * Fixed a bug when the path in add_path_resolver contains boolean values (Thanks jstroud(at)mbi(dot)ucla(dot)edu). * Fixed loss of microsecond precision in timestamps (Thanks edemaine(at)mit(dot)edu). * Fixed loading an empty YAML stream. * A number of smaller fixes and improvements (see http://pyyaml.org/wiki/PyYAML#History for more details). Resources ========= PyYAML homepage: http://pyyaml.org/wiki/PyYAML PyYAML documentation: http://pyyaml.org/wiki/PyYAMLDocumentation TAR.GZ package: http://pyyaml.org/download/pyyaml/PyYAML-3.05.tar.gz ZIP package: http://pyyaml.org/download/pyyaml/PyYAML-3.05.zip Windows installer: http://pyyaml.org/download/pyyaml/PyYAML-3.05.win32-py2.3.exe http://pyyaml.org/download/pyyaml/PyYAML-3.05.win32-py2.4.exe http://pyyaml.org/download/pyyaml/PyYAML-3.05.win32-py2.5.exe PyYAML SVN repository: http://svn.pyyaml.org/pyyaml Submit a bug report: http://pyyaml.org/newticket?component=pyyaml YAML homepage: http://yaml.org/ YAML-core mailing list: http://lists.sourceforge.net/lists/listinfo/yaml-core About PyYAML ============ YAML is a data serialization format designed for human readability and interaction with scripting languages. PyYAML is a YAML parser and emitter for Python. PyYAML features a complete YAML 1.1 parser, Unicode support, pickle support, capable extension API, and sensible error messages. PyYAML supports standard YAML tags and provides Python-specific tags that allow to represent an arbitrary Python object. PyYAML is applicable for a broad range of tasks from complex configuration files to object serialization and persistance. Example ======= >>> import yaml >>> yaml.load(""" ... name: PyYAML ... description: YAML parser and emitter for Python ... homepage: http://pyyaml.org/wiki/PyYAML ... keywords: [YAML, serialization, configuration, persistance, pickle] ... """) {'keywords': ['YAML', 'serialization', 'configuration', 'persistance', 'pickle'], 'homepage': 'http://pyyaml.org/wiki/PyYAML', 'description': 'YAML parser and emitter for Python', 'name': 'PyYAML'} >>> print yaml.dump(_) name: PyYAML homepage: http://pyyaml.org/wiki/PyYAML description: YAML parser and emitter for Python keywords: [YAML, serialization, configuration, persistance, pickle] Copyright ========= The PyYAML module is written by Kirill Simonov . PyYAML is released under the MIT license. From afriere at yahoo.co.uk Thu May 10 04:53:39 2007 From: afriere at yahoo.co.uk (Asun Friere) Date: 10 May 2007 01:53:39 -0700 Subject: Newbie Prob : IDLE can't import Tkinter In-Reply-To: References: Message-ID: <1178787219.280717.146400@e65g2000hsc.googlegroups.com> On May 10, 6:31 pm, Romain FEUILLETTE wrote: > Hello, > > I'have just install Python 2.5.1 on Linux and the IDLE doesn't seem to > works because it didn't find Tcl/Tk > Perhaps you haven't installed Tkinter? I'm not sure which distribution you are using, but on my box (with Python2.4 installed) the relevant package is tkinter-2.4.4-1.fc6.rpm. From jorgen.maillist at gmail.com Mon May 21 16:00:52 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Mon, 21 May 2007 22:00:52 +0200 Subject: Python and GUI In-Reply-To: <1179776176.28714.21.camel@contra.chem.byu.edu> References: <1179761984.704369.116310@b40g2000prd.googlegroups.com> <4651C776.30105@redhat.com> <1179776176.28714.21.camel@contra.chem.byu.edu> Message-ID: <11e49df10705211300k4a2c6ba4h879d82bfff766ebe@mail.gmail.com> Well wxPython offers all of the above. They use XRC which is a XML file which can be loaded inside the GUI, that auto-creates the components + layout for you. It also supports creating the gui programatically, which might be very handy when your layout is undetermined or changes when users select options etc. I use wxPython because I am used to wxWidgets C++ and it is very good under python (I am a python newbie and the integration in python is fine). I use wxGlade to auto generate the GUI from inside the GUI designer, works great as well As for tkinter, PyQt or PyGTK, I do not have much experience with them. You don't change a winning formula ;-) - Jorgen On 5/21/07, Michael L Torrie wrote: > On Mon, 2007-05-21 at 18:23 +0200, Petr Muller wrote: > > There's PyQt thingy, imho very good and easy to learn/use, but still > > powerful. I've used it for a small gui-oriented project with almost no > > problems and it worked like a charm. However, sometimes I had troubles > > finding useful documentation for it. > > I've also tried to play with PyGTK, it's quite nice and easy (and you > > have the advantage of Glade), but I don't like GTK way of creating GUI. > > I haven't used Tkinter a lot, only looked at it. And I didn't like it much. > > How does GTK's way of creating the GUI (I presume you're not talking > look and feel) differ from Qt's? From what I can see (having developed > large apps in both GTKmm and Qt (C++), they both function the same. In > other words you create the widget first, then parent it in a container > and add callbacks. Whereas wxPython's approach is somewhat different. > > It appears that most wxPython apps setup the GUI programmatically, > whereas Most Qt and Gtk apps tend to use XML-based gui-building > factories. In this latter case, Glade's method is quite different from > Qt's. > > > > > I would really suggest PyQt. (with a big IMHO :) > > > > Petr > > -- > http://mail.python.org/mailman/listinfo/python-list > From S.Mientki-nospam at mailbox.kun.nl Thu May 24 15:51:00 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Thu, 24 May 2007 21:51:00 +0200 Subject: Can I reference 1 instance of an object by more names ? rephrase In-Reply-To: References: <4654289a$0$2326$426a74cc@news.free.fr> Message-ID: <3dc25$4655ebd1$d443bb3a$31378@news.speedlinq.nl> Maric Michaud wrote: > def bit(): > def fset(self, value): > index = 5 > value = ( value & 1L ) << index > mask = ( 1L ) << index > self._d = ( self._d & ~mask ) | value > def fget(self): > index = 5 > return ( self._d >> index ) & 1 > return property(**locals()) > > > class cpu_ports(object) : > > p1 = bit() > p2 = bit() > p3 = bit() > p4 = bit() > p5 = bit() > Looks good, but I miss the index :-( p3 = bit(3) I tried several of these kind of constructs, but I can't find a way to pass the index of the bit, all trials gave Python errors. This is obvious above my level of knowledge. So if this isn't possible, I just use the 8 copies ;-) > But i wonder if you shouldn't use arrays instead : > > In [6]:import array > > In [7]:help(array) > I don't think arrays will help, because most operations will be done on a complete byte. btw, the first notes about what I'm planning to do, can be seen here: http://oase.uci.ru.nl/~mientki/data_www/pic/jalcc/python/jal_simulation.html thanks, Stef Mientki > > > From half.italian at gmail.com Mon May 14 17:00:03 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 14 May 2007 14:00:03 -0700 Subject: Path python versions and Macosx In-Reply-To: <1179143193.232099.285980@u30g2000hsc.googlegroups.com> References: <1178915809.065874.133030@o5g2000hsb.googlegroups.com> <1178924996.452067.308320@h2g2000hsg.googlegroups.com> <1179143193.232099.285980@u30g2000hsc.googlegroups.com> Message-ID: <1179176403.535076.185320@u30g2000hsc.googlegroups.com> On May 14, 4:46 am, andrea wrote: > On 12 Mag, 01:09, half.ital... at gmail.com wrote: > > > > > On May 11, 1:36 pm, andrea wrote: > > > > Hi everyone, > > > I use python on macosx with textmate as editor (great program). > > > > I also use macport to install unix programs from the command line and > > > I find it great too. > > > Well I would like to have all my modules in the path when I'm using > > > textmate AND when I use the commandline (ipython), but because > > > textmate and the command line use different python versions they also > > > search in different places.. > > > > I found somewhere to write .pythonrc.py like this > > > > #!/usr/bin/env python > > > import sys > > > PATH='/opt/local/lib/python2.4/site-packages/' > > > sys.path.append(PATH) > > > del sys > > > > But it doesn't work either, I also tried to append this > > > PATH="/Library/Frameworks/Python.framework/Versions/Current/bin:/opt/ > > > local/lib/python2.4/site-packages:${PATH} > > > to .bash_profile but nothing. > > > > Where should I set this variables?? > > > > Thanks a lot > > > You can set environment variables for gui apps with this freeware:http://www.versiontracker.com/dyn/moreinfo/macosx/15073 > > > You can edit some text files as well, but this thing just makes it > > much easier. > > > ~Sean > > Ok thanks, but why it doesn't work setting the .bash_profile?? What > should I set manually theorically?? The problem is also that I have > many modules for python 2.4 and trying to import them from the 2.5 of > course gives errors.. > I installed them with macports (compiling), how can I make them switch > to 2.5??? > thanks Gui applications are not launched through the bash shell. The .bash_profile never gets read. You can accomplish the same thing as the freewware app I mentioned by editing the xml file at ~/.MacOSX/environment.plist. Its a simple xml file with keys and their corresponding values. Not sure about the modules. You can force a script to look for libs in a given directory like you mentioned, but that needs to go at the top of each python file instead of a .pythonrc file. Maybe the modules will work with 2.5, maybe not. ~Sean From 2007 at jmunch.dk Mon May 14 12:01:11 2007 From: 2007 at jmunch.dk (Anders J. Munch) Date: Mon, 14 May 2007 18:01:11 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <4648252D.5020704@web.de> <46483740.4050406@web.de> Message-ID: <46488865$0$4161$ba624c82@nntp02.dk.telia.net> Eric Brunel wrote: > You could tell that the rule should be that if the project has the > slightest chance of becoming open-source, or shared with people not > speaking the same language as the original coders, one should not use > non-ASCII identifiers. I'm personnally convinced that *any* industrial > project falls into this category. So accepting non-ASCII identifiers is > just introducing a disaster waiting to happen. Not at all. If the need arises, you just translate the whole thing. Contrary to popular belief, this is a quick and easy thing to do. So YAGNI applies, and even if you find that you do need it, you may still have won on the balance! As the time saved by using your native language just might outweigh the time spent translating. - Anders From python at rcn.com Sat May 19 13:19:44 2007 From: python at rcn.com (Raymond Hettinger) Date: 19 May 2007 10:19:44 -0700 Subject: Many-to-many pattern possiable? In-Reply-To: <1179592414.652507.4110@p77g2000hsh.googlegroups.com> References: <1179592414.652507.4110@p77g2000hsh.googlegroups.com> Message-ID: <1179595183.999677.323410@p47g2000hsd.googlegroups.com> On May 19, 9:33 am, Jia Lu wrote: > I see dict type can do 1-to-1 pattern, But is there any method to do > 1-to-many, many-to-1 and many-to-many pattern ? >>> mm = {'a': ['A', 'B', 'C'], 'c': ['C', 'D', 'E'], 'b': ['A', 'D']} >>> # Now, invert the relation >>> mmr = {} >>> for k, seq in mm.items(): ... for elem in seq: ... mmr.setdefault(elem, []).append(k) >>> mmr {'A': ['a', 'b'], 'C': ['a', 'c'], 'B': ['a'], 'E': ['c'], 'D': ['c', 'b']} > What about using some > Serialized objects? from pickle import loads, dumps d = dict(a=dumps(someobj), b=dumps(anotherobj)) obj = loads(d['a']) Raymond From bbxx789_05ss at yahoo.com Thu May 3 13:32:41 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 3 May 2007 10:32:41 -0700 Subject: sqlite for mac? In-Reply-To: References: <1177993261.572563.70370@n76g2000hsh.googlegroups.com> <5f56302b0705010308h5c3f64a8ka05cd92de879f6bd@mail.gmail.com> <1178165109.102244.188860@c35g2000hsg.googlegroups.com> Message-ID: <1178213561.252237.171420@c35g2000hsg.googlegroups.com> On May 3, 8:37 am, "Daniel Nogradi" wrote: > > If all tests ran fine then pysqlite can see your sqlite installation. > How are you importing sqlite? It's usually something like "from > pysqlite2 import dbapi2 as sqlite" not simply "import sqlite". > I just checked the errata for the book, and it says to use the import statement you suggested: > from pysqlite2 import dbapi2 as sqlite From jUrner at arcor.de Tue May 15 15:13:37 2007 From: jUrner at arcor.de (=?iso-8859-1?q?J=FCrgen_Urner?=) Date: 15 May 2007 12:13:37 -0700 Subject: Get a control over a window In-Reply-To: <1179234413.915336.263660@n59g2000hsh.googlegroups.com> References: <1179234413.915336.263660@n59g2000hsh.googlegroups.com> Message-ID: <1179256416.956735.150110@e65g2000hsc.googlegroups.com> On 15 Mai, 15:06, Tom Gur wrote: > Hi, > > I was wondering how do I get control over a window (Win32). > to be more specific, I need to find a handle to a window of a certain > program and minimize the window. There are many ways to get the handle of a window. Assuming you have ctypes at hand, you could try: >> user32 = ctypes.windll.user32 >> hwnd = user32.FindWindowA(classname, title) >> if hwnd: >> user32.PostMessageA(hwnd, WM_SYSCOMMAND, SC_ICON, 0) If you need it more acurate you could search MSDN for how to enumerate all running processes and get the handles of their windows. Process32First (...) could be a start for reading. J?rgen From brad_brock at yahoo.com Sat May 19 13:40:55 2007 From: brad_brock at yahoo.com (Brad Brock) Date: Sat, 19 May 2007 10:40:55 -0700 (PDT) Subject: getting thread object from SocketServer.ThreadingTCPServer Message-ID: <454738.13521.qm@web54111.mail.re2.yahoo.com> Hi list. I have a little problem when using SocketServer.ThreadingTCPServer. I want to make a list of thread-objects generated by the ThreadingTCPServer. How can I get the thread object? Thank you. ____________________________________________________________________________________Looking for a deal? Find great prices on flights and hotels with Yahoo! FareChase. http://farechase.yahoo.com/ From saif.shakeel at gmail.com Wed May 9 07:57:42 2007 From: saif.shakeel at gmail.com (saif.shakeel at gmail.com) Date: 9 May 2007 04:57:42 -0700 Subject: Problems in string replacement Message-ID: <1178711862.894346.212580@l77g2000hsb.googlegroups.com> HI, Thanks for the reply.that seems to work,but i was doing this so as to attach it to a bigger code where it will be utilised before a parsing. #Input file and Output file path from user file_input = raw_input("Enter The ODX File Path:") (shortname,ext)=os.path.splitext(file_input) f_open_out=shortname+".ini" log=shortname+".xls" test_file=shortname+"testxml.xml" saveout = sys.stdout input_xml = open(file_input,'r') xmlcont=input_xml.read() xmlcont=xmlcont.replace('localId','dataPackageId') output_file = open(test_file,"w") output_file.write(xmlcont) output_file.close() f_open=open(f_open_out, 'w') logfile=open(log,"w") sys.stdout = f_open #Parse the input file,and check for correct ODX version xmldoc = minidom.parse(input_xml) I am opening 2 more files in addition to the file where the new xml goes.One file is written using the sys.stdout command as most of the output has to go there printing takes place in many places (so cant use f_open.write) each time. When i attach the part of replacing the string 'localid' in xml file with something else as given above with xmlcont=xmlcont.replace('localId','dataPackageId') the code does not run and hangs.Can more than 3 files be opened at a time .I dotn know what the problem is here. Thanks From bob at snee.com Tue May 22 19:03:15 2007 From: bob at snee.com (bob at snee.com) Date: 22 May 2007 16:03:15 -0700 Subject: trying to gzip uncompress a StringIO In-Reply-To: <46536E01.2080702@lexicon.net> Message-ID: <1179874995.129700.286400@p47g2000hsd.googlegroups.com> Perfect, thanks! Now I have a working WMF file and everything. Bob From stefan.behnel-n05pAM at web.de Tue May 15 07:39:37 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 15 May 2007 13:39:37 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46499940$0$10199$9b4e6d93@newsspool4.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476081.7080609@web.de> <46498514$0$6402$9b4e6d93@newsspool2.arcor-online.net> <4649882E.3060005@web.de> <46499940$0$10199$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <46499BF9.30209@web.de> Ren? Fleschenberg wrote: > Stefan Behnel schrieb: >> Sounds like high time for an editor that supports the project team in their >> work, don't you think? > > I think your argument about "isolated projects" is flawed. It is not at > all unusual for code that was never intended to be public, whose authors > would have sworn that it will never ever be need to read by anyone > except themselves, to surprisingly go public at some point in the future. Ok, but how is "using non-ASCII identifiers" different from "using mandarin tranliterated ASCII identifiers" in that case? Please try to understand what the point of this PEP is. Stefan From steve at REMOVEME.cybersource.com.au Wed May 2 21:33:59 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Thu, 03 May 2007 11:33:59 +1000 Subject: Slicing Arrays in this way References: <4638fe20$0$16403$88260bb3@free.teranews.com> <1178146865.383519.326430@c35g2000hsg.googlegroups.com> Message-ID: On Wed, 02 May 2007 16:01:05 -0700, John Machin wrote: > The OP has already confessed. Don't rub it in. Sorry, I sent my comment before I received his confession. -- Steven D'Aprano From jsaacmk at gmail.com Wed May 16 13:36:14 2007 From: jsaacmk at gmail.com (jsaacmk at gmail.com) Date: 16 May 2007 10:36:14 -0700 Subject: pyhdf Message-ID: <1179336974.691021.106680@k79g2000hse.googlegroups.com> Has anyone had success installing the pyhdf library with python 2.4 under linux 2.6.18 (debian)? I have installed the HDF library and development package from apt and have downloaded the pyhdf installation files. I've had failures in two ways: 1) When I install, I do not wish to use the szip library, so I disable it in the setup.py. The install finishes and I try to use the library: >>> from pyhdf.SD import * Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/site-packages/pyhdf/SD.py", line 991, in ? import hdfext as _C File "/usr/lib/python2.4/site-packages/pyhdf/hdfext.py", line 4, in ? import _hdfext ImportError: /usr/lib/python2.4/site-packages/pyhdf/_hdfext.so: undefined symbol: SDgetcompress 2) So I try it with szip enabled. I download the source for the library and ./configure it. Make it. Then Make install it. I then try to install the pyhdf package. $ sudo python setup.py install pyhdf/hdfext_wrap.c: In function '_HEprint': pyhdf/hdfext_wrap.c:898: warning: implicit declaration of function 'HEprint' pyhdf/hdfext_wrap.c: In function '_SDreaddata_0': pyhdf/hdfext_wrap.c:1036: warning: implicit declaration of function 'SDreaddata' pyhdf/hdfext_wrap.c: In function '_SDwritedata_0': pyhdf/hdfext_wrap.c:1145: warning: implicit declaration of function 'SDwritedata' pyhdf/hdfext_wrap.c: In function '_SDgetcompress': pyhdf/hdfext_wrap.c:1205: warning: implicit declaration of function 'SDgetcompress' pyhdf/hdfext_wrap.c:1217: error: 'COMP_CODE_SZIP' undeclared (first use in this function) pyhdf/hdfext_wrap.c:1217: error: (Each undeclared identifier is reported only once pyhdf/hdfext_wrap.c:1217: error: for each function it appears in.) pyhdf/hdfext_wrap.c:1218: error: 'comp_info' has no member named 'szip' pyhdf/hdfext_wrap.c:1219: error: 'comp_info' has no member named 'szip' pyhdf/hdfext_wrap.c:1220: error: 'comp_info' has no member named 'szip' pyhdf/hdfext_wrap.c:1221: error: 'comp_info' has no member named 'szip' pyhdf/hdfext_wrap.c:1222: error: 'comp_info' has no member named 'szip' pyhdf/hdfext_wrap.c: In function '_SDsetcompress': pyhdf/hdfext_wrap.c:1245: error: 'COMP_CODE_SZIP' undeclared (first use in this function) pyhdf/hdfext_wrap.c:1246: error: 'comp_info' has no member named 'szip' pyhdf/hdfext_wrap.c:1247: error: 'comp_info' has no member named 'szip' pyhdf/hdfext_wrap.c:1251: warning: implicit declaration of function 'SDsetcompress' pyhdf/hdfext_wrap.c: In function '_wrap_VSseek': pyhdf/hdfext_wrap.c:3531: warning: implicit declaration of function 'VSseek' pyhdf/hdfext_wrap.c: In function '_wrap_VSread': pyhdf/hdfext_wrap.c:3551: warning: implicit declaration of function 'VSread' pyhdf/hdfext_wrap.c: In function '_wrap_VSwrite': pyhdf/hdfext_wrap.c:3571: warning: implicit declaration of function 'VSwrite' pyhdf/hdfext_wrap.c: In function '_wrap_VSfpack': pyhdf/hdfext_wrap.c:3597: warning: implicit declaration of function 'VSfpack' error: command 'gcc' failed with exit status 1 From andy.rockford at gmail.com Mon May 7 01:11:48 2007 From: andy.rockford at gmail.com (Andy) Date: 6 May 2007 22:11:48 -0700 Subject: Counting In-Reply-To: References: <1177873864.502180.283390@u30g2000hsc.googlegroups.com> Message-ID: <1178514708.093527.293860@y5g2000hsa.googlegroups.com> .o0 From sjmachin at lexicon.net Mon May 7 17:38:15 2007 From: sjmachin at lexicon.net (John Machin) Date: 7 May 2007 14:38:15 -0700 Subject: msbin to ieee In-Reply-To: <1178545075.530201.180120@u30g2000hsc.googlegroups.com> References: <1178487847.671199.108140@h2g2000hsg.googlegroups.com> <1178502738.104124.3840@h2g2000hsg.googlegroups.com> <1178525916.145819.264070@n59g2000hsh.googlegroups.com> <1178536910.566119.6650@o5g2000hsb.googlegroups.com> <1178539202.316506.199940@p77g2000hsh.googlegroups.com> <1178542593.668743.71500@u30g2000hsc.googlegroups.com> <1178545075.530201.180120@u30g2000hsc.googlegroups.com> Message-ID: <1178573895.164509.82270@u30g2000hsc.googlegroups.com> On May 7, 11:37 pm, revuesbio wrote: > On 7 mai, 14:56, John Machin wrote: > > > > > On May 7, 10:00 pm, revuesbio wrote: > > > > On 7 mai, 13:21, John Machin wrote: > > > > > On May 7, 6:18 pm, revuesbio wrote: > > > > > > On 7 mai, 03:52, John Machin wrote: > > > > > > > On May 7, 7:44 am, revuesbio wrote: > > > > > > > > Hi > > > > > > > Does anyone have the python version of the conversion from msbin to > > > > > > > ieee? > > > > > > > Thank u > > > > > > > Yes, Google has it. Google is your friend. Ask Google. It will lead > > > > > > you to such as: > > > > > > >http://mail.python.org/pipermail/python-list/2005-August/337817.html > > > > > > > HTH, > > > > > > John > > > > > > Thank you, > > > > > > I've already read it but the problem is always present. this script is > > > > > for double precision MBF format ( 8 bytes). > > > > > It would have been somewhat more helpful had you said what you had > > > > done so far, even posted your code ... > > > > > > I try to adapt this script for single precision MBF format ( 4 bytes) > > > > > but i don't find the right float value. > > > > > > for example : 'P\xad\x02\x95' will return '0.00024924660101532936' > > > > > If you know what the *correct* value is, you might like to consider > > > > shifting left by log2(correct_value/erroneous_value) :-) > > > > > Do you have any known correct pairs of (mbf4 string, decimal_float > > > > value)? My attempt is below -- this is based on a couple of > > > > descriptive sources that my friend Google found, with no test data. I > > > > believe the correct answer for the above input is 1070506.0 i.e. you > > > > are out by a factor of 2 ** 32 > > > > > def mbf4_as_float(s): > > > > m0, m1, m2, m3 = [ord(c) for c in s] > > > > exponent = m3 > > > > if not exponent: > > > > return 0.0 > > > > sign = m2 & 0x80 > > > > m2 |= 0x80 > > > > mant = (((m2 << 8) | m1) << 8) | m0 > > > > adj = 24 + 128 > > > > num = mant * 2.0 ** (exponent - adj) > > > > if sign: > > > > return -num > > > > return num > > > > > HTH, > > > > John > > > > well done ! it's exactly what i'm waiting for !! > > > > my code was:>>> from struct import * > > > >>> x = list(unpack('BBBB','P\xad\x02\x95')) > > > >>> x > > > [80, 173, 2, 149] > > > >>> def conversion1(bytes): > > > > b=bytes[:] > > > sign = bytes[-2] & 0x80 > > > b[-2] |= 0x80 > > > exp = bytes[-1] - 0x80 - 56 > > > acc = 0L > > > for i,byte in enumerate(b[:-1]): > > > acc |= (long(byte)<<(i*8)) > > > return (float(acc)*2.0**exp)*((1.,-1.)[sign!=0]) > > > Apart from the 2**32 problem, the above doesn't handle *any* of the > > 2**24 different representations of zero. Try feeding \0\0\0\0' to it > > and see what you get. > > > > >>> conversion1(x) > > > > 0.00024924660101532936 > > > > this script come from google groups but i don't understand bit-string > > > manipulation (I'm a newbie). informations about bit-string > > > manipulation with python is too poor on the net. > > > The basic operations (and, or, exclusive-or, shift) are not specific > > to any language. Several languages share the same notation (& | ^ << > > > >>), having inherited it from C. > > > > thank you very much for your script. > > > Don't thank me, publish some known correct pairs of values so that we > > can verify that it's not just accidentally correct for 1 pair of > > values. > > pairs of values : > (bytes string, mbf4_as_float(s) result) right > float value > ('P\xad\x02\x95', 1070506.0) > 1070506.0 > ('\x00\x00\x00\x02', 5.8774717541114375e-039) 0.0 There is no way that \x00\x00\x00\x02' could represent exactly zero. What makes you think it does? Rounding? > ('\x00\x00\x00\x81', 1.0) > 1.0 > ('\x00\x00\x00\x82', 2.0) > 2.0 > ('\x00\x00@\x82', 3.0) > 3.0 > ('\x00\x00\x00\x83', 4.0) > 4.0 > ('\x00\x00 \x83', 5.0) > 5.0 > ('\xcd\xcc\x0c\x81', 1.1000000238418579) 1.1 > ('\xcd\xcc\x0c\x82', 2.2000000476837158) 2.2 > ('33S\x82', 3.2999999523162842) 3.3 > ('\xcd\xcc\x0c\x83', 4.4000000953674316) 4.4 It is not apparent whether you regard the output from the function as correct or not. 4.4 "converted" to mbf4 format is '\xcd\xcc\x0c\x83' which is 4.4000000953674316 which is the closest possible mbf4 representation of 4.4 (difference is 9.5e-008). The next lower mbf4 value '\xcc\xcc\x0c\x83' is 4.3999996185302734 (difference is -3.8e-007). Note that floating-point representation of many decimal fractions is inherently inexact. print repr(4.4) produces 4.4000000000000004 Have you read this: http://docs.python.org/tut/node16.html ? If you need decimal-fraction output that matches what somebody typed into the original software, or saw on the screen, you will need to know/guess the precision that was involved, and round the numbers accordingly -- just like the author of the original software would have needed to do. >>> ['%.*f' % (decplaces, 4.4000000953674316) for decplaces in range(10)] ['4', '4.4', '4.40', '4.400', '4.4000', '4.40000', '4.400000', '4.4000001', '4.40000010', '4.400000095'] HTH, John From nszabolcs at gmail.com Thu May 24 13:33:21 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 24 May 2007 10:33:21 -0700 Subject: need advice on building core code for python and PHP In-Reply-To: <1180025115.704410.250890@a35g2000prd.googlegroups.com> References: <1180025115.704410.250890@a35g2000prd.googlegroups.com> Message-ID: <1180028001.569139.317660@q66g2000hsg.googlegroups.com> > Is there a way I could code the base (core) code in Python and have > PHP call it? I've really liked using SQLAlchemy and there are other * quick and dirty solution: in a shell: $ python yourscript.py pipe_out in the php script: fwrite(pipe_in, input_data); results = fread(pipe_out, sizeof_results); * simple and nice solution: do not ever use php From jadestar at idiom.com Wed May 16 21:38:01 2007 From: jadestar at idiom.com (James T. Dennis) Date: Thu, 17 May 2007 01:38:01 -0000 Subject: python shell References: <1179337107.842668.112690@k79g2000hse.googlegroups.com> <1179356351.981354.175100@q23g2000hsg.googlegroups.com> Message-ID: <1179365881.131403@smirk> mensanator at aol.com wrote: > On May 16, 12:38 pm, Krypto wrote: >> I have been using python shell to test small parts of the big program. >> What other ways can I use the shell effectively. My mentor told me >> that you can virtually do anything from testing your program to >> anything in the shell. Any incite would be useful. > Yeah? Well tell your mentor he can take his programs and > his literal interpretaions to the other side of the river!! > Oh...wait. Did you mean "insight"? > One thing that covers a LOT of ground is you can run other > programs from the shell and capture their output (assuming > the output is text to stdout). > For example, I can run the program factor!.exe from the > command line: > C:\python25\user>factor!.exe 27 > PRIME_FACTOR 3 > PRIME_FACTOR 3 > PRIME_FACTOR 3 > But I can also run it from the Python shell: >>>> import os >>>> f = os.popen("factor! 27").readlines() >>>> f > ['PRIME_FACTOR 3\n', 'PRIME_FACTOR 3\n', 'PRIME_FACTOR > 3\n'] >>>> q = [int(i.split()[1]) for i in f] >>>> q > [3, 3, 3] > Now, you've got the factors without having to write your own > factoring program and you never had to leave the shell. > What more could you ask for? I could ask for some tricks that would let me do things like: * os.fork() --- but have that spawned in it's own xterm/shell so I can no interact with each of the children separately * Use the curses library --- with the interpreter reading from one shell/xterm and the curses display controlling another one. I'm sure they're out there ... and I've love to see pointers to them. -- Jim Dennis, Starshine: Signed, Sealed, Delivered From showell30 at yahoo.com Mon May 28 11:49:52 2007 From: showell30 at yahoo.com (Steve Howell) Date: Mon, 28 May 2007 08:49:52 -0700 (PDT) Subject: Newbie question - better way to do this? In-Reply-To: <465af249$0$90266$14726298@news.sunsite.dk> Message-ID: <877578.39392.qm@web33508.mail.mud.yahoo.com> --- Nis J?rgensen wrote: > > I disagree that word.istitle is the correct idiom - > from the naming of > the function in the original example, I would guess > "word[0].isupper" > would do the trick. > That would return something like this: You want to add parens: word[0].isupper() ____________________________________________________________________________________Luggage? GPS? Comic books? Check out fitting gifts for grads at Yahoo! Search http://search.yahoo.com/search?fr=oni_on_mail&p=graduation+gifts&cs=bz From artdent at freeshell.org Thu May 10 18:39:23 2007 From: artdent at freeshell.org (Jacob Lee) Date: Thu, 10 May 2007 22:39:23 +0000 (UTC) Subject: Erlang style processes for Python References: <1178759792.268979.206630@p77g2000hsh.googlegroups.com> <1178781551.927028.256380@y80g2000hsf.googlegroups.com> Message-ID: On Thu, 10 May 2007 00:19:11 -0700, Kay Schluehr wrote: > [snip] >> I do admit that Erlang's pattern >> matching would be nice, although you can get pretty far by using uniform >> message formats that can easily be dispatched on -- the tuple >> (tag, sender, args, kwargs) >> in the case of PARLEY, which maps nicely to instance methods of a >> dispatcher class. > > Yes, I do think so too. It is more interesting to think about what > might be qualify as a message. Destructuring it is not hard in anyway > and I do also have a few concerns with naive pattern matching: > > http://www.fiber-space.de/EasyExtend/doc/gallery/gallery.html#4._Chainlets_and_the_switch-statement > Interesting. Scala's pattern matching also looks nice. They have a construct called a "case class" which is sort of like an algebraic data type in that == compares the actual internal structure of the objects... come to think of it, it reminds me of the proposal for named tuples that floated around one of the python lists recently. > [snip] > Actors don't need locking primitives since their data is locked by > virtue of the actors definition. That's also why I'm in favour for a > runtime / compiler based solution. Within the shiny world of actors > and actresses the GIL has no place. So a thread that runs actors only, > does not need to be blocked or block other threads - at least not for > data locking purposes. It is used much like an OS level process with > better sharing capabilities ( for mailbox addresses and messages ). > Those threads shall not take part of the access/release GIL game. They > might also not be triggered explicitely using the usual threading > API. > There are also a lot of places where Python implicitly shares data, though. Global variables are one -- if you disallow those, then each actor has to have its own copy of all imported modules. I think the GC is also not at all threadsafe. I'm not familiar enough with how the interpreter works to judge whether disallowing shared memory would make any of the existing obstacles to removing the GIL easier to deal with. Certainly, if it's doable, it would be a big win to tackle these problems. >> PARLEY currently only works within a single process, though one can choose >> to use either tasklets or threads. My next goal is to figure out I/O, at >> which point I get to tackle the fun question of distribution. >> >> So far, I've not run into any cases where I've wanted to change the >> interpreter, though I'd be interested in hearing ideas in this direction >> (especially with PyPy as such a tantalizing platform!). >> -- >> Jacob Lee > > I guess you mean tantalizing in both of its meanings ;) > > Good luck and inform us when you find interesting results. > > Kay Thanks! -- Jacob Lee From mangabasi at gmail.com Wed May 23 14:54:42 2007 From: mangabasi at gmail.com (Mangabasi) Date: 23 May 2007 11:54:42 -0700 Subject: Inheriting from Python list object(type?) In-Reply-To: Message-ID: <1179946482.783009.148130@p47g2000hsd.googlegroups.com> On May 23, 1:43 pm, "Jerry Hill" wrote: > On 23 May 2007 11:31:56 -0700, Mangabasi wrote: > > > When I modified this to: > > > class Point(list): > > def __init__(self,x,y): > > super(Point, self).__init__([x, y]) > > self.x = x > > self.y = y > > > It worked. > > Are you sure? > > >>> p = Point(10, 20) > >>> p > [10, 20] > >>> p.x > 10 > >>> p.x = 15 > >>> p > [10, 20] > >>> p[0] > 10 > >>> p.x > 15 > > That doesn't look like what you were asking for in the original post. > I'm afraid I don't know anything about numpy arrays or what special > attributes an object may need to be put into a numpy array though. > > -- > Jerry You are right. I did not include the whole story in my last post. This is the real code I used and so far it worked. I am still testing it though. Toes and fingers crossed! class Point(list): def __init__(self, x, y, z = 1): super(Point, self).__init__([x, y, z]) self.x = x self.y = y self.z = z def __getattr__(self, name): if name == 'x': return self[0] if name == 'y': return self[1] if name == 'z': return self[2] def __setattr__(self, name, value): if name == 'x': self[0] = value if name == 'y': self[1] = value if name == 'z': self[2] = value Thanks for the correction. From martin at v.loewis.de Thu May 17 08:55:27 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 17 May 2007 14:55:27 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <464c50c0$0$31548$9b622d9e@news.freenet.de> >> So, please provide feedback, e.g. perhaps by answering these >> questions: >> - should non-ASCII identifiers be supported? why? > > I think the biggest argument against this PEP is how little similar > features are used in other languages and how poorly they are supported > by third party utilities. Your PEP gives very little thought to how > the change would affect the standard Python library. Are non-ASCII > identifiers going to be poorly supported in Python's own library and > utilities? For other languages (in particular Java), one challenge is that you don't know the source encoding - it's neither fixed, nor is it given in the source code file itself. Instead, the environment has to provide the source encoding, and that makes it difficult to use. The JDK javac uses the encoding from the locale, which is non-sensical if you check-out source from a repository. Eclipse has solved the problem: you can specify source encoding on a per-project basis, and it uses that encoding consistently in the editor and when running the compiler. For Python, this problem was solved long ago: PEP 263 allows to specify the source encoding within the file, and there was always a default encoding. The default encoding will change to UTF-8 in Python 3. IDLE has been supporting PEP 263 from the beginning, and several other editors support it as well. Not sure what other tools you have in mind, and what problems you expect. Regards, Martin From claird at lairds.us Fri May 18 15:30:14 2007 From: claird at lairds.us (Cameron Laird) Date: Fri, 18 May 2007 19:30:14 +0000 Subject: alternative to eclipse [ python ide AND cvs ] References: Message-ID: <6fb1i4-t9n.ln1@lairds.us> In article , yomgui wrote: >Hi, > >Eclipse is just not really working on linux 64 bit >(I tried ubuntu and centos, it is freesing and crashing >and extremly slow) > >I use eclipse for python and cvs, what is "the" good alternative ? . . . From broek at cc.umanitoba.ca Mon May 21 09:53:08 2007 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Mon, 21 May 2007 09:53:08 -0400 Subject: TIFF to PDF In-Reply-To: References: <1179687595.142454.23850@z24g2000prd.googlegroups.com> <1179744141.027494.60590@r3g2000prh.googlegroups.com> Message-ID: <4651A444.9040901@cc.umanitoba.ca> Gabriel Genellina said unto the world upon 05/21/2007 07:01 AM: > En Mon, 21 May 2007 07:42:21 -0300, revuesbio > escribi?: > >> os.system('"C:\Program Files\GnuWin32\bin\tiff2pdf.exe" -o C:\test.pdf >> C:\test.TIF') > > \ is used as a escape character in strings. > Use either \\ or a raw string, that is: > > os.system('"C:\\Program Files\\GnuWin32\\bin\\tiff2pdf.exe" -o > C:\\test.pdf C:\\test.TIF') > os.system(r'"C:\Program Files\GnuWin32\bin\tiff2pdf.exe" -o C:\test.pdf > C:\test.TIF') > > (This should be added to the Python FAQ - the most related entry is about > raw strings ending in \) Better still, use / as the path separator. That works fine on both windows and *nixes. Best, Brian vdB From jelle.feringa at ezct.net Sun May 27 04:53:54 2007 From: jelle.feringa at ezct.net (jelle feringa) Date: Sun, 27 May 2007 08:53:54 +0000 (UTC) Subject: Color Segmentation w/ PIL? References: <1174549126.754309.317260@n76g2000hsh.googlegroups.com> <10822775.post@talk.nabble.com> Message-ID: You might be interested in the ndimage module of scipy: http://www.scipy.org/SciPyPackages/Ndimage If you need a very serious image processing framework, ITK is might be very interesting: http://www.itk.org/ If so, have a look at the more Pythonic interface developed for it: www.insight-journal.org/ .../1926/188/2/WrapITK_-_Enhanced_languages_support_for_the_Insight_Toolkit.pdf Cheers, -jelle From sturlamolden at yahoo.no Fri May 11 11:05:54 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 11 May 2007 08:05:54 -0700 Subject: Towards faster Python implementations - theory In-Reply-To: References: <1210i.7468$2v1.2505@newssvr14.news.prodigy.net> <1178804728.527486.196400@y80g2000hsf.googlegroups.com> Message-ID: <1178895954.457221.277820@p77g2000hsh.googlegroups.com> On May 10, 7:18 pm, "Terry Reedy" wrote: > Unfortunately, native machine code depends on the machine, or at least the > machine being emulated by the hardware. Fortunately or not, the dominance > of the x386 model makes this less of a problem. CMUCL and SBCL depends on the dominance of the x86 architecture. GCL uses the GCC backend, which supports a wide range of architectures. Building a compiler backend is not needed for a Python JIT, one can accept the GPL license and use GCC as a backend. Or one could translate between Python and Lisp on the fly, and use a compiled Lisp (CMUCL, SBCL, Franz, GCL) as runtime backend. From rzantow at gmail.com Sat May 26 15:17:37 2007 From: rzantow at gmail.com (rzed) Date: Sat, 26 May 2007 19:17:37 +0000 Subject: Python and GUI References: Message-ID: Brian Blais wrote in news:mailman.8119.1180016569.32031.python-list at python.org: [...] > Finally, consider wax (http://zephyrfalcon.org/labs/wax.html). > In my view, this is *exactly* what python needs, and its not > being maintained anymore as far as I can tell. What I like > about it is: > > 1) it is small...I can include the entire wax distribution in my > app with only a 780k > footprint. > 2) it is a very thin layer on wx, so when something doesn't > quite work, I can immediately fall back onto wx, mixing and > matching wax and wx objects. it's just that the wax objects > have more pythonic calling and use properties > > > Is there a reason that the port of wxPython doesn't include wax, > or something similar? It would seem pretty straightforward, > when porting the wx to Python, to simply include such a wrapper. > I wish I were more clever, and had more time, to take over the > maintenance of wax because I think it is the most > straightforward, practical, and pythonic solution out there. > > > Do others think like me here? > I certainly do. Whether wax is the particular solution or not, something very like it should be. Something like this was tried at one time (Anygui) and the general consensus seems to be that it doesn't work as an approach because the packages are too different. I think that it's past time to revisit that conclusion. It would be very useful to a user of the Language we call Python to be able to write GUI code without regard to the back-end package. If there were a standard Python GUI API (call it the PGA, say) that be the target for app developers, they wouldn't have to worry about the back end. The PGA would have to be flexible enough to handle incompatibilities among the various approaches to displaying widgets and text. In order for that to happen, some kind of meeting of minds (among those who now deal with the murky middle between gui packages and python) would have to take place. A standard would have to be hammered out and then used. The standard would have to allow for generic calls for tasks that any reasonable GUI would have to handle. It would also have to provide for system-specific calls for those things that each package might require uniquely. The interface to the system- specific stuff should itself be the same regardless of the back end. What I mean by this is that, where wax's limitations are overcome by dropping to wx directly, there should instead by a PGA winsys() call that permits passing command strings, values, or whatever in a dict-like object that would be permit the pga2wx interface to create the specific calls it needs. When the back end changes to Qt, the pga2Qt interface would make the translation instead. The code from the app programmer should not have to change, except maybe to add another item or items to the winsys dict. I also think there should something similar for an interface for Python database access (PDBA). Anydb might not be the solution, but it could be. It would take cleverness (which abounds in the Python community), determination (which may not be in such abundance) and project coordination for either of these projects to come to fruition. A summer of code kind of thing would provide a good initial push, and some sprints could move things along at a good clip. Wax, anygui, and anydb seem to be acceptable starting points, but the key thing is to get agreement from key players (like the developers of wxPython, dabo, PythonCard, and so on) to agree that this is a good direction to go in, and to try to work out the requirements for a flexible PGA and PDBA. I'm sure that the approach could produce usable results in short order, and then attack the remaining limitations over time. Do I think this is going to happen? No. There are two overlapping things we call Python: the Language and the Package. The Language comes from Guido and a few others, but the Package comes from many sources, mostly volunteers. The GUI interfaces come from many such sources, each with a different view of what constitutes a good Pythonic interface. Having put a lot of time and effort into getting their version up and running, they're not about to change for some abstract reason, but nonetheless, I do believe that the Language of Python should have a GUI API defined, and that the Package of Python should accommodate to that. Unless that happens, we'll see more of what we now see: continual questions about what is the best GUI or the best Database. Because once you start building an app, you commit to the syntax of the package and you are no longer (in my view) coding in Python, but in that subset that includes the GUI Package of your choice. -- rzed From gagsl-py2 at yahoo.com.ar Sat May 19 03:28:01 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 19 May 2007 04:28:01 -0300 Subject: pyodbc.Error Crash References: Message-ID: En Fri, 18 May 2007 20:48:49 -0300, Joe Salmeri escribi?: > I believe this bug is also related to the other problem I just reported. I think you'll get best results reporting them to the author(s) directly: http://pyodbc.sourceforge.net/ and click on "Bug tracker" -- Gabriel Genellina From attn.steven.kuo at gmail.com Fri May 11 19:52:33 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 11 May 2007 16:52:33 -0700 Subject: matplotlib: howto set title of whole window? In-Reply-To: <1178923478.087792.101170@n59g2000hsh.googlegroups.com> References: <1178923478.087792.101170@n59g2000hsh.googlegroups.com> Message-ID: <1178927552.965037.282360@u30g2000hsc.googlegroups.com> On May 11, 3:44 pm, dmitrey wrote: > hi all, > does anyone know howto set title of whole window? (I mean not just > area above plot but string in the same line where buttons 'close', > 'iconify', 'fullscreen' are situated) > Use coordinates to set a title for the current figure. E.g., from pylab import * from matplotlib.font_manager import FontProperties figtitle = 'This is my title above all subplots' t = gcf().text(0.5, 0.95, figtitle, horizontalalignment='center', fontproperties=FontProperties(size=16)) subplot(121) subplot(122) show() -- Hope this helps, Steven From mangabasi at gmail.com Wed May 23 15:07:47 2007 From: mangabasi at gmail.com (Mangabasi) Date: 23 May 2007 12:07:47 -0700 Subject: Inheriting from Python list object(type?) In-Reply-To: Message-ID: <1179947267.368622.92350@m36g2000hse.googlegroups.com> On May 23, 1:43 pm, "Jerry Hill" wrote: > On 23 May 2007 11:31:56 -0700, Mangabasi wrote: > > > When I modified this to: > > > class Point(list): > > def __init__(self,x,y): > > super(Point, self).__init__([x, y]) > > self.x = x > > self.y = y > > > It worked. > > Are you sure? > > >>> p = Point(10, 20) > >>> p > [10, 20] > >>> p.x > 10 > >>> p.x = 15 > >>> p > [10, 20] > >>> p[0] > 10 > >>> p.x > 15 > > That doesn't look like what you were asking for in the original post. > I'm afraid I don't know anything about numpy arrays or what special > attributes an object may need to be put into a numpy array though. > > -- > Jerry This is the winner: class Point(list): def __init__(self, x, y, z = 1): super(Point, self).__init__([x, y, z]) self.x = x self.y = y self.z = z def __getattr__(self, name): if name == 'x': return self[0] elif name == 'y': return self[1] elif name == 'z': return self[2] else: return self.__dict__[name] def __setattr__(self, name, value): if name == 'x': self[0] = value elif name == 'y': self[1] = value elif name == 'z': self[2] = value else: self.__dict__[name] = value From LarinAM at gmail.com Wed May 16 08:20:26 2007 From: LarinAM at gmail.com (LarinAM at gmail.com) Date: 16 May 2007 05:20:26 -0700 Subject: Garbage Collector in Zope 2.8 Message-ID: <1179318026.356062.26240@q75g2000hsh.googlegroups.com> Hi. Can anyone tell me how to run garbage collector in zope manually in zope runtime? From kyosohma at gmail.com Thu May 24 17:05:36 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 24 May 2007 14:05:36 -0700 Subject: Accessing iTunes with Python via the Windows SDK In-Reply-To: <1179986398.203388.244090@q66g2000hsg.googlegroups.com> References: <1179980636.045976.145070@q75g2000hsh.googlegroups.com> <1179983821.769700.45870@d30g2000prg.googlegroups.com> <1179986398.203388.244090@q66g2000hsg.googlegroups.com> Message-ID: <1180040736.683029.291810@p77g2000hsh.googlegroups.com> On May 24, 12:59 am, Denrael wrote: > On May 24, 12:17 am, Tony Meyer wrote: > > > On May 24, 4:23 pm, Denrael wrote:> I've been playing with the iTunes sdk on windows, and have come across > > > a strange problem. With the following code: > > > The object you get back from iTunes.CurrentTrack (the traceback shows > > this) is an IITTrack. If you check the iTunes SDK, you'll see that > > IITTrack objects don't have a "SkippedCount" attribute - > > IITFileOrCDTrack objects do (from memory, this excludes things like > > radio links). You need to conver the IITrack object to a > > IITFileOrCDTrack object (assuming that it is one); you can do this > > with win32com.client.CastTo, as follows: > > > Cheers, > > Tony > > Thanks Tony! > > I had a suspicion it had to do with casting it, but I was missing some > synapses to figure out exactly how to do that. Things have changed > from my Assembly Language PL/1 and REXX days. :) I figure if I'm > gonna learn a new language, Python's a lot more usable than VBS, and > it has an elegance to it that I already appreciate. I'm working my way > thru Learning Python ... I suppose I better find some doc on the Win32 > COM stuff too. The best Python docs on win32 in general is "Python Programming on Win32" by Hammond & Robinson. It has some stuff on Python and COM as well. I'm sure a win32 COM book would be good too. Mike From deepbroke7 at gmail.com Wed May 16 04:04:04 2007 From: deepbroke7 at gmail.com (deepbroke7 at gmail.com) Date: 16 May 2007 01:04:04 -0700 Subject: ~!~ Britneys New BOOB job fails Silcone Valley everywhere!!!! Message-ID: <1179302644.495139.26440@l77g2000hsb.googlegroups.com> http://scargo.in/2007/05/attorney-lawyers-say-whats-in-your.html - Britneys Boob job spurs lawsuit.!! From mtobis at gmail.com Mon May 7 23:45:52 2007 From: mtobis at gmail.com (Michael Tobis) Date: 7 May 2007 20:45:52 -0700 Subject: interesting exercise Message-ID: <1178595952.641173.76540@y80g2000hsf.googlegroups.com> I want a list of all ordered permutations of a given length of a set of tokens. Each token is a single character, and for convenience, they are passed as a string in ascending ASCII order. For example permute("abc",2) should return ["aa","ab","ac","ba","bb","bc","ca","cb","cc"] and permute("13579",3) should return a list of 125 elements ["111","113", ... ,"997","999"] permute("axc",N) or permute("2446",N) should raise ValueError as the alphabet is not strictly sorted. I have a reasonably elegant solution but it's a bit verbose (a couple dozen lines which I'll post later if there is interest). Is there some clever Pythonism I didn't spot? thanks mt From jbmccrann at gmail.com Wed May 2 23:10:20 2007 From: jbmccrann at gmail.com (Midex) Date: 2 May 2007 20:10:20 -0700 Subject: Firefighters at the site of WTC7 "Move away the building is going to blow up, get back the building is going to blow up." Message-ID: <1178161820.731367.264500@y80g2000hsf.googlegroups.com> 100% EVIDENCE - SEE THE TRUTH FINALLY - ON THE GROUND VIDEO WITNESSES http://www.youtube.com/watch?v=YNN6apj5B2U In order to appreciate just what Truthers are talking about when they cry Treason over WTC7, you would want to see this History Channel documentary on what they claim happened to WTC7: http://www.youtube.com/watch?v=TVSxeJH_RCY Ben Chertoff can't get his story straight http://www.youtube.com/watch?v=9YND7XocMocj LIES LIES LIES LIES LIES 9/11 Truth Focoist Revolution. "When peaceful revolution is made impossible, violent revolution is inevitable" - Martin Luther King. How long shall they kill our prophets? Look up Focoism. Write about it. Spread the method. It will be how this revolution will take shape. From ceball at gmail.com Fri May 4 01:39:24 2007 From: ceball at gmail.com (Chris) Date: 3 May 2007 22:39:24 -0700 Subject: Strange terminal behavior after quitting Tkinter application In-Reply-To: <462dc8a4$0$44860$c30e37c6@lon-reader.news.telstra.net> References: <1177389473.935407.20950@o40g2000prh.googlegroups.com> <462dc8a4$0$44860$c30e37c6@lon-reader.news.telstra.net> Message-ID: <1178257164.415485.155290@q75g2000hsh.googlegroups.com> (I apologize if some similar version of this message has already appeared; I've tried several time to post it, seemingly without success.) > If that is satisfactory, well and good. However, there > is a possibility that you may lose some settings that you would > prefer to keep. The terminal settings have been trashed, and > stty sane has restored a minimally workable set, but some > settings may not be what you expect. I agree: I'll consider saving the terminal settings as you suggest. > Just in case, I did a google search. I am not familiar > withTKinter, but a couple of articles out there imply > that rather than calling sys.exit you should be calling aTkInterroutine root.destroy. I am not sure if root is a > variable for the main window (ie you call the destroy method > on the main window) or if it has some specialTkintermeaning. > Presumably this routine cleans things up before calling sys.exit > or an equivalent. "root" is the name of a variable typically used by people to hold an instance of Tkinter.Tk, the main application window (from http://epydoc.sourceforge.net/stdlib/Tkinter.Tk-class.html: "Toplevel widget of Tk which represents mostly the main window of an appliation. It has an associated Tcl interpreter."). Instead of subclassing Tkinter.Tk and instantiating that subclass for my application, I could create a Tk instance and withdraw() it, then use a Toplevel. In my example code above, I could call any 'root' methods on an instance of my Application class, presumably with the same effect. In any case, that might not be important - I think the problem comes from not calling mainloop(): import Tkinter import sys root = Tkinter.Tk() Tkinter.Button(root,text="Quit",command=sys.exit).pack() root.mainloop() Clicking 'Quit' or on the window's 'x' causes the application to quit without messing up the terminal. With root.mainloop() commented out, though, no combination of root.quit(), root.destroy(), and sys.exit() stops the terminal from getting messed up. So, I should call mainloop() for my application...except that I want to use the commandline, too, and calling mainloop() freezes the commandline. I wonder if there is another way to use the commandline and have a GUI? I couldn't find any clear information about that. Thanks again, Chris From mensanator at aol.com Tue May 15 00:37:07 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 14 May 2007 21:37:07 -0700 Subject: Interesting list Validity (True/False) In-Reply-To: References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> <1178914190.166662.285410@p77g2000hsh.googlegroups.com> <1178915791.584216.293130@l77g2000hsb.googlegroups.com> <1178918808.091358.233740@o5g2000hsb.googlegroups.com> <1179017740.656323.209590@e51g2000hsg.googlegroups.com> <1179020634.130689.171960@o5g2000hsb.googlegroups.com> <1179031812.090768.248750@l77g2000hsb.googlegroups.com> <1179168081.603409.39970@e51g2000hsg.googlegroups.com> Message-ID: <1179203827.881205.287910@l77g2000hsb.googlegroups.com> On May 14, 8:10?pm, Carsten Haese wrote: > On Mon, 2007-05-14 at 11:41 -0700, mensana... at aol.com wrote: > > On May 13, 8:24 am, Steven D'Aprano > > wrote: > > > On Sat, 12 May 2007 21:50:12 -0700, mensana... at aol.com wrote: > > > >> > > > > >> > "if arg==True" tests whether the object known as arg is equal to the > > > >> > object known as True. > > > >> > > > > > >> Not at all, it makes perfect sense. X == Y always tests whether the > > > >> argument X is equal to the object Y regardless of what X and Y are. > > > > > Except for the exceptions, that's why the statement is wrong. > > > > But there are no exceptions. > > > > > Sec 2.2.3: > > Objects of different types, *--->except<---* different numeric types > > and different string types, never compare equal; > > > > The exceptions you mean are not exceptions to "'X==Y' means 'X equals > Y'". I never said they were. I said they were exceptions to "Obbjects of different types never compare equal". > They are exceptions to "'X equals Y' means 'X is mathematically the > same as Y'," Who's "they"?. (1,2) and [1,2] are mathematically equal but the == comparison returns False. They are not an exception to "mathematically equal", neither are they exceptions to "different types never compare equal". 1 and mpz(1) compare equal so aren't an exception to "mathematically equal" although they are an exception to "different types never compare equal". You need to be more explicit about what you're talking about, as this last argument makes no sense. > but that is not how equality is actually defined. Ok, I'll bite. How is "equality" defined? Are you implying that I can interchange 1 and mpz(1) because the == comparison returns True? Are you implying that I can't interchange (1,2) and [1,2] because the == comparison returns False? Please make sure your definition deals with these cases. > > -- > Carsten Haesehttp://informixdb.sourceforge.net From foto at tempinbox.com Sun May 20 20:03:12 2007 From: foto at tempinbox.com (Rico) Date: 20 May 2007 17:03:12 -0700 Subject: Python Web Programming - looking for examples of solid high-traffic sites In-Reply-To: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> Message-ID: <1179705792.275598.276530@a26g2000pre.googlegroups.com> On May 16, 2:04 pm, Victor Kryukov wrote: > Hello list, > > our team is going to rewrite our existing web-site, which has a lot of > dynamic content and was quickly prototyped some time ago. > > Today, as we get better idea of what we need, we're going to re-write > everything from scratch. Python is an obvious candidate for our team: > everybody knows it, everybody likes it, it has *real* objects, nice > clean syntax etc. > > Our main requirement for tools we're going to use is rock-solid > stability. As one of our team-members puts it, "We want to use tools > that are stable, has many developer-years and thousands of user-years > behind them, and that we shouldn't worry about their _versions_." The > main reason for that is that we want to debug our own bugs, but not > the bugs in our tools. > > Our problem is - we yet have to find any example of high-traffic, > scalable web-site written entirely in Python. We know that YouTube is > a suspect, but we don't know what specific python web solution was > used there. > > TurboGears, Django and Pylons are all nice, and provides rich features > - probably too many for us - but, as far as we understand, they don't > satisfy the stability requirement - Pylons and Django hasn't even > reached 1.0 version yet. And their provide too thick layer - we want > something 'closer to metal', probably similar to web.py - > unfortunately, web.py doesn't satisfy the stability requirement > either, or so it seems. > > So the question is: what is a solid way to serve dynamic web pages in > python? Our initial though was something like python + mod_python + > Apache, but we're told that mod_python is 'scary and doesn't work very > well'. > > And althoughhttp://www.python.org/about/quotes/lists many big names > and wonderful examples, be want more details. E.g. our understanding > is that Google uses python mostly for internal web-sites, and > performance is far from perfect their. YouTube is an interesting > example - anybody knows more details about that? > > Your suggestions and comments are highly welcome! > > Best Regards, > Victor. Teenwag runs on Python, with a hacked up Framework and recieves about 2million visitors a day and is constantly increasing http://teenwag.com/profile?friendid=326 From rrr at ronadam.com Fri May 25 15:19:11 2007 From: rrr at ronadam.com (Ron Adam) Date: Fri, 25 May 2007 14:19:11 -0500 Subject: webbrowser module bug? In-Reply-To: <1180118146.617722.300670@g4g2000hsf.googlegroups.com> References: <1180118146.617722.300670@g4g2000hsf.googlegroups.com> Message-ID: Paul Boddie wrote: > On 25 May, 00:03, Ron Adam wrote: >> Is anyone else having problems with the webbrowser module? >> >> Python 2.5.1c1 (release25-maint, Apr 12 2007, 21:00:25) >> [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> import webbrowser >> >>> webbrowser.open('http://www.python.org') >> True >> >>> >> >> It opens firefox as expected, but the url is ... >> >> file:///home/ron/%22http://www.python.org%22 > > Since %22 is the URL-encoded double-quote character ("), I can only > imagine that something is quoting the URL for the shell, resulting in > the following command: > > firefox '"http://www.python.org/"' > > Or something similar, at least. Firefox 1.5 seems to refuse to open > such URLs, though. > > Paul Yes, thats it. I've traced it down the the subproccess.Popen call. This works >>> subprocess.Popen(['firefox', 'http://python.org']) This reproduces the problem I'm having. >>> subprocess.Popen(['firefox', '"http://python.org"']) The quoting does happen in the webbrowser module. The cmdline is passed as... ['/usr/lib/firefox/firefox', '"http://python.org"'] I've traced it back to the following line where self.args is ['"%s"'] Line 187 in webbrowser.py: cmdline = [self.name] + [arg.replace("%s", url) for arg in self.args] Now I just need to figure out why self.args is double quoted. Cheers, Ron From aleax at mac.com Fri May 4 22:54:47 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 4 May 2007 19:54:47 -0700 Subject: Why are functions atomic? References: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> <1178044821.864741.235260@o5g2000hsb.googlegroups.com> <1178063341.779617.289690@o5g2000hsb.googlegroups.com> <1178065685.161372.81790@y80g2000hsf.googlegroups.com> <1178083318.404304.76100@q75g2000hsh.googlegroups.com> <1178260571.160570.299160@p77g2000hsh.googlegroups.com> <1178308503.420603.158120@e65g2000hsc.googlegroups.com> Message-ID: <1hxltle.haomya7z5hdwN%aleax@mac.com> Michael wrote: > Thus, whenever I need to pass information to a function, I use default > arguments now. Is there any reason not to do this other than the fact > that it is a bit more typing? You're giving your functions a signature that's different from the one you expect it to be called with, and so making it impossible for the Python runtime to diagnose certain errors on the caller's part. For example, consider: def makecounter_good(): counts = {} def count(item): result = counts[item] = 1 + counts.get(item, 0) return result return count c = makecounter_good() for i in range(3): print c(23) def makecounter_hmmm(): counts = {} def count(item, counts=counts): result = counts[item] = 1 + counts.get(item, 0) return result return count cc = makecounter_hmmm() for i in range(3): print cc(23) print cc(23, {}) print c(23, {}) Counters made by makecounter_good take exactly one argument, and properly raise exceptions if incorrectly called with two; counters made by makecounter_hmmm take two arguments (of which one is optional), and thus hide some runtime call errors. >From "import this": """ Errors should never pass silently. Unless explicitly silenced. """ The miniscule "optimization" of giving a function an argument it's not _meant_ to have somewhat breaks this part of the "Zen of Python", and thus I consider it somewhat unclean. Alex From ratchetgrid at googlemail.com Tue May 1 10:56:39 2007 From: ratchetgrid at googlemail.com (Nathan Harmston) Date: Tue, 1 May 2007 15:56:39 +0100 Subject: Restricting the alphabet of a string In-Reply-To: <1177956850.096236.95040@y5g2000hsa.googlegroups.com> References: <1177956850.096236.95040@y5g2000hsa.googlegroups.com> Message-ID: <676224240705010756q211bb17dufc12e493429b9768@mail.gmail.com> Thanks, I might just move my trinary string (if I get that far) to be encoded as 0, 1, 2, thanks for your help. On 30 Apr 2007 11:14:10 -0700, John Machin wrote: > On Apr 30, 9:53 pm, "Nathan Harmston" > wrote: > > Hi, > > > > I ve being thinking about playing around with bit strings but use in > > some encoding problems I m considering and was trying to decide how to > > implement a bit string class. Is there a library out there for doing > > basic things with bit strings already is my first question? > > > > I know that I can extend string to bit string, but is there anyway I > > can force the alphabet to be restricted to 1's and 0's (or even 1, 0 > > and -1, as an extension to from trinary strings). > > > > class Binary_String(String): > > pass > > > > See if you can pick which line below is impractically different to the > others: > > binary: 0, 1 > "trinary": -1, 0, 1 > octal: 0, 1, 2, 3, 4, 5, 6, 7 > decimal: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 > > HTH, > John > > -- > http://mail.python.org/mailman/listinfo/python-list > From info at egenix.com Thu May 10 11:31:55 2007 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Thu, 10 May 2007 17:31:55 +0200 Subject: ANN: eGenix mx Base Distribution 3.0.0 (mxDateTime, mxTextTools, etc.) Message-ID: <46433AEB.2030006@egenix.com> ________________________________________________________________________ ANNOUNCING eGenix.com mx Base Extension Package Version 3.0.0 Open Source Python extensions providing important and useful services for Python programmers. This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-mx-Base-Distribution-3.0-GA.html ________________________________________________________________________ ABOUT The eGenix.com mx Base Extensions for Python are a collection of professional quality software tools which enhance Python's usability in many important areas such as fast text searching, date/time processing and high speed data types. The tools have a proven record of being portable across many Unix and Windows platforms. You can write applications which use the tools on Windows and then run them on Unix platforms without change due to the consistent platform independent interfaces. All available packages have proven their stability and usefulness in many mission critical applications and various commercial settings all around the world. * About Python: Python is an object-oriented Open Source programming language which runs on all modern platforms (http://www.python.org/). By integrating ease-of-use, clarity in coding, enterprise application connectivity and rapid application design, Python establishes an ideal programming platform for todays IT challenges. * About eGenix: eGenix is a consulting and software product company focused on providing professional quality services and products to Python users and developers (http://www.egenix.com/). ________________________________________________________________________ NEWS The 3.0 release of the eGenix mx Base Distributions comes with a huge number of enhancements, bug fixes and additions. Some highlights: * All mx Extensions have been ported to Python 2.5. * mxDateTime has support for working with Python's datetime module types, so you can use and combine both if necessary. The parser was enhanced to support even more formats and make it more reliable than ever before. * mxTextTools now fully supports Unicode, so you can parse Unicode data just as fast as you can 8-bit string data. The package also includes a tag table compiler and new jump target support to simplify working with tag tables. * mxURL and mxUID were previously released as part of our mx Experimental distribution. They have now been integrated into the base distribution, providing easy-to-use data types for common tasks in web programming. * We've switched from the old distutils wininst installer to the new MSI installer for the Windows Python 2.5 build. This gives you a lot more options for automatic installs, including unattended installs. See http://www.python.org/download/releases/2.5/msi/ for details. For a more detailed description of changes, please see the respective package documentation on our web-site. As always we are providing pre-compiled versions of the package for Windows, Linux, Mac OS X, FreeBSD and Solaris as well as sources which allow you to install the package on all other supported platforms. ________________________________________________________________________ DOWNLOADS The download archives and instructions for installing the packages can be found on the eGenix mx Base Distribution page: http://www.egenix.com/products/python/mxBase/ ________________________________________________________________________ UPGRADING Please note that the 2.0 series of the eGenix mx Base Distribution does not support Python 2.5 on 64-bit platforms due to the Py_ssize_t changes in the Python C API. You are encouraged to upgrade to the new 3.0 series, if you plan to deploy on 64-bit platforms and use Python 2.5 as basis for your applications. ________________________________________________________________________ LICENSES & COSTS The eGenix mx Base package is distributed under the eGenix.com Public License which is a CNRI Python License style Open Source license. You can use the package in both commercial and non-commercial settings without fee or charge. The package comes with full source code ________________________________________________________________________ SUPPORT Commercial support for these packages is available from eGenix.com. Please see http://www.egenix.com/services/support/ for details about our support offerings. Enjoy, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, May 10 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 walterbyrd at iname.com Thu May 10 11:58:54 2007 From: walterbyrd at iname.com (walterbyrd) Date: 10 May 2007 08:58:54 -0700 Subject: Newbie look at Python and OO Message-ID: <1178812734.860473.236370@y80g2000hsf.googlegroups.com> I learned to program with Pascal, way back when. Went into software development for a while, then went into systems admin. Have programmed in several languages, just learning Python. Some things I find odd: 1) 5/-2 == -3? 2) list assignment handling, pointing two vars to the same list: With simple data types: >>> a = 5 >>> b = a >>> a = 3 >>> a,b (3, 5) Which is what I'd expect, since I have changed a, but not b. But with lists: >>> a = list("1234") >>> b = a >>> a.append("5") >>> a,b (['1', '2', '3', '4', '5'], ['1', '2', '3', '4', '5']) b changes even though I have not touched b. I know why, but this is not what I would ordinarilly expect, it does not seem intuitive. And, IMO, it gets worse: >>> a = list("1234") >>> b = a >>> a = a + ['5'] >>> a,b (['1', '2', '3', '4', '5'], ['1', '2', '3', '4']) Sometimes changing a changes b, and sometimes not. You also have to remember that subseqent changes to a will not change b - after some operation but not others. To those who think in Python, I'm sure this all seems normal. But, having programmed in about one dozen other language, this seems downright bizare to me. I know why it works like this, but it seems like an odd way to do things. 3) ambiguous use of the form: this.that() Sometimes, this.that() means module.funcion() as in: >>> os.dirlist(".") Other times, "this" is sort of like a parameter to the "that" function: >>> a = list("1234") >>> "_".join(a) '1_2_3_4_5' And still other times, is seems that "this" is an object, acted upon by "that" : >>> a = list("1234") >>> b = "_".join(a) >>> b.split("_") ['1', '2', '3', '4', '5'] BTW: it seems a bit odd to that the positions of the string, and the delimitor, are reversed between the complementory functions join(), and split(). I suppose if it weren't for OO, we have something terribly complicated, like: split(str, "_") join(str, "_") Again, those who think in Python, will understand right away that: math.count(x) is counting the substring "x" in the "math" string. But can you see where that might be confused to be a function called count() in the math module? I'm not complaining. Python is a great language in many respects. But, I would take some issue with those claiming Python is intuitive and easy. IMO: there seems to be many ambiguous, unintuitve, and confusing, aspects to Python. From aleax at mac.com Sun May 6 18:34:15 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 6 May 2007 15:34:15 -0700 Subject: My newbie annoyances so far References: <1177688082.758043.133920@r30g2000prh.googlegroups.com> <_9pYh.1787$uJ6.894@newssvr17.news.prodigy.net> <1178400807.051103.95690@q75g2000hsh.googlegroups.com> Message-ID: <1hxp15f.1bvtgo11ydx3cvN%aleax@mac.com> John Nagle wrote: > igouy2 at yahoo.com wrote: > > On Apr 27, 9:07 am, John Nagle wrote: > > > >>The CPython implementation is unreasonably slow compared > >>to good implementations of other dynamic languages such > >>as LISP and JavaScript. > > > > > > Why do you say CPython is slower than JavaScript? Please provide > > examples. > > See > > http://www.mozilla.org/projects/tamarin/faq.html > > Tamarin is a just-in-time compiler for Javascript. ...and is not yet released, as far as I can tell; this makes it kind of diffcult to verify any kinds of claims about its speed. So, I tried to check the current speed of actual, existing, released open-source stand-alone Javascript engines -- starting with Mozilla's own "spidermonkey" -- versus the CPython implementation which you claim is "unreasonably slow". I set myself a simple benchmark which I thought would be impartial (AKA "equally unfair to both sides":-) because it's a pretty weird task, for which neither engine has definitely been optimized: find out what pair (number-of-vowels, number-of-consonants) happens most often among the words in /usr/share/dict/words (the one I have on my Macbook Pro: the wordlist from Webster's Second International, 1934 edition). I ran into a few snags tied to me not being a particularly good Javascript programmer, and to limitations of the spidermonkey js that I could easily install (via MacPorts): no file I/O support (except for stdin/stdout), so the input has to come from stdin -- etc, etc; I tried making things fair by placing the same limitations on each implementation (also forcing Python to use stdin, etc). I'm sure my Javascript code can be made much better, but here is what I have so far, as a.js: var vowels_re = /[aeiou]/gi; var conson_re = /[bcdfghjklmnpqrstvwxyz]/gi; var v_w_count = new Object; while (1) { var x = readline(); if (x=='' || x==null) { break; } var vows = x.match(vowels_re); var numvows = (vows==null)?0:vows.length; var cons = x.match(conson_re); var numcons = (cons==null)?0:cons.length; var key = 100*numvows + numcons; v_w_count[key] = 1 + (v_w_count[key] || 0); } var topcombo = 0; var maxcount = 0; for (key in v_w_count) { var newcount = v_w_count[key]; if (newcount > maxcount) { maxcount = newcount; topcombo = key; } } var nc = topcombo % 100; var nv = (topcombo-nc) / 100; print("top combination: "+nv+" vowels, "+nc+" consonants (occurs "+maxcount+" times)."); and the result and timing: $ time js -f a.js #include #include int re_count(char* st, pcre* re) { int ovec[3]; int count = 0; int len = strlen(st); int start = 0; int rc; while( (rc=pcre_exec(re, NULL, st, len, start, 0, ovec, 3)) >= 0) { count++; start = ovec[1]; } if (rc != PCRE_ERROR_NOMATCH) { printf("rc was %d\n", rc); } return count; } int store_counts[100*100]; void add_count(int nc, int nv) { store_counts[nc + 100*nv]++; } int max_count(int* nc, int* nv) { int bestloc = 0; int topcoun = 0; int i; for(i=0; i<100*100; i++) { if (store_counts[i] > topcoun) { bestloc = i; topcoun = store_counts[i]; } } *nc = bestloc % 100; *nv = bestloc / 100; return topcoun; } int main() { const char* errms; int erof; pcre* vowels_re = pcre_compile("[aeiou]", PCRE_CASELESS, &errms, &erof, NULL); if (!vowels_re) { printf("(%s) at (%d) on vowels\n", errms, erof); return 1; } pcre* conson_re = pcre_compile("[bcdfghjklmnpqrstvwxyz]", PCRE_CASELESS, &errms, &erof, NULL); if (!conson_re) { printf("(%s) at (%d) on conson\n", errms, erof); return 1; } char buffer[1000]; while (gets(buffer)) { int nv = re_count(buffer, vowels_re); int nc = re_count(buffer, conson_re); add_count(nv, nc); } int pnv, pnc, maxc; maxc = max_count(&pnv, &pnc); printf("top combination: %d vowels, %d consonants (occurs %d times).\n", pnv, pnc, maxc); return 0; } $ time ./a.out #include char * vowels = "aeiouAEIOU"; char * conson = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"; void count_letters(char* astr, int* pnv, int* pnc) { int c; int nv=0; int nc=0; while(c = *astr++) { if(strchr(vowels, c)) nv++; else if(strchr(conson, c)) nc++; } *pnv = nv; *pnc = nc; } int store_counts[100*100]; void add_count(int nc, int nv) { store_counts[nc + 100*nv]++; } int max_count(int* nc, int* nv) { int bestloc = 0; int topcoun = 0; int i; for(i=0; i<100*100; i++) { if (store_counts[i] > topcoun) { bestloc = i; topcoun = store_counts[i]; } } *nc = bestloc % 100; *nv = bestloc / 100; return topcoun; } int main() { char buffer[1000]; while (gets(buffer)) { int nv, nc; count_letters(buffer, &nv, &nc); add_count(nv, nc); } int pnv, pnc, maxc; maxc = max_count(&pnv, &pnc); printf("top combination: %d vowels, %d consonants (occurs %d times).\n", pnv, pnc, maxc); return 0; } None of these sources is "super-optimized" (in particular, I'm sure it's just as easy to make the Javascript 3-4 times faster as it was for Python and C, if I only knew Javascript better -- but even the faster Python and C programs could well be pushed further), but I think that exactly because of this factor they may be "representative" of typical uses of the languages (inasmuch as a tiny benchmark can ever be "representative", of course). Alex From vatamane at gmail.com Mon May 14 12:10:03 2007 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 14 May 2007 09:10:03 -0700 Subject: Beginner question: module organisation In-Reply-To: <1179148188.698342.317080@w5g2000hsg.googlegroups.com> References: <1179148188.698342.317080@w5g2000hsg.googlegroups.com> Message-ID: <1179159003.658864.187100@u30g2000hsc.googlegroups.com> On May 14, 9:09 am, Mail.To.Nathan... at gmail.com wrote: > Hello :) > > I am new to python and I don't have much expirience in object-oriented > technologies neither. > > The problem is the following: I have to create a simple python > template script that will always follow the same algorithm, let's say: > - read a mesh > - transform the mesh (let's say, refine) > > The last step should be a kind of a black box: > - the same input data format > - some algorithme inside > - the same output data format > > A number of different refine methods should be implemented. The end- > user must be able to write easily a new method and call it from the > base script without any major change. > > Something like this would be a solution (no classes created, no OO > programming): > - a module defining REFINE1(mesh), REFINE2(mesh), ... > - in the script: > from MODULE import REFINE2 as REFINE > REFINE(mesh) > > Is it a proper solution for this kind of problem? How would you > implement this kind of task? Why not OO? This is a good problem for OO. For example: there is a base class (BaseMesh) that will take care of loading your mesh,provide a generic (possibly empty) refine() method, output the mesh and have a bunch of utility functions. You can put that in a module like meshing.py. Then the user will do: -------------------------------------------- from meshing import BaseMesh class UsersMesh(BaseMesh): def __init__(self,...): BaseMesh.__init__(self,...) ....etc. initializer... def refine(self,...): ...user's refine method would go here... -------------------------------------------------- So for each different refine() method the user can derive a new class from BaseMesh and overload the refine(...) method. Hope that helps, -Nick Vatamaniuc From bob.NGs at somewhere.com Tue May 1 15:23:44 2007 From: bob.NGs at somewhere.com (Bob Phillips) Date: Tue, 1 May 2007 20:23:44 +0100 Subject: SEO - Search Engine Optimization - Seo Consulting References: <1177808356.681710.42980@n76g2000hsh.googlegroups.com> <#O8fXGAjHHA.3700@TK2MSFTNGP06.phx.gbl> Message-ID: That is the oft-quoted, idiotic type of example. The reality is that if we follow the thread, we know the question, we only want to see the answer, not wade through a morass of stuff we have already seen. If we haven't seen it, guess what, we can go and read it. "funfly3" wrote in message news:EmLZh.835$r4.705 at newsfe1-gui.ntli.net... > David wrote: >> I am not going to join the argument, > > except you have > except to say that as you can see, I >> top post. In outlook express, you can see the messages as a thread, so >> you read the initial message, come to the reply and you read the response >> without having to scroll. Bottom posting would be fine if the previous >> message that promted the response was removed from the server, but it >> isn't, therefore, top posting is very logical. >> > only of you top post its logical as we all don't top post its not > > > A bird > > > Q name an animal that fly's > > see top posting is illogical > From olsongt at verizon.net Thu May 24 14:52:50 2007 From: olsongt at verizon.net (olsongt at verizon.net) Date: 24 May 2007 11:52:50 -0700 Subject: Windows Debugging w/o MS In-Reply-To: References: <1179933005.903709.258250@q75g2000hsh.googlegroups.com> Message-ID: <1180032770.689743.190460@u30g2000hsc.googlegroups.com> On May 24, 5:54 pm, "Christopher Anderson" wrote: > > Debug builds are incompatible with release builds. You'll need to > > build every binary extension in debug mode (assuming the original > > authors don't provide debug builds). > > Right, and this is what I would like to avoid having to do. > > Thanks, > Chris > > PS. Sorry for the duplicate olsongt Well I guess what I'm saying is, it's a pain to get a python debug environment up and running, regardless of your toolchain, but there isn't really any way of avoiding it. (Although I guess this is the case with any project that uses a bunch of different 3rd party components.) So you might as well buckle down and do it with whatever environment you like to use. I'd say maybe you could figure things out with a map file, but I'm guessing at least some .dlls are getting their addresses relocated when they're loaded. From steven.bethard at gmail.com Sat May 19 11:06:15 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 19 May 2007 09:06:15 -0600 Subject: docs patch: dicts and sets In-Reply-To: References: Message-ID: <_5-dnU7aIN73j9LbnZ2dnUVZ_uCinZ2d@comcast.com> Alan Isaac wrote: > I submitted the language based on Bill and Carsten's proposals: > > https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1721372&group_id=5470 > > That language has been rejected. > You many want to read the discussion and see if > acceptible language still seems discoverable. Seems to me that you're focusing on the wrong part of the docs. The source of this "bug" is not sets or dicts, but the default __hash__ method implementation. Why don't you propose adding something like: The default __hash__ method is based on an object's id(), and can therefore change between different iterations of the same program. to the docs for __hash__: http://docs.python.org/ref/customization.html Then if you really feel you need to add something for sets and dicts, you can add a cross-reference to the __hash__ docs. STeVe From hanser at club-internet.fr Tue May 15 15:07:30 2007 From: hanser at club-internet.fr (Pierre Hanser) Date: Tue, 15 May 2007 21:07:30 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> <4648294F.2000704@web.de> <46487a6c$0$2400$426a74cc@news.free.fr> Message-ID: <464a04e4$0$21147$7a628cd7@news.club-internet.fr> hello i work for a large phone maker, and for a long time we thought, very arrogantly, our phones would be ok for the whole world. After all, using a phone uses so little words, and some of them where even replaced with pictograms! every body should be able to understand appel, bis, renvoi, m?vo, ... nowdays we make chinese, corean, japanese talking phones. because we can do it, because graphics are cheaper than they were, because it augments our market. (also because some markets require it) see the analogy? of course, +1 for the pep -- Pierre From showell30 at yahoo.com Sun May 27 19:32:45 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 27 May 2007 16:32:45 -0700 (PDT) Subject: unit testing In-Reply-To: Message-ID: <223710.79740.qm@web33505.mail.mud.yahoo.com> Let me preface every reply here by YMMV. I strongly, strongly encourage people to tap into the unit testing community for all tools that are available to them. Also, let me say that despite any place where Steven and I disagree about the mechanics of unit testing, we're in firm agreement that UNIT TESTING IS IMPORTANT. And sorry for shouting. And, really, if you're not doing automated tests on your application now, you don't know what you're missing. --- Steven Bethard wrote: > > > 1) For flat-out failures, we just fail with a > > traceback right away. > > Looks like that's the -x/--exitfirst option in > py.test. > Yes, but for my purposes, it's even easier to do absolutely nothing when a test fails, just let it pass through. > > 2) We don't use assertions very often, but > rather > > just diff the output files to the GOLD files. > This > > may eventually stop to scale, but it hasn't yet. > > I guess I don't do enough stuff with file input and > file output for this > to make sense for me. > First, I should say that we don't completely ignore assertion tests, as it's useful for testing truly functional code, such as something that simply parses a message. But most of our application is I/O driven, and the actual tricky modules of our application do manage a conversation between a terminal and a host, and it's that conversation between the terminal that we want to proceed in a predictable fashion. > > 4) We have quite a few mock-ish objects, mainly > > relating to simulating I/O situations. > > > You might look into the Python Mock module: > > http://python-mock.sourceforge.net/ > Again, this is a case, where pardon my arrogance, I already know how my objects work, so I already know how to emulate them. I've read up on mock objects, so I'm not totally ignoring common wisdom, it's just that I get it, have a powerful language at my disposal, etc. I fully concede that my mock objects might be missing key features from the Python Mock module, but I also assert that I can implement pretty robust unit testing without it. ____________________________________________________________________________________Got a little couch potato? Check out fun summer activities for kids. http://search.yahoo.com/search?fr=oni_on_mail&p=summer+activities+for+kids&cs=bz From jmg3000 at gmail.com Mon May 14 20:55:28 2007 From: jmg3000 at gmail.com (jmg3000 at gmail.com) Date: 14 May 2007 17:55:28 -0700 Subject: customary way of keeping your own Python and module directory in $HOME In-Reply-To: References: <1179175513.896546.313500@y80g2000hsf.googlegroups.com> Message-ID: <1179190528.707235.324010@e65g2000hsc.googlegroups.com> On May 14, 6:00 pm, James Stroud wrote: > jmg3... at gmail.com wrote: > [snip], but on *nix, > you can compile python with the "--prefix=" option set to a directory in > your home dir and install there. Check. > I recommend having your own python install if you want a comprehensive > approach. Yup. I dropped the src in ~/src/Python-2.5.1, created a ~/py-2.5.1 directory, and did ./configure --prefix=/home/me/py-2.5.1 make make install and it worked fine. The only other step after that was creating a symlink: cd ln -s py-2.5.1 py and adding /home/me/py/bin to my $PATH. > Doesn't seem like hyper-paranoid sysadmining is all that efficient, does it? Well, on a server with many other users, they've pretty much gotta keep you confined to your home directory. My issues have been with keeping a ~/pylib directory for extra modules, and reconciling that with setuptools / Easy Install. I'm curious to hear how other folks manage their own local module directory. From wockehful at gmail.com Tue May 29 22:14:33 2007 From: wockehful at gmail.com (Mike) Date: 29 May 2007 19:14:33 -0700 Subject: Key Listeners Message-ID: <1180491273.446164.281990@q75g2000hsh.googlegroups.com> Are there key listeners for Python? Either built in or third party? From gagsl-py2 at yahoo.com.ar Thu May 17 22:22:43 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 17 May 2007 23:22:43 -0300 Subject: omissions in python docs? References: <1179419983.750044.65030@n59g2000hsh.googlegroups.com> <1179447228.985134.64860@y80g2000hsf.googlegroups.com> Message-ID: En Thu, 17 May 2007 21:13:49 -0300, John Machin escribi?: > On May 18, 9:24 am, "Gabriel Genellina" > wrote: >> En Thu, 17 May 2007 13:39:43 -0300, 7stud >> escribi?: >> >> > 2) The fnmatch module does not even mention translate(). >> >> At least for 2) you're late. It's already documented on >> 2.5.1:http://sourceforge.net/tracker/index.php?func=detail&aid=1630844&grou... >> > Not quite. All that says is that you raised the problem and that > somebody else's patch was accepted. > It's not in 2.5.1 AFAICT: not in "current docs" on Python website, not > in CHM file distributed with Windows version of Python 2.5.1 But it *is* corrected on the CHM file from Release 2.5.1c1 (5th April, 2007), and also in the source distribution for 2.5.1 final (libfnmatch.tex). I don't have the 2.5.1-final Windows binaries to check, but if it's not updated there, perhaps there was a hiccup on the release process. And the docs on python.org aren't updated either. Hiccups comes in sequence... -- Gabriel Genellina From http Mon May 28 18:52:24 2007 From: http (Paul Rubin) Date: 28 May 2007 15:52:24 -0700 Subject: Is PEP-8 a Code or More of a Guideline? References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <1180289911.951691.78640@k79g2000hse.googlegroups.com> <1hyttp5.cy5uldv00db3N%aleax@mac.com> Message-ID: <7xveec36jb.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > There was also Hypercard from Apple in (by memory) 1988. Although case was > not significant, handlers were usually written mouseDown, mouseUp, > openStack, openCard, etc. Apple (*cough*) Xerox PARC (*cough*). I think that style got into the Macintosh by way of Smalltalk, and got into X11 the same way indirectly, via the CMU Andrew system and its relatives that also were influenced by Smalltalk. From antroy at gmail.com Thu May 10 04:19:11 2007 From: antroy at gmail.com (Ant) Date: 10 May 2007 01:19:11 -0700 Subject: elegant python style for loops In-Reply-To: <1178776272.535735.166540@h2g2000hsg.googlegroups.com> References: <1178776272.535735.166540@h2g2000hsg.googlegroups.com> Message-ID: <1178785151.451094.104300@p77g2000hsh.googlegroups.com> On May 10, 6:51 am, ian.team.pyt... at saltmob.com wrote: ... > into a list of tuples to allow moving through multiple lists, or is > the for i in range(len(listkeys)): the only solution? > > Any suggestions? For the specific case of indexing lists, the following is cleaner than the 'for i in range...' solution above, and works in cases where zipping the lists may not be appropriate: for i, item in enumerate(mylist): print "%s) My item: %s; My other item: %s" % (i, item, my_non_iterable_object.thing_at(i)) -- Ant. From bj_666 at gmx.net Thu May 10 04:29:11 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 10 May 2007 10:29:11 +0200 Subject: replacing string in xml file--revisited References: <1178783809.444544.79640@w5g2000hsg.googlegroups.com> Message-ID: In <1178783809.444544.79640 at w5g2000hsg.googlegroups.com>, saif.shakeel wrote: > Although this works alone it is nto > working when i handle multiple file I/O.Is there a alternative to do > this.(maybe without read() operation) Why do you want to change the part that *works* instead of fixing the code that doesn't!? Ciao, Marc 'BlackJack' Rintsch From steve at holdenweb.com Thu May 24 14:11:41 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 24 May 2007 14:11:41 -0400 Subject: question about getch() In-Reply-To: References: Message-ID: gliquidsnake at hotmail.com wrote: > Hey all, > > I'm having a problem with using msvcrt.getch() . What I want is some > functionality like this: > > print 'blah blah blah, good_input to do blah blah blah, exit_key to exit' > > while input != exit_key: > input = get_input_from_getch() > > if input == good_input: > print input > #do something > if input == bad_input: > #ask for new input > if input == exit_key: > pass > > so, if the user's input is good, the input is printed to the screen and > the user is allowed to put in more input. > if the user's input is bad, the input is not printed to the screen and > python ignores the input. > if the user presses a designated key then the program continues. > > for some reason, all I get when I try to implement getch() is python > getting stuck in an infinite loop and printing "?" continuously. I > tried using msvcrt.kbhit() to wait for a key to be pressed before > continuing to getch() but it seems the program then skips the loop entirely. > > I guess I just don't really understand how to use getch(). =( > More likely, you don't understand Python loops. Rather than "pass" in the last option (which won't terminate the loop) try "break". 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From roy at panix.com Sat May 26 16:19:33 2007 From: roy at panix.com (Roy Smith) Date: Sat, 26 May 2007 16:19:33 -0400 Subject: Ancient projectiles (was: Muzzle Velocity (was: High resolution sleep (Linux)) References: <1178274122.142071.91740@y5g2000hsa.googlegroups.com> 0$3P3.9064@newssead3.news.pas.eeeeeeeeeeeeee ilman.7404.1178822935.32031.pytton-list@python..... j63.3876@newsreed2.news.pas.earrrrrrrrrrrr <3f0mi4-mj8.ln1@lairds.us> Message-ID: In article <3f0mi4-mj8.ln1 at lairds.us>, claird at lairds.us (Cameron Laird) wrote: > Hmmm; now you've got me curious. What *were* the first > composite projectiles? Fetchez la Vache! From luismgz at gmail.com Mon May 28 00:08:58 2007 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M=2E_Gonz=E1lez?=) Date: 27 May 2007 21:08:58 -0700 Subject: PHP5 programmer learning Python In-Reply-To: <1180280496.946434.26760@q69g2000hsb.googlegroups.com> References: <1180280496.946434.26760@q69g2000hsb.googlegroups.com> Message-ID: <1180325338.421710.32680@w5g2000hsg.googlegroups.com> On May 27, 12:41 pm, romiro wrote: > Hi all, > > I'm a PHP5 developer looking to "broaden my horizons" so to speak by > learning a new language. I emphasize the 5 in PHP since I have fully > engrossed myself in the full OOP of version 5 with my own ground-up > projects as well as some work with PRADO (http://pradosoft.com) > > I've dabbled with a number of languages in the past, Python being no > exception, but always ended up coming back to PHP due to being > comfortable with it. Python has stuck to me as a language I _really_ > think I should know more about. I've recently tried C#, a very short > lived re-attempt at C++ and Java, and Ruby. None of those seemed > "fun" except for Ruby, although from what I've seen the syntax between > Ruby and Python are very similar to each other compared to the other > languages. > > Anyway, my first question was if anyone knows of a tutorial that > focuses on PHP -> Python learning, in such that there might be a block > of PHP code alongside an example of how to do the same thing in > Python. One example of something I've already mapped a comparison to > thanks to standard tutorials is a PHP numeric indexed array being > similar to a list and a PHP associative array being similar to a > dictionary. Of course finding such of a tutorial isn't a deal breaker > by any means, but I figured that having it available would be a boon > for me to actually make some headway in my Python learning adventure. > > If there's anything else that could be said about the migration > between the two languages, I'm all ears. I also don't really need to > hear about how "disgusting" php is as a language...I am aware of the > contained chaos that is PHP4, which is why I develop strictly in 5 > using its OOP to the extent my feeble brain allows, a wariness toward > the insecure pitfalls the language has begat in the past, and an > attempt to produce as clean of a syntax as the language can allow. > > Thanks in advance for any help. I don't know of anything like a PHP to Python migration guide. But I think that you should just forget about PHP for awhile an inmerse yourself into learning Python, which is a general purpose programming language suitable for many tasks, and not only for the web. Start with the official tutorial or, if you want something more advanced, read "Dive into Python". Once you get a rough idea of all the cool things you can do with Python, you can concentrate again in web development. You'll be able to write more complex web sites with less code and a cleaner syntax, although you will have to spend some time deciding how to use Python in a web development context. There are many frameworks to choose from, and trying them all can be a daunting task... The choices range from the so called "full stack frameworks" (such as Django or TurboGears) that give you everything you need to build complex web sites and even more (templates, dispatching mechanisms, object-relational mappers, etc, etc) to minimalist solutions such as webpy. But this is something to evaluate after you have a good grasp of the language itself. Be warned: Python is highly addictive and it can make you a hopeless junkie... Good luck! Luis From kyosohma at gmail.com Wed May 30 14:54:15 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 30 May 2007 11:54:15 -0700 Subject: Off Topic: What is the good book to learn Python ? In-Reply-To: <1180549522.350380.276570@q66g2000hsg.googlegroups.com> References: <1180549522.350380.276570@q66g2000hsg.googlegroups.com> Message-ID: <1180551255.649269.251000@u30g2000hsc.googlegroups.com> On May 30, 1:25 pm, Katie Tam wrote: > I am new to this filed and begin to learn this langague. Can you tell > me the good books to start with ? > > Katie Tam > Network administratorhttp://www.linkwaves.com/main.asphttp://www.linkwaves.com Depends on what you like. For easy stuff that's fun, I liked "Python Programming for the Beginner" by Dawson as it let you create real applications (mostly silly games). "Beginning Python" by Hetland and the Python for Dummies book are both good. Hetland's goes over everything you'd need to know and it has some pretty cool, albeit complex examples in the last few chapters. If you want good exercises to go with what you learned in the book, I'd have to recommend "Python Programming: And Introduction to Computer Science" by Zelle. It's the only book I've seen with good exercises (or any exercises) at the end. Most don't have them. Once you're through all that wonderfulness, I would recommend "Python Programming 3rd Ed." by Lutz and/or "Core Python Programming" by Chun for excellent references. If you have any questions about any of these books let me know. I've read all of them (except for Lutz's...only halfway done with it). Mike From steve at holdenweb.com Fri May 25 21:19:47 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 25 May 2007 21:19:47 -0400 Subject: Module listing in order. In-Reply-To: <46578369.5050408@freakmail.de> References: <1179905562.541601.264400@m36g2000hse.googlegroups.com> <1180120016.349259.9540@x18g2000prd.googlegroups.com> <46578369.5050408@freakmail.de> Message-ID: <46578B33.7090209@holdenweb.com> Wildemar Wildenburger wrote: > Peter Otten wrote: >> Ramashish Baranwal wrote: >> >> >>>>> I want a way to get the contents in the order of their declaration, >>>>> i.e. [B, A, D]. Does anyone know a way to get it? >>>>> >>>> My suggestion would be to actually parse the text of the module. "Brute >>>> force" is what it's called ;). But doing so with, say, pyparsing >>>> shouldn't be *very* difficult. >>>> >> >>> Nevertheless, it would be interesting to see how it can be done.:) >>> >> >>>>> import pyclbr >>>>> classes = pyclbr.readmodule("mymodule") >>>>> sorted(classes, key=lambda name: classes[name].lineno) >>>>> >> ['B', 'A', 'D'] >> >> > > Good God! Is there *anything* that python does not already do? I hardly > feel the need to write programs anymore ... +1 QOTW > Its really 80% like of the questions that are asked here get answered > along the lines of: > > import some_fancy_module > > solution = some_fancy_module.exactly_the_right_function_to_solve(problem) > > > > Kinda scary ... :) And you haven't seen the time machine working yet ... 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From noagbodjivictor at gmail.com Sun May 6 17:01:20 2007 From: noagbodjivictor at gmail.com (noagbodjivictor at gmail.com) Date: 6 May 2007 14:01:20 -0700 Subject: c macros in python. Message-ID: <1178485280.394666.51970@n76g2000hsh.googlegroups.com> Hey, I'm writing a script to generate code. I'm a bit tired of typing outfile.write(....). Does python have a way to c-like macros? Every instance of o(...) in the code will be replaced by outfile.write(...)? From bdesth.quelquechose at free.quelquepart.fr Thu May 10 18:30:37 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 11 May 2007 00:30:37 +0200 Subject: Newbie look at Python and OO In-Reply-To: <1178832483.730331.248430@n59g2000hsh.googlegroups.com> References: <1178812734.860473.236370@y80g2000hsf.googlegroups.com> <1178832102.256466.235020@l77g2000hsb.googlegroups.com> <1178832483.730331.248430@n59g2000hsh.googlegroups.com> Message-ID: <46439304$0$2331$426a74cc@news.free.fr> half.italian at gmail.com a ?crit : (snip) > After thought: > > I do run into problems testing boolean values on a regular basis. FWIW, booleans were a late add-on. Originally, Python didn't had a bool type, only rules about the boolean value of a given object, mostly: 0, 0.0, '', [], (,), {} and None are false (you'll probably notice a pattern with a concept of emptyness). These rules still apply of course. From john at datavoiceint.com Fri May 11 17:46:54 2007 From: john at datavoiceint.com (HMS Surprise) Date: 11 May 2007 14:46:54 -0700 Subject: Time In-Reply-To: <1178916422.065108.312920@l77g2000hsb.googlegroups.com> References: <1178916216.893542.257320@y80g2000hsf.googlegroups.com> <1178916422.065108.312920@l77g2000hsb.googlegroups.com> Message-ID: <1178920014.621031.301860@n59g2000hsh.googlegroups.com> Sorry, reading a little closer I see that the time tuple is apparently an ordinary list. jvh From bj_666 at gmx.net Thu May 31 09:41:57 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 31 May 2007 15:41:57 +0200 Subject: file reading by record separator (not line by line) References: <1180614374.027569.235540@g4g2000hsf.googlegroups.com> Message-ID: In <1180614374.027569.235540 at g4g2000hsf.googlegroups.com>, Lee Sander wrote: > Dear all, > I would like to read a really huge file that looks like this: > >> name1.... > line_11 > line_12 > line_13 > ... >>name2 ... > line_21 > line_22 > ... > etc > > where line_ij is just a free form text on that line. > > how can i read file so that every time i do a "read()" i get exactly > one record > up to the next ">" There was just recently a thread with a `itertools.groupby()` solution. Something like this: from itertools import count, groupby, imap from operator import itemgetter def mark_records(lines): counter = 0 for line in lines: if line.startswith('>'): counter += 1 yield (counter, line) def iter_records(lines): fst = itemgetter(0) snd = itemgetter(1) for dummy, record_lines in groupby(mark_records(lines), fst): yield imap(snd, record_lines) def main(): source = """\ > name1.... line_11 line_12 line_13 ... > name2 ... line_21 line_22 ...""".splitlines() for record in iter_records(source): print 'Start of record...' for line in record: print ':', line Ciao, Marc 'BlackJack' Rintsch From rajarshi.guha at gmail.com Thu May 17 10:46:28 2007 From: rajarshi.guha at gmail.com (Rajarshi) Date: 17 May 2007 07:46:28 -0700 Subject: progress indicator in a mod_python script Message-ID: <1179413183.860119.264040@q23g2000hsg.googlegroups.com> Hi, I have a web application built using mod_python.Currently it behaves like a standard CGI - gets data from a form, performs a query on a backend database and presents a HTML page. However the query can sometimes take a bit of time and I'd like to show the user some form of indeterminate progress indicator (spinning dashes etc). My searching seems to indicate that this is based on some form of asynchronous calls (AJAX) and I'm not sure how I can achieve this effect in my mod_python app. Any pointers to achieve this would be very appreciated. Thanks, From spe.stani.be at gmail.com Mon May 28 11:02:31 2007 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: 28 May 2007 08:02:31 -0700 Subject: gettext backwards Message-ID: <1180364551.715547.65280@m36g2000hse.googlegroups.com> I am developping an international application for which I use gettext. An user can fill in certain fields with variable names which are also localized, eg: filename _('filename') = 'bestandsnaam' #for dutch As an english user might save this configuration, I want that eg a Dutch user can open this configuration but see 'filename' in Dutch ('bestandsnaam'). So my question is, does gettext supports reverse translation (assuming all translation strings are unique)? The reverse function would take a translated string and put it back in the original: foo('bestandsnaam') = 'filename' #to allow an english user to work with a file saved by a dutch user Of course I can customize _() so it keeps track of the translations in a reverse dictionary or I could build an external reverse dictionary, but I was wondering if there was a more elegant solution. Stani -- http://www.stani.be http://pythonide.stani.be In my code this would be called like From khemkaamit at gmail.com Thu May 24 08:23:12 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Thu, 24 May 2007 17:53:12 +0530 Subject: Changing Unicode object to Tuple Type In-Reply-To: <1180007132.103030.149770@q66g2000hsg.googlegroups.com> References: <1180007132.103030.149770@q66g2000hsg.googlegroups.com> Message-ID: <1360b7230705240523n56069f73g435a94c1d9571d34@mail.gmail.com> On 24 May 2007 04:45:32 -0700, laxmikiran.bachu at gmail.com wrote: > Can we have change a unicode string Type object to a Tuple type > object.. If so how ???? *Loosely* speaking a tuple is a collection of multiple objects. So what are the objects that you want to put in that tuple ?! Or do you want to store the unicode string as one of the member in a tuple ? In which case you can just do it the obvious way (though i guess thats not the question you asked)! Cheers, ---- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. From aleax at mac.com Sun May 20 00:03:50 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 19 May 2007 21:03:50 -0700 Subject: Inverse of id()? References: <1179618173.280286.284120@n59g2000hsh.googlegroups.com> Message-ID: <1hydot7.10wx666n6ryiiN%aleax@mac.com> Paul McGuire wrote: > Is there an inverse function to the builtin 'id'? The poster who No, there isn't. > Now is there anything better than this search technique to get back a > variable, given its id? For your own classes/types, you could override __new__ to maintain a class-wide (or even wider) weakref.WeakValueDictionary with id as the key and the instance as the (weakly held) value. For the general case, this wouldn't work -- however as your "search technique" checks globals only, it's pretty weak (it wouldn't find a value that's only held as an item in a list even if that list were global, for example). You might do a bit better by checking through gc.get_objects(), but that won't get objects of many types, such as int, float, str... Alex From mail at microcorp.co.za Sat May 26 02:31:13 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 26 May 2007 08:31:13 +0200 Subject: Newsgroups and mailing lists (was Re: Slightly OT: Why all thespam?) References: <3bb44c6e0705220008y10f5deb7v86ed82d3f8241761@mail.gmail.com> Message-ID: <004601c79f5f$7655ea40$03000080@hendrik> "Steve Holden" wrote: >I *did* try to explain all this a week or two ago. Did I not make myself >clear? Aah ! This makes a couple of assumptions, none of which are necessarily based on fact, namely: 1) That the people involved read what you wrote. 2) That they understood it. 3) That they remembered it. and possibly: 4) That they agreed with it and humiliatingly: 5) That you are not in their killfiles. : - ) - Hendrik From steven at REMOVE.THIS.cybersource.com.au Tue May 15 20:14:58 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 16 May 2007 00:14:58 GMT Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <7x4pmg716p.fsf@ruckus.brouhaha.com> <4648EC26.8020907@v.loewis.de> Message-ID: On Tue, 15 May 2007 09:09:30 +0200, Eric Brunel wrote: > Joke aside, this just means that I won't ever be able to program math in > ADA, because I have absolutely no idea on how to do a 'pi' character on > my keyboard. Maybe you should find out then? Personal ignorance is never an excuse for rejecting technology. -- Steven From bbxx789_05ss at yahoo.com Tue May 1 18:35:59 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 1 May 2007 15:35:59 -0700 Subject: Having problems accepting parameters to a function In-Reply-To: <1178055738.454313.182040@l77g2000hsb.googlegroups.com> References: <1178037488.163487.114930@l77g2000hsb.googlegroups.com> <1178039183.030942.86270@y5g2000hsa.googlegroups.com> <1178039953.223506.52760@y80g2000hsf.googlegroups.com> <1178055738.454313.182040@l77g2000hsb.googlegroups.com> Message-ID: <1178058959.327468.250510@q75g2000hsh.googlegroups.com> kwargs is not a built in name--it's a made up name used in the docs. Would you expect this function to work: def somefunc(x=10, y=20): print a The best way to figure out a feature of a programming language that you don't understand is not in the middle of some complex program. Instead, you should begin a new program, or if you are smart you will already have several blank programs already created waiting in the wings for testing purposes. In the new program, you can play around with functions, default values and catch all parameters like *a and **b to figure out how they work. From __peter__ at web.de Tue May 22 03:59:56 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 22 May 2007 09:59:56 +0200 Subject: doctest environment question References: <1179762737.153434.143030@b40g2000prd.googlegroups.com> <1179775483.685881.236940@x18g2000prd.googlegroups.com> <1179818466.394663.222390@k79g2000hse.googlegroups.com> Message-ID: tag wrote: > Thanks again Peter. Here's something much closer to what I really want > to do. You should be able to cut and paste this post into a file > "post.txt". Running the command `python -c "import doctest; > doctest.testfile('post.txt')"` gives a test failure even though > everything works fine in an interpreted Python session. I'd like to > find a way to make the doctest pass. > >>>> def announce(f): > ... " Return a function which announces calls to the input > function. " > ... def wrapper(*v, **k): > ... print "Calling %s" % f.__name__ > ... return f(*v, **k) > ... return wrapper > > We can rebind a function to announce calls to it: > >>>> def g(): pass > ... >>>> g = announce(g) >>>> g() > Calling g > > Or we can use decorator syntax: > >>>> @announce > ... def f(): pass > ... >>>> f() > Calling f > > Here's a function which rebinds a function at the top level of a > module (it won't work for nested functions). > >>>> def announce_function(f): > ... " Rebind f within a module so that calls to f are announced. " > ... import inspect > ... setattr(inspect.getmodule(f), f.__name__, announce(f)) inspect.getmodule(f) returns None because f() is not defined in a module. You can either move f() to a helper module and then from helper_module import f or modify anouncement_function() to not rely on that non-existent module >>> def announce_function(f): ... " Rebind f within a module so that calls to f are announced. " ... f.func_globals[f.__name__] = announce(f) ... > Let's give it a try. This next works fine in an interactive Python > session but fails when doctested. > >>>> def h(): pass > ... >>>> announce_function(h) >>>> h() > Calling h Even when it works, implicitly modifying global variables is bad style. Peter From andy.terrel at gmail.com Thu May 3 22:28:52 2007 From: andy.terrel at gmail.com (Andy Terrel) Date: 3 May 2007 19:28:52 -0700 Subject: Decorating class member functions In-Reply-To: <1178244237.702552.201410@l77g2000hsb.googlegroups.com> References: <1178241696.641350.292210@n59g2000hsh.googlegroups.com> <1178244237.702552.201410@l77g2000hsb.googlegroups.com> Message-ID: <1178245732.628599.251020@l77g2000hsb.googlegroups.com> I just need to keep the state around. I make a call to some function that is pretty expensive so I want to save it as a member during the __init__ of the decorator. Yeah I'm afraid it can't be done either, that's why I asked the group. From aisaac at american.edu Fri May 11 20:59:24 2007 From: aisaac at american.edu (Alan Isaac) Date: Sat, 12 May 2007 00:59:24 GMT Subject: docs patch: dicts and sets Message-ID: This is an attempt to synthesize Bill and Carsten's proposals. (I'm changing the subject line to better match the topic.) http://docs.python.org/lib/typesmapping.html: for footnote (3) Keys and values are listed in an arbitrary order. This order is indeterminate and generally depends on factors outside the scope of the containing program. However, if items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond. http://docs.python.org/lib/types-set.html: append a new sentence to 2nd par. Iteration over a set returns elements in an indeterminate order,which generally depends on factors outside the scope of the containing program. Alan Isaac From duncan.booth at invalid.invalid Wed May 16 04:34:49 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 May 2007 08:34:49 GMT Subject: Get a control over a window References: <1179234413.915336.263660@n59g2000hsh.googlegroups.com> Message-ID: Tom Gur wrote: > I was wondering how do I get control over a window (Win32). > to be more specific, I need to find a handle to a window of a certain > program and minimize the window. > Here's a function which returns a list of all windows where the class is 'PuTTY' or the title contains a particular string: from win32gui import EnumWindows, GetClassName, EnumChildWindows from win32ui import CreateWindowFromHandle, MessageBox def toplevelWindows(): res = [] def callback(hwnd, arg): name = GetClassName(hwnd) w = CreateWindowFromHandle(hwnd) title = w.GetWindowText() if "'s password:" in title or name=='PuTTY': res.append(w) EnumWindows(callback, 0) return res You can minimize a window once you have found it by calling ShowWindow (or SetWindowPlacement). If you don't want to depend on Python's win32 extensions being installed then you can also do the same thing using ctypes. In either case be very careful that you are only picking up the windows you wanted to find as enumerating top level windows will return a lot of hidden windows and if you start messing with these you will probably need to reboot your system. Here's something adapted from some stuff where I was playing with ctypes (so you could probably cut out a lot of crud). It's a complete program which will find a Firefox window with a specified string in the title and minimize it (without the test for the classname it will also minimize the command window you run it from). --------- minimize.py ------------- # # Minimize a specified window. # import sys import ctypes from ctypes import * def _stdcall(dllname, restype, funcname, *argtypes): # a decorator for a generator. # The decorator loads the specified dll, retrieves the # function with the specified name, set its restype and argtypes, # it then invokes the generator which must yield twice: the first # time it should yield the argument tuple to be passed to the dll # function (and the yield returns the result of the call). # It should then yield the result to be returned from the # function call. def decorate(func): api = getattr(WinDLL(dllname), funcname) api.restype = restype api.argtypes = argtypes def decorated(*args, **kw): iterator = func(*args, **kw) nargs = iterator.next() if not isinstance(nargs, tuple): nargs = (nargs,) try: res = api(*nargs) except Exception, e: return iterator.throw(e) return iterator.send(res) return decorated return decorate from ctypes.wintypes import HWND #, RECT, POINT LPARAM = c_ulong class metaENUM(type(ctypes.c_int)): def __init__(cls, name, bases, namespace): '''Convert enumeration names into attributes''' names = namespace.get('_names_', {}) if hasattr(names, 'keys'): for (k,v) in names.items(): setattr(cls, k, cls(v)) names[v]=k else: for (i,k) in enumerate(names): setattr(cls, k, cls(i)) super(metaENUM, cls).__init__(name, bases, namespace) class ENUM(ctypes.c_int): '''Enumeration base class. Set _names_ attribute to a list of enumeration names (counting from 0) or a dictionary of name:value pairs.''' __metaclass__ = metaENUM def __str__(self): return self.__repr__(fmt="%(value)s") def __repr__(self, fmt="<%(name)s %(value)s>"): try: return self._names_[self.value] except: return fmt % dict(name=self.__class__.__name__, value=self.value) def __int__(self): return self.value class BITMASK(ENUM): '''Some Microsoft 'enums' are actually bitmasks with several bits or'd together''' def __repr__(self, fmt="<%(name)s %(value)s>"): v = self.value values = [] while v: bit = v&(~v+1) try: values.append(self._names_[bit]) except (KeyError, IndexError): values.append(fmt % dict(name=self.__class__.__name__, value=self.value)) v &= ~bit if not values: return '0' return '|'.join(values) def __or__(self, other): return type(self)(int(self.value)|int(other.value)) class SHOWCMD(ENUM): _names_ = '''SW_HIDE SW_NORMAL SW_SHOW_MINIMIZED SW_SHOW_MAXIMIZED SW_SHOW_NOACTIVATE SW_SHOW SW_MINIMIZE SW_SHOWMINNOACTIVE SW_SHOWNA SW_RESTORE SW_SHOWDEFAULT SW_FORCEMINIMIZE'''.split() class WindowPlacementFlags(BITMASK): _names_ = dict(WPF_SETMINPOSITION = 1, WPF_RESTORETOMAXIMIZED = 2, WPF_ASYNCWINDOWPLACEMENT = 4) class Structure(ctypes.Structure): """As ctypes Structure but with added repr and comparison testing""" def __repr__(self): return "%s(%s)" % (self.__class__.__name__, ", ".join("%s=%r" % (f, getattr(self, f)) for (f,t) in self._fields_)) def __eq__(self, other): if self._fields_ != other._fields_: return False for (f,t) in self._fields_: if getattr(self,f) != getattr(other,f): return False return True class RECT(Structure): _fields_ = [("left", c_long), ("top", c_long), ("right", c_long), ("bottom", c_long)] class POINT(Structure): _fields_ = [("x", c_long), ("y", c_long)] class StructureWithLength(Structure): _fields_ = [('length', ctypes.c_ulong)] def __init__(self): ctypes.Structure.__init__(self) self.length = ctypes.sizeof(self) class WINDOWPLACEMENT(StructureWithLength): _fields_ = [ ('flags', WindowPlacementFlags), ('showCmd', SHOWCMD), ('ptMinPosition', POINT), ('ptMaxPosition', POINT), ('rcNormalPosition', RECT), ] def nonzero(result): # If the result is zero, and GetLastError() returns a non-zero # error code, raise a WindowsError if result == 0 and GetLastError(): raise WinError() return result WNDENUMPROC = ctypes.WINFUNCTYPE(ctypes.c_int, HWND, LPARAM) @ _stdcall("user32", c_int, "EnumWindows", WNDENUMPROC, LPARAM) def EnumWindows(callback, lparam=0): yield nonzero((yield WNDENUMPROC(callback), lparam)) @ _stdcall("user32", c_int, "GetWindowTextLengthW", HWND) def GetWindowTextLength(hwnd): yield nonzero((yield hwnd,)) @ _stdcall("user32", c_int, "GetWindowTextW", HWND, c_wchar_p, c_int) def GetWindowText(hwnd): len = GetWindowTextLength(hwnd)+1 buf = create_unicode_buffer(len) nonzero((yield hwnd, buf, len)) yield buf.value @ _stdcall("user32", c_int, "GetClassNameW", HWND, c_wchar_p, c_int) def GetClassName(hwnd): len = 256 buf = create_unicode_buffer(len) nonzero((yield hwnd, buf, len)) yield buf.value @ _stdcall("user32", c_int, "GetWindowRect", HWND, POINTER(RECT)) def GetWindowRect(hwnd): buf = RECT() nonzero((yield hwnd, buf)) yield buf @ _stdcall("user32", c_int, "GetClientRect", HWND, POINTER(RECT)) def GetClientRect(hwnd): buf = RECT() nonzero((yield hwnd, buf)) yield buf @ _stdcall("user32", c_int, "GetWindowPlacement", HWND, POINTER(WINDOWPLACEMENT)) def GetWindowPlacement(hwnd): buf = WINDOWPLACEMENT() nonzero((yield hwnd, buf)) yield buf @ _stdcall("user32", c_int, "SetWindowPlacement", HWND, POINTER(WINDOWPLACEMENT)) def SetWindowPlacement(hwnd, placement): yield nonzero((yield hwnd, placement)) @ _stdcall("user32", c_int, "IsWindow", HWND) def IsWindow(hwnd): yield bool((yield hwnd,)) @ _stdcall("user32", c_int, "ShowWindow", HWND, SHOWCMD) def ShowWindow(hwnd, showcmd): yield bool((yield hwnd,showcmd)) def toplevelWindows(): res = [] def callback(hwnd, arg): res.append(hwnd) return True EnumWindows(callback, 0) return res def iterWindows(klass, match): for hwnd in toplevelWindows(): if IsWindow(hwnd): try: title = GetWindowText(hwnd) except WindowsError, e: continue if klass==GetClassName(hwnd) and match in title: yield hwnd if __name__=='__main__': for hwnd in iterWindows("MozillaUIWindowClass", sys.argv[1]): wp = GetWindowPlacement(hwnd) ShowWindow(hwnd, SHOWCMD.SW_MINIMIZE) else: print "Sorry, I couldn't find the window" ----------------------------------- From steven at REMOVE.THIS.cybersource.com.au Tue May 15 05:33:56 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 15 May 2007 09:33:56 GMT Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <20070513160046.GC29172@v.igoro.us> <7x646wa9wz.fsf@ruckus.brouhaha.com> <7xfy608bkk.fsf@ruckus.brouhaha.com> <7xejlk3xpk.fsf@ruckus.brouhaha.com> <7xy7jsjaqi.fsf@ruckus.brouhaha.com> Message-ID: On Sun, 13 May 2007 21:21:57 -0700, Paul Rubin wrote: > Steven D'Aprano writes: >> password_is_correct is all ASCII. > > How do you know that? What steps did you take to ascertain it? Why would I care? I don't bother to check it is ASCII because it makes no difference whether it is ASCII or not. Allowing non-ASCII chars adds no new vulnerability. Here's your example again, modified to show what I mean: if user_entered_password != stored_password_from_database: password_is_correct = False # much code goes here... password_is_correct = True # sneaky backdoor inserted by Black Hat # much code goes here... if password_is_correct: log_user_in() Your example was poor security in the first place, but the vulnerability doesn't come from the name of the identifier. It comes from the algorithm you used. -- Steven. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri May 18 03:58:29 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 18 May 2007 09:58:29 +0200 Subject: Sending a JavaScript array to Python script? In-Reply-To: <1179405295.865954.241740@e65g2000hsc.googlegroups.com> References: <1179405295.865954.241740@e65g2000hsc.googlegroups.com> Message-ID: <464d5ca5$0$24177$426a74cc@news.free.fr> placid a ?crit : > Hi All, > > Just wondering if there is any way of sending a JavaScript array to a > Python cgi script? A quick Google search didn't turn up anything > useful. Look for "json". From pecora at anvil.nrl.navy.mil Fri May 4 09:49:53 2007 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Fri, 04 May 2007 09:49:53 -0400 Subject: Plot with scipy References: <1178283196.755609.241790@n59g2000hsh.googlegroups.com> Message-ID: In article <1178283196.755609.241790 at n59g2000hsh.googlegroups.com>, redcic wrote: > Hi all, > > I've just downloaded scipy v 0.5.2 and I would like to be able to draw > plots. I've tried: > import scipy.gplt > import scipy.plt > import scipy.xplt > > and none of them work. Are these modules still included in scipy ? If > not, where can I find them ? > > Thanks for your answers, > > C?dric > You really want matplotlib and PyLab the library built on top of it. Search on the python.org site for examples. Google will turn up a lot. Matplotlib w/ PyLab is a nice, easy plotting package. From tjreedy at udel.edu Mon May 14 14:01:16 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 14 May 2007 14:01:16 -0400 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <7x4pmg716p.fsf@ruckus.brouhaha.com> <4648571B.9050102@web.de> Message-ID: "Stefan Behnel" wrote in message news:4648571B.9050102 at web.de... | Sounds like CPython would better follow IronPython here. One could also turn the argument around and say that there is no need to follow IronPython; people who want non-ASCII identifiers can just juse IronPython. From bj_666 at gmx.net Sun May 27 06:51:57 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sun, 27 May 2007 12:51:57 +0200 Subject: totally lost newbie References: <1180261154.969654.147850@n15g2000prd.googlegroups.com> Message-ID: In <1180261154.969654.147850 at n15g2000prd.googlegroups.com>, mark wrote: > Hi all > > I posted earlier on this but have changed my approach so here is my > latest attempt at solving a problem. I have been working on this for > around 12 hours straight and am still struggling with it. > > Write a program that reads the values for a random list of cards from > a file, where each line in the file specifies a single card with the > rank and then the suit separated by a space. The rank should be an > integer in the range of 1 to 13 (Ace:1, King:13), while the suit > should be a lower case character in the set { 'h', 'd', 'c', 's' }. > Sort the card entries into suits ordered by rank, and print out the > ordered list. Hint: sort the list first by rank, and then by suit. > > The format of the cards.txt file is; > > 1 h > 1 d > 13 c > 10 s > > and so on for the whole deck. > > Can someone help me to get the mycomp function to work. > > Any help appreciated > > J > > def read_cards(filename): > > cards = [] > for card in open(filename, 'r'): > # strip the trailing newline character > cards.append(card.strip()) > return cards > > filename = 'cards.txt' > cards = read_cards(filename) > > > > def cards_str2tup(cards): > > cards_tup = [] > for card in cards: > rank, suit = card.split() > cards_tup.append((suit, int(rank))) > return cards_tup > > def cards_tup2str(cards_tup): > > cards = [] > space = ' ' > for tup in cards_tup: > suit, rank = tup > s = str(rank) + space + suit > cards.append(s) > return cards > > def mycmp( a, b): > #define the order in which the characters are to be sorted > order = [ 'h', 'd', 'c', 's' ] > # if the characters from each element ARENT the same > if a[1] <> b[1]: > #return the result of comparing the index of each elements > character in the order list > return cmp( order.index( a[1] ), order.index( b[1] ) ) > #otherwise > else : > #return the result of comparing each elements number > return cmp( a[0], b[0] ) > > cards.sort( mycmp ) > #print cards Maybe it's easier to use a key function instead of a compare function. A key function receives an element and must return something that is then sorted and the element ends up where the computed key is in the sorted list. Little example for sorting a list of strings first by length and strings of the same length by alphabetical order: def key_func(item): return (len(item), item) data = ['viking', 'spam', 'parrot', 'ham', 'eric'] data.sort(key=key_func) print data Ciao, Marc 'BlackJack' Rintsch From stefan.behnel-n05pAM at web.de Mon May 21 09:36:23 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 21 May 2007 15:36:23 +0200 Subject: howto check does module 'asdf' exist? (is available for import) In-Reply-To: <1179753436.736228.321400@x35g2000prf.googlegroups.com> References: <1179753436.736228.321400@x35g2000prf.googlegroups.com> Message-ID: <4651A057.8060800@web.de> dmitrey wrote: > howto check does module 'asdf' exist (is available for import) or no? Walk through sys.path and find it yourself? > (without try/cache of course) Why is the obvious (and most common) try/import/catch solution "of course" out? Stefan From stesch at no-spoon.de Thu May 3 03:20:22 2007 From: stesch at no-spoon.de (Stefan Scholl) Date: Thu, 3 May 2007 09:20:22 +0200 Subject: Microsoft's Dynamic Languages Runtime (DLR) References: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> Message-ID: <0T42enagIhkcNv8%stesch@parsec.no-spoon.de> In comp.lang.lisp sturlamolden wrote: > I am curious to know how it performs in comparison to CPython and an > efficient compiled Lisp like CMUCL. Speed is a major problem with You are not allowed to publish .NET benchmarks. :-) -- Web (en): http://www.no-spoon.de/ -*- Web (de): http://www.frell.de/ From nospam at noemailhere.nowhere Wed May 16 23:37:26 2007 From: nospam at noemailhere.nowhere (Anthony Irwin) Date: Thu, 17 May 2007 13:37:26 +1000 Subject: problem with import in python 2.2.3 Message-ID: Hi, I have written a python script that works perfectly in python 2.4.4 and python 2.4.3 but when I try to use the same script on an older system with python 2.2.3 I get the following error. ./backup_all_mysql_databases.py Traceback (most recent call last): File "./backup_all_mysql_databases.py", line 5, in ? from datetime import date ImportError: No module named datetime Does anyone know why the datetime module is not being found in python 2.2.3 and how I can make the script work in the older version of python? -- Kind Regards, Anthony Irwin http://www.irwinresources.com http://www.makehomebusiness.com email: anthony at above domains, - www. From fsckedagain at gmail.com Thu May 10 16:43:04 2007 From: fsckedagain at gmail.com (fscked) Date: 10 May 2007 13:43:04 -0700 Subject: path stuff In-Reply-To: <1178826330.282268.132350@p77g2000hsh.googlegroups.com> References: <1178734266.858048.311740@y5g2000hsa.googlegroups.com> <1178818879.239014.152210@e65g2000hsc.googlegroups.com> <1178826330.282268.132350@p77g2000hsh.googlegroups.com> Message-ID: <1178829783.996168.48250@u30g2000hsc.googlegroups.com> On May 10, 12:45 pm, fscked wrote: > On May 10, 10:41 am, fscked wrote: > > > > > > > On May 9, 7:02 pm, "Gabriel Genellina" wrote: > > > > En Wed, 09 May 2007 15:11:06 -0300, fscked > > > escribi?: > > > > > I am walking some directories looking for a certain filename pattern. > > > > This part works fine, but what if I want to exclude results from a > > > > certain directory being printed? > > > > Using os.walk you can skip undesired directories entirely: > > > > for dirpath, dirnames, filenames in os.walk(starting_dir): > > > if "archived" in dirnames: > > > dirnames.remove("archived") > > > # process filenames, typically: > > > for filename in filenames: > > > fullfn = os.path.join(dirpath, filename) > > > ... > > > > -- > > > Gabriel Genellina > > > OK, this is on Winbloze and it keeps giving me "The directory name is > > invalid: u"blahblahblah" with double backslashies everywhere. I am > > currently trying to figure out how to make those go away. I shall > > check back in a bit. > > > thanks for all the help so far. :)- Hide quoted text - > > > - Show quoted text - > > ok, got the backslashies fixed, not I want it to print just a single > line for each matching filename and dirpath, but it prints 3... hmm...- Hide quoted text - > > - Show quoted text - Nevermind, I am indentationally challenged. I was printing under the for dirpath, dirname, filename part and had to unindent uno time. It works as desired now, thanks! From byte8bits at gmail.com Mon May 21 09:46:33 2007 From: byte8bits at gmail.com (brad) Date: Mon, 21 May 2007 09:46:33 -0400 Subject: re.compile for names Message-ID: I am developing a list of 3 character strings like this: and bra cam dom emi mar smi ... The goal of the list is to have enough strings to identify files that may contain the names of people. Missing a name in a file is unacceptable. For example, the string 'mar' would get marc, mark, mary, maria... 'smi' would get smith, smiley, smit, etc. False positives are OK (getting common words instead of people's names is OK). I may end up with a thousand or so of these 3 character strings. Is that too much for an re.compile to handle? Also, is this a bad way to approach this problem? Any ideas for improvement are welcome! I can provide more info off-list for those who would like. Thank you for your time, Brad From python at rcn.com Fri May 11 21:41:32 2007 From: python at rcn.com (Raymond Hettinger) Date: 11 May 2007 18:41:32 -0700 Subject: docs patch: dicts and sets In-Reply-To: References: Message-ID: <1178934092.773288.31830@o5g2000hsb.googlegroups.com> On May 11, 5:59 pm, "Alan Isaac" wrote: > This is an attempt to synthesize Bill and Carsten's proposals. > (I'm changing the subject line to better match the topic.) > > http://docs.python.org/lib/typesmapping.html:for footnote (3) > > Keys and values are listed in an arbitrary order. This order is > indeterminate and generally depends on factors outside the scope of > the > containing program. However, if items(), keys(), values(), > iteritems(), iterkeys(), and itervalues() are called with no > intervening modifications to the dictionary, the lists will directly > correspond. > > http://docs.python.org/lib/types-set.html:append a new sentence to 2nd par. > > Iteration over a set returns elements in an indeterminate > order,which > generally depends on factors outside the scope of the containing > program. This doesn't improve the docs. It suggests some mystic forces at work while offering nothing that is actionable or that improves understanding. Adding this kind of muck will only make the docs less clear. Recommend dropping this one and moving on to solve some real problems. Raymond From rayiner at gmail.com Fri May 4 11:14:26 2007 From: rayiner at gmail.com (Rayiner Hashem) Date: 4 May 2007 08:14:26 -0700 Subject: Why stay with lisp when there are python and perl? In-Reply-To: <463a9668$0$8719$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: <1178291666.199541.73360@u30g2000hsc.googlegroups.com> > It is worth noting that eager, statically-typed languages like OCaml and F# > are many times faster than the other languages at this task. This is > precisely the forte of OCaml and F#, manipulating trees and graphs. To be fair, it is also worth noting that both the OCaml and F# implementations have code generators that are much more advanced than the usual suspects in the Lisp world (save maybe for Allegro, with which I have no experience). The OCaml code generator is reknowned for producing good code. And of course, F# has the benefit of the CLR code generator, which is state of the art. I don't know why the ML-family language implementations tend to have better code generators, but they do. SML/NJ's register allocator is an iterated-coalescing implementation written by Appel himself. Meanwhile, SBCL's allocator is a simple heuristic implementation, which wouldn't have been state of the art even 25 years ago. MLton does a full suite of SSA-based optimizations. SBCL's doesn't even do peephole optimization. And of course the CLR does *everything* (with Microsoft's $$$, there is no excuse for it not to). PS) I don't mean to pick on SBCL here. I'm just using it as an example because it's state of the art as far as free Lisp compilers go. From aleax at mac.com Tue May 8 01:24:25 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 7 May 2007 22:24:25 -0700 Subject: interesting exercise References: <1178595952.641173.76540@y80g2000hsf.googlegroups.com> <1178598876.913274.184850@p77g2000hsh.googlegroups.com> <1178599363.051648.235280@w5g2000hsg.googlegroups.com> <1178599567.894918.288450@l77g2000hsb.googlegroups.com> Message-ID: <1hxrks6.3v5xj5a4jv0bN%aleax@mac.com> wrote: ... > def p(a,b): > if list( a ) != sorted( list( a ) ): raise ValueError, "String not > ordered." > if not b: return [''] > return [i+j for i in list(a) for j in p(a,b-1)] No need for 2/3 of the list(...) calls. sorted(a) and sorted(list(a)) will ALWAYS be the same sequence; "for i in a" and "for i in list(a)" will always iterate on the same sequence [as long as you're not changing a inside the iteration, which, in this case, you aren't]. Alex From carsten at uniqsys.com Sun May 13 15:09:46 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sun, 13 May 2007 15:09:46 -0400 Subject: Interesting list Validity (True/False) In-Reply-To: <1179073565.933957.174250@o5g2000hsb.googlegroups.com> References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> <1178914190.166662.285410@p77g2000hsh.googlegroups.com> <1178915791.584216.293130@l77g2000hsb.googlegroups.com> <1178918808.091358.233740@o5g2000hsb.googlegroups.com> <1179017740.656323.209590@e51g2000hsg.googlegroups.com> <1179020634.130689.171960@o5g2000hsb.googlegroups.com> <1179073565.933957.174250@o5g2000hsb.googlegroups.com> Message-ID: <1179083386.3283.13.camel@localhost.localdomain> On Sun, 2007-05-13 at 09:26 -0700, mensanator at aol.com wrote: > > The statement I made is simply the meaning of "if arg==True" by > > definition, so I don't see how it can be nonsensical. > > Because you didn't allow for exceptions, which are > prominently pointed out in the Python docs. I said: "if arg==True" tests whether the object known as arg is equal to the object known as True. There are no exceptions. "==" means "equal", period! Your problem is that Python's notion of "equal" is different from your notion of "equal". > > The problem is that you consider equality tests in Python to be > > nonsensical because they don't fit with your opinion of what equality > > should mean. > > No, it has nothing to do with what it means. 1, [1], (1,) > and mpz(1) are all different types and all mathmatically > the same. Yet 1 and mpz(1) compare equal but (1,) and > [1] do not. And that just proves my point. You insist on the notion that equality means "mathematically the same". Python's equality tests sometimes work out that way, but that's not how equality actually works, nor how it is actually defined in Python. Regards, -- Carsten Haese http://informixdb.sourceforge.net From gregory.lielens at gmail.com Thu May 3 07:49:56 2007 From: gregory.lielens at gmail.com (gregory.lielens at gmail.com) Date: 3 May 2007 04:49:56 -0700 Subject: assigning to __class__ for an extension type: Is it still possible? In-Reply-To: <1178182978.525197.130690@u30g2000hsc.googlegroups.com> References: <1178182978.525197.130690@u30g2000hsc.googlegroups.com> Message-ID: <1178192996.610480.79370@c35g2000hsg.googlegroups.com> > We have then added the Py_TPFLAGS_HEAPTYPE tp_flag, which turn _PClass > into a heap > class and should make this class assignment possible... A precision: it seems that just addind Py_TPFLAGS_HEAPTYPE flag in the PyTypeObject tp_flags is not all you have to do to turn a static type into a heap type: indeed, when doing such in the Noddy examples, I have a segfault when just typing: n=Noddy() n there is an access to the ht_name slot that is apparently non initialized... So Maybe the core of the problem is that I do not define the heap type correctly....Do anybody have (or can tell me where to find) a small example of an extension module defining a heap class? Similar to the Noddy examples from the python doc? I did not find any concrete example of Py_TPFLAGS_HEAPTYPE in the current doc or on the net... Best regards, Greg. From rzantow at gmail.com Mon May 21 08:01:24 2007 From: rzantow at gmail.com (rzed) Date: Mon, 21 May 2007 12:01:24 +0000 Subject: Lists vs tuples (newbie) References: Message-ID: Szabolcs wrote in news:f2s0ut$128f$1 at toralf.uib.no: > > I was wondering about why are there both tuples and lists? Is > there anything I can do with a tuple that I cannot do with a > list? > > In what circumstances is it advantageous to use tuples instead > of lists? Is there a difference in performance? > > I am still learning Python, so please be gentle ... > This topic comes up from time to time in this newsgroup. If you want a lot of viewpoints about it, Google is your friend. A short answer, though: tuples can be used as dictionary keys and lists cannot. I would guess (but would have to test to confirm) that tuples occupy less space for the same data. I don't know whether any differences in, say, iteration speed would be terribly significant, but I would expect tuples to be marginally faster. -- rzed From quiettechblue at yahoo.com Sun May 6 23:49:21 2007 From: quiettechblue at yahoo.com (joseph2k) Date: Sun, 06 May 2007 20:49:21 -0700 Subject: Firefighters at the site of WTC7 "Move away the building is going to blow up, get back the building is going to blow up." References: <1178161820.731367.264500@y80g2000hsf.googlegroups.com> <1178163974.007362.13870@c35g2000hsg.googlegroups.com> <1178172877.755445.101340@q75g2000hsh.googlegroups.com> <1178173090.238547.62190@o5g2000hsb.googlegroups.com> <1178207619.155007.129860@o5g2000hsb.googlegroups.com> <1178267509.310342.146910@o5g2000hsb.googlegroups.com> Message-ID: <6lx%h.490$mR2.107@newssvr22.news.prodigy.net> mike3 wrote: > On May 3, 7:22 pm, The Great Attractor > wrote: >> On 3 May 2007 08:53:39 -0700, malibu wrote: >> >> >> >> >> >> >On May 3, 12:18 am, Eric Gisse wrote: >> >> On May 2, 10:14 pm, malibu wrote: >> >> >> > On May 2, 9:46 pm, Eric Gisse wrote: >> >> >> > > On May 2, 7:10 pm, Midex wrote: >> >> >> > > [...] >> >> >> > > I guess the explanation that people were looking at the building >> >> > > and watching its' structure deform is too rational. >> >> >> > Also, that was a Larry Silverstein impostor who >> >> > said they were going to 'pull it'. >> >> >> ...maybe if you read the context, it would make a little more rational >> >> sense. Fucking nutter. >> >> >> > And the only reason he took out huge amounts >> >> > of extra insurance on the buildings two months >> >> > before this happened was because of global >> >> > warming, because we all know a little bit of heat >> >> > will bring down steel buildings. >> >> >> A little heat and major structural damage. >> >> >> > John >> >> >Gee, I'll bet all those explosions in the >> >subfloors of WTC1 + WTC2 did some >> >structural damage also! >> >> You're an idiot. >> > > You did not refute the claim. How do you > know this claim is wrong? > >> >> >> >Come to think of it. >> >> Slugs do not think. >> > > You did not refute the claim. > >> >> >> >When the firefighters got there, all the glass >> >on the street floors was blown out. >> >> You're an idiot. >> > > You did not refute the claim. > >> >Shock wave from the plane hitting >> >80 floors up? >> >> You're a goddamned retard, boy. ARe you an islamic extremist by >> chance? >> > > You did not refute the claim. > >> >> >> >Janitors and such coming up from the basement levels >> >bleeding and dazed. >> >> You're full of shit. >> > > You did not refute the claim. > > >> >> >> >Jet fuel trickling down the elevator shafts being ignited >> >by someone's roach? And exploding? >> >> You're an ifiot. >> > > You did not refute the claim. > >> >Severing the three-foot thick steel columns? >> >All 5 dozen of them? >> >(That's mighty fine primo, pardner!) >> >> The buildings collapsed WAY WAY UP on the floors where the planes >> hit, and fell from there down, taking floors out as the large top >> section of the building fell. >> > > First good argument so far... > >> You could be a bit more retarded, just not in this life. >> >> >Your brain got structural damage? >> >> No, but your never was right from the moment your retarded felon >> criminal mother shat you out of her ass and forgot to flush. >> > > You did not refute the claim. > >> >Dropped on your head as a kid? >> >> Got any more adolescent baby bullshit, little boy? >> > > You did not refute the claim. > >> >Don't put that fire iron too close >> >to the flames, honey. It'll melt >> >and deform! >> >> You're an idiot. There was a tanker crash in Oakland a couple days >> back (Sunday) that melted sections of the bridge it was on. > > Second good argument so far. > Not actually a good argument. Difference #1. The beams on the bridge were not coated with fireproofing, thus were far more vulnerable. Difference #2. The petroleum fire had hours to act on bare metal in a concentrated way, WTC buildings #1 and #2 came down far less than an hour after impact; not enough time to get through the fireproofing as demonstrated by the comparison tests. Down to one pro self-collapse argument. > Two good arguments and eight non-arguments, > but those two good arguments happen to clinch the thing > anyway... > >> >> Got Clue? You and Rosie are retarded. -- JosephKK Gegen dummheit kampfen die Gotter Selbst, vergebens.?? --Schiller From carsten at uniqsys.com Sat May 5 09:21:10 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 05 May 2007 09:21:10 -0400 Subject: How do I get type methods? In-Reply-To: <1178353143.859683.200420@e65g2000hsc.googlegroups.com> References: <1178220806.664557.245780@c35g2000hsg.googlegroups.com> <1178253260.075515.43810@q75g2000hsh.googlegroups.com> <1178283588.694886.204250@c35g2000hsg.googlegroups.com> <1178289484.265718.198060@c35g2000hsg.googlegroups.com> <1178353143.859683.200420@e65g2000hsc.googlegroups.com> Message-ID: <1178371270.3134.23.camel@localhost.localdomain> On Sat, 2007-05-05 at 01:19 -0700, yavannadil at yahoo.com wrote: > On May 4, 7:13 pm, Marc 'BlackJack' Rintsch wrote: > > The OPs problem is, there is no access to the class or type because > > there is no name. > > Exactly :-( > > > You can get just instances from a factory function. > > Worse, if I call > > localContext.ServiceManage > > I'll get something with different set of methods, but of the same type > - 'pyuno' :-( 'pyuno' objects are proxy objects that represent UNO objects, services, and interfaces. Since all attribute lookups are handled by the UNO bridge, the proxy object doesn't actually know what attributes it has, which is why it won't respond anything useful to the usual dir() inspection. To list the methods and properties that the UNO object behind a pyuno proxy object has, you need to use UNO inspection capabilities. Something like the following seems to work: # unodir.py def unodir(unoobj): import uno from com.sun.star.beans.MethodConcept import ALL as ALLMETHS from com.sun.star.beans.PropertyConcept import ALL as ALLPROPS ctx = uno.getComponentContext() introspection = ctx.ServiceManager.createInstanceWithContext( "com.sun.star.beans.Introspection", ctx) access = introspection.inspect(unoobj) meths = access.getMethods(ALLMETHS) props = access.getProperties(ALLPROPS) return [ x.getName() for x in meths ] + [ x.Name for x in props ] >>> import uno >>> from unodir import unodir >>> localContext = uno.getComponentContext() >>> unodir(localContext) [u'queryInterface', u'acquire', u'release', u'getValueByName', u'getServiceManager', u'getElementType', u'hasElements', u'getByName', u'getElementNames', u'hasByName', u'replaceByName', u'insertByName', u'removeByName', u'getTypes', u'getImplementationId', u'queryAdapter', u'dispose', u'addEventListener', u'removeEventListener', u'ServiceManager', u'ElementType', u'ElementNames', u'Types', u'ImplementationId'] Hope this helps, Carsten From sjmachin at lexicon.net Mon May 7 19:32:14 2007 From: sjmachin at lexicon.net (John Machin) Date: 7 May 2007 16:32:14 -0700 Subject: getmtime differs between Py2.5 and Py2.4 In-Reply-To: References: Message-ID: <1178580734.350502.315630@l77g2000hsb.googlegroups.com> On May 8, 3:26 am, Josef Dalcolmo wrote: > I tried this on Windows only: > > In Python 2.4 os.path.getmtime returned the local time, > in Python 2.5 it seems to return GMT: > > import os, time > print ctime.time(os.path.getmtime(foo)) I think you mean time.ctime :-) > > differs on Python 2.4 and Python 2.5 by the timezone. > You have presented no evidence. Did you read my reply to your previous post? > Is this a bug? Is what a bug? My timezone is *TEN* hours away from UTC. Here's what I get [Windows XP Pro SP2]: C:\junk>dir newfile.txt Volume in drive C has no label. Volume Serial Number is 7D12-D6D2 Directory of C:\junk 08/05/2007 09:17 AM 0 newfile.txt 1 File(s) 0 bytes 0 Dir(s) 44,508,061,696 bytes free C:\junk>for %v in (4,5) do \python2%v\python -c "import os, time, sys; print sys .version, time.ctime(float(os.path.getmtime('C:\\junk\ \newfile.txt')))" C:\junk>\python24\python -c "import os, time, sys; print sys.version, time.ctime (float(os.path.getmtime('C:\\junk\\newfile.txt')))" 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] Tue May 08 09:17: 12 2007 C:\junk>\python25\python -c "import os, time, sys; print sys.version, time.ctime (float(os.path.getmtime('C:\\junk\\newfile.txt')))" 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] Tue May 08 09:17:12 2007 C:\junk> To avoid bandwidth waste, I've omitted similar results for Python 2.1, 2.2, and 2.3. From imageguy1206 at gmail.com Thu May 10 06:48:10 2007 From: imageguy1206 at gmail.com (imageguy) Date: 10 May 2007 03:48:10 -0700 Subject: msbin to ieee In-Reply-To: <1178487847.671199.108140@h2g2000hsg.googlegroups.com> References: <1178487847.671199.108140@h2g2000hsg.googlegroups.com> Message-ID: <1178794090.436098.322540@p77g2000hsh.googlegroups.com> On May 6, 6:44 pm, revuesbio wrote: > Hi > Does anyone have the python version of the conversion from msbin to > ieee? > Thank u Not sure if this helps, but I think this thread has the answer; http://groups.google.com/group/comp.lang.python/browse_thread/thread/286d9f6daff9bfab/ce76d5fcd887a47d?lnk=gst&q=geskerrett&rnum=2#ce76d5fcd887a47d Check out the response from Bengt Richter. His function did the right thing. From martin at v.loewis.de Fri May 18 00:45:30 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 18 May 2007 06:45:30 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <464C5227.7060804@v.loewis.de> Message-ID: <464D2F6A.4000404@v.loewis.de> > Possibly. One Java program I remember had Japanese comments encoded > in Shift-JIS. Will Python be better here? Will it support the source > code encodings that programmers around the world expect? It's not a question of "will it". It does today, starting from Python 2.3. >> Another possible reason is that the programmers were unsure whether >> non-ASCII identifiers are allowed. > > If that's the case, I'm not sure how you can improve on that in Python. It will change on its own over time. "Not allowed" could mean "not permitted by policy". Indeed, the PEP explicitly mandates a policy that bans non-ASCII characters from source (whether in identifiers or comments) for Python itself, and encourages other projects to define similar policies. What projects pick up such a policy, or pick a different policy (e.g. all comments must be in Korean) remains to be seen. Then, programmers will not be sure whether the language and the tools allow it. For Python, it will be supported from 3.0, so people will be worried initially whether their code needs to run on older Python versions. When Python 3.5 comes along, people hopefully have lost interest in supporting 2.x, so they will start using 3.x features, including this one. Now, it may be tempting to say "ok, so lets wait until 3.5, if people won't use it before anyway". That is trick logic: if we add it only to 3.5, people won't be using it before 4.0. *Any* new feature takes several years to get into wide acceptance, but years pass surprisingly fast. > There are lots of possible reasons why all these programmers around > the world who want to use non-ASCII identifiers end-up not using them. > One is simply that very people ever really want to do so. However, > if you're to assume that they do, then you should look the existing > practice in other languages to find out what they did right and what > they did wrong. You don't have to speculate. That's indeed how this PEP came about. There were early adapters, like Java, then experience gained from it (resulting in PEP 263, implemented in Python 2.3 on the Python side, and resulting in UAX#39 on the Unicode consortium side), and that experience now flows into PEP 3131. If you think I speculated in reasoning why people did not use the feature in Java: sorry for expressing myself unclearly. I know for a fact that the reasons I suggested were actual reasons given by actual people. I'm just not sure whether this was an exhaustive list (because I did not interview every programmer in the world), and what statistical relevance each of these reasons had (because I did not conduct a scientific research to gain statistically relevant data on usage of non-ASCII identifiers in different regions of the world). Regards, Martin From sturlamolden at yahoo.no Sat May 12 19:11:16 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 12 May 2007 16:11:16 -0700 Subject: Optimizing numpy In-Reply-To: <1179003123.707683.37360@y80g2000hsf.googlegroups.com> References: <1179003123.707683.37360@y80g2000hsf.googlegroups.com> Message-ID: <1179011476.298423.71260@w5g2000hsg.googlegroups.com> On May 12, 10:52 pm, Gerdus van Zyl wrote: > I have the following, that is used to convert pixel data and thus > should be as fast as possible: > > b = numpy.ndarray (shape=(w,h,4), dtype=numpy.uint8) > > a = numpy.frombuffer(buf, numpy.uint8) > a.shape = (w, h, 3) > > b[:,:,0] = a[:,:,2] > b[:,:,1] = a[:,:,1] > b[:,:,2] = a[:,:,0] > b[:,:,3] = 255 You can express this as: b[:,:,0:3] = a[:,:,2:-1:-1] b[:,:,3] = 255 > Can anyone tell me if there is a faster way? Will making use of > weave.blitz or pyrex help? If you are going to use wave, then don't bother with weave.blitz use wave.inline instead. You'll need something like this: code = """ register char a0, a1, a2; for (int i=0; i References: <4638fe20$0$16403$88260bb3@free.teranews.com> Message-ID: Tobiah wrote: > > >>> elegant_solution([1,2,3,4,5,6,7,8,9,10]) > [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] > > Here's one I use: def elegant_solution(alist): i = iter(alist) return [[j, i.next()] for j in i] py> elegant_solution(range(14)) [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11], [12, 13]] James From gagsl-py2 at yahoo.com.ar Tue May 1 05:06:08 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 01 May 2007 06:06:08 -0300 Subject: Log-in to forums (using cookielib)? References: <4636f011$0$329$e4fe514c@news.xs4all.nl> <4636fcb2$0$336$e4fe514c@news.xs4all.nl> Message-ID: En Tue, 01 May 2007 05:39:14 -0300, Olivier Oost escribi?: > Gabriel Genellina wrote: >> En Tue, 01 May 2007 04:44:57 -0300, Olivier Oost >> escribi?: >> >>> Can someone please tell me how I should log-in and leave a message on >>> the board? >> Sure. But considering that this smells like an Automatic Spamming >> Machine, I hope nobody will. > No, it's not meant as a spamming machine. I only need to post a message > and then (if that's possible) lock the topic (I'm admin on the forum > where I need this). The program first needs to read the topic for > certain words (that's already working), and then reply that those words > aren't welcome. I would verify that in the forum code if possible, not remotely. Anyway, the examples at the end of the cookielib section in the library reference are what you need: create an OpenerDirector using urllib2.build_opener, adding a suitable HTTPCookieProcessor handler. -- Gabriel Genellina From warren at muse.com Thu May 31 11:09:47 2007 From: warren at muse.com (Warren Stringer) Date: Thu, 31 May 2007 08:09:47 -0700 Subject: c[:]() In-Reply-To: <465E8CA4.4010506@isy.liu.se> References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180504773.374529.161740@q66g2000hsg.googlegroups.com><002801c7a2eb$288a8750$240110ac@Muse> <465E8CA4.4010506@isy.liu.se> Message-ID: <001e01c7a395$ba917d20$240110ac@Muse> Cool! Yes. By the way, I've discovered that [] are quite difficult on cell phones. But periods and parens are easy. So, I'm using your approach for creating a dot operator for {} > -----Original Message----- > From: python-list-bounces+warren=muse.com at python.org [mailto:python-list- > bounces+warren=muse.com at python.org] On Behalf Of Mikael Olofsson > Sent: Thursday, May 31, 2007 1:52 AM > To: python-list at python.org > Subject: Re: c[:]() > > Warren Stringer wrote: > > I want to call every object in a tupple, like so: > > [snip examples] > > Why? Because I want to make Python calls from a cell phone. > > Every keystroke is precious; even list comprehension is too much. > > If you are going to do this just a few times in your program, I cannot > help. But: If you want to do it several times, perhaps you have space > for an initial class definition, like so: > > class CallableList(list): > def __call__(self,*args,**kwargs): > return [f(*args,**kwargs) for f in self] > > def a(): return 'a called' > def b(): return 'b called' > c = CallableList([a,b])() > > You might want to trim the class to fit your needs, perhaps use a > shorter name, and perhaps you don't need to handle arguments. Can the > class be placed in a module, so that it only needs to be typed once in > your application? > > /MiO > -- > http://mail.python.org/mailman/listinfo/python-list From nogradi at gmail.com Tue May 1 14:05:34 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Tue, 1 May 2007 20:05:34 +0200 Subject: sqlite for mac? In-Reply-To: <6B264C2F-99A8-49F8-9D79-A052BE6602D6@jedimindworks.com> References: <1177993261.572563.70370@n76g2000hsh.googlegroups.com> <1178039558.882802.214030@n59g2000hsh.googlegroups.com> <1178041154.480155.78220@o5g2000hsb.googlegroups.com> <6B264C2F-99A8-49F8-9D79-A052BE6602D6@jedimindworks.com> Message-ID: <5f56302b0705011105t4aeca5d2p8f4012180911133a@mail.gmail.com> > >> I'm using python 2.4.4 because the download said there were more mac > >> modules available for 2.4.4. than 2.5, and I can't seem to locate a > >> place to download sqlite for mac. > > > > I it comes on OS X Tiger, and possibly earlier versions as well (it's > > used as an index for Mail.app).. You just need to download and > > install the pysqlite libraries. > > The system sqlite btw (which reports itself as version 3.1.3), is not > the same as what is included in Python 2.5. Will somebody please > say what version of sqlite is supported by Python 2.5 I'm using sqlite 3.3.11 with python 2.5 (on linux) but I guess some earlier versions will also work. Daniel From stefan.behnel-n05pAM at web.de Tue May 15 08:06:04 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 15 May 2007 14:06:04 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <4649a08c$0$23148$9b4e6d93@newsspool1.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <4648252D.5020704@web.de> <46483740.4050406@web.de> <46498cb1$0$6411$9b4e6d93@newsspool2.arcor-online.net> <46499273.6050806@web.de> <46499a54$0$10199$9b4e6d93@newsspool4.arcor-online.net> <46499B16.2070901@web.de> <4649a08c$0$23148$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <4649A22C.8010207@web.de> Ren? Fleschenberg wrote: > Stefan Behnel schrieb: >>>> Admittedly, it's done in Java, but why should Python fail to support unicode >>>> identifiers in the way Java does? >>> Your example does not prove much. The fact that some people use >>> non-ASCII identifiers when they can does not at all prove that it would >>> be a serious problem for them if they could not. >> Are we trying to prove that? > > IMO, if you cannot prove it, the PEP should be rejected, since that > would mean it introduces new problems without any proven substantial > benefits. > >> And, would we have serious problems and people running from Python if Python >> 2.5 did not integrate the "with" statement? > > 1) Which additional potential for bugs and which hindrances for > code-sharing do you see with the with-statement? I'm not sufficiently used to it to understand it immediately when I read it. So I would have to look deeper into patches that use it, for example, and couldn't accept them at first look. Plus, some editors do not highlight it as a Python keyword. So it should have been rejected. > 2) The with-statement does have proven substantial benefits, IMO. Not to me. I don't use it, so no-one should. And since it does not make sense in public projects, it should also be forbidden in in-house projects. Stefan From S.Mientki-nospam at mailbox.kun.nl Thu May 24 17:22:46 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Thu, 24 May 2007 23:22:46 +0200 Subject: Python and GUI In-Reply-To: <135bvon3ej90a0e@corp.supernews.com> References: <1179761984.704369.116310@b40g2000prd.googlegroups.com> <4651CDBC.1070508@ulmcnett.com> <5abb0$4655ee4c$d443bb3a$510@news.speedlinq.nl> <135bs4dfpdl8q33@corp.supernews.com> <8abbd$4655f7b0$d443bb3a$21589@news.speedlinq.nl> <135bvon3ej90a0e@corp.supernews.com> Message-ID: <3083e$46560153$d443bb3a$6284@news.speedlinq.nl> > >> Sorry, maybe I'm not Pythonic enough, but talking about "GUI >> framework", the first thing I want to see are screenshots. > > 0) While wax is a GUI framework, it is not a GUI designer, so I > was wondering who you were quoting when you wrote "a GUI > designer [...]". > > 1) Wax doesn't have any effect on the appearance of > applications, only on the appearance of the Python code used > to write the applications. So, screenshots are irrelevent. > > If you want screenshots of what wxWidgets apps look like, > there are lots of them at wxWidgets.org. But, since > wxWidgets generally uses "native" widgets, wxWidget apps > look pretty much like any other app on the given platform. > Thanks for the information, didn't know that. cheers, Stef Mientki From mail at timgolden.me.uk Tue May 8 10:59:32 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 08 May 2007 15:59:32 +0100 Subject: CPU usage In-Reply-To: <480063.86498.qm@web54508.mail.yahoo.com> References: <480063.86498.qm@web54508.mail.yahoo.com> Message-ID: <46409054.9070504@timgolden.me.uk> Navid Parvini wrote: > I want to get the CPU usage in my code. > Is there any module in Python to get it? What Operating System are you on? TJG From mailmaverick666 at gmail.com Thu May 31 04:42:04 2007 From: mailmaverick666 at gmail.com (rishi pathak) Date: Thu, 31 May 2007 14:12:04 +0530 Subject: Good Python style? In-Reply-To: <465E804B.9060904@a-beyer.de> References: <465E804B.9060904@a-beyer.de> Message-ID: <180b672e0705310142m7544a93fj42231ed5671971fc@mail.gmail.com> What if I want to process lines.In this case I would have to iterate over the set and do the processing On 5/31/07, Andreas Beyer wrote: > > Hi, > > I found the following quite cryptic code, which basically reads the > first column of some_file into a set. > In Python I am used to seeing much more verbose/explicit code. However, > the example below _may_ actually be faster than the usual "for line in > ..." > Do you consider this code good Python style? Or would you recommend to > refrain from such complex single-line code?? > > Thanks! > Andreas > > inp = resource(some_file) > # read first entries of all non-empty lines into a set > some_set = frozenset([line.split()[0] for line in \ > filter(None, [ln.strip() for ln in inp])]) > -- > http://mail.python.org/mailman/listinfo/python-list > -- Regards-- Rishi Pathak -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at microcorp.co.za Fri May 18 03:00:26 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 18 May 2007 09:00:26 +0200 Subject: Python-URL! - weekly Python news and links (May 16) References: <1179408898.460231.292340@k79g2000hse.googlegroups.com> Message-ID: <00a901c7991b$2b1c7340$03000080@hendrik> "Beliavsky" wrote: > On May 16, 2:45 pm, "Cameron Laird" wrote: > > QOTW: "Sometimes you just have to take the path of least distaste". - Grant > > Edwards > > > > "I want to choose my words carefully here, so I'm not misunderstood. > > > > I think Cameron Laird does a good job with the Python digest but > blundered here. Why did he highlight a foul comment having nothing to > do with Python? > Because its funny - you normally only say "I choose my words carefully", when you are about to say something that can be easily misconstrued, or that is technically difficult to follow - That particular preamble prepares you mentally for something difficult, and the coarse comment that follows is in such contrast that it had me ROTFLMAO - Hendrik From ask at me Wed May 9 00:37:04 2007 From: ask at me (alf) Date: Tue, 08 May 2007 23:37:04 -0500 Subject: which is more pythonic/faster append or +=[] Message-ID: two ways of achieving the same effect l+=[n] or l.append(n) so which is more pythonic/faster? -- alfz1 From mailmaverick666 at gmail.com Thu May 31 01:33:27 2007 From: mailmaverick666 at gmail.com (rishi pathak) Date: Thu, 31 May 2007 11:03:27 +0530 Subject: Usage of the __and__ method In-Reply-To: <1180588305.004419.127680@d30g2000prg.googlegroups.com> References: <1180588305.004419.127680@d30g2000prg.googlegroups.com> Message-ID: <180b672e0705302233r432c00b4ob0ff7c8ae07997d6@mail.gmail.com> class Person: def __init__(self,name): self.name = name def print_name(self): print self.name def __and__(self,other): print "self.name : ",self.name print "other.name : ",other.name self.name = '%s AND %s' %(self.name,other.name) return self.name p = Person("John") q = Person("George") #r = p and q #This does'nt call __and__ print p.__and__(q) #this works #print r.print_name() On 30 May 2007 22:11:45 -0700, theju wrote: > > Hello all, > I've two objects (both instances of a class called Person) and I want > to use the __and__ method and print the combined attributes of the two > instances. > > To be precise, here is my code.... > > class Person: > def __init__(self,name): > self.name = name > def print_name(self): > print self.name > def __and__(self,other): > self.name = '%s AND %s' %(self.name,other.name) > return self.name > > p = Person("John") > q = Person("George") > > r = p and q > print r.print_name() > > Output: > ----------- > George > None > > I've also tried this: > class Person: > def __init__(self,name): > self.name = name > def print_name(self): > print self.name > def __and__(self,other): > a = Person() > a.name = '%s AND %s' %(self.name,other.name) > return a > > p = Person("John") > q = Person("George") > > r = p and q > print r.print_name() > > Output: > ----------- > George > None > > The above output in both cases is giving me a doubt if __and__ method > is over-ridable or not? > > The output that I am accepting is: > John AND George > > What are the changes if to be made? > > Thanking You > Thejaswi Puthraya > http://thejuhyd.blogspot.com > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Regards-- Rishi Pathak National PARAM Supercomputing Facility Center for Development of Advanced Computing(C-DAC) Pune University Campus,Ganesh Khind Road Pune-Maharastra -------------- next part -------------- An HTML attachment was scrubbed... URL: From jstroud at mbi.ucla.edu Thu May 3 15:53:34 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 03 May 2007 12:53:34 -0700 Subject: Article on wxPython ToolKit for Mac OS X In-Reply-To: References: <1178204986.383057.264690@y80g2000hsf.googlegroups.com> Message-ID: James Stroud wrote: > miah_gbg wrote: > >> Hi there! >> >> Just wanted to let people know in this group that I have recently >> (April 24th) published an introductory article on wxPython and Mac OS >> X. It is available here: http://www.macdevcenter.com/ >> >> Hope someone finds it useful. >> >> Regards, >> >> Jeremiah >> > > Nice article, but it has an inaccuracy: > > "The first thing we need to do is download wxPython so we can begin > creating applications." > > This is not entirely correct. The stock 10.4 that came in a G5 bought in > June has wx built-in: > > cabin % /usr/bin/python > Python 2.3.5 (#1, Oct 5 2005, 11:07:27) > [GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> import wx > >>> > > Of course the stock python is 2.3, but its very cool that one can depend > on wx being present on 10.4+ machines. So there is no need to bundle > python/wx with your app when developing for Macs. (Yes, I noticed the > author is running OS X 10.3.) > > James Oh yes, a mactel (Quad Xeon) bought in January? platinum 1% /usr/bin/python Python 2.3.5 (#1, Aug 12 2006, 00:08:11) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import wx >>> Hell yeah, baby! From nick at craig-wood.com Sat May 5 06:30:03 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Sat, 05 May 2007 05:30:03 -0500 Subject: High resolution sleep (Linux) References: <1178274122.142071.91740@y5g2000hsa.googlegroups.com> Message-ID: John wrote: > > The table below shows the execution time for this code snippet as > measured by the unix command `time': > > for i in range(1000): > time.sleep(inter) > > inter execution time ideal > 0 0.02 s 0 s > 1e-4 4.29 s 0.1 s > 1e-3 4.02 s 1 s > 2e-3 4.02 s 2 s > 5e-3 8.02 s 5 s > > Hence it seems like the 4 s is just overhead and that the time.sleep > method treats values below approximately 0.001 as 0. The exact minimum sleep time will be determined by the HZ value that your kernel was compiled with. In newer kernels that is typically 250 or 1000, it used to be 100 in older kernels. If you look at the config file used to build your kernel you can discover the HZ value. If you try to sleep for less than a timer tick, then the kernel performs a yield. > Is there a standard way (or slick trick) to get higher resolution? If > it is system dependent it's acceptable but not very nice :) I assume you are using sleep for timing purposes.. This isn't a terribly good idea, but here is an idea for you.... # ------------------------------------------------------------ from time import time, sleep def hr_sleep(duration): end = time() + duration if duration > 0.02: sleep(duration) while time() - end < 0: sleep(0) if __name__ == "__main__": from timeit import Timer for e in range(0,7): dt = 10**-e loops = 10**e t = Timer("hr_sleep(%f)" % dt, "from __main__ import hr_sleep") print "expected = %.2E actual = %.2E" % (dt, t.timeit(loops)/loops) # ------------------------------------------------------------ This prints expected = 1.00E+00 actual = 1.00E+00 expected = 1.00E-01 actual = 1.00E-01 expected = 1.00E-02 actual = 1.00E-02 expected = 1.00E-03 actual = 1.00E-03 expected = 1.00E-04 actual = 1.02E-04 expected = 1.00E-05 actual = 1.19E-05 expected = 1.00E-06 actual = 2.66E-06 on my 250 HZ machine You could then do run-time calibration to work out the overhead of the function on any given machine to make it more accurate. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From andy.terrel at gmail.com Fri May 4 10:01:47 2007 From: andy.terrel at gmail.com (Andy Terrel) Date: 4 May 2007 07:01:47 -0700 Subject: Decorating class member functions In-Reply-To: <1178257019.771078.224620@e65g2000hsc.googlegroups.com> References: <1178241696.641350.292210@n59g2000hsh.googlegroups.com> <1178257019.771078.224620@e65g2000hsc.googlegroups.com> Message-ID: <1178287307.237246.245110@h2g2000hsg.googlegroups.com> Thanks Peter and 7stud. That is the solution that really works for me. From martin at v.loewis.de Sun May 6 04:23:30 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 06 May 2007 10:23:30 +0200 Subject: FIXED: webmaster@python.org In-Reply-To: <463D1EB3.8060400@lexicon.net> References: <463D1EB3.8060400@lexicon.net> Message-ID: <463D9082.6020801@v.loewis.de> > """ > Error... > > There's been a problem with your request > > psycopg.ProgrammingError: ERROR: could not serialize access due to > concurrent update > > delete from browse_tally > """ If that happens, just try again. I don't know how to fix it, but if you retry, it should work. Regards, Martin From mail at sphinx.net.ru Sat May 12 14:40:47 2007 From: mail at sphinx.net.ru (Dmitry Dzhus) Date: Sat, 12 May 2007 22:40:47 +0400 Subject: Basic question In-Reply-To: <1178992910.318929.77790@e51g2000hsg.googlegroups.com> (Cesar G. Miguel's message of "12 May 2007 11\:01\:50 -0700") References: <1178986686.510137.195490@p77g2000hsh.googlegroups.com> <1178991933.421386.58500@u30g2000hsc.googlegroups.com> <1178992910.318929.77790@e51g2000hsg.googlegroups.com> Message-ID: <874pmhq40g.fsf@sphinx.net.ru> > Actually I'm trying to convert a string to a list of float numbers: > str = '53,20,4,2' to L = [53.0, 20.0, 4.0, 2.0] str="53,20,4,2" map(lambda s: float(s), str.split(',')) Last expression returns: [53.0, 20.0, 4.0, 2.0] -- Happy Hacking. Dmitry "Sphinx" Dzhus http://sphinx.net.ru From cjw at sympatico.ca Sun May 13 20:47:48 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Sun, 13 May 2007 20:47:48 -0400 Subject: append In-Reply-To: <2adc542f0705101011y3164db06n3447c4263ae15249@mail.gmail.com> References: <1178816546.689849.255070@y5g2000hsa.googlegroups.com> <2adc542f0705101011y3164db06n3447c4263ae15249@mail.gmail.com> Message-ID: <4647B1B4.5020507@sympatico.ca> Sick Monkey wrote: > http://docs.python.org/tut/node7.html > > Yes there is a pop function. > > "An example that uses most of the list methods: > >>>> a = [66.25, 333, 333, 1, 1234.5] >>>> print a.count(333), a.count(66.25), a.count('x') > 2 1 0 >>>> a.insert(2, -1) >>>> a.append(333) >>>> a > [66.25, 333, -1, 333, 1, 1234.5, 333] >>>> a.index(333) > 1 >>>> a.remove(333) >>>> a > [66.25, -1, 333, 1, 1234.5, 333] >>>> a.reverse() >>>> a > [333, 1234.5, 1, 333, -1, 66.25] >>>> a.sort() >>>> a > [-1, 1, 66.25, 333, 333, 1234.5] > > " > > > On 10 May 2007 10:02:26 -0700, *HMS Surprise* > wrote: > > Trying not to be a whiner but I sure have trouble finding syntax in > the reference material. I want to know about list operations such as > append. Is there a pop type function? I looked in tutorial, language > reference, and lib for list, append, sequence. Is there a place where > us doofi ( who may not have our heads out in the sunlight) may find > all related syntax grouped together? > > thanx, > > jh > > -- > http://mail.python.org/mailman/listinfo/python-list > > Most of the syntax is set out in Sections 5, 6, 7 & 8 of the Language Reference Manual, with a very small part in Section 2. Colin W. From stefan.behnel-n05pAM at web.de Tue May 22 20:30:53 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 23 May 2007 02:30:53 +0200 Subject: Create an XML document In-Reply-To: <1179846012.972391.160800@z28g2000prd.googlegroups.com> References: <1179846012.972391.160800@z28g2000prd.googlegroups.com> Message-ID: <46538B3D.2060307@web.de> kyosohma at gmail.com wrote: > I am attempting to create an XML document dynamically with Python. It > needs the following format: > > > > 1179775800 > 1800 > > Try lxml.objectify. http://codespeak.net/lxml/dev/objectify.html >>> from lxml import etree, objectify >>> zAppointments = objectify.Element("zAppointments") >>> zAppointments.set("reminder", "15") >>> zAppointments.appointment = objectify.Element("appointment") >>> zAppointments.appointment.begin = 1179775800 >>> zAppointments.appointment.duration = 1800 >>> print etree.tostring(zAppointments, pretty_print=True) 1179775800 1800 Pretty much what one would expect. Stefan From bdesth.quelquechose at free.quelquepart.fr Sun May 20 17:02:06 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 20 May 2007 23:02:06 +0200 Subject: Python compared to other language In-Reply-To: <1179556574.341550.229190@q23g2000hsg.googlegroups.com> References: <1179540061.598417.13870@y80g2000hsf.googlegroups.com> <1hybvdz.1qnlesglcv0vcN%aleax@mac.com> <1179556574.341550.229190@q23g2000hsg.googlegroups.com> Message-ID: <4650acf1$0$4867$426a74cc@news.free.fr> walterbyrd a ?crit : > On May 18, 10:24 pm, a... at mac.com (Alex Martelli) wrote: > > >>I think that Ruby, which roughly speaking sits somewhere between Python >>and Perl, is closer to Python than Perl is. > > > I don't know much about Ruby, but it does not seem to be commonly used > for anything other than web-development. It may be that Ruby could be > used for other purposes, but I don't seem to see it happen much. Ruby is probably far better than Python at sys-admin tasks. And, while recently made much more visible because of the hype around Rails, it's definitively not specialized in web development. > I know that PHP can used at the command line, and could be used for > the same sort of sys-admin tasks for which, Perl and Python are often > used, but I don't seem to see that happening either. > > I'm not sure if Ruby, or PHP, are as general purpose as Perl or Python. Perl is not what I'd call a "general purpose" language. It has been explicitly designed as a sys-admin tool. PHP is of course not a general purpose language - the only serious reason to use PHP is that it's widely available on cheap web-hosting. Python and Ruby are general purpose languages - they have been designed to help writing applications, whatever the domain and the UI. From gagsl-py2 at yahoo.com.ar Tue May 8 20:53:11 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 08 May 2007 21:53:11 -0300 Subject: e-mailing multiple values References: <050820072307.24482.464102B3000B7E4300005FA222135753330D010C0E06A10407020E@comcast.net> Message-ID: En Tue, 08 May 2007 20:19:22 -0300, Ian Clark escribi?: > On 5/8/07, anil_jacob at comcast.net wrote: >> >> I have a script which has a method which returns multiple strings at >> once using the yield. I would like to send an e-mail of these values in >> a single e-mail instead of a mail for each string. How would I be able >> to do that? > > Are you looking for something like the following? If not, try posting > a small sampling of your code. > >>>> def get_data(): > ... data = ['ham', 'eggs', 'spam'] > ... for item in data: > ... yield item > ... >>>> all_data = [item for item in get_data()] >>>> all_data > ['ham', 'eggs', 'spam'] Or simply: all_data = list(get_data()) -- Gabriel Genellina From michael at jedimindworks.com Mon May 14 02:17:46 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Mon, 14 May 2007 01:17:46 -0500 Subject: Removing part of string In-Reply-To: <1179122203.691267.64200@o5g2000hsb.googlegroups.com> References: <1179122203.691267.64200@o5g2000hsb.googlegroups.com> Message-ID: On May 14, 2007, at 12:56 AM, saif.shakeel at gmail.com wrote: > Hi, > I am parsing an xml file ,and one part of structure looks > something like this: > > - PhysicalLink="Infotainment_Control_Bus_CAN"> > Infotainment_Control_Bus_CAN_TIMEOUT_AX > Timeout N_As/N_Ar > Time from transmit request until a CAN frame transmit > confirmation is received. > > > In my code i am extracting the data within > ,which is Timeout N_As/N_Ar.These tags repeat and will have > different timer names..like > > - PhysicalLink="Infotainment_Control_Bus_CAN"> > Infotainment_Control_Bus_CAN_TIMEOUT_BS > Timeout N_Bs > Time that the transmitter of a multi-frame message > shall wait to receive a flow control (FC) frame before timing out with > a network layer error. > > > I need to remove the words Timeout from the data,and > take only the abbrevation..i.e.N_As/N_bs like that .In short i have to > remove the words which come with name Time,and also the space which > comes next to it. > and take only the abbreviation.Can someone help me in this. > Thanks Assuming you're naming the string 'logname' and the only space is between the Time* word and the tags, this should work: logname.split() [-1] From Eric_Dexter at msn.com Mon May 28 06:04:21 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 28 May 2007 03:04:21 -0700 Subject: python -- prolog bridge error In-Reply-To: <1180316448.193656.262300@o5g2000hsb.googlegroups.com> References: <1180224507.324418.52170@q69g2000hsb.googlegroups.com> <1180316448.193656.262300@o5g2000hsb.googlegroups.com> Message-ID: <1180346661.932837.314560@o5g2000hsb.googlegroups.com> On May 27, 8:40 pm, yuce wrote: > Hello, > > PySWIP requires "libpl.dll" to be on the path. There are two ways to > do this: > > 1) Add 'bin' directory of SWI-Prolog to the PATH (it's C:\Program Files > \pl\bin on my system), > > 2) Or, copy 'libpl.dll' and 'pthreadVC.dll' to C:\WINDOWS\system32 > > That should solve the problem, happy hacking :) > > Yuce Tekol > > On 27 May?s, 03:08, "Eric_Dex... at msn.com" wrote: > > > > > I am getting an error with pyswip on xp that says the .dll isn't > > installed as a shared library. Is there a manual way to install > > the .dll as such??? prolog seems to work fine it is just the bridge > > that gives an error- Hide quoted text - > > - Show quoted text - I am not sure how to add it to the path... I did get it to work and now I have a interactive screen up... I will have to look into the docs to see if I can get it do anything else.. From steve at holdenweb.com Wed May 30 07:24:58 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 30 May 2007 07:24:58 -0400 Subject: Python 2.5 and WXPython demo's In-Reply-To: <1180523448.993195.59180@q69g2000hsb.googlegroups.com> References: <1180523448.993195.59180@q69g2000hsb.googlegroups.com> Message-ID: Andrew P wrote: > Hello, > > I am new (very) to Python and have just down loaded the latest version > of Python (2.5) and WXPython (2.8). > > For some reason I cannot get the WXPython demo to run at all. I run > windows XP and it can't find a program to run the demo. Any advice? > (apologies if this has been posted before). > The demo is a separate download nowadays. Do you mean you just can't find it, or are you running it and does it give you some error message that you feel we shouldn't be told about? A little more information, 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 ------------------ Asciimercial --------------------- Get on the web: Blog, lens and tag your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From johnjsal at NOSPAMgmail.com Tue May 8 15:23:31 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 08 May 2007 15:23:31 -0400 Subject: Suggestions for how to approach this problem? In-Reply-To: <4640ca5b$0$23392$c3e8da3@news.astraweb.com> References: <4640ca5b$0$23392$c3e8da3@news.astraweb.com> Message-ID: <4640cba9$0$30544$c3e8da3@news.astraweb.com> John Salerno wrote: > typed, there are often line breaks at the end of each line Also, there are sometimes tabs used to indent the subsequent lines of citation, but I assume with that I can just replace the tab with a space. From __peter__ at web.de Fri May 4 14:24:10 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 04 May 2007 20:24:10 +0200 Subject: How safe is a set of floats? References: <1178288509.067493.5140@e65g2000hsc.googlegroups.com> <1hxkw5d.1ipc1zfocmqm9N%aleax@mac.com> <1178294650.738576.205690@q75g2000hsh.googlegroups.com> <1178297450.812110.322140@q75g2000hsh.googlegroups.com> <1178298957.102330.50060@u30g2000hsc.googlegroups.com> Message-ID: Paul McGuire wrote: > Just to beat this into the ground, "test for equality" appears to be > implemented as "test for equality of hashes". So if you want to > implement a class for the purposes of set membership, you must > implement a suitable __hash__ method. It is not sufficient to > implement __cmp__ or __eq__, which I assumed "test for equality" would > make use of. Not having a __hash__ method in my original class caused > my initial confusion. As with dictionaries, only items with the same hash are considered for equality testing. > So would you suggest that any class implemented in a general-purpose > class library should implement __hash__, since one cannot anticipate > when a user might want to insert class instances into a set? (It > certainly is not on my current checklist of methods to add to well- > behaved classes.) A meaningful implementation would also have to make sure that the attributes used to calculate hash and equality don't change over time. No, I wouldn't bother because YAGNI. Peter From bhochstetler at gmail.com Fri May 4 08:17:21 2007 From: bhochstetler at gmail.com (bhochstetler at gmail.com) Date: 4 May 2007 05:17:21 -0700 Subject: hp 11.11 64 bit python 2.5 build gets error "import site failed" In-Reply-To: <1178255842.821465.114090@u30g2000hsc.googlegroups.com> References: <1178131203.719353.91360@y80g2000hsf.googlegroups.com> <4638fe11$0$1098$9b622d9e@news.freenet.de> <1178197261.294121.157120@h2g2000hsg.googlegroups.com> <463a5a2c$0$6904$9b622d9e@news.freenet.de> <1178255842.821465.114090@u30g2000hsc.googlegroups.com> Message-ID: <1178281041.121288.28700@e65g2000hsc.googlegroups.com> On May 4, 1:17 am, Leo Kislov wrote: > On May 3, 2:54 pm, "Martin v. L?wis" wrote: > > > > > >>> "import site failed" > > >>> OverflowError: signed integer is greater than the maximum. > > >> - what is the value of ival? > > > ival: 4294967295 > > > I see. This is 0xFFFFFFFF, which would be -1 if it were of type > > int. So perhaps some value got cast incorrectly at some point, > > breaking subsequent computations > > > >> - where does that number come from? > > > > It is coming from the call to PyInt_AsLong. In that function there is > > > a call to: > > > PyInt_AS_LONG((PyIntObject*)op) > > > which returns the value of ival. > > > That was not my question, really. I wanted to know where the object > > whose AsLong value was taken came from. And before you say "it's > > in the arg parameter" of convertsimple() - sure it is. However, how > > did it get there? It's in an argument tuple - and where came > > that from? > > Looking at the call stack OP posted, -1 is coming as forth parameter > of > __import__, I *guess* at the first import in site.py or at implicit > "import site". I think it'd be helpful if OP also tried if it works: > python -S -c -v "print -1, type(-1), id(0), id(-1)" > > -- Leo Here is the output, along with my printf statements that show the call stack: builtin___import__ PyArg_ParseTupleAndKeywords vgetargskeywords: positional arg: 0 convertitem vgetargskeywords: positional arg: 1 convertitem vgetargskeywords: positional arg: 2 convertitem vgetargskeywords: positional arg: 3 convertitem builtin___import__ PyArg_ParseTupleAndKeywords vgetargskeywords: positional arg: 0 convertitem vgetargskeywords: positional arg: 1 convertitem vgetargskeywords: positional arg: 2 convertitem vgetargskeywords: positional arg: 3 convertitem BRAD 20 PyArg_ParseTupleAndKeywords vgetargskeywords: positional arg: 0 convertitem vgetargskeywords: positional arg: 1 convertitem vgetargskeywords: positional arg: 2 convertitem builtin___import__ PyArg_ParseTupleAndKeywords vgetargskeywords: positional arg: 0 convertitem vgetargskeywords: positional arg: 1 convertitem vgetargskeywords: positional arg: 2 convertitem vgetargskeywords: positional arg: 3 convertitem builtin___import__ PyArg_ParseTupleAndKeywords vgetargskeywords: positional arg: 0 convertitem vgetargskeywords: positional arg: 1 convertitem vgetargskeywords: positional arg: 2 convertitem vgetargskeywords: positional arg: 3 convertitem convertitem convertitem convertitem convertitem builtin___import__ PyArg_ParseTupleAndKeywords vgetargskeywords: positional arg: 0 convertitem vgetargskeywords: positional arg: 1 convertitem vgetargskeywords: positional arg: 2 convertitem vgetargskeywords: positional arg: 3 convertitem vgetargskeywords: positional arg: 4 convertitem ival: 4294967295 builtin___import__ PyArg_ParseTupleAndKeywords vgetargskeywords: positional arg: 0 convertitem vgetargskeywords: positional arg: 1 convertitem vgetargskeywords: positional arg: 2 convertitem vgetargskeywords: positional arg: 3 convertitem vgetargskeywords: positional arg: 4 convertitem ival: 4294967295 Traceback (most recent call last): File "", line 1, in NameError: name 'v' is not defined From obaudys at gmail.com Tue May 15 20:50:15 2007 From: obaudys at gmail.com (Ondrej Baudys) Date: Wed, 16 May 2007 10:50:15 +1000 Subject: Quote aware split Message-ID: <41749080705151750m3367c65dy4d1ae6ca66c2a16b@mail.gmail.com> Hi, After trawling through the archives for a simple quote aware split implementation (ie string.split-alike that only splits outside of matching quote) and coming up short, I implemented a quick and dirty function that suits my purposes. It's ugly and it doesn't use a stack, it only supports a single character as a 'sep' function, only supports one type of quote (ie ' or " but not both), but it does the job, and since there have been a few appeals over the years for something of this sort I have decided to post what I have: --- BEGIN --- #!/usr/bin/env python def qsplit(chars, sep, quote="'"): """ Quote aware split """ qcount = 0 splitpoints = [-1] # ie. seperator char found before first letter ;) for index, c in enumerate(chars): if c is quote: qcount += 1 if c is sep and qcount % 2 == 0: splitpoints.append(index) # slice chars by splitpoints *omitting the separator* slices = [chars[splitpoints[i]+1:splitpoints[i+1]] for i in range(len(splitpoints)-1)] # last slice will be of the form chars[last:] which we couldnt do above slices.append(chars[splitpoints[-1]+1:]) return slices if __name__ == "__main__": test = "This is gonna be in quotes ';' and this is not; lets see how we split" test2 = """ A more complex example; try this on for size: create function blah ' split me once; split me twice; ' end; 'one more time;' and again; """ print "*--split--*".join(qsplit(test, ';')) print "*--split--*".join(qsplit(test2, ';')) # vim:tabstop=4:shiftwidth=4:expandtab --- END --- Regards, Ondrej Baudys From DustanGroups at gmail.com Wed May 2 21:04:50 2007 From: DustanGroups at gmail.com (Dustan) Date: 2 May 2007 18:04:50 -0700 Subject: How to check if a string is empty in python? In-Reply-To: References: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> Message-ID: <1178154290.811928.208900@h2g2000hsg.googlegroups.com> On May 2, 5:50 pm, Steven D'Aprano wrote: > On Wed, 02 May 2007 13:35:47 -0700, noagbodjivictor wrote: > > How to check if a string is empty in python? > > if(s == "") ?? > > In no particular order, all of these methods will work: > > # test s is equal to another empty string > if s == "": > > # assuming s is a string, test that it is empty > if not s: > > # test s is a string and it is empty > if isinstance(s, str) and not s: > > # test s has length 0 > if len(s) == 0: > > # test the length of s evaluates as false > if not len(s): > > # a long way to test the length of s > if s.__len__() < 1: > > # a stupid way to test s is empty > if bool(s) == False: > > # a REALLY stupid way to test s is empty > if (bool(s) == False) == True: LOL > # test that appending s to itself is itself > if s+s == s: > > # test that s has none of any character > if not filter(None, [1 + s.find(chr(n)) for n in range(256)]): > > That last one is really only good for wasting CPU cycles. and the other ones are... ? > -- > Steven. From mail at timgolden.me.uk Wed May 23 04:04:10 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 23 May 2007 09:04:10 +0100 Subject: Shared Memory Space - Accross Apps & Network In-Reply-To: <003a01c79b8a$8f1f8c30$ad5ea490$@rawlins@thinkbluemedia.co.uk> References: <003a01c79b8a$8f1f8c30$ad5ea490$@rawlins@thinkbluemedia.co.uk> Message-ID: <4653F57A.2090903@timgolden.me.uk> Robert Rawlins - Think Blue wrote: > I've got an application that runs on an embedded system, the application > uses a whole bunch or dicts and other data types to store state and other > important information. > I'm looking to build a small network of these embedded systems, and I'd love > to have them all share the same set or data. Is it possible to share the > applications variables across multiple applications, so certain lists are > like a 'pool' written to by the different systems? I'm sure I could cobble > something together by writing the lists to shared files instead of keeping > them in RAM, but that feels a little inefficient. I'd like to try and > configure some form of master/slave relationship between my applications if > possible. I was really surprised you hadn't received a whole slew of answers for this (even if they were: search the newsgroup for the last time this was asked!) But then I noticed that the post hadn't appeared on Google Groups, at least. I read things via the mailing list; is it possible your post hasn't made it across to Usenet either? Just to get the ball rolling, I'd suggest two things: Pyro - http://pyro.sf.net This is actively maintained and has been going for a while. We use it here (on a fairly small scale) and I know that others use it elsewhere for bigger things. It's based on a threaded socket server so whenever someone starts to say: "I know; I'll roll my own threaded socket server", I'm inclined to say: "Don't reinvent the wheel; try Pyro". PyLinda - http://www-users.cs.york.ac.uk/~aw/pylinda/ This implements the tuplespace paradigm. It's great fun to use, but as far as I know this implementation was a PhD project and lacks the robustness and wide use of other things. That said, it works perfectly well within its remit and might be a good match for what you're trying to do. No doubt other people can chime in with suggestions TJG From john at datavoiceint.com Mon May 7 18:06:29 2007 From: john at datavoiceint.com (HMS Surprise) Date: 7 May 2007 15:06:29 -0700 Subject: No module named urllib Message-ID: <1178575589.059564.226060@q75g2000hsh.googlegroups.com> I edited environment varialbes and have added C:\Python25\Lib to PYTHONPATH but get the no module message when the statement import urllib is executed. Even tried copying the urllib file to my working directory. Any suggestions? Thanks, jh From showell30 at yahoo.com Sun May 27 18:59:59 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 27 May 2007 15:59:59 -0700 (PDT) Subject: Newbie question - better way to do this? In-Reply-To: Message-ID: <95117.38736.qm@web33509.mail.mud.yahoo.com> --- Steven D'Aprano wrote: > On Sun, 27 May 2007 14:55:42 -0700, John Machin > wrote: > > Bzzzt. > Bzzzt! Can we please refrain from buzzer sounds in this mostly civil forum, even if one beep deserves another? ____________________________________________________________________________________ Looking for earth-friendly autos? Browse Top Cars by "Green Rating" at Yahoo! Autos' Green Center. http://autos.yahoo.com/green_center/ From enleverlesX.XmcX at XmclaveauX.com Tue May 1 15:00:09 2007 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Tue, 1 May 2007 21:00:09 +0200 Subject: SilverLight, a new way for Python? References: Message-ID: <46378e49$0$27370$ba4acef3@news.orange.fr> Re! >>> it can do much more than active scripting. Hummm.... Perhaps. But, with ActiveScripting, I can define functions & class in Python, Ruby(script), Jscript, VBscript, Perl. I can call these functions/objects directly from Python, and share many objects (& libraries). I am not sure to find these features in SilverLight. >>> Have you at least run the demos? Yes, I downloaded two demos, and run-it. I had look (quickly) the code. It's run. But it's too few for call that a true "try". However, these demos are nice & fun. Another thing: I have VS-2005. I had install the plug-in SilverLight/VS ; OK, but I don't found it in VS. Perhaps because I use a french version? (sorry, I don't speak english). This soft is young. I will wait some times, for read messages & realizations from new users. @-salutations Michel Claveau From bronger at physik.rwth-aachen.de Fri May 18 03:35:06 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Fri, 18 May 2007 09:35:06 +0200 Subject: Regexes: How to handle escaped characters References: <87tzubqniq.fsf@wilson.homeunix.com> <87irarqkz7.fsf@wilson.homeunix.com> <1179435962.962404.191600@y80g2000hsf.googlegroups.com> Message-ID: <877ir6r3dh.fsf@wilson.homeunix.com> Hall?chen! John Machin writes: > On May 18, 6:00 am, Torsten Bronger > wrote: > >> [...] >> >> Example string: u"Hollo", escaped positions: [4]. Thus, the >> second "o" is escaped and must not be found be the regexp >> searches. >> >> Instead of re.search, I call the function guarded_search(pattern, >> text, offset) which takes care of escaped caracters. Thus, while >> >> re.search("o$", string) >> >> will find the second "o", >> >> guarded_search("o$", string, 0) > > Huh? Did you mean 4 instead of zero? No, the "offset" parameter is like the "pos" parameter in the search method of regular expression objects. It's like guarded_search("o$", string[offset:]) Actually, my real guarded_search even has an "endpos" parameter, too. > [...] > > Quite apart from the confusing use of "escape", your requirements are > still as clear as mud. Try writing up docs for your "guarded_search" > function. Note that I don't want to add functionality to the stdlib, I just want to solve my tiny annoying problem. Okay, here is a more complete story: I've specified a simple text document syntax, like reStructuredText, Wikimedia, LaTeX or whatever. I already have a preprocessor for it, now I try to implement the parser. A sectioning heading looks like this: Introduction ============ Thus, my parser searches (among many other things) for r"\n\s*={4,}\s*$". However, the author can escape any character with a backslash: Introduction or Introduction \=========== ====\======= This means the first (or fifth) equation sign is an equation sign as is and not part of a heading underlining. This must not be interpreted as a section begin. The preprocessor generates u"===========" with escaped_positions=[0]. (Or [4], in the righthand case.) This is why I cannot use normal search methods. > [...] > > Whatever your exact requirement, it would seem unlikely to be so > wildly popularly demanded as to warrant inclusion in the "regexp > machine". You would have to write your own wrapper, something like > the following totally-untested example of one possible > implementation of one possible guess at what you mean: > > import re > def guarded_search(pattern, text, forbidden_offsets, overlap=False): > regex = re.compile(pattern) > pos = 0 > while True: > m = regex.search(text, pos) > if not m: > return > start, end = m.span() > for bad_pos in forbidden_offsets: > if start <= bad_pos < end: > break > else: > yield m > if overlap: > pos = start + 1 > else: > pos = end > 8<------- This is similar to my current approach, however, it also finds too many "^a" patterns because it starts a fresh search at different positions. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From nagle at animats.com Sun May 20 22:49:53 2007 From: nagle at animats.com (John Nagle) Date: Mon, 21 May 2007 02:49:53 GMT Subject: Newbie Question: python mysqldb performance question In-Reply-To: <1179705306.956396.261700@a26g2000pre.googlegroups.com> References: <1179705306.956396.261700@a26g2000pre.googlegroups.com> Message-ID: cjl wrote: > Group: > > I'm new to python and new to mysql. > > I have a csv file that is about 200,000 rows that I want to add to a > mysql database. Yes, I know that I can do this directly from the > mysql command line, but I am doing it through a python script so that > I can munge the data before adding it. > > I have the following example code: > > conn = MySQLdb.connect(db="database", host="localhost", user="root", > passwd="password") > c = conn.cursor() > > reader = csv.reader(open(sys.argv[1])) > for row in reader: > data1, data2, data3, data4 = row > data = (data1,data2,data3,data4) > c.execute("""insert into datatable values (%s, %s, %s, %s)""", > data) > conn.commit() > > This takes a really long time to execute, on the order of minutes. > Directly importing the csv file into mysql using 'load infile' takes > seconds. > > What am I doing wrong? What can I do to speed up the operation? "LOAD INFILE" is generally faster than doing many inserts. There are ways to speed things up, especially if you can reconfigure MySQL to use more memory. You may want to load the data without indexing it, then build the indices. Ask in a MySQL group, or read the manual. If you can use LOAD INFILE, do so. Preferably from an empty database. Then it can sort the records and insert them all at once. You can create a file for LOAD INFILE from Python, then issue the LOAD INFILE command. A few minutes isn't a "really long time" for that. I had to do 15,000,000 INSERT operations a few months back, and it took three days. John Nagle From nospam1.reifenberg at gmx.de Wed May 30 14:30:43 2007 From: nospam1.reifenberg at gmx.de (Nebur) Date: 30 May 2007 11:30:43 -0700 Subject: How can an Exception pass over an "except" clause ? In-Reply-To: References: <1180540010.548057.220270@m36g2000hse.googlegroups.com> Message-ID: <1180549843.351694.279660@p77g2000hsh.googlegroups.com> > However by being *VERY* perverse, I was able to reproduce the above > error by overwriting AttributeError with some other exception class (say > SyntaxError): > AttributeError = SyntaxError > Then your code will be will produce a real AttributeError, but miss it > because (despite the spelling) it checks for a SyntaxError, Yes ... this would be some kind of criminal joke > > Question... I don't know what contract.py is, but could it be doing > something that *bad*? No. I've searched the source for "AttributeError" and it appears only in except clauses. contracty.py is a library that adds Eiffel-like "design-by- contract" (DBC) to Python. Precisely, I can add preconditions (and postconditions) about the arguments into the methods docstring. These are checked at runtime (and appear in the epydoc docu.) This is a great thing I never want to miss anymore (and it was working fine for some months now.) (See http://www.wayforward.net/pycontract/ ) When the problem appears, contract.py is doing a pre-condition check. > You could check py printing AttributeError and see what it really is. > In my case it's: > >>> print AttributeError > exceptions.SyntaxError > > Gary Herron > > P.S.: Anyone who does this kind of thing is a danger to society. May > their finger fall off before they get a chance to distribute such a program. :-) @Tijs: I think when re-raising, the backtrace will always point to the line where it was re-raised but not to line 1265. (Or can we re-raise an exception so that it preserves the backtrace of the "original" exception?) --- I'm speculating about there's a misleading backtrace. Maybe another exception happens, but somehow using the obsolete exc_info of the last exception (the AttributeError). I remember about some way to clear the exc_info, maybe this must be added into contract.py? I'll find it out, or a debugger session this night will help (I'll post again) Ruben From apardon at forel.vub.ac.be Thu May 24 05:38:07 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 24 May 2007 09:38:07 GMT Subject: Basic Class/Instance Question References: <1179918439.085344.171330@u30g2000hsc.googlegroups.com> <46542543$0$6795$426a74cc@news.free.fr> Message-ID: On 2007-05-23, Wildemar Wildenburger wrote: > Antoon Pardon wrote: >>> This is a FAQ. Default arguments are only evaled once - when the def >>> statement is evaled (which is usually at import time). The solution is >>> simple: don't use mutable objects as default arguments: >>> >> >> An immutable object would have given the same behaviour in this case >> >> class A(object): >> def __init__(self, val = ()): >> self.val=val >> >> obj1 = A() >> obj2 = A() >> >> print obj1 is obj2 # False >> print obj1.val is obj2.val # True >> >> > Yeah, but is that a problem? Since you can not change them anyway, > there's no harm. I think it can make comprehension harder if you suggest in your explanation that a partcilular behaviour is linked to an object being mutable while that has nothing to do with it. You are correct that one can't mutate the val attribute but some code might depend on the distinction identical or not instead of equal or not. Not understanding this issue of default arguments could cause a bug in such code even if the default argument is not mutable. -- Antoon Pardon From george.sakkis at gmail.com Mon May 28 23:46:52 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 28 May 2007 20:46:52 -0700 Subject: Storing tracebacks Message-ID: <1180410412.643608.30050@q66g2000hsg.googlegroups.com> I'm reading the docs on sys.exc_info() but I can't tell for sure whether I'm using it safely to get a snapshot of an exception and reraise it later. The use case is a class which acts like a deferred callable, a callable that will be called at some point in the future (possibly in a different thread) and whose result or raised exception is to be stored as an attribute. This will be available by calling the result() method, which returns the original result or reraises the exception: class JobRequest(object): def __init__(self, *args, **kwds): self.args = args self.kwds = kwds self._exc_info = None def __call__(self): raise NotImplementedError('Abstract method') def process(self): try: self._result = self(*self.args, **self.kwds) except: self._exc_info = sys.exc_info() else: self._exc_info = None def result(self): if self._exc_info is not None: type,exception,traceback = self._exc_info raise type,exception,traceback try: return self._result except AttributeError: raise UnprocessedRequestError() class UnprocessedRequestError(RuntimeError): pass So far it seems it works as expected but I'd like to know if this is error-prone and why. George From gagsl-py2 at yahoo.com.ar Sat May 19 16:50:31 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 19 May 2007 17:50:31 -0300 Subject: getting thread object from SocketServer.ThreadingTCPServer References: <454738.13521.qm@web54111.mail.re2.yahoo.com> Message-ID: En Sat, 19 May 2007 14:40:55 -0300, Brad Brock escribi?: > Hi list. I have a little problem when using > SocketServer.ThreadingTCPServer. I want to make a list > of thread-objects generated by the > ThreadingTCPServer. How can I get the thread object? If getting the list of ALL threads (using threading.enumerate()) is not enough, you would need to override the process_request method to save the thread object in your own list. -- Gabriel Genellina From bignose+hates-spam at benfinney.id.au Fri May 18 02:10:25 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 18 May 2007 16:10:25 +1000 Subject: How to convert a number to binary? References: <1179444832.775573.55830@y80g2000hsf.googlegroups.com> <1179445546.307017.275850@p77g2000hsh.googlegroups.com> Message-ID: <87lkfm64ry.fsf@benfinney.id.au> Lyosha writes: > On May 17, 4:40 pm, Michael Bentley wrote: > > On May 17, 2007, at 6:33 PM, Lyosha wrote: > > > Is there an *easy* way to convert a number to binary? > > > > def to_base(number, base): > > [function definition] > > > > Hope this helps, > > Michael > > That's way too complicated... Is there any way to convert it to a > one- liner so that I can remember it? You put in a module so you don't *have* to remember it. Then, you use it in this one-liner: foo = to_base(15, 2) Carrying a whole lot of one-liners around in your head is a waste of neurons. Neurons are far more valuable than disk space, screen lines, or CPU cycles. -- \ "Quidquid latine dictum sit, altum viditur." ("Whatever is | `\ said in Latin, sounds profound.") -- Anonymous | _o__) | Ben Finney From peter_7003 at yahoo.com Tue May 8 08:16:38 2007 From: peter_7003 at yahoo.com (Peter Fischer) Date: Tue, 8 May 2007 05:16:38 -0700 (PDT) Subject: Specification for win32com.client package In-Reply-To: <46404D24.4040602@timgolden.me.uk> Message-ID: <23617.87850.qm@web63415.mail.re1.yahoo.com> Hello Tim, thank you for your answer and sorry for the multiple e-mails. Thank you also for the hint on the book. I already read into it in our local library. Its good, but a little outdated (Jan. 2000) as I mentioned in http://mail.python.org/pipermail/python-list/2007-May/438800.html Do you know, whether something has changed, since the book was written, in the use of the dcomcnfg tool? I heard that DCOM is included in COM since some time. I am not clear what steps are necessary under today's WinXP Professional to get DCOM run. But it is said that it shouldn't be difficult. However, I yet didn't manage to get it run. If you could give me a hint that would be helpful. One short question back to the documentation: I read that 'makepy' could be helpful to generate documentation to the package? Okay, thank you again so much for your great help so far, best regards, Peter. Tim Golden wrote: Peter Fischer wrote: > Hello, (sorry, the first message bounced; because it is urgent and I wait since > yesterday, here it's again): > > > I am searching for documentation about the interface the win32com package > provides, especially win32com.client. I searched the web and Mark Hammond?s > homepage but only found example code using Dispatch() and DispatchEx() etc. > Isn?t there a full list of the functions win32.com.client provides? Or do I have to > use makepy to somehow generate documentation (how)? > I would be thankful if someone could give me a hook about that. > > Best regards, Peter. I'm afraid you're pretty much out of luck on full documentation, Peter. Mark Hammond & Andy Robinson's book (of several years ago) is still being published: http://www.amazon.com/exec/obidos/tg/detail/-/1565926218?v=glance and certainly contains quite a bit of information on the subject. The .chm which comes with the pywin32 extensions has some information (although not much). Examples from the python-win32 list and this mailing list plus examples from around the web, plus finally the source code itself are pretty much staple fare for people working in the Win32 area under Python. Obviously, what it needs is someone or someones with the energy to get that Python Win32 wiki underway, but at the moment all my energies are devoted elsewhere, I'm afraid. TJG --------------------------------- Ahhh...imagining that irresistible "new car" smell? Check outnew cars at Yahoo! Autos. -------------- next part -------------- An HTML attachment was scrubbed... URL: From duane at franz.com Tue May 1 16:20:32 2007 From: duane at franz.com (Duane Rettig) Date: Tue, 01 May 2007 13:20:32 -0700 Subject: Lisp-like macros in Python? References: <1178035825.193334.184250@o5g2000hsb.googlegroups.com> Message-ID: sturlamolden writes: > Hello > > The Lisp crowd always brags about their magical macros. I was > wondering if it is possible to emulate some of the functionality in > Python using a function decorator that evals Python code in the stack > frame of the caller. The macro would then return a Python expression > as a string. Granted, I know more Python than Lisp, so it may not work > exactly as you expect. > > Any comments and improvements are appreciated. > > Regards, > Sturla Molden I don't know python, but check out http://www.cl-user.net/asp/libs/clpython -- Duane Rettig duane at franz.com Franz Inc. http://www.franz.com/ 555 12th St., Suite 1450 http://www.555citycenter.com/ Oakland, Ca. 94607 Phone: (510) 452-2000; Fax: (510) 452-0182 From paul at boddie.org.uk Mon May 21 05:55:19 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 21 May 2007 02:55:19 -0700 Subject: Inverse of id()? In-Reply-To: <1179618173.280286.284120@n59g2000hsh.googlegroups.com> References: <1179618173.280286.284120@n59g2000hsh.googlegroups.com> Message-ID: <1179741319.122807.56960@z24g2000prd.googlegroups.com> On 20 May, 01:42, Paul McGuire wrote: > > >>> re = Regex("(\d*)").setResultsName("x").setParseAction(lambda t:int(t[0])) > >>> results = re.parseString("123") > > pyparsing results have some special lookup behavior, that if the > results name is a Python-friendly identifier, can use the name as if > it were an object attribute: > > >>> results.x > 123 First of all, having recently looked at pyparsing again, I must say that it's a nice framework for writing parsers quickly. Now I'm not sure what the intention is behind this inquiry, so the following may seem somewhat tangential, but one thing that I tend to do a lot with pyparsing is to automatically set the results name by having a special grammar object: class Grammar: def __setattr__(self, name, value): self.__dict__[name] = Group(value.setResultsName(name)) This permits stuff like the following: g = Grammar() g.x = Regex("(\d*)").setParseAction(lambda t:int(t[0])) You'd even be able to incorporate the parse action, too, with some extra magic. As pyparsing is a library which seems to encourage clean grammar definitions, I think this makes quite a difference, although I now expect to be told that there's a class in the library which supports this. Anyway, back to the scheduled programme... Paul From george.sakkis at gmail.com Tue May 29 14:13:33 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 29 May 2007 11:13:33 -0700 Subject: Storing tracebacks In-Reply-To: References: <1180410412.643608.30050@q66g2000hsg.googlegroups.com> <1180446376.879439.55840@m36g2000hse.googlegroups.com> <1180457469.296553.291590@x35g2000prf.googlegroups.com> Message-ID: <1180462413.787936.125830@q66g2000hsg.googlegroups.com> On May 29, 1:21 pm, "Gabriel Genellina" wrote: > En Tue, 29 May 2007 13:51:09 -0300, George Sakkis > escribi?: > > > The traceback module is handy if you want a text representation of the > > traceback, not the actual traceback. The reason I want to store the > > actual traceback is to make the exception transparent to the user, > > i.e. not be able to tell whether the exception was thrown in the > > current stack frame or in another thread or even process. > > Unfortunately tracebacks are not pickleable, otherwise I could just > > pickle them in process() and unpickle them in result(). > > A traceback contains a linked list of frames, each with its own globals > and locals and lot of context info. > I'm not sure that moving a traceback across processes has any sense; a > textual representation should be enough, as t.b. are usually a debugging > aid and not supposed to reach the final user. The final user in this case is another programmer that uses a library, not some random guy using an application, so he certainly would be interested in seeing the traceback. I agree that the traceback is useful for debugging and the text representation would be enough if, for example, it was stored as an attribute in the Exception object and then used automatically by the runtime system (instead of calling sys.exc_info()). Of course nobody stops me from sticking traceback.format_tb() as an attribute in the Exception object and then have the client access it explicitly, something like: try: r = job.result() except Exception, ex: print ex.traceback The problem with this is that it's not transparent any more. The client must know that the originally raised object has been modified (or wrapped), sys.exc_info() doesn't work as expected, etc. It's not a show stopper by any means, but it would be convenient if there was a standardized optional "traceback" attribute that the runtime looks for and treats as the 3rd item of sys.exc_info() (otherwise it falls back to the current behavior). Would this be a reasonable feature request ? George From deets at nospam.web.de Wed May 23 18:39:24 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 24 May 2007 00:39:24 +0200 Subject: Properties/Decorators [WAS: Can I reference 1 instance of an object by more names ? rephrase] In-Reply-To: References: <4654289a$0$2326$426a74cc@news.free.fr> <5bj1ddF2sd0aoU1@mid.uni-berlin.de> Message-ID: <5bju51F2taechU1@mid.uni-berlin.de> Wildemar Wildenburger schrieb: > Diez B. Roggisch wrote: >> It is that very apply. >> >> And apply takes a function as argument + additional arguments, and >> executes >> that function, returning the result of that function-call. It was used >> before the >> f(*args, **kwargs) >> >> notation was introduced. >> >> Now what we have here is "value" as function, passed as single >> argument to >> apply (because decorators are just callables), which will invoke "value" >> with no arguments. The result of that operation is the property-object, >> that thus is returned by apply. And in the end gets assigned to the name >> value in the cpu_ports-class. >> > Sooo clever :). But apply is deprecated ... can I do the same thing some > other way? Deprecated doesn't mean it's not available. And even if it goes away, you can simply write it yourself: def apply(f, *args, **kwargs): return f(*args, **kwargs) So, if you want to, you can introduce your own function, e.g. def makeprop(f): return f and then do class Foo(object): @makeprop def bar(): ... # the fancy stuff Diez From martin at v.loewis.de Tue May 8 03:15:49 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 08 May 2007 09:15:49 +0200 Subject: Windows, subprocess.Popen & encodage In-Reply-To: <46401c16$0$5072$ba4acef3@news.orange.fr> References: <46401c16$0$5072$ba4acef3@news.orange.fr> Message-ID: <464023a6$0$4795$9b622d9e@news.freenet.de> > But, I don't found anything, in any documentations, on this. > > Sombody can confirm? Am I misled? Am I right? You are right, and you are misled. The encoding of the data that you get from Popen.read is not under the control of Python: i.e. not only you don't know, but Python doesn't know, either. The operating system simply has no mechanism of indicating what encoding is used on a pipe. So different processes may chose different encodings. Some may produce UTF-16, others may produce CP-850, yet others UTF-8, and so on. There really is no way to tell other than reading the documentation *of the program you run*, and, failing that, reading the source code of the program you run. On Windows, many programs will indeed use one of the two system code pages, or UTF-16. It's true that UTF-16 can be quite reliably detected by looking at the first two bytes. However, the two system code pages (OEM CP and ANSI CP) are not so easy to tell apart. Regards, Martin From tmp123 at menta.net Wed May 16 09:06:22 2007 From: tmp123 at menta.net (tmp123) Date: 16 May 2007 06:06:22 -0700 Subject: Execute commands from file Message-ID: <1179320782.594398.67980@u30g2000hsc.googlegroups.com> Hello, Thanks for your time. We have very big files with python commands (more or less, 500000 commands each file). It is possible to execute them command by command, like if the commands was typed one after the other in a interactive session? ( Better using command flags than with an small script like "while 1: input()" ) Thanks a lot. From ranaeng at hotmail.com Mon May 7 02:14:45 2007 From: ranaeng at hotmail.com (majeed rana) Date: Sun, 6 May 2007 23:14:45 -0700 Subject: PChess 0.9 Message-ID: An HTML attachment was scrubbed... URL: From arkanes at gmail.com Thu May 31 13:25:17 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 31 May 2007 12:25:17 -0500 Subject: speeding things up with C++ In-Reply-To: <1180608332.725330.306800@z28g2000prd.googlegroups.com> References: <1180171179.687276.77930@z28g2000prd.googlegroups.com> <1180608332.725330.306800@z28g2000prd.googlegroups.com> Message-ID: <4866bea60705311025o3eba2a91j1ddfea8c3b27d6d7@mail.gmail.com> On 31 May 2007 03:45:32 -0700, bullockbefriending bard wrote: > Thanks this is good news. I think my C/C++ background is sufficient to > manage to figure things out if I RTFM carefully. > > Basically I want to pass in a Python list of integer tuples, create an > STL container full of equivalent tuples, apply some processor- > intensive algorithm to said list of tuples, and finally poke the > results back into another Python list of integer tuples and return it > to the calling Python environment. Data structures are well-defind and > simple, and the most complex case would be 3-deep nested list, so I > will seriously consider figuring out how to do it manually as you > suggest. > Are you sure you want an STL container? Since the primary operator here is Python, the extra benefits from the STL container over plain C arrays isn't as evident. Pyrex is a good way to write the interface between your C++ code and the Python code - it handles the refcounting and boilerplate for you - and perhaps for writing the algorithms as well, depending on how complicated and performance sensitive they are. Also, using numeric/Numarray can be a very big win. It can potentially save you a fair amount of marshalling overhead. From ebgssth at gmail.com Sun May 20 06:26:03 2007 From: ebgssth at gmail.com (js ) Date: Sun, 20 May 2007 19:26:03 +0900 Subject: Closing socket file descriptors In-Reply-To: References: Message-ID: Hi Yang. > Hi, thanks for your answer. Should I just use that object's close() > method? Is it safe to assume that objects that have fileno() also have > close()? (Statically typed interfaces would come in handy now.) > I'm writing a simple asynchronous I/O framework (for learning purposes - > I'm aware of the myriad such frameworks for Python), and I'm writing a > wrapper around objects that can be passed into select.select(). Since > select() requires objects that have fileno's, that's the only > requirement I place on the wrapped object's interface, and thus why I've > been using FD-based operations: I'm not sure whether objects which have fileno always have close, but I think it's always safe to use the object's close method. How about keeping the wrapped object's interface consistent in your framework? It'd make your work moch easier. From hafeliel at yahoo.com Sat May 19 13:05:40 2007 From: hafeliel at yahoo.com (Gre7g Luterman) Date: Sat, 19 May 2007 11:05:40 -0600 Subject: Many-to-many pattern possiable? References: <1179592414.652507.4110@p77g2000hsh.googlegroups.com> Message-ID: "Jia Lu" wrote in message news:1179592414.652507.4110 at p77g2000hsh.googlegroups.com... > I see dict type can do 1-to-1 pattern, But is there any method to do > 1-to-many, many-to-1 and many-to-many pattern ? Dict objects can do many-to-1 relationships. Dict[Key1] = Obj Dict[Key2] = Obj Dict[Key3] = Obj 1-to-many relationships are more tricky and not something built-in to dictionaries. You can make each value in the dictionary a list of associated values: Dict[Key] = [Obj1, Obj2, Obj3] You can even subclass dict to give it the members you like, for example: class OneToMany(dict): def Add(self, Index, Value): V = self.get(Index, []) V.append(Value) self[Index] = V From bbxx789_05ss at yahoo.com Fri May 25 12:57:29 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 25 May 2007 09:57:29 -0700 Subject: sockets, gethostname() changing In-Reply-To: <1hynrtd.tvqdopconrxnN%aleax@mac.com> References: <1180062244.266857.300830@m36g2000hse.googlegroups.com> <1180063489.535893.182970@x35g2000prf.googlegroups.com> <1180065033.520142.37050@q66g2000hsg.googlegroups.com> <1180076739.557165.196900@x35g2000prf.googlegroups.com> <1hynrtd.tvqdopconrxnN%aleax@mac.com> Message-ID: <1180112249.598777.126950@m36g2000hse.googlegroups.com> >For local testing it is *much* easier to have your client >and server use IP address 127.0.0.1 According to my book, an address is a tuple of the form (hostname, port), so I didn't know what you meant by using 127.0.0.1 as the address. I played around with it, and using the tuple ("127.0.0.1", 1234) for the address worked(the server and client were able to communicate) and I got the expected output -- whether I was connected to the internet or not. I experimented a little more and "localhost" also worked for the hostname, and when I did that this line: c, addr = s.accept() produced an addr that contained "127.0.0.1" for the hostname. > Don't use any hostname at all; use '' instead. That should bind > to any interfase on your computer. That worked too when I was connected to the internet, and addr once again contained "127.0.0.1" for the hostname. > Looks like a DHCP configuration issue to me; one might try the > remedies suggested at I previously read similar postings about changing the HOSTNAME in /etc/ hostconfig from AUTOMATIC to a chosen name, but when I looked at /etc/ hostconfig there was no entry for HOSTNAME. Ok, I'll give it a whirl... I added the line: HOSTNAME=my.comp to /etc/hostconfig, and after restarting my computer, that succeeded in making the prompt in Terminal stay the same whether I was connected to the internet or not. But I got these errors when I tried to run my client/server programs: not connected to internet: --------------------------- Traceback (most recent call last): File "./programs_python/socketsServer.py", line 9, in ? s.bind((host, port)) File "", line 1, in bind socket.gaierror: (7, 'No address associated with nodename') connected to the internet: ------------------------- Traceback (most recent call last): File "./programs_python/socketsServer.py", line 9, in ? s.bind((host, port)) File "", line 1, in bind socket.error: (49, "Can't assign requested address") ------------------- So I deleted the line: HOSTNAME=my.comp from the hostconfig file and restarted my computer. After that my client/server programs would run as before. But now I get different output from my server program: Got socket connection from ('127.0.0.1', 49222) The strange thing is: the hostname and port in the output are not what I'm using in my server program: --------- import socket s = socket.socket() print "made changes 2" host = socket.gethostname() #I'm not connected to the internet when I use this line print host port = 1291 s.bind((host, port)) s.listen(5) while("Ctrl-C hasn't been entered"): c, addr = s.accept() #blocks and waits for client connection print "Got socket connection from", addr c.send("Thank you for connecting. Now get lost.") c.close() ---------- The full output of that program is: made changes 2 my-names-computer.local Got socket connection from ('127.0.0.1', 49222) The hostname now appears to be permanently stuck as "127.0.0.1", and the port is wrong. That output was so confusing to me, I wasn't even sure whether the file I was editing was actually the file that was executing, so I printed out "made changes #" at the top of the file to make sure the file I was editing was the one that was actually executing. I can't remember exactly what the output was for addr before I started messing around with the HOSTNAME in /etc/config, but I'm pretty sure addr contained the same hostname as the line above it in the output, and the port matched the port in the program. Any ideas why the hostname and port in the last line of the output are not the same as the ones used in the program anymore? From jstroud at mbi.ucla.edu Fri May 4 18:07:01 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 04 May 2007 15:07:01 -0700 Subject: behavior difference for mutable and immutable variable in function definition In-Reply-To: <1178314206.701824.291560@n59g2000hsh.googlegroups.com> References: <1178314206.701824.291560@n59g2000hsh.googlegroups.com> Message-ID: jianbing.chen at gmail.com wrote: > Hi, > > Can anyone explain the following: > > Python 2.5 (r25:51908, Apr 9 2007, 11:27:23) > [GCC 4.1.1 20060525 (Red Hat 4.1.1-1)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>>>def foo(): > > ... x = 2 > ... > >>>>foo() >>>>def bar(): > > ... x[2] = 2 > ... > >>>>bar() > > Traceback (most recent call last): > File "", line 1, in > File "", line 2, in bar > NameError: global name 'x' is not defined > > Thanks, > Jianbing > 1. Each function call creates its own namespace, so "x" in foo() is "isolated" from the global namespace or from calls of bar(). 2. Think of assignment as assigning a name to a value rather than "putting a value" into the name. When you assign, you completely change the identity of name, rather than changing the contents of the name. For example: py> x = object() py> id(x) 1074201696 py> x = object() py> id(x) 1074201704 Notice how the identity (id) of x changes. James From broek at cc.umanitoba.ca Tue May 22 19:53:33 2007 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Tue, 22 May 2007 19:53:33 -0400 Subject: Can I reference 1 instance of an object by more names ? In-Reply-To: References: Message-ID: <4653827D.3050600@cc.umanitoba.ca> Stef Mientki said unto the world upon 05/22/2007 07:44 PM: > hello, > > I'm trying to build a simple functional simulator for JAL (a Pascal-like language for PICs). > My first action is to translate the JAL code into Python code. > The reason for this approach is that it simplifies the simulator very much. > In this translation I want to keep the JAL-syntax as much as possible intact, > so anyone who can read JAL, can also understand the Python syntax. > > One of the problems is the alias statement, assigning a second name to an object. > I've defined a class IO_port, > and I create an instance of that port with the name port_D > > port_D = IO_port('D') > > Now I want to assign a more logical name to that port, > (In JAL: "var byte My_New_Name IS port_D") > > Is that possible ? > > I think the answer is "no", > because the object itself is not mutable. > Am I right ? > > But I read: "An object can have any number of names, or no name at all." > So am I wrong ? > > Sorry this has been discussed before, but I'm totally confused. > > thanks, > Stef Mientki > Stef, You can have multiple names pointing to an object. Consider: >>> class Example(object): ... pass ... >>> c1 = Example() >>> c2 = c1 >>> id(c1), id(c2) (136764076, 136764076) >>> c1, c2 (<__main__.Example object at 0x826daac>, <__main__.Example object at 0x826daac>) >>> del(c2) >>> c1, c2 Traceback (most recent call last): File "", line 1, in NameError: name 'c2' is not defined >>> c1 <__main__.Example object at 0x826daac> >>> HTH, Brian vdB From 2007 at jmunch.dk Sun May 13 18:53:01 2007 From: 2007 at jmunch.dk (Anders J. Munch) Date: Mon, 14 May 2007 00:53:01 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476081.7080609@web.de> Message-ID: <46479769$0$4170$ba624c82@nntp02.dk.telia.net> Michael Torrie wrote: > > So given that people can already transliterate their language for use as > identifiers, I think avoiding non-ASCII character sets is a good idea. Transliteration makes people choose bad variable names, I see it all the time with Danish programmers. Say e.g. the most descriptive name for a process is "k?r forl?ns" (run forward). But "koer_forlaens" is ugly, so instead he'll write "run_fremad", combining an English word with a slightly less appropriate Danish word. Sprinkle in some English spelling errors and badly-chosen English words, and you have the sorry state of the art that is today. - Anders From sjmachin at lexicon.net Mon May 7 08:56:33 2007 From: sjmachin at lexicon.net (John Machin) Date: 7 May 2007 05:56:33 -0700 Subject: msbin to ieee In-Reply-To: <1178539202.316506.199940@p77g2000hsh.googlegroups.com> References: <1178487847.671199.108140@h2g2000hsg.googlegroups.com> <1178502738.104124.3840@h2g2000hsg.googlegroups.com> <1178525916.145819.264070@n59g2000hsh.googlegroups.com> <1178536910.566119.6650@o5g2000hsb.googlegroups.com> <1178539202.316506.199940@p77g2000hsh.googlegroups.com> Message-ID: <1178542593.668743.71500@u30g2000hsc.googlegroups.com> On May 7, 10:00 pm, revuesbio wrote: > On 7 mai, 13:21, John Machin wrote: > > > > > On May 7, 6:18 pm, revuesbio wrote: > > > > On 7 mai, 03:52, John Machin wrote: > > > > > On May 7, 7:44 am, revuesbio wrote: > > > > > > Hi > > > > > Does anyone have the python version of the conversion from msbin to > > > > > ieee? > > > > > Thank u > > > > > Yes, Google has it. Google is your friend. Ask Google. It will lead > > > > you to such as: > > > > >http://mail.python.org/pipermail/python-list/2005-August/337817.html > > > > > HTH, > > > > John > > > > Thank you, > > > > I've already read it but the problem is always present. this script is > > > for double precision MBF format ( 8 bytes). > > > It would have been somewhat more helpful had you said what you had > > done so far, even posted your code ... > > > > I try to adapt this script for single precision MBF format ( 4 bytes) > > > but i don't find the right float value. > > > > for example : 'P\xad\x02\x95' will return '0.00024924660101532936' > > > If you know what the *correct* value is, you might like to consider > > shifting left by log2(correct_value/erroneous_value) :-) > > > Do you have any known correct pairs of (mbf4 string, decimal_float > > value)? My attempt is below -- this is based on a couple of > > descriptive sources that my friend Google found, with no test data. I > > believe the correct answer for the above input is 1070506.0 i.e. you > > are out by a factor of 2 ** 32 > > > def mbf4_as_float(s): > > m0, m1, m2, m3 = [ord(c) for c in s] > > exponent = m3 > > if not exponent: > > return 0.0 > > sign = m2 & 0x80 > > m2 |= 0x80 > > mant = (((m2 << 8) | m1) << 8) | m0 > > adj = 24 + 128 > > num = mant * 2.0 ** (exponent - adj) > > if sign: > > return -num > > return num > > > HTH, > > John > > well done ! it's exactly what i'm waiting for !! > > my code was:>>> from struct import * > >>> x = list(unpack('BBBB','P\xad\x02\x95')) > >>> x > [80, 173, 2, 149] > >>> def conversion1(bytes): > > b=bytes[:] > sign = bytes[-2] & 0x80 > b[-2] |= 0x80 > exp = bytes[-1] - 0x80 - 56 > acc = 0L > for i,byte in enumerate(b[:-1]): > acc |= (long(byte)<<(i*8)) > return (float(acc)*2.0**exp)*((1.,-1.)[sign!=0]) Apart from the 2**32 problem, the above doesn't handle *any* of the 2**24 different representations of zero. Try feeding \0\0\0\0' to it and see what you get. > > >>> conversion1(x) > > 0.00024924660101532936 > > this script come from google groups but i don't understand bit-string > manipulation (I'm a newbie). informations about bit-string > manipulation with python is too poor on the net. The basic operations (and, or, exclusive-or, shift) are not specific to any language. Several languages share the same notation (& | ^ << >>), having inherited it from C. > > thank you very much for your script. Don't thank me, publish some known correct pairs of values so that we can verify that it's not just accidentally correct for 1 pair of values. From martin at v.loewis.de Fri May 11 02:12:30 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 11 May 2007 08:12:30 +0200 Subject: How to find C source In-Reply-To: References: <1178844459.271906.92560@o5g2000hsb.googlegroups.com> Message-ID: <4644094e$0$18978$9b622d9e@news.freenet.de> Gabriel Genellina schrieb: > En Thu, 10 May 2007 21:47:39 -0300, escribi?: > >> How do I get to the source for parser.suite()? > > Are you looking for function parser_suite in parsermodule.c? To give some URL for convenience: http://svn.python.org/projects/python/trunk/Modules/parsermodule.c Regards, Martin From JiaFangTao at gmail.com Wed May 23 03:02:34 2007 From: JiaFangTao at gmail.com (Bruce) Date: 23 May 2007 00:02:34 -0700 Subject: how to use imaageop.scale Message-ID: <1179903754.084688.312200@w5g2000hsg.googlegroups.com> Hi, I want to compress a jpg file. e.g. a jpg file which has RGB band (24bit per pixel), 100 * 100 size to 50 * 50 size. I tried to use scale function in imageop module but failed. Any suggestions about this? Thanks! Bruce From steven.bethard at gmail.com Sun May 27 11:19:03 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 27 May 2007 09:19:03 -0600 Subject: PyPI bdist_wininst upload failing In-Reply-To: <1180249872.007145.48030@a26g2000pre.googlegroups.com> References: <1180249872.007145.48030@a26g2000pre.googlegroups.com> Message-ID: John Machin wrote: > On May 27, 4:20 pm, Steven Bethard wrote: >> Steven Bethard wrote: >>> I just tried to upload new versions of the argparse module to PyPI, but >>> it seems like I can no longer upload Windows installers: > [snip] >> That seems a little weird to me. Are the bdist_wininst exe files really >> zip files? Or did I just misunderstand what "content" is? > > They are exe files with a zip appended. Try out the above code on your > file; it may just help you suss out what the problem is. > E.g.: >>>> import zipfile >>>> zipfile.ZipFile('xlrd-0.6.1a4.win32.exe').namelist() > ['PURELIB/xlrd-0.6.1a4-py2.5.egg-info', 'PURELIB/xlrd/biffh.py', > ... snip ... > 'SCRIPTS/xlrdnameAPIdemo.py'] Interesting. Thanks! >>> zipfile.ZipFile('argparse-0.8.0.win32.exe').namelist() ['.../lib/argparse-0.8.0-py2.5.egg-info', '.../lib/argparse.py'] Interestingly, it looks like none of these are "safe_zipnames" according to: https://svn.python.org/packages/trunk/pypi/verify_filetype.py I wonder why that is... Also, I couldn't get the StringIO code from there to work: >>> import StringIO >>> content = open('argparse-0.8.0.win32.exe').read() >>> t = StringIO.StringIO(content) >>> t.filename = 'argparse-0.8.0.win32.exe' >>> z = zipfile.ZipFile(t) Traceback (most recent call last): File "", line 1, in File "C:\Python25\lib\zipfile.py", line 346, in __init__ self._GetContents() File "C:\Python25\lib\zipfile.py", line 366, in _GetContents self._RealGetContents() File "C:\Python25\lib\zipfile.py", line 378, in _RealGetContents raise BadZipfile, "File is not a zip file" BadZipfile: File is not a zip file STeVe From see_below_no_spam at yahoo.es Fri May 18 13:47:00 2007 From: see_below_no_spam at yahoo.es (Javier Bezos) Date: Fri, 18 May 2007 19:47:00 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <464C5382.6080403@v.loewis.de> <1179423799.254286.294930@w5g2000hsg.googlegroups.com> <1179503525.018943.95740@u30g2000hsc.googlegroups.com> <1179508599.868680.177960@e65g2000hsc.googlegroups.com> Message-ID: >> This question is more or less what a Korean who doesn't >> speak English would ask if he had to debug a program >> written in English. > > Perhaps, but the treatment by your mail/news software plus the > delightful Google Groups of the original text (which seemed intact in > the original, although I don't have the fonts for the content) would > suggest that not just social or cultural issues would be involved. The fact my Outlook changed the text is irrelevant for something related to Python. And just remember how Google mangled the intentation of Python code some time ago. This was a technical issue which has been solved, and no doubt my laziness (I didn't switch to Unicode) won't prevent non-ASCII identifiers be properly showed in general. Javier ----------------------------- http://www.texytipografia.com From fsckedagain at gmail.com Thu May 10 13:41:19 2007 From: fsckedagain at gmail.com (fscked) Date: 10 May 2007 10:41:19 -0700 Subject: path stuff In-Reply-To: References: <1178734266.858048.311740@y5g2000hsa.googlegroups.com> Message-ID: <1178818879.239014.152210@e65g2000hsc.googlegroups.com> On May 9, 7:02 pm, "Gabriel Genellina" wrote: > En Wed, 09 May 2007 15:11:06 -0300, fscked > escribi?: > > > I am walking some directories looking for a certain filename pattern. > > This part works fine, but what if I want to exclude results from a > > certain directory being printed? > > Using os.walk you can skip undesired directories entirely: > > for dirpath, dirnames, filenames in os.walk(starting_dir): > if "archived" in dirnames: > dirnames.remove("archived") > # process filenames, typically: > for filename in filenames: > fullfn = os.path.join(dirpath, filename) > ... > > -- > Gabriel Genellina OK, this is on Winbloze and it keeps giving me "The directory name is invalid: u"blahblahblah" with double backslashies everywhere. I am currently trying to figure out how to make those go away. I shall check back in a bit. thanks for all the help so far. :) From lupe at localhost.localdomain Tue May 8 17:37:53 2007 From: lupe at localhost.localdomain (Luis P. Mendes) Date: Tue, 08 May 2007 22:37:53 +0100 Subject: psycopg2 error Message-ID: Hi, I've installed psycopg2 under Slacware 11.0 along with PostgreSQL 8.2.4. When I run the python shell I get the following error: lupe at lince ~$ python Python 2.4.3 (#1, Jul 26 2006, 20:13:39) [GCC 3.4.6] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import psycopg2 Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/site-packages/psycopg2/__init__.py", line 60, in ? from _psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID ImportError: libpq.so.5: cannot open shared object file: No such file or directory The strange thing is that under root and postgres users, there is no error. postgres at lince ~$ python Python 2.4.3 (#1, Jul 26 2006, 20:13:39) [GCC 3.4.6] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import psycopg2 >>> >>> libpq files are readable by the world: root at lince pgsql # ll lib/ -d drwxr-xr-x 3 postgres postgres 1528 2007-05-07 23:25 lib/ root at lince lib # ll libpq* -rw-r--r-- 1 postgres postgres 155858 2007-05-07 23:25 libpq.a lrwxrwxrwx 1 postgres postgres 12 2007-05-07 23:25 libpq.so -> libpq.so.5.0 lrwxrwxrwx 1 postgres postgres 12 2007-05-07 23:25 libpq.so.5 -> libpq.so.5.0 -rwxr-xr-x 1 postgres postgres 126496 2007-05-07 23:25 libpq.so.5.0 The postgreSQL lib is in ld.so.conf and ldconfig has been run: # cat /etc/ld.so.conf /usr/local/lib /usr/X11R6/lib /usr/i486-slackware-linux/lib /opt/kde/lib /usr/lib/qt/lib /usr/local/pgsql/lib What is wrong? Luis From spammers at suck.die Wed May 16 05:32:20 2007 From: spammers at suck.die (Gizmo.) Date: Wed, 16 May 2007 10:32:20 +0100 Subject: =// Homeland Security on High Alert!! Fuck Blogs and Bloggers References: <1179166411.536148.186120@w5g2000hsg.googlegroups.com> Message-ID: wrote in message news:seah43di9vjbmqpjf8pum8nngj7d1ig666 at 4ax.com... > On 14 May 2007 11:13:31 -0700, ready.or.special3 at gmail.com wrote: > Links always lead to a fucking advertisement with no pics...fuck you > asshole.. And then cunts like you come along and repost spam that'd already been blocked by decent dews feeds. From adam at atlas.st Wed May 2 19:20:09 2007 From: adam at atlas.st (Adam Atlas) Date: 2 May 2007 16:20:09 -0700 Subject: __dict__s and types and maybe metaclasses... In-Reply-To: <1Nadna6BCcEWnKTbnZ2dnUVZ_u_inZ2d@comcast.com> References: <1178140405.468223.146220@l77g2000hsb.googlegroups.com> <1Nadna6BCcEWnKTbnZ2dnUVZ_u_inZ2d@comcast.com> Message-ID: <1178148009.279627.157560@n59g2000hsh.googlegroups.com> On May 2, 5:24 pm, Larry Bates wrote: > I think that most people accomplish this by: > > class blah: > __initial_values={'a': 123, 'b': 456} > > def __init__(self): > self.__dict__.update(self.__initialvalues) That's not really what I'm talking about... I'm talking about replacing the __dict__ with a SUBCLASS of dict (not just default values), and that's at the time of the class declaration (the creation of `blah` as a `type` instance), not at instance creation. From adamurbas at hotmail.com Fri May 11 23:37:20 2007 From: adamurbas at hotmail.com (adamurbas at hotmail.com) Date: 11 May 2007 20:37:20 -0700 Subject: need help with python In-Reply-To: <1178939773.253366.79710@h2g2000hsg.googlegroups.com> References: <1178934447.719778.197150@h2g2000hsg.googlegroups.com> <1178937249.263856.191460@p77g2000hsh.googlegroups.com> <1178937707.004412.22360@q75g2000hsh.googlegroups.com> <1178939773.253366.79710@h2g2000hsg.googlegroups.com> Message-ID: <1178941040.442541.61840@n59g2000hsh.googlegroups.com> On May 11, 10:16 pm, Paul McGuire wrote: > On May 11, 9:41 pm, adamur... at hotmail.com wrote: > > > > > On May 11, 9:34 pm, Paul McGuire wrote: > > > > On May 11, 8:47 pm, adamur... at hotmail.com wrote: > > > > > ya so im pretty much a newb to this whole python thing... its pretty > > > > cool but i just started today and im already having trouble. i > > > > started to use a tutorial that i found somewhere and i followed the > > > > instructions and couldnt get the correct results. heres the code > > > > stuff... > > > > > temperature=input("what is the temperature of the spam?") > > > > if temperature>50: > > > > print "the salad is properly cooked." > > > > else: > > > > print "cook the salad some more." > > > > > ya i was trying to do that but when i told it what the spams > > > > temperature was, it just turned off... well it wasnt working at all at > > > > first until i realized that i hadnt been following the instructions > > > > completely correctly and that i was supposed to type that code up in a > > > > notepad then save and open with python... so ya thats when it asked me > > > > what temperature the spam was and i typed a number then it just closed > > > > itself... im not really sure what went wrong... itd be real nice if > > > > someone would be like a mentor or something... > > > > Well, this list has a varying level of mentoring and newbie-tolerance, > > > with more latitude for people who have made some effort to start with > > > before posting things like "here's my homework problem, please send me > > > the working code so I can hand it in." > > > > I just ran your code interactively at the Python prompt, and it runs > > > just fine. See? > > > > >>> temperature=input("what is the temperature of the spam?") > > > > what is the temperature of the spam?55>>> if temperature>50: > > > > ... print "the salad is properly cooked." > > > ... else: > > > ... print "the salad is properly cooked." > > > ... > > > the salad is properly cooked. > > > > I think the problem you are having is that, when you run your program > > > by double-clicking on the xyz.py file in a file browser, the OS > > > (Windows, I assume?) opens a separate console window, and runs the > > > program, and then at the end of the program, CLOSES the window. I > > > think your code is running just fine, I think your "the salad is > > > whatever" messages get printed out, but afterward, your program ends, > > > so the window closes before you can see how your salad turned out. > > > > A simple workaround you can do is to add to the end of your program > > > this statement: > > > > input("") > > > > This will cause the process to stop and wait for you to press the > > > RETURN key, giving you time to stop and admire your salad results > > > before closing the window. > > > > One final note: many people post in a "write like I talk" style. This > > > is okay while telling your story ("well it wasn't working at all at > > > first..."), and the ee cummings all-lower-case is passable, but please > > > drop the "ya"s. They are a verbal tic that may be okay in person, but > > > do not translate at all to written posts. At least you don't say > > > "like" every other word, and I thank you for that! :) > > > > You can get a sense of other writing styles by reading through the > > > comp.lang.python archives. I would also recommend that you might find > > > more folks in the "just getting started" phase posting to the python- > > > tutor mailing list (go tohttp://mail.python.org/mailman/listinfo/tutor), > > > and you can skim through posts there for many introductory topics. > > > > Good luck to you, and welcome to Python! > > > > -- Paul > > > well... i just discovered another of my mistakes. i was writing it in > > notepad and not saving it as .py silly me... hoho ya that input thing > > to get it to make u press enter worked tho... but only with that > > one... ive got another one that i cant get to work even with the input > > message to press enter. Sorry about the bad grammar. I'm used to > > Myspace where no one gives a particular hoot about how you type. I > > hope this is better. I will follow that link though. Thanks for the > > help.- Hide quoted text - > > > - Show quoted text - > > It's possible that your next program has a runtime error, which will > raise an exception that, if not handled using try-except, will cause > the program to exit with a message (a message that will flash by and > then disappear, as the window closes immediately). > > One thing you should try is to run your python programs using a > terminal window (sometimes called a "console window", or "the command > line"). There are several ways to open one of these, the simplest on > Windows is to click the "Start" button in the lower left corner, > select "Run...", and enter the command "cmd". This will open up one > of these white-letters-on-black-background windows for typing system > commands. From this command line, you can run your Python programs by > typing "python blah.py" where blah.py is the name of your Python > script (which you created in Notepad and saved as blah.py. By running > scripts this way, you will get to see *all* of your program output, > without having the window close on you. (and please don't name all > your scripts "blah.py", you should pick different names...) > > Another thing you might try is downloading and installing SciTE for > Windows - a free super-Notepad, with built-in support for editing *and > running* Python scripts. Enter your Python code, save it as > "whatever.py", then press F5 - the editor will split down the middle, > keeping your program in the left half, and show the output messages > and exceptions on the right. I find this much easier than going back > and forth between Notepad and a terminal window. Other developer > editors (often called "IDE"s for Interactive Development Environment) > work similarly, such as pythonwin or IDLE - there are many others to > choose from, but coming from Notepad, SciTE will not be a big step, > but will move you forward. > > -- Paul I was looking around in my Python folder and saw something to do with that IDLE thing you were talking about. When I right clicked on a .py file, it said edit with IDLE. I opened it and it was my code but each line was a different color. It looked confusing so I decide to save it for later. I knew that I could get the run thing to do the command thing, but I had forgotten how to get the black window to come up. Ok. Well, I tried to us the cmd window. It says python: can't open file 'area.py' I'm guessing that's not good. It won't open any of my .py files. It's because of where I saved them. I can see how this i going to work now. Ok so I'll just move them to the place that the command line says. Now it still won't run my other program: # Area calculation program print "Welcome to the Area calculation program" print "-------------" print # Print out the menu: print "Please select a shape:" print "1 Rectangle" print "2 Circle" # Get the user's choice: shape = input("> ") # Calculate the area: if shape == 1: height = input("Please enter the height: ") width = input("Please enter the width: ") area = height*width print "The area is", area else: radius = input("Please enter the radius: ") area = 3.14*(radius**2) print "The area is", area Perhaps it isn't written correctly. I don't think it likes the pound signs. I'm not sure. But, I did go to that mailing list you recommended. Thanks for that. From vasudevram at gmail.com Sun May 13 14:25:40 2007 From: vasudevram at gmail.com (vasudevram) Date: 13 May 2007 11:25:40 -0700 Subject: GUI tutorial In-Reply-To: References: Message-ID: <1179080740.538435.83510@o5g2000hsb.googlegroups.com> On May 13, 10:51 pm, John K Masters wrote: > Can someone point me in the direction of a good tutorial on programming > python with a GUI? I'm just starting out with python and have written a > few scripts successfully but would like to add a graphical front end to > them to make it easier for my work colleagues, most of whom have never > used a command line, to use. > > Regards, John > -- > War is God's way of teaching Americans geography > Ambrose Bierce (1842 - 1914) That depends on which GUI toolkit you want to use. There are at least one or two good online tutorials on the Web for Tkinter (the Python interface to the Tk toolkit). One is by Fredrik Lundh (a.k.a the effbot, a leading Python contributor). Google for suitable keywords, e.g. Tkinter tutorial. Tkinter comes with Python by default on Windows, so that helps. But wxPython is not a bad toolkit either. (You'll have to download and install it, also the demos (see below) are often a separate download.) I've used it some, and like it. I don't know of any tutorials for it, though there may be some - again, Google for info. But if you already have some GUI programming background, its not too difficult to pick up it up. It comes with a big set of demos with source code, and I was able to learn enough wxPython to write some simple apps just by looking at the demos source code and reading some of the reference documentation. Those apps are here: http://www.packtpub.com/article/Using_xtopdf Check the last part of the article for links to the source code. PyQt is another option, recommended by some people. Haven't tried it myself but have used Qt (the C++ GUI toolkit to which PyQt is a binding) a little, and like it a lot. Qt again is supposed to be of very high quality, according to some people. I am currently reading a book Programming Qt and found most of it pretty straightforward (though not simple :-) to understand (you do need to understand the concept of signals and slots, as that is fundamental to Qt programming). HTH Vasudev Ram Dancing Bison Enterprises http://www.dancingbison.com From eric.brunel at pragmadev.com Mon May 14 11:14:09 2007 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Mon, 14 May 2007 17:14:09 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <4648252D.5020704@web.de> <46483740.4050406@web.de> Message-ID: On Mon, 14 May 2007 12:17:36 +0200, Stefan Behnel wrote: > Eric Brunel wrote: >> On Mon, 14 May 2007 11:00:29 +0200, Stefan Behnel >>> Any chance there are still kanji-enabled programmes around that were >>> not hit >>> by the bomb in this scenario? They might still be able to help you get >>> the >>> code "public". >> >> Contrarily to what one might think seeing the great achievements of >> open-source software, people willing to maintain public code and/or make >> it evolve seem to be quite rare. If you add burdens on such people - >> such as being able to read and write the language of the original code >> writer, or forcing them to request a translation or transliteration from >> someone else -, the chances are that they will become even rarer... > > Ok, but then maybe that code just will not become Open Source. There's a > million reasons code cannot be made Open Source, licensing being one, > lack of > resources being another, bad implementation and lack of documentation > being > important also. > > But that won't change by keeping Unicode characters out of source code. Maybe; maybe not. This is one more reason for a code preventing it from becoming open-source. IMHO, there are already plenty of these reasons, and I don't think we need a new one... > Now that we're at it, badly named english identifiers chosen by > non-english > native speakers, for example, are a sure way to keep people from > understanding > the code and thus from being able to contribute resources. I wish we could have an option forbidding these also ;-) But now, maybe some of my own code would no more execute when it's turned on... > I'm far from saying that all code should start using non-ASCII > characters. > There are *very* good reasons why a lot of projects are well off with > ASCII > and should obey the good advice of sticking to plain ASCII. But those are > mainly projects that are developed in English and use English > documentation, > so there is not much of a risk to stumble into problems anyway. > > I'm only saying that this shouldn't be a language restriction, as there > definitely *are* projects (I know some for my part) that can benefit > from the > clarity of native language identifiers (just like English speaking > projects > benefit from the English language). And yes, this includes spelling > native > language identifiers in the native way to make them easy to read and > fast to > grasp for those who maintain the code. My point is only that I don't think you can tell right from the start that a project you're working on will stay private forever. See Java for instance: Sun said for quite a long time that it wasn't a good idea to release Java as open-source and that it was highly unlikely to happen. But it finally did... You could tell that the rule should be that if the project has the slightest chance of becoming open-source, or shared with people not speaking the same language as the original coders, one should not use non-ASCII identifiers. I'm personnally convinced that *any* industrial project falls into this category. So accepting non-ASCII identifiers is just introducing a disaster waiting to happen. But now, I have the same feeling about non-ASCII strings, and I - as a project leader - won't ever accept a source file which has a "_*_ coding _*_" line specifying anything else than ascii... So even if I usually don't buy the "we're already half-dirty, so why can't we be the dirtiest possible" argument, I'd understand if this feature went into the language. But I personnally won't ever use it, and forbid it from others whenever I'll be able to. > It should at least be an available option to use this feature. If it's actually an option to the interpreter, I guess I'll just have to alias python to 'python --ascii-only-please'... -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From RonVick at Nospam.com Thu May 10 09:58:31 2007 From: RonVick at Nospam.com (RonV) Date: Thu, 10 May 2007 13:58:31 GMT Subject: How to installo???? Message-ID: Just got a new Vista system and puter.... Installed a newer version of Python, up from 2.2 or so... Tried to install Win extensions, but have forgotten how it's done. Clicking on setup in the Win Extsions package flashes a window by, but cannot read it. and I don't see a way to load the setup into Python without Win Extensions. Any suggestions? Thank you From showell30 at yahoo.com Tue May 29 06:44:01 2007 From: showell30 at yahoo.com (Steve Howell) Date: Tue, 29 May 2007 03:44:01 -0700 (PDT) Subject: Periodic tasks. In-Reply-To: <1180420430.610215.96330@a26g2000pre.googlegroups.com> Message-ID: <757855.37239.qm@web33515.mail.mud.yahoo.com> --- Ramashish Baranwal wrote: > Hi, > > I am trying to execute some tasks periodically, > those familiar with > unix can think of it as equivalent to cron jobs. I > have tried looking > around, but couldn't find a way. Would appreciate > any pointers or > clues.. > I'm also interested in this. On the assumption that you can't find a cron replacement in your OS, or that maybe you need a Python-written cron to do something a little different than cron, these are some things to look at: open(fn).readlines() line.split(' ', 6) time.sleep(), time.time() and other methods os.popen.readlines() (but others may disagree) In my case I need to run jobs periodically, but before running jobs, but I need to configure the times that the jobs run using a database, and I need to check on the status of the previous day's job, make sure that I'm running on the primary box, etc. Another technique people use is to use cron() and make it the responsibility of the scheduled programs to check that they should really proceed, and if there's a chance of overlapping with a previous job that's still running, you can use a file-locking scheme. ____________________________________________________________________________________ Sucker-punch spam with award-winning protection. Try the free Yahoo! Mail Beta. http://advision.webevents.yahoo.com/mailbeta/features_spam.html From conor.robinson at gmail.com Fri May 18 19:07:41 2007 From: conor.robinson at gmail.com (py_genetic) Date: 18 May 2007 16:07:41 -0700 Subject: converting strings to most their efficient types '1' --> 1, 'A' ---> 'A', '1.2'---> 1.2 Message-ID: <1179529661.555196.13070@k79g2000hse.googlegroups.com> Hello, I'm importing large text files of data using csv. I would like to add some more auto sensing abilities. I'm considing sampling the data file and doing some fuzzy logic scoring on the attributes (colls in a data base/ csv file, eg. height weight income etc.) to determine the most efficient 'type' to convert the attribute coll into for further processing and efficient storage... Example row from sampled file data: [ ['8','2.33', 'A', 'BB', 'hello there' '100,000,000,000'], [next row...] ....] Aside from a missing attribute designator, we can assume that the same type of data continues through a coll. For example, a string, int8, int16, float etc. 1. What is the most efficient way in python to test weather a string can be converted into a given numeric type, or left alone if its really a string like 'A' or 'hello'? Speed is key? Any thoughts? 2. Is there anything out there already which deals with this issue? Thanks, Conor From deets at nospam.web.de Thu May 24 08:11:45 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 24 May 2007 14:11:45 +0200 Subject: Changing Unicode object to Tuple Type In-Reply-To: <1180007144.514744.188090@q75g2000hsh.googlegroups.com> References: <1180007144.514744.188090@q75g2000hsh.googlegroups.com> Message-ID: <5bldo8F2tlcqfU1@mid.uni-berlin.de> laxmikiran.bachu at gmail.com schrieb: > Can we have change a unicode string Type object to a Tuple type > object.. If so how ???? Why? Are you getting an error that makes you think that's a good idea? Tuples are basically structs, unicode objects are strings. There is no canonical way to convert them. Tell us more about the problem you want to be solved, and we might help you better. diez From shane.buggins41 at ntlworld.com Thu May 17 04:12:20 2007 From: shane.buggins41 at ntlworld.com (shane.buggins41 at ntlworld.com) Date: 17 May 2007 01:12:20 -0700 Subject: Watch Television online for free. Message-ID: <1179389540.581328.18430@l77g2000hsb.googlegroups.com> Watch television online now for free. Includes television channels from all over the world and sport events from all over the world including, NBA, Soccer, Motor Racing and much more. http://homepage.ntlworld.com/louise.randall41 From stefan.behnel-n05pAM at web.de Mon May 14 14:52:50 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 14 May 2007 20:52:50 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <4648B002.3050508@web.de> Marc 'BlackJack' Rintsch schrieb: > In , Michel Claveau > wrote: > >> And Il1 O0 ? > > Hm, we should ban digits from identifier names. :-) Ah, good idea - and capital letters also. After all, they are rare enough in English to just plain ignore their existance. Stefan :) From alextabone at gmail.com Wed May 30 05:18:08 2007 From: alextabone at gmail.com (Alchemist) Date: 30 May 2007 02:18:08 -0700 Subject: calling Postgresql stored procedure Message-ID: <1180516688.022056.70220@q69g2000hsb.googlegroups.com> I am using Python 2.4 and Postgresql 8.2 database server. On the database I have created a stored function, example, CREATE OR REPLACE FUNCTION calculateaverage() I created a new python script and would like to call my database stored function. How can I call a database stored function/procedure in python? Thanks From duncan.booth at invalid.invalid Wed May 16 07:48:44 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 May 2007 11:48:44 GMT Subject: Splitting a quoted string. References: <1179312169.045429.80960@e65g2000hsc.googlegroups.com> Message-ID: mosscliffe wrote: > I am looking for a simple split function to create a list of entries > from a string which contains quoted elements. Like in 'google' > search. > > eg string = 'bob john "johnny cash" 234 june' > > and I want to have a list of ['bob', 'john, 'johnny cash', '234', > 'june'] > > I wondered about using the csv routines, but I thought I would ask the > experts first. > > There maybe a simple function, but as yet I have not found it. You probably need to specify the problem more completely. e.g. Can the quoted parts of the strings contain quote marks? If so how what are the rules for escaping them. Do two spaces between a word mean an empty field or still a single string delimiter. Once you've worked that out you can either use re.split with a suitable regular expression, or use the csv module specifying your desired dialect: >>> class mosscliffe(csv.Dialect): delimiter = ' ' quotechar = '"' doublequote = False skipinitialspace = False lineterminator = '\r\n' quoting = csv.QUOTE_MINIMAL >>> csv.register_dialect("mosscliffe", mosscliffe) >>> string = 'bob john "johnny cash" 234 june' >>> for row in csv.reader([string], dialect="mosscliffe"): print row ['bob', 'john', 'johnny cash', '234', 'june'] From kerny404 at gmail.com Tue May 8 06:22:33 2007 From: kerny404 at gmail.com (andrea) Date: 8 May 2007 03:22:33 -0700 Subject: Designing a graph study program Message-ID: <1178619753.077639.112510@q75g2000hsh.googlegroups.com> I'm studying some graphs algorithm (minumum spanning tree, breath search first topological sort etc etc...) and to understand better the theory I'm implementing them with python... I made my own graph class, the constructor is simply this: class graph: "in forma di matrice e' una matrice normale, in forma di lista uso un dizionario" def __init__(self,nodes,edges,dir=False,weight=[]): # inizializzatore dell'oggetto, di default in forma di lista di adiacenza e undirected # il grafo puo' essere anche pesato "di default uso la lista di adiacenza per rappresentare il grafo, usare set" self.adj_list = {} self.nodes = nodes self.edges = edges # in modo da avere comodi questi dati, se bidirezionale non ci sono tutti self.weight = weight self.dir = dir # anche questo deve essere raggiungibile for n in nodes: self.adj_list[n] = [] for n in nodes: for e in edges: if dir: # se ho la direzione guardo l'ordine dei vertici nel lato if n == e[0]: self.adj_list[n].append(e[1]) elif n in e: other = e[((e.index(n))+1) % 2] self.adj_list[n].append(other) if weight: self.w = {} for idx in range(len(edges)): self.w[edges[idx]] = weight[idx] # assegno in corrispondenza Well then I wanted to draw graphs and I found that pydot is working really nicely. BUT I'd like to do this, an interactive program to see ho the algorithms works... For example in the breath search first, every time the algorithm colors a node, the program should redraw the graphs. Which modules should I use for graphics (I use macosX and I'd like something cross platforms). Now I'm doing something like this def draw_graph(self): """disegna un grafo con pydot""" import os output = 'graph.png' self.dot_graph.write_png(output) com = 'open '+output os.popen(com) which I think is very ugly and not fitting very well for my purpose. I also created a class to represent matrix (for the matrix view of the graph) but I found that numpy has a very complete implementation, I think I'll go with it. Thank you very much, if you have any kind of suggestions/links please write it :) From sjmachin at lexicon.net Fri May 25 19:19:20 2007 From: sjmachin at lexicon.net (John Machin) Date: 25 May 2007 16:19:20 -0700 Subject: csv.reader length? In-Reply-To: <1180118981.024036.163590@p47g2000hsd.googlegroups.com> References: <1180118981.024036.163590@p47g2000hsd.googlegroups.com> Message-ID: <1180135160.484867.242240@i13g2000prf.googlegroups.com> On May 26, 4:49 am, cjl wrote: > P: > > Stupid question: > > reader = csv.reader(open('somefile.csv')) > for row in reader: > do something > > Any way to determine the "length" of the reader (the number of rows) > before iterating through the rows? > > -CJL Of course not. A CSV file (even without the embedded newline complication mentioned by Peter) is a file of variable-length records separated by a one-or-two-character sequence. Modern Python-supported filesystems' directories don't keep the information that would be required to tell you whether a file's records are fixed or variable length, let alone how many "records" there are in a file. Why are you asking? Perhaps if you tell us what you are trying to achieve, we can help you. Cheers, John From roman.yakovenko at gmail.com Tue May 8 00:16:21 2007 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Tue, 8 May 2007 07:16:21 +0300 Subject: [ANN]pygccxml-0.9.0 In-Reply-To: <7465b6170705072114o64f1b300g4b3365448aeeb1b0@mail.gmail.com> References: <7465b6170705072114o64f1b300g4b3365448aeeb1b0@mail.gmail.com> Message-ID: <7465b6170705072116v2bc6c13cgb2ba9ca5bf2091db@mail.gmail.com> Hello! I'm pleased to announce the 0.9.0 release of pygccxml. What is pygccxml? ================= "...The purpose of the GCC-XML extension is to generate an XML description of a C++ program from GCC's internal representation. " -- Introduction to GCC-XML The purpose of pygccxml is to read a generated file and provide a simple framework to navigate C++ declarations, using Python classes. Where is pygccxml? ================== Site: http://language-binding.net/pygccxml/pygccxml.html Download: http://language-binding.net/pygccxml/download.html What's new? =========== Performance ----------- Performance was improved. pygccxml is now 30-50% faster. The improvement was achieved by using "cElementTree" package, "iterparse" functionality, instead of standard XML SAX API. Small features -------------- * Class calldef_t has new property - "does_throw". It describes whether the function throws any exception or not. * "is_base_and_derived" function arguments were changed. The second argument could be a tuple, which contains classes. The function returns ``True`` if at least one class derives from the base one. Bug fixes --------- * C++ does not define implicit conversion between an integral type and ``void*``. "declarations.is_convertible" type traits was fixed. * Small bug was fixed in functionality that corrects GCC-XML reported function default arguments. Reference to "enum" declaration extracted properly. -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From carsten at uniqsys.com Tue May 15 09:32:27 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 15 May 2007 09:32:27 -0400 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <1179235947.3385.20.camel@dot.uniqsys.com> On Tue, 2007-05-15 at 08:54 -0400, Ross Ridge wrote: > wrote: > >So, please provide feedback, e.g. perhaps by answering these > >questions: > >- should non-ASCII identifiers be supported? why? > > I think the biggest argument against this PEP is how little similar > features are used in other languages That observation is biased by your limited sample. You only see open source code that chooses to restrict itself to ASCII and mostly English identifiers to allow for easier code sharing. There could be millions of kids in China learning C# in native Mandarin and you'd never know about it. > and how poorly they are supported > by third party utilities. Your PEP gives very little thought to how > the change would affect the standard Python library. Are non-ASCII > identifiers going to be poorly supported in Python's own library and > utilities? How would a choice of identifiers interact in any way with Python's standard or third-party libraries? The only things that get passed between an application and the libraries are objects that neither know nor care what identifiers, if any, are attached to them. -- Carsten Haese http://informixdb.sourceforge.net From revuesbio at gmail.com Tue May 29 04:26:16 2007 From: revuesbio at gmail.com (revuesbio) Date: 29 May 2007 01:26:16 -0700 Subject: DbiDate object In-Reply-To: <1180416165.039109.146000@w5g2000hsg.googlegroups.com> References: <1180392704.580831.229190@q75g2000hsh.googlegroups.com> <1180416165.039109.146000@w5g2000hsg.googlegroups.com> Message-ID: <1180427176.308619.94640@p77g2000hsh.googlegroups.com> On 29 mai, 07:22, Frank Millman wrote: > On May 29, 12:51 am, revuesbio wrote: > > > > > Hi all > > > I am using odbc to connect to Microsoft Access DB. When I send a > > request with a datetime column from the database, odbc returns > > something called a DbiDate object. > > ex :>>> x=data[0][2] > > > >>> print x > > > Fri Apr 20 07:27:45 2007 > > > I would like to select columns where datetime ("DbiDate column") is > > > yesterday date. > > and i don't understand how to send request with this DbiDate. > > > Could you help me ? > > thank you > > I also use the odbc module, but I store dates in my system as > datetime.datetime objects. > > I convert a DbiDate object to a datetime object like this - > > import datetime as dt > date = dt.datetime.fromtimestamp(int(dbidate)) > > For selects, I use the datetime object directly - > > cur.execute('select * from table where date = ?',(date,)) > > I'm not sure how the odbc module handles that - maybe it converts date > into str(date). In any case, it just works for me. > > HTH > > Frank Millman it works ! thank you for your help ;-) From george.sakkis at gmail.com Tue May 15 09:44:33 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 15 May 2007 06:44:33 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46473267$0$31532$9b622d9e@news.freenet.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <1179236673.893122.28800@w5g2000hsg.googlegroups.com> After 175 replies (and counting), the only thing that is clear is the controversy around this PEP. Most people are very strong for or against it, with little middle ground in between. I'm not saying that every change must meet 100% acceptance, but here there is definitely a strong opposition to it. Accepting this PEP would upset lots of people as it seems, and it's interesting that quite a few are not even native english speakers. George From Maksim.Kasimov at gmail.com Fri May 25 04:35:37 2007 From: Maksim.Kasimov at gmail.com (sim.sim) Date: 25 May 2007 01:35:37 -0700 Subject: just a bug (was: xml.dom.minidom: how to preserve CRLF's inside CDATA?) In-Reply-To: <1179841504.782279.86490@u36g2000prd.googlegroups.com> References: <1179841504.782279.86490@u36g2000prd.googlegroups.com> Message-ID: <1180082137.329142.45350@p77g2000hsh.googlegroups.com> On 22 ???, 16:45, "sim.sim" wrote: > Hi all. > i'm faced to trouble using minidom: > > #i have a string (xml) within CDATA section, and the section includes > "\r\n": > iInStr = '\n \nEND:VCALENDAR\r\n]]>\n' > > #After i create DOM-object, i get the value of "Data" without "\r\n" > > from xml.dom import minidom > iDoc = minidom.parseString(iInStr) > iDoc.childNodes[0].childNodes[0].data # it gives u'BEGIN:VCALENDAR > \nEND:VCALENDAR\n' > > according tohttp://www.w3.org/TR/REC-xml/#sec-line-ends > > it looks normal, but another part of the documentation says that "only > the CDEnd string is recognized as markup":http://www.w3.org/TR/REC-xml/#sec-cdata-sect > > so parser must (IMHO) give the value of CDATA-section "as is" (neither > both of parts of the document do not contradicts to each other). > > How to get the value of CDATA-section with preserved all symbols > within? (perhaps use another parser - which one?) > > Many thanks for any help. Hi all, I have another problem with minidom and now it is really critical. Below the code that tryes to parse an well-formed xml, but it fails with error message: "not well-formed (invalid token): line 3, column 85" from xml.dom import minidom iMessage = "3c3f786d6c2076657273696f6e3d22312e30223f3e0a3c6d657373616\ 7653e0a202020203c446174613e3c215b43444154415bd094d0b0d0bdd0bdd18bd0b5\ 20d0bfd0bed0bfd183d0bbd18fd180d0bdd18bd18520d0b7d0b0d0bfd180d0bed181d\ 0bed0b220d0bcd0bed0b6d0bdd0be20d183d187d0b8d182d18bd0b2d0b0d182d18c20\ d0bfd180d0b820d181d0bed0b1d181d182d0b2d0b5d0bdd0bdd18bd18520d180d0b5d\ 0bad0bbd0b0d0bcd0bdd15d5d3e3c2f446174613e0a3c2f6d6573736167653e0a0a".\ decode('hex') iMsgDom = minidom.parseString(iMessage) The "problem" within CDATA-section: it consists a part of utf-8 encoded string wich was splited (widely used for memory limited devices). When minidom parses the xml-string, it fails becouse it tryes to convert into unicode the data within CDATA-section, insted of just to return the value of the section "as is". The convertion contradicts the specification http://www.w3.org/TR/REC-xml/#sec-cdata-sect So my question still open: How to get the value of CDATA-section with preserved all symbols within? (perhaps use another parser - which one?) Thanks for help. Maksim From wgwigw at gmail.com Wed May 30 09:00:27 2007 From: wgwigw at gmail.com (momobear) Date: 30 May 2007 06:00:27 -0700 Subject: Periodic tasks. In-Reply-To: <1180420430.610215.96330@a26g2000pre.googlegroups.com> References: <1180420430.610215.96330@a26g2000pre.googlegroups.com> Message-ID: <1180530027.689010.33950@z28g2000prd.googlegroups.com> On May 29, 2:33 pm, Ramashish Baranwal wrote: > Hi, > > I am trying to execute some tasks periodically, those familiar with > unix can think of it as equivalent to cron jobs. I have tried looking > around, but couldn't find a way. Would appreciate any pointers or > clues.. > > Thanks, > -Ram I googled "twisted cron", if u use twisted, that's maybe help u: http://svn.zope.org/Zope3/trunk/src/scheduler/cron.py?rev=38967&view=auto http://twistedmatrix.com/pipermail/twisted-python/2006-June/013525.html From martin at v.loewis.de Thu May 17 13:26:16 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 17 May 2007 19:26:16 +0200 Subject: omissions in python docs? In-Reply-To: <1179419983.750044.65030@n59g2000hsh.googlegroups.com> References: <1179419983.750044.65030@n59g2000hsh.googlegroups.com> Message-ID: <464C9038.6000109@v.loewis.de> 7stud schrieb: > I have a hard time believing I am the first one to notice those > omissions. Are the docs just old and poorly maintained? Or, is there > some reason those methods were omitted? You are likely the first one to notice, and then talk about that. It often happened in the past that patches were admitted which don't simultaneously update the documentation, hence they diverge. These days, patches are regularly rejected for not providing proper documentation changes. As you now found a difference, please write a patch and submit it to sf.net/projects/python. Regards, Martin From turbana at gmail.com Tue May 8 19:57:23 2007 From: turbana at gmail.com (Ian Clark) Date: Tue, 8 May 2007 16:57:23 -0700 Subject: FW: Re: e-mailing multiple values In-Reply-To: <050820072352.447.46410D4F0009B8BD000001BF22058864420D010C0E06A10407020E@comcast.net> References: <050820072352.447.46410D4F0009B8BD000001BF22058864420D010C0E06A10407020E@comcast.net> Message-ID: On 5/8/07, axjacob at comcast.net wrote: > Thanks. > That does help. When teh script sends a mail of the list item(all_data), the data shows up like this: > > [(' Ham \n', ' eggs \n'), > (' chicken \n', ' thighs \n')] > > So I have to figure out a way to cleanup the content > > Thanks > Anil Have to run, but look at strip() on string objects. Ian From gh at gregor-horvath.com Wed May 16 12:31:29 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Wed, 16 May 2007 18:31:29 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <7x4pmg716p.fsf@ruckus.brouhaha.com> <4648EC26.8020907@v.loewis.de> Message-ID: Eric Brunel schrieb: > > The point is that today, I have a reasonable chance of being able to > read, understand and edit any Python code. With PEP 3131, it will no > more be true. That's what bugs me. That's just not true. I and others in this thread have stated that they use German or other languages as identifiers today but are forced to make a stupid and unreadable translation to ASCII. > > Same question again and again: how does he know that non-Russian > speakers will *ever* get in touch with his code and/or need to update it? If you didn't get non English comments and identifiers until now, you will not get any with this PEP either. And if you do get them today or with the PEP it doesn't make a difference for you to get some glyphs not properly displayed, doesn't it? Gregor From tbrkic at yahoo.com Tue May 29 13:38:57 2007 From: tbrkic at yahoo.com (glomde) Date: 29 May 2007 10:38:57 -0700 Subject: How to set a class inheritance at instance creation? In-Reply-To: <1180459227.403312.176370@j4g2000prf.googlegroups.com> References: <1180453971.556244.91370@q69g2000hsb.googlegroups.com> <1180459227.403312.176370@j4g2000prf.googlegroups.com> Message-ID: <1180460337.697060.296880@p47g2000hsd.googlegroups.com> On 29 Maj, 19:20, Ramashish Baranwal wrote: > On May 29, 8:52 pm, glomde wrote: > > > > > Hi I wonder if you can set what subclass a class should > > have at instance creation. > > > The problem is that I have something like: > > > class CoreLang(): > > def AssignVar(self, var, value): > > pass > > > class Lang1(CoreLang): > > def AssignVar(self, var, value): > > return var, "=", value > > > class Lang2(CoreLang): > > def AssignVar(self, var, value): > > return var, "<=", value > > > class WriteStruct(): > > def Generate(self, vars): > > for var in vars: > > print self.AssignVar() > > > The problem is that I want WriteStruct to sometimes be a subclass of > > Lang1 and sometimes > > of Lang2. > > In the above example I could but the Generate Method in CoreLang. But > > in my real > > example I also want to able to subclass WriteStruct to be able to easy > > customize WriteStruct. > > Which I wouldnt be able to do if it was a method in CoreLang. > > > So in code I would like to write something like: > > > WriteStruct(Lang1).Generate(vars) > > class WriteStruct: > def __init__(self, SubClass): > self._sub = SubClass() > def Generate(self, vars): > for var in vars: > print self._sub.AssignVar() > > This does what you want but isn't inheritance. This would work I think. Thanks. > > > Even better would be that if I in the Lang1 class could > > just do WriteStruct().Generate(vars) and Lang1 class would > > magically make WriteStruct a subclass of itself. > > I don't think I understood what you want here. > I just dont want to pass the class in the instancecreation. Somhehow in my: class Lang1(CoreLang): def Function(self): WriteStruct().Generate() Then somehow this WriteStruct should magically know that has been instantiated in Lang1. But this is not really needed. Just wondered if it was possible. > Ram From joshusdog at gmail.com Mon May 7 18:30:24 2007 From: joshusdog at gmail.com (joshusdog at gmail.com) Date: 7 May 2007 15:30:24 -0700 Subject: integrating embedded interpreter with external controls Message-ID: <1178577024.946609.4840@h2g2000hsg.googlegroups.com> I need some advice about how to go about architecting a solution to the following problem. I'd like to create an application that has an interactive listener/ console window in which the user can enter commands (in much the same vain as 3D Studio Max, for those who are familiar with the product). The console would essentially be an embedded Python interpreter running the interactive loop (a call to the C API's PyRun_InteractiveLoop()). I'd also like buttons and other UI controls to be able to access functions and objects that are defined through the console. I'm not really sure how to integrate the UI controls with the console though, especially if the console is running PyRun_InteractiveLoop(), which is a tight loop. I'm guessing that the solution will most likely require the console to run in a separate thread, but I still don't know how to get the UI to interact with the console. Does anyone have any helpful suggestions? From vasudevram at gmail.com Tue May 29 10:05:56 2007 From: vasudevram at gmail.com (vasudevram) Date: 29 May 2007 07:05:56 -0700 Subject: python unix install, sqlite3 In-Reply-To: <1180443141.119281.304880@q66g2000hsg.googlegroups.com> References: <1180443141.119281.304880@q66g2000hsg.googlegroups.com> Message-ID: <1180447556.474075.12800@q19g2000prn.googlegroups.com> On May 29, 5:52 pm, Simon wrote: > I installed the source code on unix for python 2.5.1. The install went > mainly okay, except for some failures regarding: > _ssl, _hashlib, _curses, _curses_panel. > > No errors regarding sqlite3. > However, when I start python and do an import sqlite3 I get: > > /ptmp/bin/> python > Python 2.5.1 (r251:54863, May 29 2007, 05:19:30) > [GCC 3.3.2] on sunos5 > Type "help", "copyright", "credits" or "license" for more information.>>> import sqlite3 > > Traceback (most recent call last): > File "", line 1, in > File "/ptmp/Python-2.5.1/lib/python2.5/sqlite3/__init__.py", line > 24, in > from dbapi2 import * > File "/ptmp/Python-2.5.1/lib/python2.5/sqlite3/dbapi2.py", line 27, > in > from _sqlite3 import * > ImportError: No module named _sqlite3 Some ideas: I don't know if sqlite3 comes bundled with the standard Python source bundle. My guess is not. If not, that's the cause of the error - you need to install sqlite3 (and probably pysqlite3 (not sure of the name (whether it has a trailing 3) which, if I remember, is the Python binding/wrapper for sqlite3 (which is a C library, I think). Other possible cause of the error (if sqlite3 _is_ bundled with Python and no Python binding/wrapper is needed, is that sqlite3 depends on one of those other libraries you mention (such as _hashlib) for which you got errors while installing Python from source. HTH Vasudev Ram Dancing Bison Enterprises www.dancingbison.com From kyosohma at gmail.com Tue May 29 09:25:08 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 29 May 2007 06:25:08 -0700 Subject: stdout and threads In-Reply-To: <465aa6cc$0$52109$edfadb0f@dread11.news.tele.dk> References: <465aa6cc$0$52109$edfadb0f@dread11.news.tele.dk> Message-ID: <1180445108.611572.18530@p47g2000hsd.googlegroups.com> On May 28, 4:54 am, "Troels Thomsen" wrote: > Hello All > > I have trouble printing to stdout from a thread and main program. > > Not only will it look strange when they try to print at the same time, that > is ok, but i think i see lock-ups. (strange exceptions in Tkinker etc) Or is > it an issue with IDLE ? > > Should I implement a lock'ed / queued version and hook it into the > sys.stdout ? > > (sorry if this has been answered recently in this group) > > using > Python 2.5 (r25:51908 > Idle 1.2 > > tpt I've read in multiple sites/books that running Tkinter from IDLE can cause screwy errors and I've seen a little bit of that behavior myself. This website mentions the problem: http://www.ferg.org/thinking_in_tkinter/index.html >From what I've read in Lutz's book, Programming Python, it sounds like using the Queue module for messages is a good way to go, using producer and consumer threads. Then just check the queue from time to time to grab the messages and print them out, maybe to a separate text widget. Mike From nogradi at gmail.com Tue May 29 11:11:24 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Tue, 29 May 2007 17:11:24 +0200 Subject: Resize image NO PIL!! In-Reply-To: <1180406398.615904.22230@g4g2000hsf.googlegroups.com> References: <1180406398.615904.22230@g4g2000hsf.googlegroups.com> Message-ID: <5f56302b0705290811q22da1aa1j6c15ba4ef18f07ee@mail.gmail.com> > I have created an image hosting site and when a user uploads an image, > I want a service to run on the server to create a few thumbnails while > the user does other things. > > My stupid host (pair.com) doesn't have PIL installed and I'm too much > of a stupid newbie to figure out how to get it to work with them > (access denied while installing it, of course). > > Also, they don't have any python interface setup for GD. > > Anyway, I don't know what my options are. I'm thinking: > > 1) Find another host with mod_python, PIL, and other Python goodies > 2) use PHP to create the thumbnails > 3) Open the images into a buffer and try to do the calculations > myself > > I'm thinking I might have to go with 1. > > I want the script to run as a service so I don't know how well number > 2 would work and I certainly don't want number 3 (on a time-line > here). Why don't you put PIL where your modules are? You are surely allowed to upload your own python modules somewhere where you can access them (and import them) so you can put PIL into the same place and happily import them just as any other module you wrote. You might need to find out what the architecture of the machine is (as far as I remember PIL has some C extensions) and compile PIL for that architecture. HTH, Daniel From manstey at csu.edu.au Sun May 20 20:50:41 2007 From: manstey at csu.edu.au (manstey) Date: 20 May 2007 17:50:41 -0700 Subject: subclassing list question Message-ID: <1179708641.582702.229530@u36g2000prd.googlegroups.com> test From bj_666 at gmx.net Sun May 13 19:48:17 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 14 May 2007 01:48:17 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476081.7080609@web.de> Message-ID: In , Michael Torrie wrote: > I think non-ASCII characters makes the problem far far worse. While I > may not understand what the function is by it's name in your example, > allowing non-ASCII characters makes it works by forcing all would-be > code readers have to have all kinds of necessary fonts just to view the > source code. Things like reporting exceptions too. At least in your > example I know the exception occurred in zieheDreiAbVon. But if that > identifier is some UTF-8 string, how do I go about finding it in my text > editor, or even reporting the message to the developers? I don't happen > to have that particular keymap installed in my linux system, so I can't > even type the letters! You find it in the sources by the line number from the traceback and the letters can be copy'n'pasted if you don't know how to input them with your keymap or keyboard layout. Ciao, Marc 'BlackJack' Rintsch From ruoyu0088 at gmail.com Tue May 15 09:30:50 2007 From: ruoyu0088 at gmail.com (HYRY) Date: 15 May 2007 06:30:50 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179226183.215907.140450@q75g2000hsh.googlegroups.com> Message-ID: <1179235850.886650.237440@e65g2000hsc.googlegroups.com> > That is a good point, but I'd like to ask out of curiosity, at what age > do children generally learn pinyin? (Assuming you speak Mandarin. If > not, replace pinyin with the name of whatever phonetic transliteration > is common in your region.) Granted, pinyin shoehorned into ASCII loses > its tone marks, but the result would still be more mnemonic than an > English word that the student has to learn. > Yes, we use Pinyin, and add a number to deal with tone marks, it is better than English words, but as a Chinese, reading pingyin is much slower than reading HanZi. From carsten at uniqsys.com Tue May 8 09:55:01 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 08 May 2007 09:55:01 -0400 Subject: No module named urllib In-Reply-To: <1178630341.147781.39380@y5g2000hsa.googlegroups.com> References: <1178575589.059564.226060@q75g2000hsh.googlegroups.com> <87tzuop8s2.fsf@gmail.com> <1178577562.498615.222340@e51g2000hsg.googlegroups.com> <87ps5cp816.fsf@gmail.com> <1178578923.067315.14440@q75g2000hsh.googlegroups.com> <1178580280.902179.248000@w5g2000hsg.googlegroups.com> <1178630341.147781.39380@y5g2000hsa.googlegroups.com> Message-ID: <1178632501.3357.25.camel@dot.uniqsys.com> On Tue, 2007-05-08 at 06:19 -0700, HMS Surprise wrote: > Thanks for posting. How does one ensure (or even detect) that their > libraries are compatible? You ensure that by taking the library from the version of Python that you're running. > I loaded this library as part of Python 2.5. That's too new. Since you're using Jython, you're running either 2.1 or 2.2 depending on whether you've installed the stable version or the beta version. Go grab a Python distribution of the correct version and get the modules you need from there. Note this, though: http://www.jython.org/Project/installation.html#can-t-access-standard-python-modules : "Not all the modules form CPython is available in Jython. Some modules require a C language dynamic link library that doesn't exists in java. Other modules are missing from Jython just because nobody have had a need for it before and no-one have tested the CPython module with Jython. If you discover that you are missing a module, try to copy the .py file from a CPython distribution to a directory on your Jython sys.path. If that works you are set. If it doesn't work, try asking on jython-users mailing list." To summarize, you could be looking at a rather deep rabbit hole of possibly unsatisfiable dependencies. To summarize the summary, are you sure you need to use Jython instead of standard CPython? Good luck, -- Carsten Haese http://informixdb.sourceforge.net From slewin at rogers.com Fri May 18 17:38:23 2007 From: slewin at rogers.com (scott) Date: Fri, 18 May 2007 17:38:23 -0400 Subject: Python compared to other language In-Reply-To: <92e04$464e1855$d443bb3a$4136@news.speedlinq.nl> References: <92e04$464e1855$d443bb3a$4136@news.speedlinq.nl> Message-ID: <464E1CCF.6040702@rogers.com> Thank you everyone for your help. I will make sure to check the archives, something I should have done first :) -- Your friend, Scott Sent to you from a 100% Linux computer using Kubuntu Version 7.04 (Feisty Fawn) From john at datavoiceint.com Tue May 15 11:05:25 2007 From: john at datavoiceint.com (HMS Surprise) Date: 15 May 2007 08:05:25 -0700 Subject: File record separators. Message-ID: <1179241525.667682.112220@y80g2000hsf.googlegroups.com> I need to write 2 member lists to a file. For each record the number of these lists can be different. I think a good way to handle that may be to make each record a list of lists. I am restricted to using version 2.2. That being the case what is a good standard record separator to use to ensure that I read in one record (list of lists) at a time, '\n'? I want to try to stay with what is considered standard python idioms. Thanks, jvh From eric.brunel at pragmadev.com Tue May 15 04:52:21 2007 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Tue, 15 May 2007 10:52:21 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> <4648294F.2000704@web.de> <46487a6c$0$2400$426a74cc@news.free.fr> Message-ID: On Tue, 15 May 2007 09:38:38 +0200, Duncan Booth wrote: > Recently there has been quite a bit of publicity about the One Laptop Per > Child project. The XO laptop is just beginning rollout to children and > provides two main programming environments: Squeak and Python. It is an > exciting thought that that soon there will be millions of children in > countries such as Nigeria, Brazil, Uruguay or Nepal[*] who have the > potential to learn to program, but tragic if the Python community is too > arrogant to consider it acceptable to use anything but English and ASCII. You could say the same about Python standard library and keywords then. Shouldn't these also have to be translated? One can even push things a little further: I don't know about the languages used in the countries you mention, but for example, a simple construction like 'if ' will look weird to a Japanese (the Japanese language has a "post-fix" feel: the equivalent of the 'if' is put after the condition). So why enforce an English-like sentence structure? > Yes, any sensible widespread project is going to mandate a particular > language for variable names and comments, but I see no reason at all why > they all have to use English. Because that's what already happens? We definitely are in a globalized world, and the only candidate language having a chance to allow people to communicate with each other is English. Period. And believe me, I don't like that (I'm French, if that can give you an idea about how much I don't...). But that's a fact. Even people knowing the same language sometimes communicate in English just in case they have to widen the discussion to somebody else. To give you a perfect example, I had to discuss just yesterday an answer we had to do to a Belgian guy, who speaks French without any problem. His mail was written in English, and we answered in English. Anyway: > I don't believe that Python should be restricted to people *serious* > about programming. You have a point here. When learning to program, or when programming for fun without any intention to do something serious, it may be better to have a language supporting "native" characters in identifiers. My problem is: if you allow these, how can you prevent them from going public someday? -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From johnjsal at NOSPAMgmail.com Wed May 9 15:48:13 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 09 May 2007 15:48:13 -0400 Subject: preferred windows text editor? In-Reply-To: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> References: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> Message-ID: <464222d8$0$30508$c3e8da3@news.astraweb.com> T. Crane wrote: > Right now I'm using Notepad++. What are other people using? > > trevis > > I love UltraEdit. It's not free, but very nice. From DustanGroups at gmail.com Mon May 21 18:12:18 2007 From: DustanGroups at gmail.com (Dustan) Date: 21 May 2007 15:12:18 -0700 Subject: NEWBIE: Extending a For Statement. In-Reply-To: <1179757278.283371.263860@y2g2000prf.googlegroups.com> References: <1179749446.179064.222990@z28g2000prd.googlegroups.com> <1179756164.506426.116210@x18g2000prd.googlegroups.com> <1179757278.283371.263860@y2g2000prf.googlegroups.com> Message-ID: <1179785538.678166.53280@z28g2000prd.googlegroups.com> On May 21, 9:21 am, mosscliffe wrote: > On 21 May, 15:02, bearophileH... at lycos.com wrote: > > > mosscliffe: > > > > if key in xrange (60,69) or key == 3: > > > I keep seeing again and again code like this, mostly from people not > > much expert of Python, but the PEP 260 shows the fast in was removed, > > so it's O(n). Maybe removing the fast __contains__ was bad for > > necomers (or just the casual Python users, that I belive is really > > large). > > > Bye, > > bearophile > > Being a non-expert in python in fact just a beginner / casual user, > can you expand on how 0(n) relates to > if key in xrange (60,69) or key == 3: the "key in xrange(60,69)" part: all that does is iterate through xrange(60, 69) and when a match is met, it returns true. If it ends up iterating through the whole list without finding a match, it returns false. > My mind tends to go blank at the mention of __xxx__. The above is the default behavior of the 'in' operator. That default behavior can be overridden by a class that has the __contains__ method. So "XXX in YYY" expands roughly to the following (as I understand it; I haven't actually looked it up): if hasattr(YYY, "__contains__"): return YYY.__contains__(XXX) else: for i in YYY: if XXX == YYY: return True return False > R From kyosohma at gmail.com Thu May 3 14:48:35 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 3 May 2007 11:48:35 -0700 Subject: problem with py2exe and microsoft speech SDK 5.1 In-Reply-To: References: Message-ID: <1178218115.578246.321800@q75g2000hsh.googlegroups.com> On May 3, 1:29 pm, Dave Lim wrote: > Hello, this is my first time in the mailing list so > bear with me. > > Basically what I did was I followed this site:http://surguy.net/articles/speechrecognition.xml > > So I installed microsoft speech SDK 5.1 and then used > pythonwin COM MakePy utility for it and it worked out > fine. However, I need to compile my program into a > .exe and I have no idea how to make this work. I tried > using py2exe but I get the error: > > Traceback (most recent call last): > File "simple-speech-recognition.py", line 57, in ? > TypeError: Error when calling the metaclass bases > cannot create 'NoneType' instances > > If anybody knows a good solution to this problem I > would very much appreciate it if you can guide me to > the right path / solution. > > Thank you very much! > -Dave Lim > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection aroundhttp://mail.yahoo.com I've never done this, but I want to at some point, so I went and grabbed some good links on packaging up Python apps: http://davidf.sjsoft.com/mirrors/mcmillan-inc/install1.html http://www.pharscape.org/content/view/33/51/ http://wiki.python.org/moin/Py2Exe http://www.py2exe.org/index.cgi/Tutorial There's also growth in using Python Eggs: http://peak.telecommunity.com/DevCenter/PythonEggs Mike From rrr at ronadam.com Fri May 25 16:00:38 2007 From: rrr at ronadam.com (Ron Adam) Date: Fri, 25 May 2007 15:00:38 -0500 Subject: webbrowser module bug? In-Reply-To: References: <1180118146.617722.300670@g4g2000hsf.googlegroups.com> Message-ID: Ron Adam wrote: > Paul Boddie wrote: >> On 25 May, 00:03, Ron Adam wrote: >>> Is anyone else having problems with the webbrowser module? >>> >>> Python 2.5.1c1 (release25-maint, Apr 12 2007, 21:00:25) >>> [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 >>> Type "help", "copyright", "credits" or "license" for more information. >>> >>> import webbrowser >>> >>> webbrowser.open('http://www.python.org') >>> True >>> >>> >>> >>> It opens firefox as expected, but the url is ... >>> >>> file:///home/ron/%22http://www.python.org%22 >> Since %22 is the URL-encoded double-quote character ("), I can only >> imagine that something is quoting the URL for the shell, resulting in >> the following command: >> >> firefox '"http://www.python.org/"' >> >> Or something similar, at least. Firefox 1.5 seems to refuse to open >> such URLs, though. >> >> Paul > > Yes, thats it. I've traced it down the the subproccess.Popen call. > > > This works > > >>> subprocess.Popen(['firefox', 'http://python.org']) > > > > This reproduces the problem I'm having. > > >>> subprocess.Popen(['firefox', '"http://python.org"']) > > > The quoting does happen in the webbrowser module. > > The cmdline is passed as... > > ['/usr/lib/firefox/firefox', '"http://python.org"'] > > > > I've traced it back to the following line where self.args is ['"%s"'] > > Line 187 in webbrowser.py: > > cmdline = [self.name] + [arg.replace("%s", url) > for arg in self.args] > > Now I just need to figure out why self.args is double quoted. Got it. It looks like the problem started when I told firefox to make itself the default browser. That changed the way webbrowser.py figured out the browser to use. So instead of trying them in order, it asked the gnome configure tool for it. def register_X_browsers(): # The default Gnome browser if _iscommand("gconftool-2"): # get the web browser string from gconftool gc = 'gconftool-2 -g /desktop/gnome/url-handlers/http/command 2>/dev/null' out = os.popen(gc) commd = out.read().strip() retncode = out.close() After this commd is: '/usr/lib/firefox/firefox "%s"' It's then split, but the quotes aren't removed. I'm not sure why this doesn't show up in 2.6. Maybe it's been fixed there already. Cheers, Ron From mail at microcorp.co.za Tue May 22 02:16:15 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 22 May 2007 08:16:15 +0200 Subject: tkinter button state = DISABLED References: <588D53831C701746A2DF46E365C018CE01D2CAA2@LITEXETSP001.etrsouth.corp.entergy.com> Message-ID: <01ac01c79c3c$81ccc540$03000080@hendrik> "Hamilton, William " wrote: > > From: Eric Brunel > On Thu, 17 May 2007 09:30:57 +0200, Hendrik van Rooyen > > wrote: > > > "Gabriel Genellina" wrote: > > >> En Wed, 16 May 2007 03:22:17 -0300, Hendrik van Rooyen > > >>> I have never seen this working in Tkinter, unless the button was > > >>> pressed > > >>> on the > > >>> widget > > >>> in question - and worse, once you have clicked down on a ButtonRelease > > >>> binding > > >>> you can move the mouse pointer anywhere you like, even out of the > > >>> application > > >>> and when you release it, the bound function is called... > > >>> > > >>> Its either a bug or a feature, I don't know. > > >> > > >> Uhmm... I'm not sure I understand you completely. I only said that the > > >> "command" is fired only when the mouse button is pressed on the widget, > > >> AND released inside the same widget. If both events don't happen in the > > >> same widget, "command" won't fire. Maybe you are saying the same > > >> thing... > > >> anyway I'm not a Tk expert. > > > > > > No command is ok and you have described it right - its ButtonRelease > > that > > > seems broken to me > > > > Apparently, this behaviour is the intended one, at least for buttons; see: > > http://www.tcl.tk/man/tcl8.4/TkCmd/bind.htm#M11 > > > > As for the question "why?", maybe you should ask it on the c.l.tcl > > newsgroup? > > The difference between bind and the button's command parameter makes sense > to me. You'd use bind to create something like a right-click menu, where > you want the same thing to happen whether the button is disabled or not. > You use the command parameter when you care about the state of the button. > That is a good point. What I was actually nattering on about was the unexpected behaviour of the ButtonRelease binding - from its name, you would expect it to call the bound function when a click is released on the button. It does not do that. Having been told that its the expected behaviour, I can imagine it to be useful in "drag and drop" scenarios, to implement something from the source side - a "thrower" - as opposed to the "catcher" type of behaviour that its name suggests. - Hendrik From zefria at gmail.com Wed May 30 23:11:08 2007 From: zefria at gmail.com (Daniel Gee) Date: 30 May 2007 20:11:08 -0700 Subject: trouble with wxPython intro Message-ID: <1180581067.908739.252960@a26g2000pre.googlegroups.com> I'm trying to learn WxPython with the tutorial: http://wiki.wxpython.org/Getting_Started But I can't seem to get the example for events to work. I pasted the code they had directly into an interpreter and it got a dialog to appear and the program was able to close itself, but my own copy won't work. As far as I can see, it isn't at all different except for the name of the main frame, and so I differ to you for help. my own code: #!/usr/bin/python import wx ID_ABOUT=101 ID_EXIT=110 class MainWindow(wx.Frame): def __init__(self,parent,id,title): wx.Frame.__init__(self,parent,id,title,size=(200,100)) self.control = wx.TextCtrl(self,1,style=wx.TE_MULTILINE) self.CreateStatusBar() #adds a status bar to the bottom #Menu setup filemenu = wx.Menu() filemenu.Append(wx.ID_ABOUT,"&About","Info about the program") filemenu.AppendSeparator() filemenu.Append(wx.ID_EXIT,"E&xit","Terminate the program.") #Menubar setup menuBar = wx.MenuBar() menuBar.Append(filemenu,"&File") #add file to the menubar self.SetMenuBar(menuBar) #add in the menubar # Add events wx.EVT_MENU(self,ID_ABOUT,self.OnAbout) wx.EVT_MENU(self,ID_EXIT,self.OnExit) # Go! self.Show(True) def OnAbout(self,e): print "Show!" d = wx.MessageDialog(self,"A sample editor.","About Sample Ed",wx.OK) d.ShowModal() d.Destroy() def OnExit(self,e): print "close!" self.Close(True) app = wx.PySimpleApp() frame = MainWindow(None,wx.ID_ANY,'Small Ed!') app.MainLoop() From vb at itechart.com Mon May 7 06:48:57 2007 From: vb at itechart.com (VB) Date: 7 May 2007 03:48:57 -0700 Subject: Custom software development Message-ID: <1178534937.448568.60540@l77g2000hsb.googlegroups.com> iTechArt Group - Custom Software Development and Offshore outsourcing Company http://www.itechart.com/ Offshore custom software development company iTechArt - Web site and Content Management Solutions development, CMS consulting: Ektron, Drupal and DotNetNuke iTechArt Group provides high quality custom software development services and offshore software development. On December 2006, iTechArt Group became an authorized Microsoft Certified Partner. This means that our company has been recognized by Microsoft for our vast expertise and authorized to custom software development; provide IT service consulting and custom business solutions. Custom Software Development and Offshore outsourcing Company iTechArt has worked together since 2003 to design build and deliver .NET Web Content Management software solutions that help clients meet their strategic objectives. We are agile oriented development partner able to consistently deliver solid results. iTechArt software development team assemblies specialists in the development of custom software applications and offshore software outsourcing services. Working concepts of our company are based on proven approaches and international standards used for custom software development such as Capability Maturity Model Integration for Software Engineering (CMMI- SW). In the same breath we have our own standpoint on software development process management which is fully effective and comprehensible for our clients. iTechArt offers software development in the next main directions: 1. Custom Software Development (Offshore outsourcing for worldwide based software development companies.) 2. Software Development for Digital Signage (Media content development and remote displays / information kiosks Web-based software application management.) 3. Web Site Development (E-commerce solutions, CMS/DotNetNuke/Ektron/ Drupal, Web 2.0/PHP/MySQL/AJAX, Flash/Action script/Flex and many more.) 4. Offshore Development Center (Dedicated development team of software developers. Our offshore development centers operate as an extension to clients' existing software engineering business.) Contact iTechArt ( http://www.itechart.com/ )about custom software development, end-to-end software solutions, outsourcing software development, custom DotNetNuke module development, DotNetNuke consulting, dotnetnuke hosting, first class Java and .Net developers, software application design, software testing, Quality Assurance, functionality testing and defect analysis, performance and stress testing, usability testing, Microsoft Media Services and Adobe Media Flash Server solutions, digital signage solutions and custom development, Ektron CMS400.NET developers, CMS, .NET Web Content Management software solutions Web: http://www.itechart.com/ http://www.itechart.com/Pages/ProductsServices/HowWeWork.aspx http://www.itechart.com/Pages/ProductsServices/BusinessModels.aspx http://www.itechart.com/Pages/ProductsServices/CustomSoftwareDevelopment.aspx http://www.itechart.com/Pages/ProductsServices/DotNetNukeModuleDevelopment.aspx From martin at v.loewis.de Wed May 23 00:48:43 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 23 May 2007 06:48:43 +0200 Subject: Windows Debugging w/o MS In-Reply-To: References: Message-ID: <4653C7AB.3080202@v.loewis.de> > I am trying to build an extension module written in C++ on windows XP. > I am trying to use only open-source tools, such as mingw. I'm using > the Python 2.5 official, and it seems to compile my module just fine > (I'm using the --compiler=mingw32). I can also import the module. The > problem is, when I attempt to use it, I get a segfault. Does it segfault if you import it, or just when you invoke functions of the module? You should get it in a state where you can import it just fine, e.g. by removing stuff from the init function. > Now, I'm > pretty sure this segfault is just a bug in my C++ code. So of course, > I would like to debug this thing somehow. I tried using the mingw gdb > giving it my python.exe to run, but obviously this python has no debug > info, and wasn't even compiled with mingw. I was hoping it would still > somehow debug my extension module right, but when I do a backtrace > after it segfaults, I get nothing useful. If you can import safely, you should do this: 1. start gdb, with python.exe as the program 2. r(un) it, in gdb 3. import your_module 4. Ctrl-c (or otherwise get back into the debugger) 5. see whether you can set breakpoints on your function gdb should be able to figure out that your extension module was loaded and has debug information. Set a breakpoint and see whether it shows line numbers. If it doesn't, it's because your module does not have debug information. > I've tried compiling python from source, and my extension module, > using MSVC8 (free express version), and I managed to get this to work. > The thing is, I don't want to have to recompile every single python > package I need (wxPython, SciPy, etc). You should also be able to compile Python with the mingw compiler, giving you gdb debug information for all modules. > So basically, I need some general advice for how to compile and debug > extension modules on windows using only open-source tools. I am still > amazed that MSVC7.1 was chosen for the official python release and not > mingw, has anyone explained this? Python uses the "system compiler" on all systems, and the system compiler on Microsoft Windows, is, well, Microsoft C. Using that compiler works better in a number of important use cases. For example, it is absolutely necessary to be able to compile extension modules that use C++, COM, and the Microsoft Foundation Classes. Such extension modules must be compiled with MSC, since g++ is not capable of compiling them (at least for MFC). One important extension module that relies on such technology is Mark Hammond's PythonWin. If Python was build with mingw, it might be that such modules could not work anymore, depending on how precisely the mingw build is done (e.g. what CRT you would use). Regards, Martin From rene at korteklippe.de Wed May 16 03:44:16 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Wed, 16 May 2007 09:44:16 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179291296.561359.286230@h2g2000hsg.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649dd55$0$23144$9b4e6d93@newsspool1.arcor-online.net> <464a25e9$0$10188$9b4e6d93@newsspool4.arcor-online.net> <1179291296.561359.286230@h2g2000hsg.googlegroups.com> Message-ID: <464ab64f$0$10185$9b4e6d93@newsspool4.arcor-online.net> rurpy at yahoo.com schrieb: > I'm not sure how you conclude that no problem exists. > - Meaningful identifiers are critical in creating good code. I agree. > - Non-english speakers can not create or understand > english identifiers hence can't create good code nor > easily grok existing code. I agree that this is a problem, but please understand that is problem is _not_ solved by allowing non-ASCII identifiers! > Considering the vastly greater number of non-English > spreakers in the world, who are not thus unable to use > Python effectively, seems like a problem to me. Yes, but this problem is not really addressed by the PEP. If you want to do something about this: 1) Translate documentation. 2) Create a way to internationalize the standard library (and possibly the language keywords, too). Ideally, create a general standardized way to internationalize code, possibly similiar to how people internationalize strings today. When that is done, non-ASCII identifiers could become useful. But of course, doing that might create a hog of other problems. > That all programers know enough english to create and > understand english identifiers is currently speculation or > based on tiny personaly observed samples. It is based on a look at the current Python environment. You do *at least* have the problem that the standard library uses English names. This assumes that there is documentation in the native language that is good enough (i.e. almost as good as the official one), which I can tell is not the case for German. -- Ren? From openopt at ukr.net Mon May 7 06:04:59 2007 From: openopt at ukr.net (dmitrey) Date: 7 May 2007 03:04:59 -0700 Subject: matplotlib: howto redraw figure automatically, without stop in show()/draw()? Message-ID: <1178532299.418643.267790@e51g2000hsg.googlegroups.com> Hi all, here is a question already mentioned below, and I'm also interested in that one very much. unfortunatly, I can't write anything to matplotlib mailing lists because I constantly get server internal error (500) Does anyone knows the answer? (howto redraw figure automatically (for example update from time to time in cycle), without stop in show()/draw()?) Thx in advance, D. redcic wrote: > I've already got this package. I just wanted to try something new. > However, since you talk about it, I've got a question regarding this > package. The execution of the code stops after the line: > pylab.show() > which is off course the last line of my code. My problem is that I > have to close the figure window in order to launch my program another > time. I'd like to be able to launch my program many times with > different parameters without having to close the figure windows before > each launch. > Just so you know, I'm using TkAgg backend. > Any hint ? From max at alcyone.com Tue May 29 14:36:07 2007 From: max at alcyone.com (Erik Max Francis) Date: Tue, 29 May 2007 11:36:07 -0700 Subject: 0 == False but [] != False? In-Reply-To: References: <1179982400.412340.178710@g4g2000hsf.googlegroups.com> <1179983482.452458.188690@q66g2000hsg.googlegroups.com> Message-ID: Donn Cave wrote: > Not that it is of no historical interest to review all these > reasonable arguments, but allow me to restore the context quote > from my follow-up: If the counterpoints are of no historical interest, then the original point must be of no historical interest either, since it was not widely granted as true. -- 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 Fear is an emotion indispensible for survival. -- Hannah Arendt From steve at holdenweb.com Thu May 24 12:32:44 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 24 May 2007 12:32:44 -0400 Subject: Module imports fine from interactive, not from script In-Reply-To: <46538a79$0$16264$88260bb3@free.teranews.com> References: <46538a79$0$16264$88260bb3@free.teranews.com> Message-ID: Joshua J. Kugler wrote: > Yes, I've read this: > http://mail.python.org/pipermail/python-list/2006-August/395943.html > That's not my problem. > > I installed PlanetPlanet via the > package's "setup.py install" command (as root). planet.py will not run, > however, giving me this error: > > Traceback (most recent call last): > File "/usr/local/bin/planet.py", line 167, in ? > main() > File "/usr/local/bin/planet.py", line 124, in main > planet.logging.basicConfig() > AttributeError: 'module' object has no attribute 'logging' > > But, from interactive session: > > jkugler at europa:~/www$ ls -l # to show that the modules are not in the > current dir > total 20 > -rw-r--r-- 1 jkugler jkugler 2247 2007-05-22 15:26 atom.xml.tmpl > -rw-r--r-- 1 jkugler jkugler 2089 2007-05-22 15:25 index.html.tmpl > -rw-r--r-- 1 jkugler jkugler 564 2007-05-22 15:43 planet.ini > -rw-r--r-- 1 jkugler jkugler 1128 2007-05-22 15:26 rss10.xml.tmpl > -rw-r--r-- 1 jkugler jkugler 838 2007-05-22 15:26 rss20.xml.tmpl > jkugler at europa:~/www$ python > Python 2.4.3 (#2, Oct 6 2006, 07:52:30) > [GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import planet >>>> planet.logging > from '/usr/local/lib/python2.4/site-packages/planet/logging/__init__.py'> >>>> planet.logging.basicConfig() >>>> > > The contents of /usr/local/lib/python2.4/site-packages/planet > jkugler at europa:~/www$ ls -la /usr/local/lib/python2.4/site-packages/planet/ > total 270 > drwxr-sr-x 4 root staff 1024 2007-05-22 16:59 . > drwxrwsr-x 4 root staff 1024 2007-05-22 15:18 .. > -rw-r--r-- 1 root staff 4315 2006-07-26 15:53 atomstyler.py > -rw-r--r-- 1 root staff 8887 2006-07-26 15:53 cache.py > -rw-r--r-- 1 root staff 126446 2006-07-26 15:53 feedparser.py > -rw-r--r-- 1 root staff 58705 2006-07-26 15:53 htmltmpl.py > -rw-r--r-- 1 root staff 38145 2006-07-26 15:53 __init__.py > drwxr-xr-x 2 root staff 1024 2007-05-22 16:59 logging > -rw-r--r-- 1 root staff 13904 2006-07-26 15:53 sanitize.py > drwxr-xr-x 2 root staff 1024 2007-05-22 16:59 tests > -rw-r--r-- 1 root staff 12681 2006-07-26 15:53 timeoutsocket.py > > planet.py is simply executing: > > import planet > . > . > . > # Activate logging > planet.logging.basicConfig() > > > I've checked permissions, I've checked import statements, everything I know > to check. Is there something terribly simple I'm missing? > > Thanks! > > j > The directory containing the script you are executing is also added to sys.path. Since you are executing a script called planet ... 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From vito.detullio at gmail.com Fri May 18 02:47:11 2007 From: vito.detullio at gmail.com (ZeD) Date: Fri, 18 May 2007 06:47:11 GMT Subject: alternative to eclipse [ python ide AND cvs ] References: Message-ID: yomgui wrote: > I use eclipse for python and cvs, what is "the" good alternative ? "the" good alternative, I dont know. But a good solution is eric3 (http://www.die-offenbachs.de/detlev/eric.html) -- Under construction From m.yanowitz at kearfott.com Wed May 9 17:31:32 2007 From: m.yanowitz at kearfott.com (Michael Yanowitz) Date: Wed, 9 May 2007 17:31:32 -0400 Subject: Checking if string inside quotes? In-Reply-To: <1178745091.682071.128670@w5g2000hsg.googlegroups.com> Message-ID: <000601c79281$697573d0$0d7d12ac@kearfott.com> Thanks, but it is a little more complicated than that, the string could be deep in quotes. The problem is in string substitution. Suppose I have a dictionary with MY_IP : "172.18.51.33" I need to replace all instances of MY_IP with "172.18.51.33" in the file. It is easy in cases such as: if (MY_IP == "127.0.0.1"): But suppose I encounter:" ("(size==23) and (MY_IP==127.0.0.1)") In this case I do not want: ("(size==23) and ("172.18.51.33"==127.0.0.1)") but: ("(size==23) and (172.18.51.33==127.0.0.1)") without the internal quotes. How can I do this? I presumed that I would have to check to see if the string was already in quotes and if so remove the quotes. But not sure how to do that? Or is there an easier way? Thanks in advance: Michael Yanowitz -----Original Message----- From: python-list-bounces+m.yanowitz=kearfott.com at python.org [mailto:python-list-bounces+m.yanowitz=kearfott.com at python.org]On Behalf Of half.italian at gmail.com Sent: Wednesday, May 09, 2007 5:12 PM To: python-list at python.org Subject: Re: Checking if string inside quotes? On May 9, 1:39 pm, "Michael Yanowitz" wrote: > Hello: > > If I have a long string (such as a Python file). > I search for a sub-string in that string and find it. > Is there a way to determine if that found sub-string is > inside single-quotes or double-quotes or not inside any quotes? > If so how? > > Thanks in advance: > Michael Yanowitz I think the .find() method returns the index of the found string. You could check one char before and then one char after the length of the string to see. I don't use regular expressions much, but I'm sure that's a more elegant approach. This will work. You'll get in index error if you find the string at the very end of the file. s = """ foo "bar" """ findme = "foo" index = s.find(findme) if s[index-1] == "'" and s[index+len(findme)] == "'": print "single quoted" elif s[index-1] == "\"" and s[index+len(findme)] == "\"": print "double quoted" else: print "unquoted" ~Sean -- http://mail.python.org/mailman/listinfo/python-list From bellman at lysator.liu.se Fri May 18 03:47:32 2007 From: bellman at lysator.liu.se (Thomas Bellman) Date: Fri, 18 May 2007 07:47:32 +0000 (UTC) Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <464D2B53.9090409@v.loewis.de> Message-ID: =?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?= wrote: >> 3) Is or will there be a definitive and exhaustive listing (with >> bitmap representations of the glyphs to avoid the font issues) of the >> glyphs that the PEP 3131 would allow in identifiers? (Does this >> question even make sense?) > As for the list I generated in HTML: It might be possible to > make it include bitmaps instead of HTML character references, > but doing so is a licensing problem, as you need a license > for a font that has all these characters. If you want to > lookup a specific character, I recommend to go to the Unicode > code charts, at > http://www.unicode.org/charts/ My understanding is also that there are several east-asian characters that display quite differently depending on whether you are in Japan, Taiwan or mainland China. So much differently that for example a Japanese person will not be able to recognize a character rendered in the Taiwanese or mainland Chinese way. -- Thomas Bellman, Lysator Computer Club, Link?ping University, Sweden "Adde parvum parvo magnus acervus erit" ! bellman @ lysator.liu.se (From The Mythical Man-Month) ! Make Love -- Nicht Wahr! From Maksim.Kasimov at gmail.com Tue May 22 13:17:30 2007 From: Maksim.Kasimov at gmail.com (sim.sim) Date: 22 May 2007 10:17:30 -0700 Subject: xml.dom.minidom: how to preserve CRLF's inside CDATA? Message-ID: <1179841434.957679.242310@z28g2000prd.googlegroups.com> Hi all. i'm faced to trouble using minidom: #i have a string (xml) within CDATA section, and the section includes "\r\n": iInStr = '\n\n' #After i create DOM-object, i get the value of "Data" without "\r\n" from xml.dom import minidom iDoc = minidom.parseString(iInStr) iDoc.childNodes[0].childNodes[0].data # it gives u'BEGIN:VCALENDAR \nEND:VCALENDAR\n' according to http://www.w3.org/TR/REC-xml/#sec-line-ends it looks normal, but another part of the documentation says that "only the CDEnd string is recognized as markup": http://www.w3.org/TR/REC-xml/#sec-cdata-sect so parser must (IMHO) give the value of CDATA-section "as is" (neither both of parts of the document do not contradicts to each other). How to get the value of CDATA-section with preserved all symbols within? (perhaps use another parser - which one?) Many thanks for any help. From steve at REMOVE.THIS.cybersource.com.au Wed May 9 22:46:05 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 10 May 2007 12:46:05 +1000 Subject: change of random state when pyc created?? References: <5ae25fF2oggbqU1@mid.uni-berlin.de> Message-ID: On Wed, 09 May 2007 16:01:02 -0500, Robert Kern wrote: > Alan G Isaac wrote: >> Robert Kern wrote: >>> http://docs.python.org/lib/typesmapping.html >>> """ >>> Keys and values are listed in an arbitrary order which is non-random, varies >>> across Python implementations, and depends on the dictionary's history of >>> insertions and deletions. >>> """ >> >> Even this does not tell me that if I use a specified implementation >> that my results can vary from run to run. That is, it still does >> not communicate that rerunning an *unchanged* program with an >> *unchanged* implementation can produce a change in results. > > The last clause does tell me that. Actually it doesn't. If you run a program twice, with the same inputs, and no other source of randomness (or at most have pseudo-randomness starting with the same seed), then the dictionary will have the same history of insertions and deletions from run to run. Go back to Peter Otten's diagnosis of the issue: "... your GridPlayer instances are located in different memory locations and get different hash values. This in turn affects the order in which they occur when you iterate over the GridPlayer.players_played set." There is nothing in there about the dictionary having a different history of insertions and deletions. It is having the same insertions and deletions each run, but the items being inserted are located at different memory locations, and _that_ changes their hash value and hence the order they occur in when you iterate over the set. That's quite a subtle thread to follow, and with all respect Robert, it's easy to say it is obvious in hindsight, but I didn't notice you solving the problem in the first place. Maybe you would have, if you had tried... and maybe you would have scratched your head too. Who can tell? As Carsten Haese says in another post: "The documentation shouldn't be expected to list every little thing that might change the order of keys in a dictionary. The documentation does say explicitly what *is* guaranteed: Order of keys is preserved as long as no intervening modifications happen to the dictionary. Tearing down the interpreter, starting it back up, and rebuilding the dictionary from scratch is very definitely an intervening modification." That's all very true, but nevertheless it is a significant gotcha. It is natural to expect two runs of any program to give the same result if there are (1) no random numbers involved; (2) the same input data; (3) and no permanent storage from run to run. One doesn't normally expect the output of a well-written, bug-free program to depend on the memory location of objects. And that's the gotcha -- with dicts and sets, they can. -- Steven. From hardcoded.software at gmail.com Thu May 3 21:33:35 2007 From: hardcoded.software at gmail.com (Virgil Dupras) Date: 3 May 2007 18:33:35 -0700 Subject: Decorating class member functions In-Reply-To: <1178241696.641350.292210@n59g2000hsh.googlegroups.com> References: <1178241696.641350.292210@n59g2000hsh.googlegroups.com> Message-ID: <1178242415.863006.138860@l77g2000hsb.googlegroups.com> On May 3, 9:21 pm, Andy Terrel wrote: > Okay does anyone know how to decorate class member functions? > > The following code gives me an error: > > Traceback (most recent call last): > File "decorators2.py", line 33, in > s.update() > File "decorators2.py", line 13, in __call__ > retval = self.fn.__call__(*args,**kws) > TypeError: update() takes exactly 1 argument (0 given) > > ------------------ > > #! /usr/bin/env python > > class Bugger (object): > def __init__ (self, module, fn): > self.module = module > self.fn = fn > > def __call__ (self,*args, **kws): > ret_val = self.fn(*args,**kws) > return ret_val > > def instrument (module_name): > ret_val = lambda x: Bugger(module_name, x) > return ret_val > > class Stupid: > def __init__(self): > self.val = 1 > > @instrument("xpd.spam") > def update(self): > self.val += 1 > > s = Stupid() > s.update() A decorator is a function that takes one single parameter: a function. "instrument" must return a decorator. From bbxx789_05ss at yahoo.com Sat May 19 12:58:47 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 19 May 2007 09:58:47 -0700 Subject: docs patch: dicts and sets In-Reply-To: <_5-dnU7aIN73j9LbnZ2dnUVZ_uCinZ2d@comcast.com> References: <_5-dnU7aIN73j9LbnZ2dnUVZ_uCinZ2d@comcast.com> Message-ID: <1179593927.503393.127350@u30g2000hsc.googlegroups.com> On May 19, 9:06 am, Steven Bethard wrote: > Alan Isaac wrote: > > I submitted the language based on Bill and Carsten's proposals: > > >https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1721372&... > > > That language has been rejected. > > You many want to read the discussion and see if > > acceptible language still seems discoverable. > > Seems to me that you're focusing on the wrong part of the docs. The > source of this "bug" is not sets or dicts, but the default __hash__ > method implementation. Why don't you propose adding something like: > > The default __hash__ method is based on an object's id(), and can > therefore change between different iterations of the same program. > > to the docs for __hash__: > > http://docs.python.org/ref/customization.html > > Then if you really feel you need to add something for sets and dicts, > you can add a cross-reference to the __hash__ docs. > > STeVe Here's an idea--add All the proposed changes to the docs. Why not allow user's to add any explanations to the docs that they want? Then readers can choose the explanations that make the most sense to them. It would eliminate endless, petty discussions about what minutiae are more important, and it would allow people to spend their time on more productive efforts. And it would improve the docs exponentially. From nagle at animats.com Tue May 1 18:20:44 2007 From: nagle at animats.com (John Nagle) Date: Tue, 01 May 2007 22:20:44 GMT Subject: Lisp-like macros in Python? In-Reply-To: References: <1178035825.193334.184250@o5g2000hsb.googlegroups.com> Message-ID: <03PZh.6904$rO7.2023@newssvr25.news.prodigy.net> Duane Rettig wrote: > sturlamolden writes: > > >>Hello >> >>The Lisp crowd always brags about their magical macros. I used LISP back when LISP macros were popular. You don't want to go there. It degrades readability without improving the language. Check out the original "MIT loop macro", used to put something comparable to a FOR statement into early versions of LISP. http://www.cs.cmu.edu/afs/cs/project/ai-repository/ai/lang/lisp/code/iter/loop/mit/0.html Note that it's at version 829. And that was with MIT people fixing it. That thing was a trouble spot for a decade or more. Scheme added a "do" statement as part of the language, which was the right answer. The "loop macro" was, at long last, retired around 1991. There are lots of "l33t" features one can put in a language, but in the end, they're mostly not that helpful. The people who advocate "l33t features" usually need to do more maintenance programming on the code of others, to get more of a sense of gives real, operational trouble in a programming language. Really. After you've fixed the bad code of others, then you're entitled to talk about language design. As someone who's programmed in all too many languages and with a background in formal proof systems, I would make few changes to Python as a language. (And most of the things I'd change involve removing less-used features that constrain implementations.) The language is fine. The problems are elsewhere. The CPython implementation is way too slow and some of the libraries are flakey. That's what needs attention. John Nagle From S.Mientki-nospam at mailbox.kun.nl Fri May 18 11:45:24 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Fri, 18 May 2007 17:45:24 +0200 Subject: (Modular-)Application Framework / Rich-Client-Platform in Python In-Reply-To: References: Message-ID: <8ea03$464dc950$d443bb3a$5229@news.speedlinq.nl> Wildemar Wildenburger wrote: > Jarek Zgoda wrote: >> There are few GUI frameworks building on various toolkits. I used to use >> Kiwi for PyGTK, it's mature and stable, although the approach is not the >> same as, for example, Delphi > Thanks for the effort, but I think I'm not well understood. I'm not > looking for a GUI framework (which, by the way, is most likely to be > wxPython), but for a pure plugin architecture. A rich-client-platform, > as it is sometimes called. Nothing specific about anythin in particular, > just something that runs plugins. Like Eclipse does these days. > > It's beginning to dawn on me that I'll have to cook something up myself. > *grumble* > ;) > > W I took a look at Eclipse page you mentioned but after reading the first page I still don't understand what you mean (and I never read beyond the first page ;-). With a plugin system, I can think of a complete operating system, or I can think of something like a DTP, or simply Word, or I can think of something like Signal WorkBench etc. I think if you don't express what all of the tasks of that framework will be, it's not well possible to create one. Do you want just launching of applications, or do they have to communicate, exchange data, launch each other, create together one document or more general control one process, and lots of more questions ;-) cheers, Stef Mientki From exarkun at divmod.com Thu May 3 08:40:20 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 3 May 2007 08:40:20 -0400 Subject: Microsoft's Dynamic Languages Runtime (DLR) In-Reply-To: Message-ID: <20070503124020.19381.1807570040.divmod.quotient.7886@ohm> On 3 May 2007 12:13:49 GMT, Duncan Booth wrote: >sturlamolden wrote: > >> I am curious to know how it performs in comparison to CPython and an >> efficient compiled Lisp like CMUCL. Speed is a major problem with >> CPython but not with .NET or CMUCL, so it will be interesting to see >> how the DLR performs in comparison. It would be great to finally see a >> Python that runs on steroids, but knowing M$ bloatware my expectations >> are not too high. > >The video of Jim Hugunin's talk from MIX has a slide showing how many >Pystones you get on some different versions of Python. Of course that is >just one benchmark and not terribly relevant to any real applications, but >if you do get a similar speedup in real code 'Python that runs on >steroids' won't be far from the truth. > >The claimed figures were 50,000 Pystones for CPython 2.5, and 101,000 for >the latest IronPython. (He didn't mention it, but I believe Psyco will >outdo both of these.) fwiw, my desktop happens to do 50,000 pystones with cpython 2.4 and 294,000 pystones with cpython 2.4 and psyco.full() Jean-Paul From bill.pursell at gmail.com Thu May 10 13:13:40 2007 From: bill.pursell at gmail.com (Bill Pursell) Date: 10 May 2007 10:13:40 -0700 Subject: append In-Reply-To: <1178816546.689849.255070@y5g2000hsa.googlegroups.com> References: <1178816546.689849.255070@y5g2000hsa.googlegroups.com> Message-ID: <1178817220.775510.60230@o5g2000hsb.googlegroups.com> On 10 May, 18:02, HMS Surprise wrote: > Trying not to be a whiner but I sure have trouble finding syntax in > the reference material. I want to know about list operations such as > append. Is there a pop type function? I looked in tutorial, language > reference, and lib for list, append, sequence. Is there a place where > us doofi ( who may not have our heads out in the sunlight) may find > all related syntax grouped together? > >>> dir(list()) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__str__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] This doesn't give syntax, but if you have any questions, try: >>> help(list().append) From steve at holdenweb.com Thu May 17 10:38:56 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 17 May 2007 10:38:56 -0400 Subject: Python Web Programming - looking for examples of solid high-traffic sites In-Reply-To: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> Message-ID: Victor Kryukov wrote: > Hello list, > > our team is going to rewrite our existing web-site, which has a lot of > dynamic content and was quickly prototyped some time ago. > And has stayed around to dog the developers, as so many quick fixes do ... > Today, as we get better idea of what we need, we're going to re-write > everything from scratch. Python is an obvious candidate for our team: > everybody knows it, everybody likes it, it has *real* objects, nice > clean syntax etc. > Yes indeedy, that's our language! > Our main requirement for tools we're going to use is rock-solid > stability. As one of our team-members puts it, "We want to use tools > that are stable, has many developer-years and thousands of user-years > behind them, and that we shouldn't worry about their _versions_." The > main reason for that is that we want to debug our own bugs, but not > the bugs in our tools. > Given that even Apache has bugs despite its venerable status I think you are setting your sights a little high here. > Our problem is - we yet have to find any example of high-traffic, > scalable web-site written entirely in Python. We know that YouTube is > a suspect, but we don't know what specific python web solution was > used there. > Zope? Plone? Django? TurboGears? All are handling large volumes of data on a daily basis, and I wouldn't use either of them (but that's just a personal issue). > TurboGears, Django and Pylons are all nice, and provides rich features > - probably too many for us - but, as far as we understand, they don't > satisfy the stability requirement - Pylons and Django hasn't even > reached 1.0 version yet. And their provide too thick layer - we want > something 'closer to metal', probably similar to web.py - > unfortunately, web.py doesn't satisfy the stability requirement > either, or so it seems. > > So the question is: what is a solid way to serve dynamic web pages in > python? Our initial though was something like python + mod_python + > Apache, but we're told that mod_python is 'scary and doesn't work very > well'. > Python CGI? mod_python is OK, but like all frameworks you have to be aware of its limitations. > And although http://www.python.org/about/quotes/ lists many big names > and wonderful examples, be want more details. E.g. our understanding > is that Google uses python mostly for internal web-sites, and > performance is far from perfect their. YouTube is an interesting > example - anybody knows more details about that? > Google use Python for all sorts of stuff. > Your suggestions and comments are highly welcome! > > Best Regards, > Victor. > I think you are chasing a chimera (and I wrote a *book* called "Python Web Programming"). 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From vatamane at gmail.com Mon May 14 01:28:03 2007 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 13 May 2007 22:28:03 -0700 Subject: Setting thread priorities In-Reply-To: <2sy1i.2542$LR5.1451@newssvr17.news.prodigy.net> References: <2sy1i.2542$LR5.1451@newssvr17.news.prodigy.net> Message-ID: <1179120483.790340.243280@h2g2000hsg.googlegroups.com> On May 13, 2:46 am, John Nagle wrote: > There's no way to set thread priorities within Python, is there? > We have some threads that go compute-bound, and would like to > reduce their priority slightly so the other operations, like > accessing the database and servicing queries, aren't slowed > as much. > > John Nagle John, You can implicitly create a priority system if you let some threads yield more to other threads. Say if your one thread has to have a higher priority, you would make other threads sleep longer. Of course, as someone mentioned, Python threads are mostly there to take advantage of I/O blocking and not to take advantage of multiple CPU cores (it can't do that at the moment anyway). Check out the small snippet of code I wrote below. Each thread is initialized with some priority value between 0.0 (the lowest) and up. Then look at the run trace and notice that on average the 0.75 priority thread is called more often than the 1.0 priority. Hope this helped, -Nick Vatamaniuc >>> from threading import Thread >>> from time import sleep >>> class Worker(Thread): ...: def __init__(self,pri): ...: Thread.__init__(self) ...: self.pri=pri ...: def run(self): ...: for i in range(20): ...: sleep(1.0*self.pri) ...: print " -> thread with priority:",self.pri >>> w1=Worker(1.0); w2=Worker(0.75) >>> w1.start(); w2.start() >>> -> thread with priority: 0.75 -> thread with priority: 1.0 -> thread with priority: 0.75 -> thread with priority: 1.0 -> thread with priority: 0.75 -> thread with priority: 1.0 -> thread with priority: 0.75 -> thread with priority: 0.75 -> thread with priority: 1.0 -> thread with priority: 0.75 -> thread with priority: 1.0 -> thread with priority: 0.75 -> thread with priority: 1.0 -> thread with priority: 0.75 -> thread with priority: 0.75 -> thread with priority: 1.0 -> thread with priority: 0.75 -> thread with priority: 1.0 -> thread with priority: 0.75 -> thread with priority: 1.0 -> thread with priority: 0.75 -> thread with priority: 0.75 -> thread with priority: 1.0 -> thread with priority: 0.75 -> thread with priority: 1.0 -> thread with priority: 0.75 -> thread with priority: 1.0 -> thread with priority: 0.75 -> thread with priority: 0.75 -> thread with priority: 1.0 -> thread with priority: 0.75 -> thread with priority: 1.0 -> thread with priority: 0.75 -> thread with priority: 1.0 -> thread with priority: 0.75 -> thread with priority: 1.0 -> thread with priority: 1.0 -> thread with priority: 1.0 -> thread with priority: 1.0 -> thread with priority: 1.0 >>> From steveo at syslang.net Fri May 4 17:03:38 2007 From: steveo at syslang.net (Steven W. Orr) Date: Fri, 4 May 2007 17:03:38 -0400 (EDT) Subject: Further adventures in array slicing. Message-ID: This is more for my education and not so much for practicality. I have a structure that sort of looks like this: mdict = {33:{'name': 'Hello0', 'fields':'fields0', 'valid': 'valid0' 55:{'name': 'Hello1', 'fields':'fields1', 'valid': 'valid1'}, 14:{'name': 'Hello2', 'fields':'fields2', 'valid': 'valid2'}} i.e, each element of the dictionary is itself a dictionary with three common keys. I need to unpack this into three seperate arrays called name, fields, valid. The old code looked like this: names = []; fields = []; valid = [] for ii in mdict: names.append(mdict[ii]['name']) fields.append(mdict[ii]['fields']) valid.append(mdict[ii]['valid']) I tried this (to see if it would work) and it seems to work just fine: def u2(m): aa = [ms[ii][jj] for jj in 'name','fields','valid' for ii in m] return tuple(zip(aa[0::3], aa[1::3], aa[2::3])) names,fields,valid = u2(mdict) I was very pleased with myself, except that the real world example of 'fields' and 'valid' is that they can be (but not always) a sequence. e.g., mdefs = {0:{'name': 'Hello0', 'fields':(('Address', 8), ('Control', 8)), 'valid': {'Address': (1,255), 'Control': (33,44)}}, 1:{'name': 'Hello1', 'fields':'fields1', 'valid': 'valid1'}, 2:{'name': 'Hello2', 'fields':'fields2', 'valid': 'valid2'}} Is there a way to do this with possibly a more concise technique than the first for loop above? A second question is: When can you use += vs .append(). Are the two always the same? Thanks. :-) -- 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 revuesbio at gmail.com Mon May 21 06:38:16 2007 From: revuesbio at gmail.com (revuesbio) Date: 21 May 2007 03:38:16 -0700 Subject: TIFF to PDF In-Reply-To: References: <1179687595.142454.23850@z24g2000prd.googlegroups.com> Message-ID: <1179743896.026308.17750@z28g2000prd.googlegroups.com> I'm trying to use tifflib but i have some problems. When i use direct command line like "C:\Program Files\GnuWin32\bin\tiff2pdf.exe" -o C:\test.pdf C: \test.TIF the pdf file is ok. but when i try to launch command line via python the pdf file doesn't create. import os os.system('"C:\Program Files\GnuWin32\bin\tiff2pdf.exe" -o C:\test.pdf C:\test.TIF') where is the problem ? From nogradi at gmail.com Sat May 12 13:07:11 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Sat, 12 May 2007 19:07:11 +0200 Subject: Dynamic subclassing ? In-Reply-To: <1178988856.774715.272120@e51g2000hsg.googlegroups.com> References: <1178976888.443891.116090@y80g2000hsf.googlegroups.com> <1178988856.774715.272120@e51g2000hsg.googlegroups.com> Message-ID: <5f56302b0705121007u75e1be2j4d3a9e2d88ef14c3@mail.gmail.com> > > > I've got an instance of a class, ex : > > > > > b=gtk.Button() > > > > > I'd like to add methods and attributes to my instance "b". > > > I know it's possible by hacking "b" with setattr() methods. But i'd > > > like to do it with inheritance, a kind of "dynamic subclassing", > > > without subclassing the class, only this instance "b" ! > > > > > In fact, i've got my instance "b", and another class "MoreMethods" > > > > > class MoreMethods: > > > def sayHello(self): > > > print "hello" > > > > > How could i write ... > > > > > "b = b + MoreMethods" > > > > > so "b" will continue to be a gtk.Button, + methods/attributs of > > > MoreMethods (it's what i call "dynamic inheritance") ...so, things > > > like this should work : > > > > > - b.set_label("k") > > > - b.sayHello() > > > > > I can't find the trick, but i'm pretty sure it's possible in an easy > > > way. > > > > How about: > > > > class MoreMethods: > > def sayHello(self): > > print "hello" > > > > class myButton( gtk.Button, MoreMethods ): > > pass > > > > b = myButton( ) > > > > isinstance( b, gtk.Button ) # True > > b.sayHello( ) # "hello" > > yes, but it needs to recreate an instance (of mybutton) ... > i can't do that, in my context. > The only things i've got is my instance "b" (which can be whatever > object). > i'd like to add methods/attributes to this instance, by adding a > heritage of another class. I think that is not possible, at least in a simple way (there might be a complicated way of messing with the MRO). Please anyone correct me if I was wrong. Daniel From mcl.office at googlemail.com Mon May 21 10:13:27 2007 From: mcl.office at googlemail.com (mosscliffe) Date: 21 May 2007 07:13:27 -0700 Subject: NEWBIE: Extending a For Statement. In-Reply-To: References: <1179749446.179064.222990@z28g2000prd.googlegroups.com> Message-ID: <1179756807.664306.244160@36g2000prm.googlegroups.com> On 21 May, 14:13, Larry Bates wrote: > mosscliffe wrote: > > I keep seeing examples of statements where it seems conditionals are > > appended to a for statement, but I do not understand them. > > > I would like to use one in the following scenario. > > > I have a dictionary of > > > mydict = { 1: 500, 2:700, 3: 800, 60: 456, 62: 543, 58: 6789} > > > for key in mydict: > > if key in xrange (60,69) or key == 3: > > print key,mydict[key] > > > I would like to have the 'if' statement as part of the 'for' > > statement. > > > I realise it is purely cosmetic, but it would help me understand > > python syntax a little better. Thank you all - it is all helping to expand my python knowledge. I appreciate your comment about sticking with the simple format. I am finding 'python', one of the most straightforward languages to learn, yet very powerful in its capabilities. The whole list concept, is so akin to programming tasks, that it means I can think more about design, than worrying about how to store and access data. Richard > > > Thanks > > > Richard > > I find something like the following easy to read and easy to > extend the contents of searchkeys in the future. > > searchkeys=range(60, 69) + [3] > goodlist=[(k, v) for k, v in mydict.items() if k in searchkeys] > for key, value in goodlist: > print k,v > > -Larry From kw at codebykevin.com Mon May 21 23:41:58 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Mon, 21 May 2007 23:41:58 -0400 Subject: A few questions In-Reply-To: References: Message-ID: <46526686.9030301@codebykevin.com> jay wrote: > > Anyway, I had one more quick question... in order to run wxPython apps, > do I have to have MacPython, etc. loaded on each Mac (or PC) in order > for it to run any apps I write? Or is there a way to compile the code > to where I can distribute an app I write and the other users don't need > to load anything in order to run the app? Google for "py2app." It's the standard tool for distributing standalone Python apps on OS X. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From half.italian at gmail.com Sun May 13 12:57:50 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 13 May 2007 09:57:50 -0700 Subject: __dict__ for instances? In-Reply-To: References: <1179029071.282774.116050@h2g2000hsg.googlegroups.com> Message-ID: <1179075470.576227.55350@e51g2000hsg.googlegroups.com> On May 13, 4:30 am, Ivan Voras wrote: > half.ital... at gmail.com wrote: > > I think you want "dir(instance)" __dict__ returns the instance > > Part of the problem is that dir(instance) returns a list of strings, so > iterating the dir(instance) gets me strings, not methods. Alternatively, > is there a way to get a "bound" instance by its name - some > introspection function perhaps? > > > variables and values as a dictionary, but doesn't return methods. > > It does on a Class :( > > -- > (\__/) > (O.o) > (> < ) > > This is Bunny. > Copy Bunny into your signature to help him on his way to world domination! > > signature.asc > 1KDownload I tried. ~Sean From vasudevram at gmail.com Tue May 29 09:56:27 2007 From: vasudevram at gmail.com (vasudevram) Date: 29 May 2007 06:56:27 -0700 Subject: Periodic tasks. In-Reply-To: References: <1180420430.610215.96330@a26g2000pre.googlegroups.com> <87lkf8nfem.fsf@benfinney.id.au> Message-ID: <1180446987.562753.238450@j4g2000prf.googlegroups.com> On May 29, 4:39 pm, Steve Holden wrote: > Alternatively, the user could make use of the already-existing "sched" > module from the standard library. With a little threading that would do > the job fine. > > 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 --------------------- Yes. Also, there's an example in the Python Cookbook (print edition) which is exactly about this - using sched. The recipe before that also shows how to do it without using the sched library. Both those recipes are purely in Python. Vasudev Ram Dancing Bison Enterprises www.dancingbison.com From wagnergc at itautec.com Thu May 24 16:46:07 2007 From: wagnergc at itautec.com (Wagner Garcia Campagner) Date: Thu, 24 May 2007 17:46:07 -0300 Subject: Web Archtecture using tow layers in Phyton In-Reply-To: <1360b7230705240535r7bd41143kfc8b70191a86ab83@mail.gmail.com> Message-ID: Thanks Amit, I'll search those python web framework and try to find what is the best for my needs. Thanks again for your help, Wagner. -----Original Message----- From: python-list-bounces+wagnergc=itautec.com at python.org [mailto:python-list-bounces+wagnergc=itautec.com at python.org]On Behalf Of Amit Khemka Sent: quinta-feira, 24 de maio de 2007 09:35 To: python-list at python.org Subject: Re: Web Archtecture using tow layers in Phyton On 5/23/07, Wagner Garcia Campagner wrote: > Hello, > > I need to develop an web applications that meet the following requirements: > > - 2 layers: the first one is the user interface (browser) and the second one > is the interaction with the operacional system of the server. > - the second layer must be developed using Python. > > I'd like to know if it is possible to implement this system... making the > second layer using python and the first layer using another web technologies > like AJAX for example. Yes, It is very much possible and you will find the quite a few of such impementations . > Does anybody have any experience in developing python web applications? > Maybe send me some links or documentation about it... Search this news-group or web for "python web framework" and you can choose one based on your specific needs. ( some names that often pop up are: django, cherrypy, webware, pylons etc) > The final goal is to make diferent user interfaces (layer 1) that can > integrate with the second layer... for example, one web interface and one > local interface using python+qt (example)... i don't know if this is > possible and how can this be implemented... any help is aprreciated... Read the documentation of the framework ( if any) you choose to work with you may find templating system useful. For standalone app you can look at wxPython, which can communicate to your server at some port. Cheers, -- ---- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- ------------------------------------------------------------------------------------- AVISO LEGAL: Esta mensagem eletr?nica (e qualquer anexo) ? confidencial e endere?ada ao(s) indiv?duo(s) referidos acima e a outros que tenham sido expressamente autorizados ? recebe-la. Se voc? n?o ? o destinat?rio(a) desta mensagem, por favor n?o copie, use ou divulgue seu conte?do ? outros. Caso voc? tenha recebido esta mensagem equivocadamente, por favor apague esta mensagem e eventuais copias. LEGAL NOTICE: This e-mail communication (and any attachments) is confidential and is intended only for the individual(s) named above and others who have been specifically authorized to receive it. If you are not the intended recipient, please do not read, copy, use or disclose the contents of this communication to others. Please then delete the e-mail and any copies of it. AVISO LEGAL: Este mensaje electr?nico (y cualquier anexo) es confidencial y est? dirigido exclusivamente a su(s) destinatario(s) arriba indicados y aquellos que hayan sido expresamente autorizados a recibirlo. Si usted no es el destinatario(s) de este mensaje, por favor no copie, use o divulgue el contenido a terceros. En caso que usted haya recibido este mensaje por error, por favor proceda a su destrucci?n y al de las posibles copias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Wed May 16 02:28:53 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 16 May 2007 07:28:53 +0100 Subject: Spotting Crashed Application In-Reply-To: References: <11505.3843394437$1178703827@news.gmane.org> Message-ID: <464AA4A5.2060605@timgolden.me.uk> Steve Holden wrote: >> Robert Rawlins - Think Blue wrote: >> I?ve got an application that I?ve written, and it sits in an embedded >> system, from time to time the application will crash, I?m not quite sure >> what?s causing this, but as we test it more and more we?ll grasp a >> better understanding and fix the issues. >> However, until then I need a quick solution which can spot the crash and >> reboot the system. >> > I don't know of any pre-written functionality, but I'd recommend using a > UDP socket for this. Let your application send a packet (say) every 30 > seconds and have the monitoring application restart it if it doesn't > hear a packet for 90 seconds. Strange. I can't see the original message to which Steve's replying, either on Google Groups or in my mailbox. Still... I second the UDP heartbeat suggestion. AFAICR there's a recipe in the printed Cookbook (and presumably the online one as well). An alternative *might* be to use WMI to watch for Win32_Process events and then to reboot, but I suspect WMI might not be available on an embedded system. TJG From nagle at animats.com Wed May 16 22:53:40 2007 From: nagle at animats.com (John Nagle) Date: Thu, 17 May 2007 02:53:40 GMT Subject: Python Web Programming - looking for examples of solid high-traffic sites In-Reply-To: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> Message-ID: Victor Kryukov wrote: > Hello list, > > our team is going to rewrite our existing web-site, which has a lot of > dynamic content and was quickly prototyped some time ago. ... > Our main requirement for tools we're going to use is rock-solid > stability. As one of our team-members puts it, "We want to use tools > that are stable, has many developer-years and thousands of user-years > behind them, and that we shouldn't worry about their _versions_." The > main reason for that is that we want to debug our own bugs, but not > the bugs in our tools. You may not be happy with Python, then. Having spent the last several months implementing a reasonably complex web site in Python, I now have an understanding of the problems involved. Which are non-trivial. Some key web site components, like the SSL interface and the MySQL interface, are written in C and maintained by third parties, often by a single person. Getting the correct version for your platform and making it work can be difficult. Getting the right versions of MySQL, OpenSSL, and Python to all play together is non-trivial. Expect to have to build from source, debug the build process, look at source repositories, submit bug reports, fix library bugs yourself, and maintain a local set of library patches. Few hosting companies will have these modules available for you. It's not like Perl or PHP, where it works out of the box. WebFaction claims to support Python well, but few other hosting companies bother. Most Linux distributions ship with older versions of Python, and that's what most hosting companies will give you. Python 2.4 is par for the course. High traffic sites are a problem. There are a number of "frameworks", all supported by different people and with different capabilities. See http://www.polimetrix.com/pycon/slides/ for a discussion. I haven't tried most of them, so I won't say anything about that issue. > Our problem is - we yet have to find any example of high-traffic, > scalable web-site written entirely in Python. We know that YouTube is > a suspect, but we don't know what specific python web solution was > used there. Not that much of YouTube is really in Python. The video codecs aren't; they'd take forever if they were. And since Google took over, the old YouTube search engine (which was terrible) was replaced by Google's search technology. John Nagle From facundo at taniquetil.com.ar Sun May 6 10:55:43 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Sun, 6 May 2007 14:55:43 +0000 (UTC) Subject: [python 2.4] unable to construct tuple with one item References: <271115400705060523t2f1c23e4ndc87e612384d4951@mail.gmail.com> Message-ID: Vyacheslav Maslov wrote: > So, the main question is why using syntax like [X] python constuct list with > one item, but when i try to construct tuple with one item using similar > syntax (X) python do nothing? Because what determines that you actually have a tuple is the comma, not the parenthesis. See the following explanations. Both empty tuples, one without arguments, the second also without arguments: >>> tuple() () >>> tuple(()) () Constructing a tuple with one argument, which is an iterable (actually, another tuple): >>> tuple((4,)) (4,) The following is not allowed, because you're calling tuple() with one argument, an int 4, and ints are not iterable. >>> tuple(4,) Traceback (most recent call last): File "", line 1, in TypeError: 'int' object is not iterable Note how we also can construct tuples by using the commas, and not the parenthesis: >>> 3,4 (3, 4) >>> a = 5,6 >>> type(a) >>> c,d = a >>> c 5 >>> d 6 Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From martin at v.loewis.de Thu May 17 09:31:34 2007 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Thu, 17 May 2007 15:31:34 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464add30$0$6401$9b4e6d93@newsspool2.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649dd55$0$23144$9b4e6d93@newsspool1.arcor-online.net> <464a25e9$0$10188$9b4e6d93@newsspool4.arcor-online.net> <1179291296.561359.286230@h2g2000hsg.googlegroups.com> <464ab64f$0$10185$9b4e6d93@newsspool4.arcor-online.net> <464AB9F2.60906@web.de> <464ac189$0$20297$9b4e6d93@newsspool3.arcor-online.net> <464ac493$0$6394$9b4e6d93@newsspool2.arcor-online.net> <464add30$0$6401$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <464C5936.5020003@v.loewis.de> > I claim that this is *completely unrealistic*. When learning Python, you > *do* learn the actual meanings of English terms like "open", > "exception", "if" and so on if you did not know them before. It would be > extremely foolish not to do so. Having taught students for many years now, I can report that this is most certainly *not* the case. Many people learn only ever the technical meaning of some term, and never grasp the English meaning. They could look into a dictionary, but they rather read the documentation. I've reported this before, but happily do it again: I have lived many years without knowing what a "hub" is, and what "to pass" means if it's not the opposite of "to fail". Yet, I have used their technical meanings correctly all these years. Regards, Martin From john at datavoiceint.com Mon May 7 19:06:51 2007 From: john at datavoiceint.com (HMS Surprise) Date: 7 May 2007 16:06:51 -0700 Subject: No module named urllib In-Reply-To: <1178578854.926104.184700@y5g2000hsa.googlegroups.com> References: <1178575589.059564.226060@q75g2000hsh.googlegroups.com> <1178578854.926104.184700@y5g2000hsa.googlegroups.com> Message-ID: <1178579211.696681.212110@w5g2000hsg.googlegroups.com> On May 7, 6:00 pm, John Machin wrote: > On May 8, 8:06 am, HMS Surprise wrote: > > > I edited environment varialbes and have added C:\Python25\Lib to > > PYTHONPATH but get the no module message when the statement > > That directory should already be in sys.path after a normal Python > install. Likewise the PYTHONPATH environment variable should be > undefined: > > DOS_prompt> set PYTHONPATH > Environment variable PYTHONPATH not defined > > What was already in PYTHONPATH before you added something? > Why did you think you needed to change things? > > Only what I added before: .; c:\maxq\bin\testScripts; c:\maxq\bin;c:\maxq\jython From jadestar at idiom.com Thu May 10 02:45:20 2007 From: jadestar at idiom.com (James T. Dennis) Date: Thu, 10 May 2007 06:45:20 -0000 Subject: Minor bug in tempfile module (possibly __doc__ error) References: <1178693438.689184@smirk> Message-ID: <1178779520.887569@smirk> Marc 'BlackJack' Rintsch wrote: > In <1178693438.689184 at smirk>, James T. Dennis wrote: >> Tonight I discovered something odd in the __doc__ for tempfile >> as shipped with Python 2.4.4 and 2.5: it says: >> >> This module also provides some data items to the user: >> >> TMP_MAX - maximum number of names that will be tried before >> giving up. >> template - the default prefix for all temporary names. >> You may change this to control the default prefix. >> >> ... which would lead one to think that the following code would work: >> >> >>> import tempfile >> >>> tempfile.template = 'mytest' >> >>> tf = tempfile.NamedTemporaryFile() >> >>> tf.name >> '/tmp/mytest-XXXXXX' >> >> It doesn't. > The source says: > __all__ = [ > "NamedTemporaryFile", "TemporaryFile", # high level safe interfaces > "mkstemp", "mkdtemp", # low level safe interfaces > "mktemp", # deprecated unsafe interface > "TMP_MAX", "gettempprefix", # constants > "tempdir", "gettempdir" > ] > Maybe the doc should be clearer in saying "constants" too. >> Secondly, the author(s) of the tempfile module apparently didn't >> understand this either. And no one else even noticed that the __doc__ >> is wrong (or at least misleading -- since the only way I can see to >> change tempfile.template is to edit the .py file! > You can change it by simply assigning to the name: > In [15]: tempfile.template = 'spam' > In [16]: tempfile.template > Out[16]: 'spam' I know you can change it. But changing it in your namespace doesn't change the results returned by the functions called from the module. > If you want to change the outcome of the functions and objects then simply > give the prefix as argument. I know how to provide the prefix arguments and that was never the issue. The issue was twofold: The docs are wrong (or at least confusing/misleading) I don't quite understand how this name/variable in my namespace (__main__) is able to change the value while the functions in the module still hold the old value. -- Jim Dennis, Starshine: Signed, Sealed, Delivered From s.mientki at id.umcn.nl Wed May 23 06:55:32 2007 From: s.mientki at id.umcn.nl (stef) Date: Wed, 23 May 2007 12:55:32 +0200 Subject: Can I reference 1 instance of an object by more names ? rephrase In-Reply-To: References: Message-ID: thanks Guys for your information, indeed you're all quit right, but I think I've not correctly described my problem :-( I need to have 2 (or more) names, that references the same instance of an object, and in assigning a value to the object (or to some property in the object), I need to do extra activities (like changing some global variables). Now if I use a "container type object", without actual using the index of the container object, I get things working OK. But now I have to use a dummy index, if I use the object in assignments, see program below. Is there another way, without using the dummy index, to achieve the same results ? thanks, Stef Mientki class cpu_ports(object): def __init__(self, value=0): self._d = value def __setitem__(self, index, value): print 'vv' self._d = value def __getitem__(self, index): return self._d def __repr__(self): return str(self._d) name1 = cpu_ports() # create an instance name2 = name1 # refer with a second name to the same instance print name1, name2 # test ok name1[0] = 25 # assign a value to the instance print name1, name2 # both references are OK name2[0] = 26 # assign another value through the other name print name1, name2 # both reference are OK name2[0] = name1[0] + 13 # use both names at either side of an assignment print name1, name2 # both references still OK From gagsl-py2 at yahoo.com.ar Mon May 7 16:51:07 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 07 May 2007 17:51:07 -0300 Subject: randomly write to a file References: <1178567497.042096.82940@w5g2000hsg.googlegroups.com> Message-ID: En Mon, 07 May 2007 16:51:37 -0300, rohit escribi?: > i am developing a desktop search.For the index of the files i have > developed an algorithm with which > i should be able to read and write to a line if i know its line > number. > i can read a specified line by using the module linecache > but i am struck as to how to implement writing to the n(th) line in a > file EFFICIENTLY > which means i don't want to traverse the file sequentially to reach > the n(th) line You can only replace a line in-place with another of exactly the same length. If the lengths differ, you have to write the modified line and all the following ones. If all your lines are of fixed length, you have a "record". To read record N (counting from 0): a_file.seek(N*record_length) return a_file.read(record_length) And then you are reinventing ISAM. -- Gabriel Genellina From Graham.Dumpleton at gmail.com Wed May 9 22:51:36 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: 9 May 2007 19:51:36 -0700 Subject: WSGI spec clarification regarding exceptions In-Reply-To: <1178762841.198053.303110@y80g2000hsf.googlegroups.com> References: <1178749576.268576.146770@l77g2000hsb.googlegroups.com> <1178762841.198053.303110@y80g2000hsf.googlegroups.com> Message-ID: <1178765495.971074.74150@y80g2000hsf.googlegroups.com> On May 10, 12:07 pm, Graham Dumpleton wrote: > On May 10, 8:26 am, Adam Atlas wrote: > > > I'm trying to figure out if there's any defined behaviour in PEP 333 > > for instances where an application returns an iterable as usual > > without error, but that iterable's next() method eventually raises an > > exception. Since any data theretofore returned by the iterable must be > > assumed to have already been written to the client, thus making it > > impossible to replace the response with a 500 error or somesuch, does > > the gateway just absorb the exception and cut off the response there? > > It seems like that's pretty much all it could do, but I'm wondering if > > that's explicitly specified anywhere (I couldn't find anything about > > that in the PEP). > > Because the WSGI specification requires that a WSGI adapter for a web > server always explicitly perform a flush after each string yielded > from the iterator then simply cutting off the response at that point > is all one can do as the first time a flush is done any response > status and headers will also have to be written out. > > Now depending on the web server being used, all the client may see is > the truncated page, or it might also see some form of error page > appended to it by the underlying web server. For example, in Apache, > if the WSGI adapter returns HTTP_INTERNAL_SERVER_ERROR back to the > server, the server disregards whether anything has already been sent > and tries to generate a 500 error page. Since the response status and > headers have already been flushed though, the original status is > received by the client, but the Apache error page content is still > sent. Thus you might get output looking like: > > Hello World! > > > 200 OK > >

    OK

    >

    The server encountered an internal error or > misconfiguration and was unable to complete > your request.

    >

    Please contact the server administrator, > y... at example.com and inform them of the time the error occurred, > and anything you might have done that may have > caused the error.

    >

    More information about this error may be available > in the server error log.

    >
    >
    Apache/2.2.2 (Unix) mod_wsgi/1.0-TRUNK Python/2.3.5 Server at > localhost Port 8002
    > > > It is actually hard to know what to do here. There are ways one could > stop the appending of the error page content, but is returning just > the truncated page any better. At least the error page content in > there highlights an issue even if status wasn't 500, but then not > being 500, the page content could get cached. > > This is where one wanders whether the WSGI way of always flushing is a > good idea. It may be better to always use buffering unless one > specifically knows that one wants to do streaming of data where size > could be large or take some time to produce. > > Anyway, for WSGI matters, you are probably better off bringing them up > on the Python WEB-SIG list. > > http://www.python.org/community/sigs/current/web-sig/ BTW, forgot to mention that one can always create a WSGI middleware component that does buffering and which only sends the complete response. If an error occurs while accumulating the response, then you can return a 500 status and error page of your own making. Graham From bulliver at badcomputer.org Mon May 21 13:09:20 2007 From: bulliver at badcomputer.org (darren kirby) Date: Mon, 21 May 2007 11:09:20 -0600 Subject: help - python can't find file In-Reply-To: <465194E3.FED4F65A@braindead.com> References: <465194E3.FED4F65A@braindead.com> Message-ID: <200705211109.20696.bulliver@badcomputer.org> quoth the enquiring mind: > - but now I get a error message 21 saying file or directory doesn't > exist. You must be in the same directory (in konsole) as the python script for this to work, else enter the relative path to the file: Assuming you are in your home directory (this is where a new konsole will start you), and the py scripts are in a directory 'pythondir': $ cd pythondir $ python myscript.py or: $ python pythondir/myscript.py You could also chmod the script to be executable and run it as a regular command ...however... I don't mean this to sound like RTFM but I do think that you could use some reading on Linux CLI usage. You say you have some Linux books? I say this as my reading of your message indicates your problems lie with misunderstanding the shell/paths etc, not with Python itself... -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 casevh at gmail.com Thu May 17 00:43:46 2007 From: casevh at gmail.com (casevh at gmail.com) Date: 16 May 2007 21:43:46 -0700 Subject: How do I tell the difference between the end of a text file, and an empty line in a text file? In-Reply-To: <1179352021.803070.200780@k79g2000hse.googlegroups.com> References: <1179352021.803070.200780@k79g2000hse.googlegroups.com> Message-ID: <1179377026.812229.38300@o5g2000hsb.googlegroups.com> On May 16, 2:47 pm, walterbyrd wrote: > Python's lack of an EOF character is giving me a hard time. > > I've tried: > > ----- > s = f.readline() > while s: > . > . > s = f.readline() > -------- > > and > > ------- > s = f.readline() > while s != '' > . > . > s = f.readline() > ------- > > In both cases, the loop ends as soon it encounters an empty line in > the file, i.e. > > xxxxxxxxxx > xxxxxxxxxxx > xxxxxxx > < - - - loop end here > xxxxxxxxxxxxxx > xxxxxxxxxx > x > < ---- loop should end here Assuming f is initialized as in your example, try --------- for s in f: print s --------- casevh From m.biddiscombe at gmail.com Wed May 16 12:26:41 2007 From: m.biddiscombe at gmail.com (m.biddiscombe at gmail.com) Date: 16 May 2007 09:26:41 -0700 Subject: pymssql query Message-ID: <1179332801.800883.318590@h2g2000hsg.googlegroups.com> Hi, I'm trying to use pymssql to execute a stored procedure. Currently, I have an Excel spreadsheet that uses VBA in this manner: Private Function CreateNewParrot(connDb As ADODB.Connection) As Long Dim objCommand As ADODB.Command Dim iParrot As Long Dim bSuccess As Boolean Set objCommand = CreateObject("ADODB.Command") objCommand.ActiveConnection = connDb objCommand.CommandText = "create_new" objCommand.CommandType = adCmdStoredProc objCommand.Parameters.Refresh On Error Resume Next Err.Clear objCommand.Execute bSuccess = (Err.Number = 0) On Error GoTo 0 If (bSuccess) Then If (IsNull(objCommand("@parrot"))) Then iParrot = 0 Else iParrot = CLng(objCommand("@parrot")) End If Else iParrot = 0 End If Set objCommand = Nothing CreateNewParrot = iParrot End Function My attempts to translate this into a python script using pymssql have so far been fruitless. Here is what I have tried: >>> import pymssql >>> con = pymssql.connect(host='blah', user='blah', password='blah', database='blah') >>> cur = con.cursor() >>> command = 'exec create_new_parrot' >>> cur.execute(command, '@parrot') Traceback (most recent call last): File "", line 1, in ? File "C:\Program Files\Python\lib\site-packages\pymssql.py", line 127, in execute self.executemany(operation, (params,)) File "C:\Program Files\Python\lib\site-packages\pymssql.py", line 153, in executemany raise DatabaseError, "internal error: %s" % self.__source.errmsg() pymssql.DatabaseError: internal error: SQL Server message 8114, severity 16, state 5, procedure create_new_parrot, line 0: Error converting data type nvarchar to int. DB-Lib error message 10007, severity 5: General SQL Server error: Check messages from the SQL Server. Any ideas? Thanks. From mitko at qlogic.com Fri May 18 17:52:25 2007 From: mitko at qlogic.com (Mitko Haralanov) Date: Fri, 18 May 2007 14:52:25 -0700 Subject: Compiling Python code within a module Message-ID: <20070518145225.2f10c63f@opal.pathscale.com> For various reason, what I need to do is be able to send some Python code (mostly entire functions in the form of a string) to a remote server (written in Python), have that server compile the code and insert it in the local namespace so it is available to be called at a later time. I have gotten the sending and receiving part already written and that works. However, I can't get the compiling part! I have looked at the compile module and while it is able to compile the code I am not entirely sure what to do with the returned code object so it get's inserted as a local function. I would appreciate any help that you guys might be able to offer? Thanks -- Mitko Haralanov mitko at qlogic.com Senior Software Engineer 650.934.8064 System Interconnect Group http://www.qlogic.com ========================================== The "cutting edge" is getting rather dull. -- Andy Purshottam From mediocre_person at hotmail.com Thu May 24 21:18:05 2007 From: mediocre_person at hotmail.com (Medi Ochre) Date: Thu, 24 May 2007 20:18:05 -0500 Subject: Tkinter help, please... In-Reply-To: References: <465602f8$0$16302$88260bb3@free.teranews.com> Message-ID: <46562cff$0$32552$88260bb3@free.teranews.com> John McMonagle wrote: > I've made a couple of minor changes to your code from the Cribbage class > down: > > class Cribbage: > def __init__(self, win): > ... > score = run.play() > if score >= best: best = score > time.sleep(1) <--- short sleep to see what's happening > win.mainloop() > > main() > > > > Regards, > > John Thank you, Mr. McMonagle! -- Posted via a free Usenet account from http://www.teranews.com From claird at lairds.us Wed May 16 14:06:02 2007 From: claird at lairds.us (Cameron Laird) Date: Wed, 16 May 2007 18:06:02 +0000 Subject: Trying to choose between python and java References: Message-ID: In article , Paul Melis wrote: . . . >your program comes out on the other platforms. You could use a GUI >toolkit that draws its own widgets instead of one that uses the native >controls, like wxPython does. PyGTK comes to mind, not sure if it is >available on the Mac. . . . It is . From rtw at freenet.co.uk Tue May 8 16:15:14 2007 From: rtw at freenet.co.uk (Rob Williscroft) Date: Tue, 08 May 2007 15:15:14 -0500 Subject: tkinter get widget option value References: <1178649638.119603.265380@y5g2000hsa.googlegroups.com> Message-ID: wrote in news:1178649638.119603.265380 at y5g2000hsa.googlegroups.com in comp.lang.python: > If I have a button widget > > w = Button(root, text = "Button", state = 'disabled') > > How can I get the value of option 'state' from the widget 'w'. > I want something like -- > > print w.state >> to print out >> 'disabled' > print w.cget( "state" ) Rob. -- http://www.victim-prime.dsl.pipex.com/ From vatamane at gmail.com Wed May 9 10:24:08 2007 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 9 May 2007 07:24:08 -0700 Subject: Questions about bsddb In-Reply-To: <1178713407.968873.260950@n59g2000hsh.googlegroups.com> References: <1178713407.968873.260950@n59g2000hsh.googlegroups.com> Message-ID: <1178720648.233560.319570@p77g2000hsh.googlegroups.com> On May 9, 8:23 am, sinoo... at yahoo.com wrote: > Hello, > > I need to build a large database that has roughly 500,000 keys, and a > variable amount of data for each key. The data for each key could > range from 100 bytes to megabytes.The data under each will grow with > time as the database is being built. Are there some flags I should be > setting when opening the database to handle large amounts of data per > key? Is hash or binary tree recommended for this type of job, I'll be > building the database from scratch, so lots of lookups and appending > of data. Testing is showing bt to be faster, so I'm leaning towards > that. The estimated build time is around 10~12 hours on my machine, so > I want to make sure that something won't get messed up in the 10th > hour. > > TIA, > JM JM, How will you access your data? If you access the keys often in a sequencial manner, then bt is better. In general, the rule is: 1) for small data sets, either one works 2) for larger data sets, use bt. Also, bt is good for sequential key access. 3) for really huge data sets where the metadata of the the btree cannot even fit in the cache, the hash will be better. The reasoning is since the metadata is larger than the cache there will be at least an I/O operation, but with a btree there might be mulple I/O to just find the key because the tree is not all in the memory and will have multiple levels. Also consider this: I had somewhat of a similar problem. I ended up using MySQL as a backend. In my application, the data actually was composed of a number of fields and I wanted to select based on some of those fields as well (i.e. select based on part of the value, not just the keys). and thus needed to have indices for those fields. The result was that my disk I/ O was saturated (i.e. the application was running as fast as the hard drive would let it), so it was good enough for me. Hope this helps, -Nick Vatamaniuc From mail at microcorp.co.za Wed May 16 02:12:41 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 16 May 2007 08:12:41 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <4648bd67$0$5110$ba4acef3@news.orange.fr> Message-ID: <03f501c7979e$82adbe80$03000080@hendrik> "M?ta-MCI" wrote: > Hi! > > - should non-ASCII identifiers be supported? why? > - would you use them if it was possible to do so? in what cases? > > Yes. > > JScript can use letters with accents in identifiers > XML (1.1) can use letters with accents in tags > C# can use letters with accents in variables > SQL: MySQL/MS-Sql/Oralcle/etc. can use accents in fields or request > etc. > etc. > > Python MUST make up for its lost time. > All those lemmings are jumping over a cliff! I must hurry to keep up! - Hendrik From carsten at uniqsys.com Mon May 28 23:36:02 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 28 May 2007 23:36:02 -0400 Subject: itertools.groupby In-Reply-To: <6Y6dnb0mTLsaCsbbnZ2dnUVZ_hCdnZ2d@comcast.com> References: <1180286272.100790.131670@q75g2000hsh.googlegroups.com> <7xveecr5xx.fsf@ruckus.brouhaha.com> <6Y6dnb0mTLsaCsbbnZ2dnUVZ_hCdnZ2d@comcast.com> Message-ID: <20070529032926.M67317@uniqsys.com> On Mon, 28 May 2007 23:02:31 -0400, Gordon Airporte wrote > ''' > class groupby(__builtin__.object) > | groupby(iterable[, keyfunc]) -> create an iterator which returns > | (key, sub-iterator) grouped by each value of key(value). > | > ''' > > "Each" seems to imply uniqueness here. Yes, I can see how somebody might read it this way. How about "...grouped by contiguous runs of key(value)" instead? And while we're at it, it probably should be keyfunc(value), not key(value). -- Carsten Haese http://informixdb.sourceforge.net From nufuhsus at gmail.com Fri May 11 15:28:24 2007 From: nufuhsus at gmail.com (nufuhsus at gmail.com) Date: 11 May 2007 12:28:24 -0700 Subject: Interesting list Validity (True/False) Message-ID: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> Hello all, First let me appologise if this has been answered but I could not find an acurate answer to this interesting problem. If the following is true: C:\Python25\rg.py>python 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. >>> [] == [] True >>> ['-o'] == [] False >>> ['-o'] == False False >>> Then why do I get the following results: C:\Python25\rg.py>help.py -o print arg ['-o'] type(arg): arg is True? False help.py version 1.0 Copyright RDEG (c) 2007 ['-o'] is an unrecognized option. Progam Exit (0) import sys _ver_ = 1.00 if '-h' in sys.argv or '--help' in sys.argv: print print " help.py Version", _ver_, "Copyright RDEG (c) 2007" print ''' Options : -h, --help -- display this message Progam Exit (0)''' sys.exit(0) else: arg = sys.argv[1:] print 'print arg', arg print 'type(arg):', type(arg) print 'arg is True?', arg == True print " help.py version", _ver_, "Copyright RDEG (c) 2007" print " ", arg, "is an unrecognized option." print " Progam Exit (0)" sys.exit(0) From cedric.louyot at gmail.com Wed May 2 10:28:32 2007 From: cedric.louyot at gmail.com (redcic) Date: 2 May 2007 07:28:32 -0700 Subject: Writing a nice formatted csv file In-Reply-To: <1178115967.124030.266090@o5g2000hsb.googlegroups.com> References: <1178115244.446071.317250@n76g2000hsh.googlegroups.com> <1178115967.124030.266090@o5g2000hsb.googlegroups.com> Message-ID: <1178116112.446167.17960@q75g2000hsh.googlegroups.com> Well then how can I format a file ? Thanks for your help, C?dric On 2 mai, 16:26, 7stud wrote: > On May 2, 8:14 am, redcic wrote: > > > > > Hi all, > > > I use the csv module of Python to write a file. My code is of the > > form : > > > cw = csv.writer(open("out.txt", "wb")) > > cw.writerow([1,2,3]) > > cw.writerow([10,20,30]) > > > And i get an out.txt file looking like: > > 1,2,3 > > 10,20,30 > > > Whereas what I'd like to get is: > > 1, 2, 3, > > 10, 20, 30 > > > which is more readable. > > > Can anybody help me to do so ? > > > Thanks, > > > C?dric > > cvs files are constructed for efficient processing not formatting so > that you can read them easier. If you want a formatted file, then > construct one. From john at datavoiceint.com Mon May 14 18:34:52 2007 From: john at datavoiceint.com (HMS Surprise) Date: 14 May 2007 15:34:52 -0700 Subject: Class name as argument Message-ID: <1179182092.643727.223740@u30g2000hsc.googlegroups.com> Snippet 1 below doesn't do much but works (more code is inserted by a generator). In the next to last line the class name is also used as argument. I have seen this construct before and have had error messages tell me that the name is expected. Why is this so? In snippet 2 that I concocted is not required. Is it related to __init__ perhaps? Thanks, jvh # Snippet 1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ from PyHttpTestCase import PyHttpTestCase # definition of test class class MaxQTest(PyHttpTestCase): def runTest(self): self.msg('Test started') # ^^^ Insert new recordings here. (Do not remove this line.) # Code to load and run the test if __name__ == 'main': test = MaxQTest("MaxQTest") test.Run() # Snippet 2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ class topClass(): str = 'abc' def tcMsg(self): print 'topClass tcMsg' class one(topClass): strOne = 'class one' def classOneFun(self): print 'this is classOneFun' self.tcMsg() if __name__ == 'main': test = one() test.classOneFun() From antroy at gmail.com Thu May 3 03:45:10 2007 From: antroy at gmail.com (Ant) Date: 3 May 2007 00:45:10 -0700 Subject: Searching for a piece of string In-Reply-To: <1178177757.536983.277330@u30g2000hsc.googlegroups.com> References: <1178177757.536983.277330@u30g2000hsc.googlegroups.com> Message-ID: <1178178309.994699.185560@c35g2000hsg.googlegroups.com> On May 3, 8:35 am, saif.shak... at gmail.com wrote: > Hi, > How can i match a part of string and branch to some part of code. > Ex If there is a string like "Timeout" and i want to search only > whether the word "Time" is present in it(which is valid in this > case).so if i have "CastinTime",still this should hold. > I need to use this in a "if" statement and code.Can someone help me > in this. > Thanks . if "Time" in text: # do stuff. From malaclypse2 at gmail.com Wed May 23 13:47:56 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 23 May 2007 13:47:56 -0400 Subject: Inheriting from Python list object(type?) In-Reply-To: <1179939516.574991.194470@u30g2000hsc.googlegroups.com> References: <1179939516.574991.194470@u30g2000hsc.googlegroups.com> Message-ID: <16651e80705231047v7787069u1980d2032513532f@mail.gmail.com> On 23 May 2007 09:58:36 -0700, Mangabasi wrote: > There must be a way to inherit from the list type without having to > redefine all the methods and attributes that regular lists have. Like this: class Point(list): def __init__(self, x, y, z = 1): list.__init__(self, [x, y, z]) def __getattr__(self, name): if name == 'x': return self[0] if name == 'y': return self[1] if name == 'z': return self[2] def __setattr__(self, name, value): if name == 'x': self[0] = value if name == 'y': self[1] = value if name == 'z': self[2] = value Does that show you what you need? -- Jerry From gagsl-py2 at yahoo.com.ar Thu May 10 01:45:53 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 10 May 2007 02:45:53 -0300 Subject: replacing string in xml file References: <1178623414.092046.91120@y5g2000hsa.googlegroups.com> <46405F73.3080501@web.de> <1178624770.794888.198450@e65g2000hsc.googlegroups.com> <1178710760.558710.262680@w5g2000hsg.googlegroups.com> <1178772925.620297.118000@h2g2000hsg.googlegroups.com> Message-ID: En Thu, 10 May 2007 01:55:25 -0300, escribi?: >> I am opening 2 more files in addition to the file >> where the new xml goes.One file is written using the sys.stdout >> command as most of the output has to go there printing takes place in >> many places (so cant use f_open.write) each time. >> When i attach the part of replacing the string >> 'localid' in xml file with something else as given above with >> xmlcont=xmlcont.replace('localId','dataPackageId') >> the code does not run and hangs. What do you mean by "hangs"? You have replaced stdout - what if the program is prompting the user for something, and you can't see it? Can you type some text and continue? >> Can more than 3 files be opened at a >> time Sure. The limit actually depends on the OS, but on "normal" circumstances it's far above 3 files. -- Gabriel Genellina From stargaming at gmail.com Tue May 29 14:23:45 2007 From: stargaming at gmail.com (Stargaming) Date: Tue, 29 May 2007 20:23:45 +0200 Subject: How to set a class inheritance at instance creation? In-Reply-To: <1180453971.556244.91370@q69g2000hsb.googlegroups.com> References: <1180453971.556244.91370@q69g2000hsb.googlegroups.com> Message-ID: glomde schrieb: > Hi I wonder if you can set what subclass a class should > have at instance creation. > > The problem is that I have something like: > > class CoreLang(): > def AssignVar(self, var, value): > pass > > class Lang1(CoreLang): > def AssignVar(self, var, value): > return var, "=", value > > class Lang2(CoreLang): > def AssignVar(self, var, value): > return var, "<=", value > > class WriteStruct(): > def Generate(self, vars): > for var in vars: > print self.AssignVar() > > The problem is that I want WriteStruct to sometimes be a subclass of > Lang1 and sometimes > of Lang2. > In the above example I could but the Generate Method in CoreLang. But > in my real > example I also want to able to subclass WriteStruct to be able to easy > customize WriteStruct. > Which I wouldnt be able to do if it was a method in CoreLang. > > So in code I would like to write something like: > > WriteStruct(Lang1).Generate(vars) > > Even better would be that if I in the Lang1 class could > just do WriteStruct().Generate(vars) and Lang1 class would > magically make WriteStruct a subclass of itself. > > > Cheers, > > /T > If you really need to inherit at runtime, you could utilize `type()`. >>> def foo(self, blah): ... print self, blah ... >>> attrs = {'foo': foo} >>> cls = type('MyCls', (object,), attrs) >>> cls().foo(4) <__main__.MyCls object at 0x009E86D0> 4 Changing ``object`` (the tuple contains all bases) will change the parent. But, better stick to previous solutions. :) Stargaming From rene at korteklippe.de Tue May 15 09:01:42 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 15 May 2007 15:01:42 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> <4648294F.2000704@web.de> <46487a6c$0$2400$426a74cc@news.free.fr> <4649a1b6$0$23131$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <4649af35$0$10195$9b4e6d93@newsspool4.arcor-online.net> Thorsten Kampe schrieb: > * Ren? Fleschenberg (Tue, 15 May 2007 14:04:07 +0200) >> Thorsten Kampe schrieb: >>> Because keywords are not meant meant to extended or manipulated or >>> something similar by the programmers. Keywords are well known and only >>> a limited set of words. That's why you can't use keywords as >>> identifiers. >> This is true for keywords, but not for the stdlib. Are you suggesting >> that the stdlib should be "internationalized"? > > No, because it's the /Standard/ Library to be used by everyone. And > the lowest common denominator is ASCII and English. This makes the argument that this PEP would allow people to write "Chinese only" Python code invalid (unless they do not use the stdlib). -- Ren? From nyamatongwe+thunder at gmail.com Sun May 13 22:37:15 2007 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Mon, 14 May 2007 02:37:15 GMT Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <7x4pmg716p.fsf@ruckus.brouhaha.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <7x4pmg716p.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: >> Plenty of programming languages already support unicode identifiers, > > Could you name a few? Thanks. C#, Java, Ecmascript, Visual Basic. Neil From steve at REMOVE.THIS.cybersource.com.au Sun May 13 09:24:45 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 13 May 2007 23:24:45 +1000 Subject: Interesting list Validity (True/False) References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> <1178914190.166662.285410@p77g2000hsh.googlegroups.com> <1178915791.584216.293130@l77g2000hsb.googlegroups.com> <1178918808.091358.233740@o5g2000hsb.googlegroups.com> <1179017740.656323.209590@e51g2000hsg.googlegroups.com> <1179020634.130689.171960@o5g2000hsb.googlegroups.com> <1179031812.090768.248750@l77g2000hsb.googlegroups.com> Message-ID: On Sat, 12 May 2007 21:50:12 -0700, mensanator at aol.com wrote: >> > Actually, it's this statement that's non-sensical. >> >> > >> > "if arg==True" tests whether the object known as arg is equal to the >> > object known as True. >> > >> >> Not at all, it makes perfect sense. X == Y always tests whether the >> argument X is equal to the object Y regardless of what X and Y are. > > Except for the exceptions, that's why the statement is wrong. But there are no exceptions. X == Y tests for equality. If it returns True, then the objects are equal by definition. That's what equal means in Python. One can abuse the technology to give nonsensical results: class EqualToEverything(object): def __eq__(self, other): return True >>> x = EqualToEverything() >>> x == 1.0 True >>> x == [2.9, "hello world"] True but that's no different from any language that allows you to override operators. >> > None of these four examples are "equal" to any other. >> >> That's actually wrong, as you show further down. > > No, it's not, as I show further down. But you show no such thing. Or, to put it another way: Did! Did not! Did! Did not! Did! Did not! ... >> >>>> a = 1 >> >>>> b = (1,) >> >>>> c = [1] >> >>>> d = gmpy.mpz(1) [snip] >> >>>> a==d >> > True >> >> See, a and d are equal. > > No, they are not "equal". Of course they are. It says so right there: "a equals d" is true. > Ints and mpzs should NEVER > be used together in loops, even though it's legal. Why ever not? If you need an mpz value in order to do something, and no other data type will do, what would you suggest? Just give up and say "Don't do this, because it is Bad, m'kay?" > The ints > ALWAYS have to be coerced to mpzs to perform arithmetic > and this takes time...LOTS of it. Really? Just how much time? timeit.Timer("x == y", "import gmpy; x = 1; y = gmpy.mpz(1)").repeat() timeit.Timer("x == y", "x = 1; y = 1").repeat() I don't have gmpy installed here, so I can't time it, but I look forward to seeing the results, if you would be so kind. Even if it is terribly slow, that's just an implementation detail. What happens when Python 2.7 comes out (or Python 3.0 or Python 99.78) and coercion from int to mpz is lightning fast? Would you then say "Well, int(1) and mpz(1) used to be unequal, but now they are equal?". Me, I'd say they always were equal, but previously it used to be slow to coerce one to the other. > The absolute stupidest > thing you can do (assuming n is an mpz) is: > > while n >1: > if n % 2 == 0: > n = n/2 > else: > n = 3*n + 1 Oh, I can think of much stupider things to do. while len([math.sin(random.random()) for i in range(n)[:]][:]) > 1: if len( "+" * \ int(len([math.cos(time.time()) for i in \ range(1000, n+1000)[:]][:])/2.0)) == 0: n = len([math.pi**100/i for i in range(n) if i % 2 == 1][:]) else: s = '+' for i in range(n - 1): s += '+' s += s[:] + ''.join(reversed(s[:])) s += s[:].replace('+', '-')[0:1] n = s[:].count('+') + s[:].count('-') > You should ALWAYS do: > > ZED = gmpy.mpz(0) > ONE = gmpy.mpz(1) > TWO = gmpy.mpz(2) > TWE = gmpy.mpz(3) > > while n >ONE: > if n % TWO == ZED: > n = n/TWO > else: > n = TWE*n + ONE > > This way, no coercion is performed. I know that algorithm, but I don't remember what it is called... In any case, what you describe is a local optimization. Its probably a good optimization, but in no way, shape or form does it imply that mpz(1) is not equal to 1. >> > And yet a==d returns True. So why doesn't b==c >> > also return True, they both have a 1 at index position 0? >> >> Why should they return true just because the contents are the same? > > Why should the int 1 return True when compared to mpz(1)? Because they both represent the same mathematical number, where as a list containing 1 and a tuple containing 1 are different containers. Even if the contents are the same, lists aren't equal to tuples. > a = [1] > b = [1] > > returns True for a==b? That's because both are the same kind of container, and they both have the same contents. > After all, it returns false if b is [2], > so it looks at the content in this case. So for numerics, > it's the value that matters, not the type. And this creates > a false sense of "equality" when a==d returns True. There's nothing false about it. Ask any mathematician, does 1 equal 1.0, and they will say "of course". >> A bag >> of shoes is not the same as a box of shoes, even if they are the same >> shoes. > > Exactly. For the very reason I show above. The fact that the int > has the same shoes as the mpz doesn't mean the int should be > used, it has to be coerced. Ints are not containers. An int doesn't contain values, an int is the value. Numeric values are automatically coerced because that's more practical. That's a design decision, and it works well. As for gmpy.mpz, since equality tests are completely under the control of the class author, the gmpy authors obviously wanted mpz values to compare equal with ints. >> Since both lists and tuples are containers, neither are strings or >> numeric types, so the earlier rule applies: they are different types, so >> they can't be equal. > > But you can't trust a==d returning True to mean a and d are > "equal". What does it mean then? > To say the comparison means the two objects are > equal is misleading, in other words, wrong. It only takes one > turd to spoil the whole punchbowl. > >> >> gmpy.mpz(1) on the other hand, is both a numeric type and a custom class. >> It is free to define equal any way that makes sense, and it treats itself >> as a numeric type and therefore says that it is equal to 1, just like 1.0 >> and 1+0j are equal to 1. > > They are equal in the mathematical sense, but not otherwise. Since they are mathematical values, what other sense is meaningful? > And to think that makes no difference is to be naive. I never said that there was no efficiency differences. Comparing X with Y might take 0.02ms or it could take 2ms depending on how much work needs to be done. I just don't understand why you think that has a bearing on whether they are equal or not. -- Steven. From sneha29 at gmail.com Thu May 24 03:11:12 2007 From: sneha29 at gmail.com (sneha29 at gmail.com) Date: 24 May 2007 00:11:12 -0700 Subject: Python Uno Bridge Architecture Message-ID: <1179990672.404925.7660@x35g2000prf.googlegroups.com> Hi, I am trying to write a bridge similar to Python- Uno bridge. I have read from these links about the PyUNO bridge. http://udk.openoffice.org/python/python-bridge.html But I haven't found information about the basic achitecture of the bridge. Eg: the basic requirements of the files, library, specific directory structure . Is there any document/tutorial available about the approach taken to write the bridge? Also can you tell me about the basic steps required to write a UNO bridge ? Thanks, Sneha From jstroud at mbi.ucla.edu Sun May 20 03:47:12 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 20 May 2007 07:47:12 GMT Subject: converting strings to most their efficient types '1' --> 1, 'A' ---> 'A', '1.2'---> 1.2 In-Reply-To: <464F93C1.8030305@lexicon.net> References: <1179529661.555196.13070@k79g2000hse.googlegroups.com> <464E6F32.7070200@lexicon.net> <61B3i.6880$H_.138@newssvr21.news.prodigy.net> <464F93C1.8030305@lexicon.net> Message-ID: <42T3i.29504$Um6.11611@newssvr12.news.prodigy.net> John Machin wrote: >Against that background, please explain to me how I can use > "results from previous tables as priors". > > Cheers, > John It depends on how you want to model your probabilities, but, as an example, you might find the following frequencies of columns in all tables you have parsed from this organization: 35% Strings, 25% Floats, 20% Ints, 15% Date MMDDYYYY, and 5% Date YYMMDD. Let's say that you have also used prior counting statistics to find that there is a 2% error rate in the columns (2% of the values of a typical Float column fail to cast to Float, 2% of values in Int columns fail to cast to Int, and so-on, though these need not all be equal). Lets also say that for non-Int columns, 1% of cells randomly selected cast to Int. These percentages could be converted to probabilities and these probabilities could be used as priors in Bayesian scheme to determine a column type. Lets say you take one cell randomly and it can be cast to an Int. What is the probability that the column is an Int? (See .) P_1(H) = 0.20 --> Prior (20% prior columns are Int columns) P(D|H) = 0.98 P(D|H') = 0.01 P_1(H|D) = 0.9607843 --> Posterior & New Prior "P_2(H|D)" Now with one test positive for Int, you are getting pretty certain you have an Int column. Now we take a second cell randomly from the same column and find that it too casts to Int. P_2(H) = 0.9607843 --> Confidence its an Int column from round 1 P(D|H) = 0.98 P(D|H') = 0.02 P_2(H|D) = 0.9995836 Yikes! But I'm still not convinced its an Int because I haven't even had to wait a millisecond to get the answer. Lets burn some more clock cycles. Lets say we really have an Int column and get "lucky" with our tests (P = 0.98**4 = 92% chance) and find two more random cells successfully cast to Int: P_4(H) = 0.9999957 P(D|H) = 0.98 P(D|H') = 0.02 P(H|D) = 0.9999999 I don't know about you, but after only four positives, my calculator ran out of significant digits and so I am at least 99.99999% convinced its an Int column and I'm going to stop wasting CPU cycles and move on to test the next column. How do you know its not a float? Well, given floats with only one decimal place, you would expect only 1/10th could be cast to Int (were the tenths-decimal place to vary randomly). You could generate a similar statistical model to convince yourself with vanishing uncertainty that the column that tests positive for Int four times in a (random sample) is not actually a Float (even with only one decimal place known). James From turbana at gmail.com Sun May 20 21:19:01 2007 From: turbana at gmail.com (Ian Clark) Date: Sun, 20 May 2007 18:19:01 -0700 Subject: Inverse of id()? In-Reply-To: References: <1179618173.280286.284120@n59g2000hsh.googlegroups.com> Message-ID: On 5/20/07, Michael Hoffman wrote: > [snip] > That's not what I get: > > Python 2.5 (r25:51908, Mar 13 2007, 08:13:14) > [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin > Type "help", "copyright", "credits" or "license" for more information. > >>> class A: pass > ... > >>> class B: pass > ... > >>> a = A() > >>> id(a) > 2146651820 > >>> b = B() > >>> id(b) > 2146651948 > -- > Michael Hoffman That's because you didn't have 'del a'. Now I tried this in the shell and got different id's for a and b, but when I typed it into a file and ran from there the id's where always the same. Must have something to do with other programs allocating space faster than I can type everything out (I do have a few processes going). Interesting. Ian From danb_83 at yahoo.com Sat May 26 14:30:56 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: 26 May 2007 11:30:56 -0700 Subject: printing list, is this a bug? In-Reply-To: <1180126524.884163.234040@k79g2000hse.googlegroups.com> References: <1180126524.884163.234040@k79g2000hse.googlegroups.com> Message-ID: <1180204256.784678.227570@q69g2000hsb.googlegroups.com> On May 25, 3:55 pm, William Chang wrote: > Is the different behavior between __repr__ and __str__ intentional > when it comes to printing lists? Basically I want to print out a list > with elements of my own class, but when I overwrite __str__, __str__ > doesn't get called but if I overwrite __repr__, __repr__ will get > called. Is this a bug? > ... As has been mentioned, this was a deliberate design decision. Partly to make things like str(['a', 'b, c']) less confusing. From sjmachin at lexicon.net Fri May 4 18:43:39 2007 From: sjmachin at lexicon.net (John Machin) Date: 4 May 2007 15:43:39 -0700 Subject: Further adventures in array slicing. In-Reply-To: References: Message-ID: <1178318619.874139.215740@e65g2000hsc.googlegroups.com> On May 5, 7:03 am, "Steven W. Orr" wrote: > This is more for my education and not so much for practicality. > [snip] > > A second question is: When can you use += vs .append(). Are the two always > the same? > Formally, they can never be the same. They can be used to produce the same result, in limited circumstances, e.g. these: alist += bseq and alist.append(anelement) will give the same result if bseq == [anelement] You can use alist.extend(bseq) instead of alist += bseq I suggest that you (a) read the manual sections on each of the 3 possibilities (b) explore their behaviours at the Python interactive prompt From arnoreg at gmail.com Wed May 30 17:14:44 2007 From: arnoreg at gmail.com (Arno Stienen) Date: Wed, 30 May 2007 23:14:44 +0200 Subject: xmlrpclib hangs execution In-Reply-To: <465d9040$0$326$e4fe514c@news.xs4all.nl> References: <45AC0631.8080601@ctw.utwente.nl> <465890FB.4030405@utwente.nl> <465A9DC7.2010708@gmail.com> <465d9040$0$326$e4fe514c@news.xs4all.nl> Message-ID: <465DE944.7040301@gmail.com> Tijs, Thank you very much for specific comments. They are most useful, and I'll try both strategies. If the latter works out, I'll post the results back on the list. Bye, Arno. Tijs wrote: > Arno Stienen wrote: > >> Arno Stienen wrote: >>> Perhaps I should be a bit more specific. When using this code to connect >>> to a remote XML-RPC server (C++, xmlrpc++0.7 library): >>> >>> import xmlrpclib >>> server = xmlrpclib.Server("http://10.10.101.62:29500") >>> print server.Connection_Request("roberto") >>> >>> the Python command line 'hangs' until I kill the server. Then, the >>> correct output is suddenly displayed: >>> >>> {'state': 0, 'id_session': '2Z3EUSLJFA13', 'port': 29501, >>> 'str': 'Connection accepted. Session attached.'} >>> >>> Yet a slightly simpler call works flawlessly: >>> >>> import xmlrpclib >>> server = xmlrpclib.Server("http://10.10.101.62:29500") >>> print server.Info_RT('Master') >>> >>> {'state': 0, 'str': 'Info_RT'} >>> > > After having a quick look at your files, I conclude that the problem is in a > combination of two problems: > > 1. Your server is crap. It answers an HTTP/1.0 request by an HTTP/1.1 > response without specifying any Connection header and without closing the > connection. Normally, a simple client that is not HTTP/1.1-aware expects > the connection to close. HTTP/1.1 leaves the connection open by default. > > 2. The Python implementation of xmlrpc is not very robust. It just waits for > the connection to close. A well-written client (like your Java client) > would detect the presence of a Content-Length header and use that. > > The other request is OK because the server closes the connection after > having sent the response. Why the difference? Don't know, but it is > something server-side. > > Try to force the server to send HTTP/1.0 responses, or turn off keep-alive, > or something like that. Otherwise, adapt xmlrpclib.py to robustly handle > 1.1 responses. > From esj at harvee.org Mon May 28 20:38:36 2007 From: esj at harvee.org (Eric S. Johansson) Date: Mon, 28 May 2007 20:38:36 -0400 Subject: Is PEP-8 a Code or More of a Guideline? In-Reply-To: <1180254338.292249.29520@h2g2000hsg.googlegroups.com> References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <1180254338.292249.29520@h2g2000hsg.googlegroups.com> Message-ID: Paul McGuire wrote: > At first, Guido seemed ambivalent, and commented on the > contentiousness of the issue, but it seems that the "non-English > speakers can more easily find word breaks marked with underscores" > justification tipped the scale in favor of > lower_case_with_underscores. > > The PEP itself on www.python.org seems to have been updated as > recently as May 17 of this year, but I don't seen any way to identify > what the change history is. > > So, those who are the stewards of the core source code have nailed > down thier coding standard to be l_c_w_u, so if sometime in the future > I find myself working on any code in the Python std libs, l_c_w_u is > the style to be followed. It just looks so old-fashioned... > link.setParseAction(emitLinkHTML) is spoken no caps link dot set no space cap parser no space cap action between parens emit no space cap link HTML jump out on the other hand, link.set_parse_action (emit_link_HTML) is much more friendly to aural interfaces. I've been using speech recognition since about 1995 when I was injured thanks to programming in high stress, ergonomically poor environments. as a result, I have become extremely sensitive to what makes a good interface for hands and for voice. Bumpy case words are extremely difficult to pronounce for both text-to-speech dependent blind users and speech recognition (speech to text) dependent users like myself. One important factor in a speech user interfaces is the difference between what you say/here and the target text. I can't say for the blind user but I know in the speech recognition context, the more time you spend thinking about what it is you say in order to get your desired text, the less brainpower you have for thinking about the problem. There are solutions to this problem but unfortunately handicapped users are in a Catch-22 situation. We know what we need to make our world better. But we don't have the hands to make our world better. Therefore we have to rely on those who don't know what we need to make our lives better which doesn't happen. There are two projects (voice coder and vr-mode) which have started making things better. Unfortunately, they are are fragile and difficult to install which defeats the purpose of a good accessibility tool. I suggest that the first option is encouraging enhanced use of full words joined by underscores for all public interfaces so that unenhanced speech recognition or text-to-speech systems can be used in a way we have become accustomed to living with. This is not to say it's good. Only that we have acquired enough scar tissue to cope. the second option would be for some of you to dig in and help some of your technical kinfolk by improving some tools so that we can start writing Python code with greater ease. A huge reason why this is important because the vast majority of software developers who are injured fall off the economic ladder. They leave the profession and had very few options for work that doesn't involve significant handy is. The last time I looked at the numbers, in the US somewhere north of 60,000 developers per year are injured. Some recover (kind of). Others, like I said, dropout. Tools to make programming by voice easier and not as damaging to the throat as unenhanced speech recognition with bumpy caps symbols, would significantly improve the lives of people you probably know and possibly your own life in the future. Feel free to contact me off list if you want. ---eric (founding member of Open Source Speech Recognition Initiative nonprofit) warning: NaturallySpeaking in use. It makes mistakes. I correct some. From arkanes at gmail.com Fri May 4 09:31:28 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 4 May 2007 08:31:28 -0500 Subject: My Python annoyances In-Reply-To: References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> <1178202431.147195.249790@u30g2000hsc.googlegroups.com> Message-ID: <4866bea60705040631q52e98f84v8a2e5f851384b0ba@mail.gmail.com> On 5/4/07, Ben Collver wrote: > Paul Boddie wrote: > > I'm sorry to hear about that. If by "macho" you mean people who insist > > that things are good enough as they are, and that newcomers should > > themselves adapt to whatever they may discover, instead of things > > being improved so that they are more intuitive and reliable for > > newcomers and experienced developers alike, then I'd certainly be > > interested in undermining that culture. > > That was the sort of response I got on freenode #python, which I realize > I should not take as representative of the whole community. Thank you > for the thoughtful response. > #python is one of the most accepting communities around. If the bug reports here and the way you've presented them in this thread (vs the way that they appear to an outside observer) are any indication, though, I'm not surprised that you might have left in a huff. Bear in mind that #python has no special status with regards to python development and is primarily a community of *users*. If you go in with some sort of thing you consider a problem, you are likely to be shown a solution. Debate over whether it should be fixed in the core is likely to be met with "patches accepted". > >> I tried to write portable Python code. The zlib CRC function returned > >> different results on architectures between 32 bit and 64 bit > >> architectures. I filed a bug report. It was closed, without a comment > >> from the person who closed it. I get the unspoken message: bug reports > >> are not welcome. > > > > Can you provide the bug identifier? Bug reports are generally welcome, > > and despite complaints about patch reviews, I've found people > > reviewing things I've submitted. > > It is problem report #1678102. I understand the problem: that a 32 bit > number looks different in a 32 bit signed int than in a 64 bit signed > int. However, the workaround of dropping a bit seems to defeat the > purpose of using a CRC. > That's a valid point. Maybe you should have responded on the tracker with that viewpoint. Your characterization of what happened in your original post borders on dishonest - how can you possibly view what happened there as "bug reports not welcomed"? > > Yes, Ctrl-Z exits Python in the standard Windows edition. Since Cygwin > > provides a POSIX-like environment, Ctrl-D should be used instead. If > > the documentation is wrong, a bug report or patch should be filed > > against the software. > > This morning I could not reproduce the problem. When the user types > "quit" at the Python prompt, the Cygwin port instructs the user to press > Control-D, which works. Even if you SSH in to Cygwin, and run the win32 > port, it instructs the user to press Control-Z plus Return, which works. > Maybe it was fixed after I had the problem. > Huh. > >> Between 2.4 and 2.5, tempfile returns a different type of object. My > >> code cannot have a single test, it has check for type(obj) == file or > >> obj.__class__ == tempfile._TemporaryFileWrapper. > > > > Try using isinstance or relying on "deeper" knowledge of how the > > object will be used. > > Thank you for the hint. I just want my function to validate that one of > its arguments is a file-like object. It isn't necessarily going to be a > temporary file, but it might be. > > >>> import temporaryfile > >>> t = tempfile.TemporaryFile() > >>> isinstance(t, file) > False > Code like this is working directly against Python philosophy. You probably got told this on #python, too. There's hardly any circumstance where you should need to validate the exact class of an object, and as long as they have the same interface theres no harm whatsoever in tempfile changing it's return value between Python versions. > > My opinions, already expressed, include the observation that the core > > development community is more interested in extending the language > > than in strengthening the standard library (and its documentation). It > > should be noted that the proposed standard library reorganisation, > > which is a very conservative affair, has actually been postponed until > > after the release of Python 3.0a1 according to a message I read > > recently. And yet, if you read people's lists about what they "hate" > > about Python (amongst actual users of Python), guess which thing > > almost always comes up? > > I guess you cannot blame folks for working on what they find interesting. > > Ben > -- > http://mail.python.org/mailman/listinfo/python-list > From bdesth.quelquechose at free.quelquepart.fr Thu May 10 17:12:50 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 10 May 2007 23:12:50 +0200 Subject: Newbie look at Python and OO In-Reply-To: <1178812734.860473.236370@y80g2000hsf.googlegroups.com> References: <1178812734.860473.236370@y80g2000hsf.googlegroups.com> Message-ID: <464380c4$0$25791$426a74cc@news.free.fr> walterbyrd a ?crit : > I learned to program with Pascal, way back when. Went into software > development for a while, then went into systems admin. Have programmed > in several languages, just learning Python. > > Some things I find odd: > > 1) 5/-2 == -3? integer division. > 2) list assignment handling, pointing two vars to the same list: > > With simple data types: > >>>>a = 5 >>>>b = a >>>>a = 3 >>>>a,b > > (3, 5) > > Which is what I'd expect, since I have changed a, but not b. s/changed/rebound/ > But with lists: > >>>>a = list("1234") >>>>b = a >>>>a.append("5") >>>>a,b > > (['1', '2', '3', '4', '5'], ['1', '2', '3', '4', '5']) > > b changes even though I have not touched b. You did call a mutating method on the object pointed by both a and b. You're comparing apples and oranges here. The second snippet should be: >>> a = [1, 2, 3] >>> b = a >>> a = [4, 5, 6] >>> a, b ([4, 5, 6], [1, 2, 3]) >>> > I know why, but this is > not what I would ordinarilly expect, it does not seem intuitive. If so your intuition is based on misconceptions. In Python, a 'variable' is really a name=>object_ref pair in a namespace (think of namespaces as dicts). The name by itself is only that : a name. The "value" is *always* a reference to an object, and a same object can be referred to by many names. In Pascal terms, this is similar to (smart) pointers to records. > And, > IMO, it gets worse: > > >>>>a = list("1234") >>>>b = a >>>>a = a + ['5'] Here you're rebinding the name 'a' to a new list object which is the concatenation of the list object previously bound to 'a' and the (anonymous) ['5'] list object. >>>>a,b > > (['1', '2', '3', '4', '5'], ['1', '2', '3', '4']) > Sometimes changing a changes b, and sometimes not. Rebinding a name doesn't affect the object previously bound to it. Changing the state of an object of course affects the object. > You also have to > remember that subseqent changes to a will not change b - after some > operation but not others. Binding and method calls are quite distinct operations. > To those who think in Python, I'm sure this > all seems normal. But, having programmed in about one dozen other > language, this seems downright bizare to me. I know why it works like > this, but it seems like an odd way to do things. This is obvious when stop thinking in term of "boxes" (ie: a variable is a box containing a value) and start thinking in terms of references. > 3) ambiguous use of the form: this.that() > > Sometimes, this.that() means module.funcion() as in: > >>>>os.dirlist(".") > > > Other times, "this" is sort of like a parameter to the "that" > function: > > >>>>a = list("1234") >>>>"_".join(a) > > '1_2_3_4_5' > > And still other times, is seems that "this" is an object, acted upon > by "that" : > > >>>>a = list("1234") >>>>b = "_".join(a) >>>>b.split("_") > > ['1', '2', '3', '4', '5'] In *all* cases, 'this' is an object, and 'that' is an attribute of 'this'. This is definitively not ambiguous. You have to understand that everything in Python is an object - including functions, classes and modules. os.listdir : this is the (function object) attribute 'listdir' of module object os >>> hasattr(os, 'listdir') True >>> listdir = getattr(os, 'listdir') >>> listdir.__class__ >>> "_".join : this is the (method object) attribute 'join' of class str: >>> ''.__class__ >>> hasattr('', 'join') True >>> join = getattr('', 'join') >>> join.__class__ >>> b.split: this is the (method object) attribute 'split' of class str. In these three examples, these attributes are callable objects, and you apply the call operator to them. > BTW: it seems a bit odd to that the positions of the string, and the > delimitor, are reversed between the complementory functions join(), > and split(). Yes, it's a bit surprising at first. But it's still logical. some_string.split(delimiter) => new_list delimiter.join(some_list) => new_string > I suppose if it weren't for OO, we have something > terribly complicated, like: > > split(str, "_") > join(str, "_") This should be: join(list, "_") > Again, those who think in Python, will understand right away that: > > math.count(x) > > is counting the substring "x" in the "math" string. But can you see > where that might be confused to be a function called count() in the > math module? No, I can't. Because 1/ my functions (or methods) are too short for such a confusion to be possible 2/ I wouldn't name a string "math" > I'm not complaining. Python is a great language in many respects. But, > I would take some issue with those claiming Python is intuitive and > easy. IMO: there seems to be many ambiguous, unintuitve, and > confusing, aspects to Python. > I guess this has to do with your (very procedural) background. Of course, Python does have it's share of gotchas and warts, but it's one of the only languages I know that you can start to be productive with in a matter of days. From jussij at zeusedit.com Sun May 20 19:47:14 2007 From: jussij at zeusedit.com (JussiJ) Date: 20 May 2007 16:47:14 -0700 Subject: python shell In-Reply-To: <1179337107.842668.112690@k79g2000hse.googlegroups.com> References: <1179337107.842668.112690@k79g2000hse.googlegroups.com> Message-ID: <1179704834.135583.321590@b40g2000prd.googlegroups.com> On May 17, 3:38 am, Krypto wrote: > My mentor told me that you can virtually do anything from > testing your program to anything in the shell. Any incite > would be useful. Using something like tee you can run the Python script in the shell and also capture it's output: http://unxutils.sourceforge.net/ For example, here are details on how to use tee within the Zeus IDE: http://www.zeusedit.com/forum/viewtopic.php?t=74 Jussi Jumppanen Author: Zeus for Windows IDE http://www.zeusedit.com - Zeus for Windows Programmer's IDE From gagsl-py2 at yahoo.com.ar Sat May 12 02:00:48 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 12 May 2007 03:00:48 -0300 Subject: name capitalization of built-in types, True, and False References: <1178915868.650553.219430@h2g2000hsg.googlegroups.com> Message-ID: En Fri, 11 May 2007 17:37:48 -0300, escribi?: > I see that naming conventions are such that classes usually get named > CamelCase. So why are the built-in types named all lowercase (like > list, dict, set, bool, etc.)? Because most of them originally were types and factory functions, not classes - and a naming convention is not a strong reason to make backwards incompatible changes. A different example: the new builtin type `set` is based on (altough not exactly equal to) the Set class from the sets module -- Gabriel Genellina From carsten at uniqsys.com Sat May 5 07:47:08 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 05 May 2007 07:47:08 -0400 Subject: Do I have to quit python to load a module? In-Reply-To: References: Message-ID: <1178365628.3134.7.camel@localhost.localdomain> On Sat, 2007-05-05 at 05:33 +0000, wang frank wrote: > Hi, > > When I edit a module, I have to quit python and then restart python and > then import the module. Are there any way to avoid quit python to load an > updated module? When I am debugging a module code, I need to constantly > make changes. It is not convenient to quit and reload. This is a frequently asked question. See http://www.python.org/doc/faq/ . The answer to your question is at http://tinyurl.com/2qc7ev . -Carsten From nagle at animats.com Thu May 3 01:58:42 2007 From: nagle at animats.com (John Nagle) Date: Thu, 03 May 2007 05:58:42 GMT Subject: More urllib timeout issues. In-Reply-To: References: Message-ID: Facundo Batista wrote: > Steve Holden wrote: > > >>1) There is work afoot to build timeout arguments into network libraries >>for 2.6, and I know Facundo Batista has been involved, you might want to >>Google or email Facundo about that. > > > Right now (in svn trunk) httplib, ftplib, telnetlib, etc, has a timeout > argument. > > If you use it, the socket timeout will be set (through s.settimeout()). > What behaviour has the socket after setting it the timeout, is beyond of > these changes, though. > > BTW, I still need to make the final step here, that is adding a timeout > argument to urllib2.urlopen(). > > Regards, urllib, robotparser, and M2Crypto also need to be updated to match. John Nagle From steve at REMOVE.THIS.cybersource.com.au Tue May 29 18:59:37 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 30 May 2007 08:59:37 +1000 Subject: 0 == False but [] != False? References: <1179982400.412340.178710@g4g2000hsf.googlegroups.com> <1179983482.452458.188690@q66g2000hsg.googlegroups.com> Message-ID: On Tue, 29 May 2007 11:36:07 -0700, Erik Max Francis wrote: > Donn Cave wrote: > >> Not that it is of no historical interest to review all these >> reasonable arguments, but allow me to restore the context quote >> from my follow-up: > > If the counterpoints are of no historical interest, then the original > point must be of no historical interest either, since it was not widely > granted as true. I hope you don't get just as confused by expressions like: if not x != 5 *wink* In English, a double negative is usually a positive. So "Not that it is of no historical interest" means "It is of historical interest". I wonder, if somebody with more time on their hands than me were to go through the threads on comp.lang.python before and after the introduction of bools, could we determine whether there were more problems caused by the introduction of True and False than by the lack of them? Although I like using bools, in my heart of hearts I suspect that Laura was right. -- Steven. From gagsl-py2 at yahoo.com.ar Thu May 17 22:45:01 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 17 May 2007 23:45:01 -0300 Subject: Python Newbie Suggestions References: <1179264515.958714.72880@l77g2000hsb.googlegroups.com> <464a50d7$1_4@mk-nntp-2.news.uk.tiscali.com> <1179282318.821090.82840@h2g2000hsg.googlegroups.com> <464cff85$1_4@mk-nntp-2.news.uk.tiscali.com> Message-ID: En Thu, 17 May 2007 22:21:05 -0300, Stephen Lewitowski escribi?: > Michael Tobis wrote: >> I think >> >> http://www.diveintopython.org/ >> >> would be very suitable for you. >> > > I disagree here. The site was last updated in 2004; its out of date. For > a newbie any material referenced should be current and include what is > available in Python 2.5. From the site headings: "Dive Into Python is a Python book for experienced programmers." The style is very clear and comprehensible - even for *non* programmers. The book is up-to-date to Python 2.3, describing generators by example, that were added on that release. After reading it, anyone should be able to grasp the newer features by himself. -- Gabriel Genellina From steven.klass at gmail.com Tue May 1 12:38:08 2007 From: steven.klass at gmail.com (rh0dium) Date: 1 May 2007 09:38:08 -0700 Subject: Having problems accepting parameters to a function Message-ID: <1178037488.163487.114930@l77g2000hsb.googlegroups.com> Hi Experts!! I am trying to get the following little snippet to push my data to the function func(). What I would expect to happen is it to print out the contents of a and loglevel. But it's not working. Can someone please help me out. ----------------------- #!/usr/bin/env python import random def func(*args, **kwargs): print kwargs.get('a', "NOPE") print kwargs.get('loglevel', "NO WAY") def main(): b = [] for x in range(5): b.append({'a':random.random(), "loglevel":10}) for y in b: apply(func,y) # First attempt - didn't work # for y in b: # func(y) if __name__ == '__main__': main() From vmaslov at swsoft.com Wed May 23 23:45:45 2007 From: vmaslov at swsoft.com (Vyacheslav Maslov) Date: Thu, 24 May 2007 10:45:45 +0700 Subject: using google search api for python In-Reply-To: <465337A0.5080808@fmed.uba.ar> References: <465337A0.5080808@fmed.uba.ar> Message-ID: <46550A69.5050201@swsoft.com> Gerardo Herzig wrote: > Hi all. Im looking for the pyGoogle for making google searchs y a python > script. The thing is, all im founding is an AJAX api, but the > application ill use is NOT a web app. So, someone know if there is a > pure python api that i can download and use? > > Thanks! > Gerardo http://www.ibm.com/developerworks/webservices/library/ws-pyth14/ -- From robert.kern at gmail.com Wed May 9 22:18:25 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 09 May 2007 21:18:25 -0500 Subject: change of random state when pyc created?? In-Reply-To: References: <5ae25fF2oggbqU1@mid.uni-berlin.de> Message-ID: Alan Isaac wrote: >>> Robert Kern wrote: >>>> http://docs.python.org/lib/typesmapping.html >>>> """ >>>> Keys and values are listed in an arbitrary order which is non-random, > varies >>>> across Python implementations, and depends on the dictionary's history > of >>>> insertions and deletions. >>>> """ > >> Alan G Isaac wrote: >>> Even this does not tell me that if I use a specified implementation >>> that my results can vary from run to run. That is, it still does >>> not communicate that rerunning an *unchanged* program with an >>> *unchanged* implementation can produce a change in results. > > "Robert Kern" wrote in message > news:mailman.7488.1178744519.32031.python-list at python.org... >> The last clause does tell me that. > > 1. About your reading of the current language: > I believe you, of course, but can you tell me **how** it tells you that? > To be concrete, let us suppose parallel language were added to > the description of sets. What about that language should allow > me to anticipate Peter's example (in this thread)? Actually, the root cause of Peter's specific example is the fact that the default implementation of __hash__() and __eq__() rely on identity comparisons. Two separate invocations of the same script give different objects by identity and thus the "history of insertions and deletions" is different. > 2. About possibly changing the docs: > You are much more sophisticated than ordinary users. > Did this thread not demonstrate that even sophisticated users > do not see into this "implication" immediately? Well, if you had a small test case that demonstrated the problem, we would have. Your example was large, complicated, and involved other semi-deterministic red herrings (the PRNG). It's quite easy to see the problem with Peter's example. > Replicability > of results is a huge deal in some circles. I think the docs > for sets and dicts should include a red flag: do not use > these as iterators if you want replicable results. > (Side note to Carsten: this does not require listing "every little thing".) They do. They say very explicitly that they are not ordered and that the sequence of iteration should not be relied upon. The red flags are there. But I'm not going to stop you from writing up something that's even more explicit. -- 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 eopadoan at altavix.com Thu May 31 14:30:45 2007 From: eopadoan at altavix.com (Eduardo "EdCrypt" O. Padoan) Date: Thu, 31 May 2007 15:30:45 -0300 Subject: strange PyLint configuration (was: PEP 8 style enforcing program) In-Reply-To: <5c8glhF2tra7sU1@mid.individual.net> References: <1180613790.317480.314600@p47g2000hsd.googlegroups.com> <5c8glhF2tra7sU1@mid.individual.net> Message-ID: On 5/31/07, Bjoern Schliessmann wrote: > Alexander Eisenhuth wrote: > > > Pylint is one of them (http://www.logilab.org/857) > > BTW: Why does pylint want all names with underscores? I tested it > and it complains about malformed names in e.g. the following cases > that are conformant to PEP 8: > > - single letter as parameter This seems to be an Logilab internal restriction. > - firstLowerCamelCase names for instances and instance methods in > class declarations ("should match [a-z_][a-z0-9_]{2,30}$") > - all lowercase method names in class declarations > No. Quoting PEP 8: Functions: """ mixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py), to retain backwards compatibility. """ Methods and instances: """ Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability. """ > Those policies are barely usable, IMHO, and neither practical. I Desagree. -- EduardoOPadoan (eopadoan->altavix::com) Bookmarks: http://del.icio.us/edcrypt From warren at muse.com Thu May 31 02:23:22 2007 From: warren at muse.com (Warren Stringer) Date: Wed, 30 May 2007 23:23:22 -0700 Subject: c[:]() In-Reply-To: <005401c7a31a$136f7fe0$240110ac@Muse> References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com><1180554872.3356.30.camel@dot.uniqsys.com><465DF3DE.40404@cc.umanitoba.ca><1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> Message-ID: <008201c7a34c$31584960$240110ac@Muse> Oops! guess I should have tested my rather hasty complaint about executable containers. This is nice: def a(): return 'b' def b(): print 'polly! wakey wakey' c = {} c['a'] = b c[a()]() #works! c[a()]() is a switch statement with an amorphous selector- very handy in its own right. But, using a() as a generator would be more expressive. This seems to work: c = [a,a] [d() for d in c] But that still isn't as simple or as direct as: c[:]() Which would you rather explain to a 12-year-old writing code for the first time? > I still want my executable container though. Would love to so this > > h[search('a//f')]() # where a//f is like an Xpath // search for leaves > From stefan.behnel-n05pAM at web.de Wed May 16 04:45:54 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 16 May 2007 10:45:54 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464ac22c$0$20297$9b4e6d93@newsspool3.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649dd55$0$23144$9b4e6d93@newsspool1.arcor-online.net> <464a25e9$0$10188$9b4e6d93@newsspool4.arcor-online.net> <464A3354.4060205@web.de> <464ac22c$0$20297$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <464AC4C2.7030007@web.de> Ren? Fleschenberg wrote: > Marc 'BlackJack' Rintsch schrieb: >> There are potential users of Python who don't know much english or no >> english at all. This includes kids, old people, people from countries >> that have "letters" that are not that easy to transliterate like european >> languages, people who just want to learn Python for fun or to customize >> their applications like office suites or GIS software with a Python >> scripting option. > > Make it an interpreter option that can be turned on for those cases. No. Make "ASCII-only" an interpreter option that can be turned on for the cases where it is really required. Stefan From deets at nospam.web.de Wed May 23 18:41:12 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 24 May 2007 00:41:12 +0200 Subject: Parallel/distributed generator In-Reply-To: <1179954101.940331.45260@u30g2000hsc.googlegroups.com> References: <1179954101.940331.45260@u30g2000hsc.googlegroups.com> Message-ID: <5bju8dF2taechU2@mid.uni-berlin.de> George Sakkis schrieb: > On May 23, 2:11 pm, "Diez B. Roggisch" wrote: > >> George Sakkis wrote: >>> I'm looking for any existing packages or ideas on how to implement the >>> equivalent of a generator (in the Python sense, i.e. >>> http://www.python.org/dev/peps/pep-0255/) in a parallel/distributed >>> way. As a use case, imagine a function that generates a range of >>> primes. I'd like to be able to do something along the following lines: >>> def iterprimes(start=1, end=None): >>> # ... >>> yield prime >>> # rpc-related initialization >>> ... >>> rpc_proxy = some_rpc_lib(iterprimes, start=1e6, end=1e12) >>> for prime in proxy: >>> print prime >>> Is there any module out there that does anything close to this ? >> Have you tried using pyro to just return a generator? After all, it's just >> an object with a next()-method, that raises a certain exception. I can't >> see why pyro shouldn't be able to handle that. > > Just tried it: > > cPickle.PicklingError: Can't pickle : attribute > lookup __builtin__.generator failed Hm. Maybe a bit of wrapping would help? Just like this: class GenWrapper(object): def __init__(self, g): self._g = g def next(self): return self._g.next() I'm not sure though if this indirection really helps. Diez From vinay_sajip at yahoo.co.uk Tue May 1 05:54:28 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 1 May 2007 02:54:28 -0700 Subject: logging SMTPHandler and Authentication In-Reply-To: <1177978114.284934.27140@l77g2000hsb.googlegroups.com> References: <1177978114.284934.27140@l77g2000hsb.googlegroups.com> Message-ID: <1178013267.964182.283440@h2g2000hsg.googlegroups.com> > http://groups.google.com/group/comp.lang.python/browse_frm/thread/ef8... That fairly old thread suggests that someone provide a patch, which hasn't happened. Sorry I missed that thread - your requirement is a reasonable one to be dealt with by the core. So I will look to implement this functionality soon. As it's not a bugfix I can't backport it, but you will be able to patch your version when I've made the change. Regards, Vinay Sajip From jstroud at mbi.ucla.edu Thu May 3 15:46:52 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 03 May 2007 12:46:52 -0700 Subject: Article on wxPython ToolKit for Mac OS X In-Reply-To: <1178204986.383057.264690@y80g2000hsf.googlegroups.com> References: <1178204986.383057.264690@y80g2000hsf.googlegroups.com> Message-ID: miah_gbg wrote: > Hi there! > > Just wanted to let people know in this group that I have recently > (April 24th) published an introductory article on wxPython and Mac OS > X. It is available here: http://www.macdevcenter.com/ > > Hope someone finds it useful. > > Regards, > > Jeremiah > Nice article, but it has an inaccuracy: "The first thing we need to do is download wxPython so we can begin creating applications." This is not entirely correct. The stock 10.4 that came in a G5 bought in June has wx built-in: cabin % /usr/bin/python Python 2.3.5 (#1, Oct 5 2005, 11:07:27) [GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import wx >>> Of course the stock python is 2.3, but its very cool that one can depend on wx being present on 10.4+ machines. So there is no need to bundle python/wx with your app when developing for Macs. (Yes, I noticed the author is running OS X 10.3.) James From gur.tom at gmail.com Thu May 17 07:19:44 2007 From: gur.tom at gmail.com (Tom Gur) Date: 17 May 2007 04:19:44 -0700 Subject: Get a control over a window In-Reply-To: References: <1179234413.915336.263660@n59g2000hsh.googlegroups.com> Message-ID: <1179400784.106553.288180@y80g2000hsf.googlegroups.com> Thanks guys, especially Duncan ! That's what I'm using now: import sys from win32gui import GetWindowText, EnumWindows, ShowWindow from win32con import SW_MINIMIZE def listWindowsHandles(): res = [] def callback(hwnd, arg): res.append(hwnd) EnumWindows(callback, 0) return res def listWindowsNames(): return (map(GetWindowText, listWindowsHandles())) def minimizeWindow(): a_hwnd = listWindowsHandles() [listWindowsNames().index(sys.argv[1])] ShowWindow(a_hwnd, SW_MINIMIZE) minimizeWindow() From mail at microcorp.co.za Sun May 27 03:03:20 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 27 May 2007 09:03:20 +0200 Subject: Muzzle Velocity (was: High resolution sleep (Linux) References: <1178274122.142071.91740@y5g2000hsa.googlegroups.com> Message-ID: <006d01c7a02d$1c837c20$03000080@hendrik> "Cameron Laird" wrote: > . > . > Ha! It's interesting, especially for "computerists", to consider > how some technologies "plateau": steam car speeds, fresco paint- > ing, dry-stone walls, ... > > >From what I remember from my reading, the Stanley Steamer had a reputation as a "Hot Rod" (pun intentional) - and people said that nobody who tried to get its maximum out of it would live. I would suspect that the cause was not the engine, but the cornering performance of the chassis. Would be interesting to put an engine like that into a modern chassis to see what it would do. Probably would not beat a mini fitted with a Kawasaki 1100 engine for each wheel, though - an interesting problem in real time control... - Hendrik From mccredie at gmail.com Thu May 24 15:40:53 2007 From: mccredie at gmail.com (Matimus) Date: 24 May 2007 12:40:53 -0700 Subject: No file from stdin In-Reply-To: <20070524184811.6e439221.tartifola@gmail.com> References: <20070524184811.6e439221.tartifola@gmail.com> Message-ID: <1180035653.188189.210480@q19g2000prn.googlegroups.com> On May 24, 9:48 am, Tartifola wrote: > Hi, > suppose a script of python is waiting for a file from the stdin and none > is given. How can I make the script to stop and, for example, print an > error message? > > Sorry for the n00b question and thanks I'm not exactly sure what you mean. This assumes that you intended the contents of the file be piped in from the command line. [code] import sys if sys.stdin.isatty(): print >>sys.stderr, "expected input from stdin" sys.exit(1) sys.stdout.write(sys.stdin.read()) [/code] If you simply want a prompt "Enter a filename:", followed by an error if it is not a valid file, I would use something like this: [code] import sys filename = raw_input("Enter a filename:") try: f = open(filename) except IOError,e: print >>sys.stderr, e.strerror, e.filename sys.exit(e.errno) #do stuff with f [/code] From nick at craig-wood.com Mon May 14 05:30:03 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 14 May 2007 04:30:03 -0500 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote: > So, please provide feedback, e.g. perhaps by answering these > questions: Firstly on the PEP itself: It defines characters that would be allowed. However not being up to speed on unicode jargon I don't have a clear idea about which characters those are. A page with some examples or even all possible allowed characters would be great, plus some examples of disallowed characters. > - should non-ASCII identifiers be supported? why? Only if PEP 8 was amended to state that ASCII characters only should be used for publically released / library code. I'm quite happy with Unicode in comments / docstrings (but that is supported already). > - would you use them if it was possible to do so? in what cases? My initial reaction is that it would be cool to use all those great symbols. A variable called OHM etc! However on reflection I think it would be a step back for the easy to read nature of python. My worries are :- a) English speaking people would invent their own dialects of python which looked like APL with all those nice Unicode mathematical operators / Greek letters you could use as variable/function names. I like the symbol free nature of python which makes for easy comprehension of code and don't want to see it degenerate. b) Unicode characters would creep into the public interface of public libraries. I think this would be a step back for the homogeneous nature of the python community. c) the python keywords are in ASCII/English. I hope you weren't thinking of changing them? ... In summary, I'm not particularly keen on the idea; though it might be all right in private. Unicode identifiers are allowed in java though, so maybe I'm worrying too much ;-) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From aleax at mac.com Wed May 9 00:11:42 2007 From: aleax at mac.com (Alex Martelli) Date: Tue, 8 May 2007 21:11:42 -0700 Subject: Parameter checking on an interfase References: <1178682591.359947.240390@y80g2000hsf.googlegroups.com> Message-ID: <1hxtbu9.oxwijuox3z7pN%aleax@mac.com> wrote: ... > In this case, could be reasonable add type checking LBYL style > on the methods, so if passed data is of wrong type, it generates a > adequate exception to be catched by the caller? In this way, the rest As maybe one of the first popular authors to use LBYL and EAFP in this sense, I think I should comment here. First, I don't agree with SQLite's design decision to be typeless -- I believe types are important in RDB's in a very different way to their limited importance in programs (where Python's "duck typing almost everywhere" suits me just fine, though some intermediate approach like Boo's might be even better). Nevertheless, SQLite is a good job and I use it happily... when I _don't_ particularly care for type issues. When I _do_ care -- I go back to PostgreSQL. It may not be quite as handy as SQLite, if you want a self-contained program to deploy as a unit... but in just about all other respects, it's got huge advantages. Do consider it -- it will do a better job protecting your data's integrity (among which type-checking of specific fields is just a beginning). For _valuable_ data, where integrity really matters, that's really a big point. ((Oracle, IBM DB2, SAP/DB, Firefly, and no doubt others, might be just as good as PostgreSQL... but I have a sweet spot for the latter; for MySQL, even though I do have to use it sometimes for work purposes, my sympathy on the other hand is pretty low indeed)). If you decide PostgreSQL is not worth the bother, then I think that's a good sign that you should avoid type-checking in your code anyway, as it indicatres that SQLite's "typeless data" approach may be OK for you. Alex From steve at holdenweb.com Wed May 30 22:56:02 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 30 May 2007 22:56:02 -0400 Subject: RDFXML Parser For "qualified Dublin Core" Database File In-Reply-To: <465e3522.75fb435e.20b3.5b51@mx.google.com> References: <465e3522.75fb435e.20b3.5b51@mx.google.com> Message-ID: <465E3942.1010302@holdenweb.com> Brandon McGinty wrote: [actually he top-posted, but I have moved his comments down because he probably doesn't realise it's naughty] > -----Original Message----- > From: python-list-bounces+brandon.mcginty=gmail.com at python.org > [mailto:python-list-bounces+brandon.mcginty=gmail.com at python.org] On Behalf > Of Steve Holden > Sent: Tuesday, May 29, 2007 11:30 PM > To: python-list at python.org > Subject: Re: RDFXML Parser For "qualified Dublin Core" Database File > > Brandon McGinty wrote: >> Hi All, >> >> My goal is to be able to read the www.gutenberg.org >> rdf catalog, parse it into a python >> structure, and pull out data for each record. >> >> The catalog is a Dublin core RDF/XML catalog, divided into sections >> for each book and details for that book. >> >> I have done a very large amount of research on this problem. >> >> I've tried tools such as pyrple, sax/dom/minidom, and some others both >> standard and nonstandard to a python installation. >> >> None of the tools has been able to read this file successfully, and >> those that can even see the data can take up to half an hour to load >> with 2 gb of ram. >> >> So you all know what I'm talking about, the file is located at: >> >> http://www.gutenberg.org/feeds/catalog.rdf.bz2 >> >> Does anyone have suggestions for a parser or converter, so I'd be able >> to view this file, and extract data? >> >> Any help is appreciated. >> > Well, have you tried xml.etree.cElementTree, a part of the standard library > since 2.5? Well worth a go, as it seems to outperform many XML libraries. > > The iterparse function is your best bet, allowing you to iterate over the > events as you parse the source, thus avoiding the need to build a huge > in-memory data structure just to get the parsing done. > > The following program took about four minutes to run on my not-terribly > up-to-date Windows laptop with 1.5 GB of memory with the pure Python version > of ElementTree: > > import xml.etree.ElementTree as ET > events = ET.iterparse(open("catalog.rdf")) count = 0 for e in events: > count += 1 > if count % 100000 == 0: print count print count, "total events" > > Here's an example output after I changed to using the extension module - by > default, only the end-element events are reported. I think you'll be > impressed by the timing. The only change was to the import staement, which > now reads > > import xml.etree.cElementTree as ET > > sholden at bigboy ~/Projects/Python > $ time python test19.py > 100000 > 200000 > 300000 > 400000 > 500000 > 600000 > 700000 > 800000 > 900000 > 1000000 > 1100000 > 1200000 > 1300000 > 1400000 > 1469971 total events > > real 0m11.145s > user 0m10.124s > sys 0m0.580s > > Good luck! > ------- End Original Message -------- > Hi, > Thanks for the info. The speed is fantastic. 58 mb in under 15 sec, just as > shown. > I did notice that in this rdf file, I can't do any sort of find or findall. > I haven't been able to find any documentation on how to search. For > instance, in perl, one can do a search for "/rdf:RDF/pgterms:etext", and > when done in python, with many many variations, find and findall return no > results, either when searching from root or children of root. > You should keep the list in the loop, as I am not an ElementTree expert, simply someone who knew of its capabilities on the basis of some earlier casual use. I am glad it is working well for you. Memory usage is also pretty low with the extension module. You may well find that other readers can advise you about the selective aspects of processing. I'd have thought find() and findall() would have been what you want. The more you explain about your requirements the more help you are likely to get. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From paul at boddie.org.uk Tue May 15 11:18:48 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 15 May 2007 08:18:48 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <4649C63C.1030508@web.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649BC4C.10200@web.de> <1179238847.407605.4620@w5g2000hsg.googlegroups.com> <4649C63C.1030508@web.de> Message-ID: <1179242328.800088.246620@h2g2000hsg.googlegroups.com> On 15 May, 16:39, Stefan Behnel wrote: > > It's difficult to extract this analysis from Java. Most people I know from the > Java world do not use this feature as it is error prone. Java does not have > support for *explicit* source encodings, i.e. the local environment settings > win. This is bound to fail e.g. on a latin-1 system where I would like to work > with UTF-8 files (which tend to work better on the Unix build server, etc.) Here's a useful link on this topic: http://www.jorendorff.com/articles/unicode/java.html A search for "Java source file encoding" on Google provides other material. Paul From dborne at gmail.com Fri May 18 10:09:55 2007 From: dborne at gmail.com (Dave Borne) Date: Fri, 18 May 2007 09:09:55 -0500 Subject: Multi-Page login WITH Cookies (POST Data) In-Reply-To: <562a25f0705171636j6a1f70d8x7dff7aefc88b5f59@mail.gmail.com> References: <562a25f0705171636j6a1f70d8x7dff7aefc88b5f59@mail.gmail.com> Message-ID: <6e42ec490705180709h10fde345y643f6fa2fb6c24f2@mail.gmail.com> > After we are able to get a succussful login, i need a way that i can browse > my site always including this cookie, like if i went to open up a page, it > would use the cookie we got from logging in. You need something like this: import cookielib,urllib2 cookiejar = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar)) more info here: http://docs.python.org/lib/module-urllib2.html and here: http://docs.python.org/lib/module-cookielib.html -Dave From kinch1967 at gmail.com Mon May 28 13:27:27 2007 From: kinch1967 at gmail.com (bullockbefriending bard) Date: 28 May 2007 10:27:27 -0700 Subject: speeding things up with C++ In-Reply-To: <1180367310.156165.177650@m36g2000hse.googlegroups.com> References: <1180171179.687276.77930@z28g2000prd.googlegroups.com> <1180367310.156165.177650@m36g2000hse.googlegroups.com> Message-ID: <1180373247.172089.165160@o11g2000prd.googlegroups.com> thanks. i'll definitely look into this. On May 28, 10:48 pm, Kay Schluehr wrote: > On May 26, 11:19 am, bullockbefriending bard > wrote: > > > > > I've done all the requisite profiling and thought fairly deeply about > > the efficiency of my python code, but am still going to have to speed > > up the innermost guts of what I am doing. > > > Essentially, I need to pass a list of 6-tuples containing only > > integers to my new sadly necessary super-fast compiled language > > function which i am not looking forward to writing: > > > input: [(1,2,3,4,5,6), (7,8,9,10,11,12),...] > > > and after much thrashing of processor resources, return data which > > looks like this to the Python calling environment: > > > output: [( (1, 2), (1,), (12,), (13), (1, 7, 11), (9,) ), ( another > > nested tuple like preceding one ), .... ] > > > Each member of the returned list is a tuple containing 6 tuples, and > > each of those 6 tuples has at least one integer member. It would also > > be acceptable for the return values to be entirely nested lists > > instead of having the two innermost sequence types as tuples. > > > I probably want to be using something like C++ because i'm going to > > need to use STL vectors and sets for what i'm doing in the algorithm > > i'm trying to speed up. IIRC Boost tuple is a bit painful for more > > than 10 elements + isn't really essential that I use a a non-mutable > > data type in what will be a small encapsulated bit of a much larger > > system. > > > Anyway, I can probably very quickly figure out some hacked way to get > > the data into my function given that in the worst case I could take > > advantage of the knowledge that each input tuple always has 6 > > elements, and simply pass in a big array of ints. Yes, I know this is > > a bit retarded, but I'm talking worst case assuming on very tight > > schedule and no time to delve deeply into SWIG or whatever. Similarly > > it wouldn't be too difficult to return the result as the mother all of > > all strings which i could then parse fairly easily. > > > However, I hope someone reading this will be able to tell me that I'm > > being a total pessimist and that in fact it isn't very difficult to do > > what I want to do using SWIG. I'm not asking for a complete solution, > > more like some general pointers from someone who has actually done > > something similar before. > > > As an added bonus, I wouldn't if this is 'easily' doable using Ocaml > > as the guts instead of C++, I'd be happy to know about it. > > A just too obvious recommendation is to drop C++ and use D together > with the Pyd/celerid bridge. Yeah, it sounds a little esoteric but D > is really the Python among the statically typed imperative languages. > > http://www.digitalmars.com/d/http://pyd.dsource.org/index.html From rene at korteklippe.de Tue May 15 07:32:37 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 15 May 2007 13:32:37 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46499273.6050806@web.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <4648252D.5020704@web.de> <46483740.4050406@web.de> <46498cb1$0$6411$9b4e6d93@newsspool2.arcor-online.net> <46499273.6050806@web.de> Message-ID: <46499a54$0$10199$9b4e6d93@newsspool4.arcor-online.net> Stefan Behnel schrieb: > Ren? Fleschenberg wrote: >> you have failed to do that, in my opinion. All you have presented are >> vague notions of rare and isolated use-cases. > > I don't think software development at one of the biggest banks in Germany can > be considered a "rare and isolated use case". And that software development at that bank is not done in Python because Python does not support non-ASCII identifiers? Can you provide a source for that? > Admittedly, it's done in Java, but why should Python fail to support unicode > identifiers in the way Java does? Your example does not prove much. The fact that some people use non-ASCII identifiers when they can does not at all prove that it would be a serious problem for them if they could not. -- Ren? From user2048 at yahoo.com Mon May 21 09:21:22 2007 From: user2048 at yahoo.com (user2048 at yahoo.com) Date: 21 May 2007 06:21:22 -0700 Subject: Python compared to other language In-Reply-To: References: Message-ID: <1179753682.661307.186540@y18g2000prd.googlegroups.com> > Python is a strongly typed but dynamic language ... In the "A few questions" thread, John Nagle's summary of Python begins "Python is a byte-code interpreted untyped procedural dynamic language with implicit declaration. " Is Python strongly typed or untyped? From maney at two14.net Sat May 19 21:45:49 2007 From: maney at two14.net (Martin Maney) Date: Sun, 20 May 2007 01:45:49 +0000 (UTC) Subject: zipfile [module and file format, both] stupidly broken References: Message-ID: Gabriel Genellina wrote: > A module in the Python Standard Library has a bug. I take the Python > Library Reference manual, go to the last pages (Appendix B), and find how > to properly report a bug. Sure, the information is *somewhere*. Silly me, I expected it to be readily findable from the project's home page, as it usually is for open source projects (and I thought I remembered it being so in the past - y'know, before the web site got prettified and dumbed down). Is there any good reason not to have it in lots of likely places, aside from the opportunity to jeer at those who didn't look in the right one while spending their time trying to report a problem? Never mind, rhetorical question. -- There is overwhelming evidence that the higher the level of self-esteem, the more likely one will be to treat others with respect, kindness, and generosity. -- Nathaniel Branden From bbxx789_05ss at yahoo.com Tue May 1 13:19:13 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 1 May 2007 10:19:13 -0700 Subject: Having problems accepting parameters to a function In-Reply-To: <1178039183.030942.86270@y5g2000hsa.googlegroups.com> References: <1178037488.163487.114930@l77g2000hsb.googlegroups.com> <1178039183.030942.86270@y5g2000hsa.googlegroups.com> Message-ID: <1178039953.223506.52760@y80g2000hsf.googlegroups.com> On May 1, 11:06 am, 7stud wrote: > > You might consider redefining func() so that you don't have to do the > unpack--repack... When you define a function like this: def func(**keywordargs): print keywordargs the function expects to receive arguments in the form: func(a="hello", b="world") not: func(adict) From jeff.self at gmail.com Wed May 2 11:00:22 2007 From: jeff.self at gmail.com (jocknerd) Date: 2 May 2007 08:00:22 -0700 Subject: I need help speeding up an app that reads football scores and generates rankings Message-ID: <1178118022.865173.266300@h2g2000hsg.googlegroups.com> About 10 years ago, I wrote a C app that would read scores from football games and calculate rankings based on the outcome of the games. In fact, I still use this app. You can view my rankings at http://members.cox.net/jocknerd/football. A couple of years ago, I got interested in Python and decided to rewrite my app in Python. I got it to work but its painfully slow compared to the C app. I have a file containing scores of over 1500 high school football games for last season. With my Python app, it takes about 3 minutes to process the rankings. With my C app, it processes the rankings in less than 15 seconds. The biggest difference in my two apps is the C app uses linked lists. I feel my Python app is doing too many lookups which is causing the bottleneck. I'd love some feedback regarding how I can improve the app. I'd like to drop the C app eventually. Its really ugly. My goal is to eventually get the data stored in PostgreSQL and then have a Django powered site to process and display my rankings. You can download the source code from http://members.cox.net/jocknerd/downloads/fbratings.py and the data file from http://members.cox.net/jocknerd/downloads/vhsf2006.txt Thanks! From tom at finland.com Thu May 10 11:55:26 2007 From: tom at finland.com (tom at finland.com) Date: Thu, 10 May 2007 15:55:26 GMT Subject: keyword checker - keyword.kwlist In-Reply-To: References: Message-ID: Still no go. I just can't get it right. My current script: #!usr/bin/env python import keyword myInput = raw_input('Enter identifier to check >> ') if myInput in keyword.kwlist: print myInput, "is keyword" else: print myInput, "is not keyword" print keyword.kwlist print keyword.__file__ And the output: Enter identifier to check >> else else is not keyword ['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield'] F:\Ohjelmat\Python25\Lib\keyword.pyc From bj_666 at gmx.net Wed May 2 13:03:41 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 02 May 2007 19:03:41 +0200 Subject: Time functions References: <1178125256.640115.26480@o5g2000hsb.googlegroups.com> Message-ID: In <1178125256.640115.26480 at o5g2000hsb.googlegroups.com>, HMS Surprise wrote: > I wish to generate a datetime string that has the following format. > '05/02/2007 12:46'. The leading zeros are required. > > I found '14.2 time' in the library reference and have pulled in > localtime. Are there any formatting functions available or do I need > to make my own? Perhaps there is something similar to C's printf > formatting. You mean like `time.strftime()`!? :-) Ciao, Marc 'BlackJack' Rintsch From tinaweb at bestemselv.com Mon May 28 05:24:57 2007 From: tinaweb at bestemselv.com (Tina I) Date: Mon, 28 May 2007 11:24:57 +0200 Subject: Unsubscribing from the mailing list In-Reply-To: <1180320778.316540.296470@q19g2000prn.googlegroups.com> References: <1180320778.316540.296470@q19g2000prn.googlegroups.com> Message-ID: marijuanated at gmail.com wrote: > Hi All, > > I do not know if this is the correct group to ask this question. But > since mailman is python-based I thought i would ask here. > > I had subscribed to a mailing list called gtk-app-devel-list at gnome.org > adventitiously. I then wanted to reverse my decision and so tried to > unsubscribe from the mailing list. The web interface told that I had > to enter my username and then click unsubscribe. I did so. I was > responded with the message that "A confirmation mail has been sent". > However I did not get any mail of that sort. Due to this I am not able > to unsubscribe and I get loads of emails from that mailing list every > day. > > Can somebody help me get out of this mess?? > > Thanks, > Sundar > Umm... why not ask on gtk-app-devel-list at gnome.org ?? From deets at nospam.web.de Wed May 23 14:11:17 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 23 May 2007 20:11:17 +0200 Subject: Parallel/distributed generator References: <1179943256.575473.62610@q66g2000hsg.googlegroups.com> Message-ID: <5bjee5F2qu0euU1@mid.uni-berlin.de> George Sakkis wrote: > I'm looking for any existing packages or ideas on how to implement the > equivalent of a generator (in the Python sense, i.e. > http://www.python.org/dev/peps/pep-0255/) in a parallel/distributed > way. As a use case, imagine a function that generates a range of > primes. I'd like to be able to do something along the following lines: > > def iterprimes(start=1, end=None): > # ... > yield prime > > > # rpc-related initialization > ... > rpc_proxy = some_rpc_lib(iterprimes, start=1e6, end=1e12) > for prime in proxy: > print prime > > Is there any module out there that does anything close to this ? Have you tried using pyro to just return a generator? After all, it's just an object with a next()-method, that raises a certain exception. I can't see why pyro shouldn't be able to handle that. diez From james.b.looney at lmco.com Tue May 8 18:17:28 2007 From: james.b.looney at lmco.com (Looney, James B) Date: Tue, 08 May 2007 16:17:28 -0600 Subject: Using os.popen and os.chdir together Message-ID: Within a script on a *nix machine, I use os.chdir then os.popen, and it appears to me as though the os.chdir had no effect so far as the os.popen is concerned. Why's that? Here's what I'm doing: >>> import os >>> os.path.realpath( os.curdir ) '/home/jlooney' >>> print os.popen( "echo $PWD" ).readlines() ['/home/jlooney\n'] >>> >>> os.chdir( "/tmp" ) >>> os.path.realpath( os.curdir ) '/tmp' >>> print os.popen( "echo $PWD" ).readlines() ['/home/jlooney\n'] >>> You'll notice that initially, the current paths are the same, and correct. After I call os.chdir, and try os.popen, it's not in the new directory. When I do other things like creating new files, the chdir did exactly what I expected. What I don't understand is why os.popen appears to be special? How do I change directories within a script and have popen see that change? -JB -------------- next part -------------- An HTML attachment was scrubbed... URL: From see.signature at no.spam Wed May 16 09:57:25 2007 From: see.signature at no.spam (Eric Brunel) Date: Wed, 16 May 2007 15:57:25 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <7x4pmg716p.fsf@ruckus.brouhaha.com> <4648EC26.8020907@v.loewis.de> Message-ID: On Wed, 16 May 2007 15:46:10 +0200, Neil Hodgson wrote: > Eric Brunel: > >> Funny you talk about Japanese, a language I'm a bit familiar with and >> for which I actually know some input methods. The thing is, these only >> work if you know the transcription to the latin alphabet of the word >> you want to type, which closely match its pronunciation. So if you >> don't know that ??? is pronounced "uriba" for example, you have >> absolutely no way of entering the word. Even if you could choose among >> a list of characters, are you aware that there are almost 2000 "basic" >> Chinese characters used in the Japanese language? And if I'm not >> mistaken, there are several tens of thousands characters in the Chinese >> language itself. This makes typing them virtually impossible if you >> don't know the language and/or have the correct keyboard. > > It is nowhere near that difficult. There are several ways to > approach this, including breaking up each character into pieces and > looking through the subset of characters that use that piece (the > Radical part of the IME). For ?, you can start with the cross with a > short bottom stroke (at the top of the character) ?, for ? look for > the crossy thing on the left ?. The middle character is simple looking > so probably not Chinese so found it in Hiragana. Another approach is to > count strokes (Strokes section of the IME) and look through the > characters with that number of strokes. Within lists, the characters are > ordered from simplest to more complex so you can get a feel for where to > look. Have you ever tried to enter anything more than 2 or 3 characters like that? I did. It just takes ages. Come on: are you really serious about entering *identifiers* in a *program* this way? -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From thorsten at thorstenkampe.de Thu May 31 13:55:23 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Thu, 31 May 2007 18:55:23 +0100 Subject: Python memory handling References: <1180611604.247696.149060@h2g2000hsg.googlegroups.com> <1180617317.969977.115660@u30g2000hsc.googlegroups.com> Message-ID: * (31 May 2007 06:15:18 -0700) > On 31 mai, 14:16, Marc 'BlackJack' Rintsch wrote: > > In <1180611604.247696.149... at h2g2000hsg.googlegroups.com>, frederic.pica > > wrote: > And I'm not sure that the system will swap first this > unused memory, it could also swap first another application... AFAIK. Definitely not, this is the principal function of virtual memory in every Operating System. From jek-gmane at kleckner.net Mon May 21 21:15:14 2007 From: jek-gmane at kleckner.net (Jim Kleckner) Date: Mon, 21 May 2007 18:15:14 -0700 Subject: Cycle detection and object memory usage? In-Reply-To: References: Message-ID: Gabriel Genellina wrote: > En Sun, 20 May 2007 23:54:15 -0300, Jim Kleckner > escribi?: > >> I understand from the documentation that types with a finalizer method >> that participate in cycles can't be collected. > > Yes; older Python versions could not manage any kind of cycles, now only > objects with __del__ cause problems. > You can explicitely break the cycle (removing the reference, ensuring that > some finalization method is always called, maybe using try/finally) or you > may use weak references (by example, in a tree-like structure, a node > might hold a weak reference to its parent). > >> What is the best way to go about finding these cycles? >> Googling gives a variety of methods none of which seem terribly >> mainstream for such a common problem. > > Avoid them in the first place :) > Use the gc module: after a call to gc.collect(), see if something remains > in gc.garbage I would have sworn that there were uncollectable objects when I tried this before. Now they don't show up. I guess that is good... Which leads to >> Object memory usage: >> >> Has anyone written a function to sweep out an object to discover how >> much memory it and all the objects it references is using? This would >> be great for performance tuning. > > A rough estimate may be the object's pickle size. But it's hard to measure > precisely; by example, strings are immutable and you may have thousands of > shared references to the same string, and they require just a few bytes > each. Good idea, thanks. I take it then that memory profiling isn't available? From ptmcg at austin.rr.com Thu May 24 01:11:22 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 23 May 2007 22:11:22 -0700 Subject: 0 == False but [] != False? In-Reply-To: <1179982400.412340.178710@g4g2000hsf.googlegroups.com> References: <1179982400.412340.178710@g4g2000hsf.googlegroups.com> Message-ID: <1179983482.452458.188690@q66g2000hsg.googlegroups.com> On May 23, 11:53 pm, Rajarshi wrote: > This is a slightly naive question, but I know that 0 can be used to > represent False. So > > >>> 0 == False > > True > > But, I know I can use [] to represent False as in > > >>> if not []: print 'empty' > > ... > empty > > But then doing the following gives a surprising (to me!) result > > >>> [] == False > > False > > Could anybody point out why this is the case? > > Thanks, > Rajarshi This has *got* to rank up there among the VFAQ's of them all, along with the mysterious shared default empty list argument. I think this particular question has been asked in one form or another at least twice a week for the past month! -- Paul From grante at visi.com Wed May 23 11:55:19 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 23 May 2007 15:55:19 -0000 Subject: Slightly OT: Why all the spam? References: <3bb44c6e0705220008y10f5deb7v86ed82d3f8241761@mail.gmail.com> <1358lu17h16a96e@corp.supernews.com> Message-ID: <1358ov765ociib4@corp.supernews.com> On 2007-05-23, Joel Hedlund wrote: > > Expired articles are removed on the server by the server. > > ... > > maybe Thunderbird is doing something weird (caching headers?). > > I can see the spam headers and also read the actual articles, Then they aren't expired. If they were expired, you wouldn't see them. > and there are lots of them for the last 5 days. Nothing much > before that, though. -- Grant Edwards grante Yow! I feel like I am at sharing a ``CORN-DOG'' visi.com with NIKITA KHRUSCHEV ... From bj_666 at gmx.net Tue May 15 12:44:00 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 15 May 2007 18:44:00 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: In , Ross Ridge wrote: > wrote: >>So, please provide feedback, e.g. perhaps by answering these >>questions: >>- should non-ASCII identifiers be supported? why? > > Ross Ridge wrote: >> I think the biggest argument against this PEP is how little similar >> features are used in other languages > > Carsten Haese wrote: >>That observation is biased by your limited sample. > > No. I've actually looked hard to find examples of source code that use > non-ASCII identifiers. While it's easy to find code where comments use > non-ASCII characters, I was never able to find a non-made up example > that used them in identifiers. I think you have to search examples of ASCII sources with transliterated identifiers too, because the authors may have skipped the transliteration if they could have written the non-ASCII characters in the first place. And then I dare to guess that much of that code is not open source. One example are macros in office programs like spreadsheets. Often those are written by semi professional programmers or even end users with transliterated identifiers. If the OpenOffice API wouldn't be so "javaesque" this would be a good use case for code with non-ASCII identifiers. Ciao, Marc 'BlackJack' Rintsch From gh at gregor-horvath.com Wed May 16 00:04:57 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Wed, 16 May 2007 06:04:57 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: Ross Ridge schrieb: > non-ASCII identifiers. While it's easy to find code where comments use > non-ASCII characters, I was never able to find a non-made up example > that used them in identifiers. If comments are allowed to be none English, then why are identifier not? This is inconsistent because there is a correlation between identifier and comment. The best identifier is one that needs no comment, because it self-describes it's content. None English identifiers enhance the meaning of identifiers for some projects. So why forbid them? We are all adults. Gregor From michael at jedimindworks.com Tue May 1 13:47:48 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Tue, 1 May 2007 12:47:48 -0500 Subject: sqlite for mac? In-Reply-To: <1178041154.480155.78220@o5g2000hsb.googlegroups.com> References: <1177993261.572563.70370@n76g2000hsh.googlegroups.com> <1178039558.882802.214030@n59g2000hsh.googlegroups.com> <1178041154.480155.78220@o5g2000hsb.googlegroups.com> Message-ID: <6B264C2F-99A8-49F8-9D79-A052BE6602D6@jedimindworks.com> On May 1, 2007, at 12:39 PM, kirkjobsluder wrote: > On May 1, 1:12 pm, 7stud wrote: >> I'm using python 2.4.4 because the download said there were more mac >> modules available for 2.4.4. than 2.5, and I can't seem to locate a >> place to download sqlite for mac. > > I it comes on OS X Tiger, and possibly earlier versions as well (it's > used as an index for Mail.app).. You just need to download and > install the pysqlite libraries. The system sqlite btw (which reports itself as version 3.1.3), is not the same as what is included in Python 2.5. Will somebody please say what version of sqlite is supported by Python 2.5? From tjreedy at udel.edu Wed May 2 21:30:16 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 2 May 2007 21:30:16 -0400 Subject: python,win32com,scipy and vb 6 : no module named scipy References: <1178141865.741042.202250@l77g2000hsb.googlegroups.com> Message-ID: scipy is a 3rd party package which I believe you get from the same place, more or less, as numpy. From sjmachin at lexicon.net Wed May 16 07:57:51 2007 From: sjmachin at lexicon.net (John Machin) Date: 16 May 2007 04:57:51 -0700 Subject: Quote aware split In-Reply-To: References: Message-ID: <1179316671.451862.184050@n59g2000hsh.googlegroups.com> On May 16, 10:50 am, "Ondrej Baudys" wrote: > # last slice will be of the form chars[last:] which we couldnt do above Who are "we"? Here's another version with the "couldn't do" problem fixed and a few minor enhancements: def qsplit2(chars, sep=",", quote="'"): """ Quote aware split """ assert sep != quote can_split = True splitpoints = [-1] # ie. separator char found before first letter ;) for index, c in enumerate(chars): if c == quote: can_split = not can_split elif c == sep and can_split: splitpoints.append(index) if not can_split: raise ValueError("Unterminated quote") splitpoints.append(len(chars)) # slice chars by splitpoints *omitting the separator* slices = [chars[splitpoints[i]+1:splitpoints[i+1]] for i in range(len(splitpoints)-1)] return slices Cheers, John From mensanator at aol.com Fri May 11 17:26:48 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 11 May 2007 14:26:48 -0700 Subject: Interesting list Validity (True/False) In-Reply-To: <1178915791.584216.293130@l77g2000hsb.googlegroups.com> References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> <1178914190.166662.285410@p77g2000hsh.googlegroups.com> <1178915791.584216.293130@l77g2000hsb.googlegroups.com> Message-ID: <1178918808.091358.233740@o5g2000hsb.googlegroups.com> On May 11, 3:36 pm, nufuh... at gmail.com wrote: > On May 11, 2:28 pm, nufuh... at gmail.com wrote: > > > > > > > > > > Hello all, > > > > First let me appologise if this has been answered but I could not find > > > an acurate answer to this interesting problem. > > > > If the following is true: > > > C:\Python25\rg.py>python > > > 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. > > > >>> [] == [] > > > True > > > >>> ['-o'] == [] > > > False > > > >>> ['-o'] == False > > > False > > > > Then why do I get the following results: > > > C:\Python25\rg.py>help.py -o > > > print arg ['-o'] > > > type(arg): > > > arg is True? False > > > help.py version 1.0 Copyright RDEG (c) 2007 > > > ['-o'] is an unrecognized option. > > > Progam Exit (0) > > > > > > > import sys > > > > _ver_ = 1.00 > > > > if '-h' in sys.argv or '--help' in sys.argv: > > > print > > > print " help.py Version", _ver_, "Copyright RDEG (c) 2007" > > > print ''' > > > > Options : -h, --help -- display this message > > > Progam Exit (0)''' > > > sys.exit(0) > > > else: > > > arg = sys.argv[1:] > > > print 'print arg', arg > > > print 'type(arg):', type(arg) > > > print 'arg is True?', arg == True > > > print " help.py version", _ver_, "Copyright RDEG (c) 2007" > > > print " ", arg, "is an unrecognized option." > > > print " Progam Exit (0)" > > > sys.exit(0) > > > > > I hope this helps (I have tried to post this twice already but it > seems to be going somewhere else) you help me. > > What I would like to happen is: > else: > arg = sys.argv[1:] > print 'print arg', arg > print 'type(arg):', type(arg) > print 'arg is True?', arg == True > if arg != True: > print " No Option Provided" > print " help.py version", _ver_, "Copyright RDEG (c) 2007" > print " ", arg, "is an unrecognized option." > print " Progam Exit (0)" > sys.exit(0) > > But as you can see by my output ['-o'] seems to be False as well as [] > so the if happens regardless. > > According to the "Book", ['-o'] should return True which should fail > the if, no? You're mistaking the porperties of an object for the object itself. if arg: tests the property (of being empty). if arg==True: tests the type property (whether a list is a boolean). Change the code I gave above to be: print if arg: print 'The argument given was:',arg else: print 'No argument given' print then you'll get ## C:\python25\user>python arghhh!.py -o ## print arg ['-o'] ## type(arg): ## arg is True? False ## ## The argument given was: ['-o'] ## ## help.py version 1.0 Copyright RDEG (c) 2007 ## ['-o'] is an unrecognized option. ## Progam Exit (0) ## ## C:\python25\user>python arghhh!.py ## print arg [] ## type(arg): ## arg is True? False ## ## No argument given ## ## help.py version 1.0 Copyright RDEG (c) 2007 ## [] is an unrecognized option. ## Progam Exit (0) From martin at browns-nospam.co.uk Thu May 24 10:52:40 2007 From: martin at browns-nospam.co.uk (Martin Evans) Date: Thu, 24 May 2007 15:52:40 +0100 Subject: Invalid thread state for this thread Message-ID: I know this has been seen before but it is not making too much sense (after reading many posts). It all appears to work fine but then dies after about 40 invocations. My app has Python embedded, it is embedded as part of a dll which initializes python and finalizes on load and unload (see below). When a script needs to be run, I create a new thread, let the script complete and close the thread. The thread contains the following type arrangement: PythonThread() { hScriptFile = OpenScriptFile(m_szActiveScript); PyEval_AcquireLock(); pInterpreter = Py_NewInterpreter(); Py_SetProgramName(szModuleFileName); PyRun_SimpleFile(hScriptFile,m_szActiveScript); PyErr_Clear(); Py_EndInterpreter(pInterpreter); PyEval_ReleaseLock(); } This appears to work fine accept that after around 30-40 invocations I always get the "Invalid thread state for this thread". ie the app and dll stay loaded and I click my "run" button manually about 40 times. In this test it is a simple "hello world" type script. The size of the script does not appear to matter. The dll is coded something like this: DllLoad() { Py_Initialize(); PyEval_InitThreads(); m_mainThreadState = PyThreadState_Get(); PyEval_ReleaseLock(); } DllUnload() (not called as part of this test) { PyEval_AcquireLock(); PyThreadState_Swap(m_mainThreadState); Py_Finalize(); } The app has been designed to allow a second interpreter to run independently (thus the need for multiple thread support) and this also appears to work fine, but for this test only this one thread was used. I have a compiled version of 2.4.2. Any ideas would be appreciated. Martin From sjmachin at lexicon.net Sat May 5 02:34:05 2007 From: sjmachin at lexicon.net (John Machin) Date: 4 May 2007 23:34:05 -0700 Subject: How to check if a string is empty in python? In-Reply-To: <1hxls08.1821ogi1l0n338N%aleax@mac.com> References: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> <1178154290.811928.208900@h2g2000hsg.googlegroups.com> <1hxia6q.18rflwk1mez8vhN%aleax@mac.com> <1hxls08.1821ogi1l0n338N%aleax@mac.com> Message-ID: <1178346845.149417.212900@h2g2000hsg.googlegroups.com> On May 5, 12:19 pm, a... at mac.com (Alex Martelli) wrote: > Larry Bates wrote: > > ... > > > Isn't deprecated like depreciated but not quite to zero yet? > > No. "To deprecate" comes from a Latin verb meaning "to ward off a > disaster by prayer"; when you're saying you deprecate something, you're > saying you're praying for that something to disappear, go away; in a > secular context, you're earnestly imploring people to NOT do it. > > "To depreciate" comes from a Latin verb meaning "to reduce the price"; > when you're saying you depreciate something, you're saying you put on > that something a lower price (and, by extension, a lower value) than it > has (or, more commonly, used to have). You're not necessarily saying > it's worth nothing at all (accountants sometimes deem an asset "fully > depreciated" to mean something close to that, but the adverb "fully" is > crucial to this meaning), just that it's worth "less than before". Seeing this thread has already deteriorated [another word with Latin ancestry, not to be conflated with "posteriorated"] to the level of a debate about how many angels can stand shoulder-to-shoulder between the quotes surrounding the repr of an empty string, I presume it's OK if I remark that a "fully depreciated" asset is one that has a *book* value of zero [essentially that the whole of its original cost has been written off (i.e. claimed as a tax deduction)] , and that this has absolutely nothing to do with the true worth of the asset. > > The two terms got somewhat entwined, no doubt because their spelling is > so similar (even though etimology and pronunciation are poles apart), > but the "correct" meanings and usage are still well distinct. > > Alex From fabian.conrad at gmail.com Sat May 12 01:02:05 2007 From: fabian.conrad at gmail.com (fabian.conrad at gmail.com) Date: 11 May 2007 22:02:05 -0700 Subject: help with Python C-API, tuple object In-Reply-To: References: <1178943066.289330.58690@w5g2000hsg.googlegroups.com> Message-ID: <1178946125.822277.150740@k79g2000hse.googlegroups.com> On May 12, 2:49 pm, "Carsten Haese" wrote: > On 11 May 2007 21:11:06 -0700, fabian.conrad wrote > > > Hi, > > sorry for the rather basic question but I've searched everywhere and > > don't find an answer. > > I want to call PyObject_CallObject from the Python C-API and pass a > > tuple I've created from a C-array > > > How can I pass the tuple as an object rather then having to declare > > the python function with the number of arguments equal to the no of > > elements in the tuple? > > The documentation athttp://docs.python.org/api/object.htmllists various Call > flavors. The one you chose will unpack the tuple as if you called > pFunc(*pArgs), which results in the undesired behavior of pFunc receiving > three arguments. You want it to receive one argument that is the tuple pArgs. > > One (bad) way of achieving this would be to build another tuple of size one, > stick pArgs into it, and pass that size-one tuple to PyObject_CallObject. A > better way is to use PyObject_CallFunctionObjArgs. If I'm not mistaken, you'll > want something like > > pValue = PyObject_CallFunctionObjArgs(pFunc, pArgs, NULL); > > Hope this helps, > > -- > Carsten Haesehttp://informixdb.sourceforge.net Thanks billions!!! Works perfect, the world would be a lot worse without Pro's like you guys helping newbies like me ;-) From mail at microcorp.co.za Tue May 8 02:24:01 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 8 May 2007 08:24:01 +0200 Subject: Muzzle Velocity (was: High resolution sleep (Linux) References: <1178274122.142071.91740@y5g2000hsa.googlegroups.com> Message-ID: <021b01c7913d$43b4bf60$03000080@hendrik> "Dennis Lee Bieber" wrote: > On Sun, 6 May 2007 10:15:26 +0200, "Hendrik van Rooyen" > declaimed the following in comp.lang.python: > > > > A rifle bullet can travel at around 5000 feet per second. > > You've got some fast rifles over there... LOL - true - I stand corrected - I was aware that: 1) All the animals were slaughtered, and the American Civil War fought with rifles of muzzle velocity around 1800 fps. This was before bullets were jacketed - if you try to push a lead slug through a rifled barrel faster than this, it strips and fouls the barrel 2) That the old NATO round (.308 Winchester) travels at around 2500 fps. - and this was some forty years ago, when I did my stint of military duty. So being an idle bugger, I just naturally assumed that the speed would have doubled in the intervening time since I was last involved in this subject. - hence the 5000. Did you know that the first military smokeless powder round was for the French Lebel? - It threw a bronze ball, and could punch through a single brick wall. Battlefields were suddenly far more dangerous places. - Hendrik From bj_666 at gmx.net Tue May 15 09:18:47 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 15 May 2007 15:18:47 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <4648252D.5020704@web.de> <46483740.4050406@web.de> <46498cb1$0$6411$9b4e6d93@newsspool2.arcor-online.net> <46499273.6050806@web.de> <46499a54$0$10199$9b4e6d93@newsspool4.arcor-online.net> <46499B16.2070901@web.de> <4649a08c$0$23148$9b4e6d93@newsspool1.arcor-online.net> <4649A22C.8010207@web.de> <4649A46D.8070504@korteklippe.de> Message-ID: In <4649A46D.8070504 at korteklippe.de>, Ren? Fleschenberg wrote: > Stefan Behnel schrieb: >>> 2) The with-statement does have proven substantial benefits, IMO. >> >> Not to me. I don't use it, so no-one should. > > Now you are starting to troll? I thought he starts to argument like you. ;-) Ciao, Marc 'BlackJack' Rintsch From castironpi at gmail.com Tue May 8 17:55:05 2007 From: castironpi at gmail.com (castironpi at gmail.com) Date: 8 May 2007 14:55:05 -0700 Subject: interesting exercise In-Reply-To: References: <1178595952.641173.76540@y80g2000hsf.googlegroups.com> <1178601624.812907.23550@u30g2000hsc.googlegroups.com> Message-ID: <1178661305.063868.130730@e65g2000hsc.googlegroups.com> On May 8, 3:55 pm, James Stroud wrote: > Steven D'Aprano wrote: > > On Tue, 08 May 2007 10:22:05 +0000, James Stroud wrote: > > >>This takes annoying past annoying to some new level of hell to which > >>even satan himself wouldn't venture. > > > And thank you for sharing that piece of spam with us again. It was so much > > less enjoyable to see it the second time. > > > Seriously James, with more and more people using automated spam filters, > > it might not be such a wise idea to keep having your name associated with > > spam content. > > Thank you for the tip. > > James We also have: p=lambda a,n: [ ''.join( y ) for y in eval('[%%s %s]'%' '.join(['for x %i in a'%i for i in range(n)]) %'(%s)'%','.join(['x%i'%i for i in range(n)]) ) ] p('abc',2) #fb: ['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc'] len(p('13579',3)) #fb: 125 edit() File under obscurities. acb From gagsl-py2 at yahoo.com.ar Thu May 17 00:00:57 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 17 May 2007 01:00:57 -0300 Subject: problem with import in python 2.2.3 References: Message-ID: En Thu, 17 May 2007 00:37:26 -0300, Anthony Irwin escribi?: > ./backup_all_mysql_databases.py > Traceback (most recent call last): > File "./backup_all_mysql_databases.py", line 5, in ? > from datetime import date > ImportError: No module named datetime > > Does anyone know why the datetime module is not being found in python > 2.2.3 and how I can make the script work in the older version of python? datetime is included on 2.3 and above. Try copying the 2.3 version on your 2.2 installation, maybe it Just Works... -- Gabriel Genellina From nautiluszd at yahoo.com Sat May 19 11:18:31 2007 From: nautiluszd at yahoo.com (Nautilus) Date: Sat, 19 May 2007 17:18:31 +0200 Subject: Start Message-ID: Can anybody halp me start using Python. From grante at visi.com Thu May 10 09:54:00 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 10 May 2007 13:54:00 -0000 Subject: Single precision floating point calcs? References: <1343v0emvdjr545@corp.supernews.com> <1344t3gauu8b486@corp.supernews.com> Message-ID: <13468voe9439haf@corp.supernews.com> On 2007-05-10, Ross Ridge wrote: > Grant Edwards wrote: >>In the C implementations, the algorithms will be done >>implemented in single precision, so doing my Python prototyping >>in as close to single precision as possible would be "a good >>thing". > > Something like numpy might give you reproducable IEEE 32-bit > floating point arithmetic, but you may find it difficult to > get that out of a IA-32 C compiler. That's OK, I don't run the C code on an IA32. The C target is a Hitachi H8/300. > (You might also want to consider whether you want to using > single precision in your C code to begin with, on IA-32 CPUs > it seldom makes a difference in performance.) Since I'm running the C code on a processor without HW floating point support, using single precision makes a big difference. -- Grant Edwards grante Yow! I have many CHARTS at and DIAGRAMS.. visi.com From __peter__ at web.de Thu May 24 18:07:37 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 25 May 2007 00:07:37 +0200 Subject: Can I reference 1 instance of an object by more names ? rephrase References: <4654289a$0$2326$426a74cc@news.free.fr> <3dc25$4655ebd1$d443bb3a$31378@news.speedlinq.nl> Message-ID: Stef Mientki wrote: > Peter Otten wrote: >> Stef Mientki wrote: >> >>> Maric Michaud wrote: >> >> def bit(index): >>>> def fset(self, value): >> >>>> value = ( value & 1L ) << index >>>> mask = ( 1L ) << index >>>> self._d = ( self._d & ~mask ) | value >>>> def fget(self): >> >>>> return ( self._d >> index ) & 1 >>>> return property(**locals()) >>>> >>>> >>>> class cpu_ports(object) : >> >> p1 = bit(1) >> p2 = bit(2) >> p3 = bit(3) >> p4 = bit(4) >> p5 = bit(5) >> >>> Looks good, but I miss the index :-( >> >> No more. > agreed, > but Python doesn't like it, > and I don't understand why Because the index is now in the locals() dict. Change the return statement to fix the error: > def bit(index): > def fset(self, value): > #index = 5 > value = ( value & 1L ) << index > mask = ( 1L ) << index > self._d = ( self._d & ~mask ) | value > def fget(self): > #index = 5 > return ( self._d >> index ) & 1 return property(fget, fset) Again, I'm confident, again I didn't test. Peter From paul at subsignal.org Sun May 27 15:54:32 2007 From: paul at subsignal.org (paul) Date: Sun, 27 May 2007 21:54:32 +0200 Subject: itertools.groupby In-Reply-To: <611756.61628.qm@web33507.mail.mud.yahoo.com> References: <474296.49047.qm@web33508.mail.mud.yahoo.com> <611756.61628.qm@web33507.mail.mud.yahoo.com> Message-ID: Steve Howell schrieb: > --- Steve Howell wrote: > >> --- 7stud wrote: >> >>> Bejeezus. The description of groupby in the docs >> is >>> a poster child >>> for why the docs need user comments. > > Regarding the pitfalls of groupby in general (even > assuming we had better documentation), I invite people > to view the following posting that I made on > python-ideas, entitled "SQL-like way to manipulate > Python data structures": > > http://mail.python.org/pipermail/python-ideas/2007-May/000807.html > > In the thread, I don't really make a proposal, so much > as a problem statement, but my radical idea is that > lists of dictionaries fit the relational model > perfectly, so why not allow some kind of native SQL > syntax in Python that allows you to manipulate those > data structures more naturally? LINQ? cheers Paul From adam at atlas.st Wed May 9 18:26:16 2007 From: adam at atlas.st (Adam Atlas) Date: 9 May 2007 15:26:16 -0700 Subject: WSGI spec clarification regarding exceptions Message-ID: <1178749576.268576.146770@l77g2000hsb.googlegroups.com> I'm trying to figure out if there's any defined behaviour in PEP 333 for instances where an application returns an iterable as usual without error, but that iterable's next() method eventually raises an exception. Since any data theretofore returned by the iterable must be assumed to have already been written to the client, thus making it impossible to replace the response with a 500 error or somesuch, does the gateway just absorb the exception and cut off the response there? It seems like that's pretty much all it could do, but I'm wondering if that's explicitly specified anywhere (I couldn't find anything about that in the PEP). From google at mrabarnett.plus.com Fri May 25 18:46:34 2007 From: google at mrabarnett.plus.com (MRAB) Date: 25 May 2007 15:46:34 -0700 Subject: Find the closest relative In-Reply-To: References: <1180074710.011260.276830@n15g2000prd.googlegroups.com> <1180078850.074308.286570@p77g2000hsh.googlegroups.com> <1180080540.316522.67020@a35g2000prd.googlegroups.com> Message-ID: <1180133194.008093.247610@q75g2000hsh.googlegroups.com> On May 25, 12:08 pm, "Gabriel Genellina" wrote: > En Fri, 25 May 2007 05:09:00 -0300, jm.sur... at no.spam.gmail.com > escribi?: > > > > > Vehicle > > | > > |--- Two Wheeler > > | | > > | |--- BatteryPowered > > | |--- PetrolPowered > > | |--- DieselPowered > > | > > |--- Three Wheeler > > | | > > | |--- AutoRicksaw > > | > > |--- Four Wheeler > > | | > > | |--- GeneralTrans > > | | |--- Car > > | | |--- Car1 > > | | |--- Car2 > > | | |--- Car3 > > | | > > | |--- PublicTrans > > | | |--- Bus > > | | |--- Bus1 > > | | |--- Bus2 > > | |--- Goods > > | |--- Lorry > > |--- Lorry1 > > |--- Lorry2 > > |--- Lorry3 > > > Now given one instance of some type, I want to choose between second > > and third, whichever > > is closest relative to the first object. > > Eg. > > Instance(Car1), Instance(Lorry1), Instance(AutoRicksaw) => > > Instance(Lorry1) > > If your classes actually form a tree (you have only single inheritance) > then you may use the mro(): > > Car1.mro() = [Car, GeneralTrans, FourWheeler, Vehicle, object] > Lorry1.mro() = [Lorry, Goods, FourWheeler, Vehicle, object] > AutoRicksaw.mro() = [ThreeWeeler, Vehicle, object] > > Now you have to find the first item in Lorr1.mro that appears also in > Car1.mro, and the same for AutoRicksaw.mro; the least index on Car1.mro > wins (Or the least index in the other list; or the least sum; that depends > on your exact definition of "closest relative"). > (Under the Argentinian law, you measure how "close" two relatives are, > starting with one person, going up the tree until you find a common > ancestor, and going down to the other person. That is, summing up the > indices on both "mro" lists for the common ancestor). > The distance between 2 classes is (roughly) the sum of the distances to the root class minus twice the distance from their common ancestor to the root class, or: def Distance(class1, class2): set1, set2 = set(class1.mro()), set(class2.mro()) return len(set1) + len(set2) - 2 * len(set1 & set2) Seems to work OK. From siona at chiark.greenend.org.uk Thu May 10 11:37:07 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 10 May 2007 16:37:07 +0100 (BST) Subject: keyword checker - keyword.kwlist References: <1178806246.179950.147750@l77g2000hsb.googlegroups.com> <_eG0i.142$Hb2.138@read3.inet.fi> Message-ID: In article <_eG0i.142$Hb2.138 at read3.inet.fi>, wrote: [ ... ] >> Try to change the 'input' variable name with other... >Changed input variable to myInput, but the result is still the same. That was good advice, but isn't going to help here. Because "input" isn't a keyword, it's a builtin. If you want to check builtins as well as keywords, you need >>> if myInput in keyword.kwlist + dir(__builtins__): (Although obviously you'd pre-build that list.) >for example, 'else' isn't identified as a keyword by the script though >it exists in keyword.kwlist. ? >>> def check(): ... input = raw_input('Enter identifier to check >> ') ... if input in keyword.kwlist: ... print input, "is keyword" ... else: ... print input, "is not keyword" ... Enter identifier to check >> input input is not keyword >>> check() Enter identifier to check >> else else is keyword >>> -- \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 martin at v.loewis.de Thu May 3 17:46:16 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 03 May 2007 23:46:16 +0200 Subject: hp 11.11 64 bit python 2.5 build gets error "import site failed" In-Reply-To: <1178131203.719353.91360@y80g2000hsf.googlegroups.com> References: <1178131203.719353.91360@y80g2000hsf.googlegroups.com> Message-ID: <463a5828$0$4854$9b622d9e@news.freenet.de> bhochstetler at gmail.com schrieb: > I am on a hp 11.11 machine doing a 64 bit python 2.5 build. When I get > my python executable created and run it, I get the error: > > "import site failed" > OverflowError: signed integer is greater than the maximum. Are you sure about the error message? That error is never produced in Python. Instead, it may print an OverflowError with signed integer is greater than maximum (i.e. no period, no "the"). Regards, Martin From grante at visi.com Fri May 11 16:32:00 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 11 May 2007 20:32:00 -0000 Subject: Interesting list Validity (True/False) References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> <1349ihg6j1e1k95@corp.supernews.com> Message-ID: <1349km0g41b565@corp.supernews.com> On Fri, May 11, 2007 at 01:20:44PM -0700, nufuhsus at gmail.com wrote: > On May 11, 3:55 pm, Grant Edwards wrote: > > You got those results because that's what your program does. > > > > Were you intending it to do something else? If so, you're > > going to have to explain what you wanted, because we can't > According to my output, it seems that arg is False even when I > give an option of '-o' which according to the book should be > True. No? '-o' is not equal to True. However, that does not mean it evaluates to false when tested by an if or while statement. > If arg == ['-o'] then shouldn't arg == True return True and > skip the if? No. See the folloing link regarding the "truth value" of an object: http://docs.python.org/lib/truth.html There are many objects other than True that evaluate to "true" in the context of an if/while statement. Just because an objecty has a "true" truth-value doesn't mean that it is equal to the True object. -- Grant Edwards grante Yow! Why don't you ever at enter any CONTESTS, visi.com Marvin?? Don't you know your own ZIPCODE? From mcPas.De.Spam at mclaveauPas.De.Spam.com Tue May 15 16:28:32 2007 From: mcPas.De.Spam at mclaveauPas.De.Spam.com (Michel Claveau) Date: Tue, 15 May 2007 22:28:32 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: Hi! Yes, for legibility. If letters with accents are possible: d=dict(num?ro=1234, name='L?wis', pr?nom='Martin', t?l?phone='+33123') or p1 = personn() #class p1.num?ro = 1234 p1.name='L?wis' p1.pr?nom='Martin' p1.t?l?phone='+33123' Imagine the same code, is accents are not possible... Don't forget: we must often be connected to databases who already exists -- @-salutations Michel Claveau From sjmachin at lexicon.net Tue May 8 18:03:25 2007 From: sjmachin at lexicon.net (John Machin) Date: 8 May 2007 15:03:25 -0700 Subject: Python regular expressions just ain't PCRE In-Reply-To: <1178660057.587786.95450@e51g2000hsg.googlegroups.com> References: <1178323901.381993.47170@e65g2000hsc.googlegroups.com> <1178380335.646708.260540@h2g2000hsg.googlegroups.com> <1178401499.480169.140940@e65g2000hsc.googlegroups.com> <1178416665.895916.299360@p77g2000hsh.googlegroups.com> <1178660057.587786.95450@e51g2000hsg.googlegroups.com> Message-ID: <1178661805.660766.148080@e65g2000hsc.googlegroups.com> On May 9, 7:34 am, Klaas wrote: > On May 5, 6:57 pm, Wiseman wrote: > > > > There's also the YAGNI factor; most folk would restrict using regular > > > expressions to simple grep-like functionality and data validation -- > > > e.g. re.match("[A-Z][A-Z]?[0-9]{6}[0-9A]$", idno). The few who want to > > > recognise yet another little language tend to reach for parsers, using > > > regular expressions only in the lexing phase. > > > Well, I find these features very useful. I've used a complex, LALR > > parser to parse complex grammars, but I've solved many problems with > > just the PCRE lib. Either way seeing nobody's interested on these > > features, I'll see if I can expose PCRE to Python myself; it sounds > > like the fairest solution because it doesn't even deal with the re > > module - you can do whatever you want with it (though I'd rather have > > it stay as it is or enhance it), and I'll still have PCRE. That's if I > > find the time to do it though, even having no life. > > A polished wrapper for PCRE would be a great contribution to the > python community. If it becomes popular, then the argument for > replacing the existing re engine becomes much stronger. > > -Mike You seem to be overlooking my point that PCRE's unicode support isn't, just like the Holy Roman Empire wasn't. From mlivingstone at internode.on.net Mon May 7 01:42:54 2007 From: mlivingstone at internode.on.net (Mark Livingstone) Date: Mon, 07 May 2007 15:42:54 +1000 Subject: Help creating Tiger hash function in Python Message-ID: <133tf2ucg5dpd0f@corp.supernews.com> Hello! I am a Uni student and for a project in Information Systems Security due in just under two weeks, I have tried to make a Python version of the Biham / Anderson Tiger Hash function. I have put the original C source and my two files Tiger.py and doHash.py on my website: http://www.users.on.net/~mlivingstone/ My problems are doubtless basic since I have been teaching myself Python. My best knowledge is Java :-( Firstly, in doHash.py, I cannot invoke tiger() without getting unbounded errors and / or complaints about no such method. The C code is peppered with typedefs for word64 and word 32 and byte and I am unsure how to treat these. t2, t3, t4 are some sort of index into the S-Box table. How can I pythonise them? I don't expect you to write my program for me but any help / clues would be gratefully received. I have been using the latest Core Python Programming 2E by Wesley Chun which has been very helpful but I have not found help for these specific areas. I have taken out all the Bigendian code, Alpha code and ternary operator within ternary operator code but the C is still a bit complex for me. Many thanks in advance for your help MarkL From justin.mailinglists at gmail.com Wed May 23 02:39:07 2007 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: 22 May 2007 23:39:07 -0700 Subject: how to execute a system command? In-Reply-To: Message-ID: <1179902347.007402.275380@q75g2000hsh.googlegroups.com> On May 23, 2:25 pm, wrb wrote: > i want to open a excel file in a button click event. > i found that os.popen4("excel.xls") would work but it is too slow have you tried os.startfile From axjacob at comcast.net Wed May 9 19:44:11 2007 From: axjacob at comcast.net (axjacob at comcast.net) Date: Wed, 09 May 2007 23:44:11 +0000 Subject: e-mailing multiple values Message-ID: <050920072344.9596.46425CCB000DBD7F0000257C22064244130D010C0E06A10407020E@comcast.net> Since e-mail requires a string. Here is what I could do. list.append(item1) list.append(item2) finalstr = ''.join(list) return finalstr -------------- Original message ---------------------- From: "Gabriel Genellina" > En Tue, 08 May 2007 20:19:22 -0300, Ian Clark escribi?: > > > On 5/8/07, anil_jacob at comcast.net wrote: > >> > >> I have a script which has a method which returns multiple strings at > >> once using the yield. I would like to send an e-mail of these values in > >> a single e-mail instead of a mail for each string. How would I be able > >> to do that? > > > > Are you looking for something like the following? If not, try posting > > a small sampling of your code. > > > >>>> def get_data(): > > ... data = ['ham', 'eggs', 'spam'] > > ... for item in data: > > ... yield item > > ... > >>>> all_data = [item for item in get_data()] > >>>> all_data > > ['ham', 'eggs', 'spam'] > > Or simply: all_data = list(get_data()) > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list From maric at aristote.info Mon May 28 04:21:32 2007 From: maric at aristote.info (Maric Michaud) Date: Mon, 28 May 2007 10:21:32 +0200 Subject: Is PEP-8 a Code or More of a Guideline? In-Reply-To: <873b1hq2e8.fsf@benfinney.id.au> References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <87myzqpstb.fsf@benfinney.id.au> <1180282164.427316.51710@p47g2000hsd.googlegroups.com> <873b1hq2e8.fsf@benfinney.id.au> Message-ID: <465A910C.3040808@aristote.info> Ben Finney a ?crit : > Paul McGuire writes: > >> It is a bit reassuring that I am not the only one who turns a blind >> eye to this part of the PEP, that l_c_w_u bothers others as well. > > I see similar support for lower_case, and opposition to > camelCase. It's nice that we're both reassured by what we see. What > now? > So it's actually a matter of taste, and that's why PEP 8 exists, to answer the subject's question, make decision about conventions when only taste is in balance, am I wrong ? Asking the question is like asking : "I don't like the convention, can I use another one for myself ?" I think the answer is, of course, yes, but it is highly discouraged... (and that's why PEP 8 exists after all). From __peter__ at web.de Wed May 30 04:31:50 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 30 May 2007 10:31:50 +0200 Subject: binascii.unhexlify ... not clear about usage, and output References: <1180511251.625790.280260@h2g2000hsg.googlegroups.com> Message-ID: Vishal wrote: > I have a file with a long list of hex characters, and I want to get a > file with corresponding binary characters > > here's what I did: > >>>> import binascii >>>> f1 = 'c:\\temp\\allhex.txt' >>>> f2 = 'c:\\temp\\allbin.txt' >>>> sf = open(f1, 'rU') >>>> df = open(f2, 'w') >>>> slines = sf.readlines() >>>> for line in slines: > ... x = line.rstrip('\n') > ... y = binascii.unhexlify(x) > ... df.write(y) > ... >>>> df.close() >>>> sf.close() Your code is OK, but you have to open f2 in binary mode if your data is truly binary (an image, say). > But what I get is all garbage, atleast textpad and notepad show that > I tried doing it for only one string, and this is what I am seeing on > the interpreter: > >>>> x > '0164' >>>> y > '\x01d' > > I was expecting 'y' would come out as a string with binary > characters!!! What are "binary characters"? > What am i missing here? Can someone please help. What /exactly/ did you expect? Note that "\x01d" and "\x01\x64" are just different renderings of the same string chr(0x01) + chr(0x64). Peter From jpgreer17 at hotmail.com Sat May 26 17:59:50 2007 From: jpgreer17 at hotmail.com (John Greer) Date: Sat, 26 May 2007 16:59:50 -0500 Subject: A project needing Python programmers Message-ID: Hello, I am writing this in the hopes of gathering as many programmers familiar with the Python programming language as possible. There is a project that exists called NVDA. NVDA is a screen reader project that is completely open source. For those of you that may not know what a screen reader is, it is a program that is able to tell a blind user what text or object is on the screen by using a text to speech engine such as SAPI 5 etc. In this way a blind person is able to use the internet, write documents, email and yeah even program their computer. The actual number of programmers for the project is still very small and the popularity of the project is getting quite large. In turn the programmers are finding themselves swamped and always searching for more people able to program in Python. If you wish to check out the project further then go to http://www.nvda-project.org/ Thank you for your time. -------------- next part -------------- An HTML attachment was scrubbed... URL: From grflanagan at yahoo.co.uk Fri May 25 11:34:43 2007 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 25 May 2007 08:34:43 -0700 Subject: extra xml header with ElementTree? In-Reply-To: References: Message-ID: <1180107283.591686.48190@u30g2000hsc.googlegroups.com> On May 25, 3:55 pm, "Tim Arnold" wrote: > Hi, I'm using ElementTree which is wonderful. I have a need now to write out > an XML file with these two headers: > > > > My elements have the root named tocbody and I'm using: > newtree = ET.ElementTree(tocbody) > newtree.write(fname) > > I assume if I add the encoding arg I'll get the xml header: > newtree = ET.ElementTree(tocbody) > newtree.write(fname,encoding='utf-8') > > but how can I get the into the tree? > > python2.4.1,hpux10,ElementTree1.2.6 > #This import is for 2.5, change for 2.4 from xml.etree import cElementTree as ET tocbody = 'onetwo' doc = ET.ElementTree(ET.fromstring(tocbody)) outfile = open('\\working\\tmp\\toctest.xml', 'w') outfile.write('') outfile.write('') doc._write(outfile, doc._root, 'utf-8', {}) outfile.close() ----------------- one two From martin at v.loewis.de Wed May 2 17:09:37 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 02 May 2007 23:09:37 +0200 Subject: hp 11.11 64 bit python 2.5 build gets error "import site failed" In-Reply-To: <1178131203.719353.91360@y80g2000hsf.googlegroups.com> References: <1178131203.719353.91360@y80g2000hsf.googlegroups.com> Message-ID: <4638fe11$0$1098$9b622d9e@news.freenet.de> > "import site failed" > OverflowError: signed integer is greater than the maximum. > > > This is happening in the convertsimple() routine when it tries to > return a signed int: > > ival = PyInt_AsLong(arg) > > the ival is larger than what is defined in INT_MAX. > > Why is this happening in a standard HP 64 bit build? Can you provide a complete gdb/dbx backtrace? Some function tries to convert a Python int into a C int, using the "i" conversion character. Python int uses C long for internal representation, and that particular C long happens to be larger than INT_MAX. This is quite reasonable to happen in principle, but shouldn't happen on interpreter startup. So the questions are: - what are the callers of convertsimple here? (in particular, where does the call to PyArg_ParseTuple come from?) - what is the value of ival? - where does that number come from? The first two questions are best answered with a C debugger. Depending on the answer, the third question may nor may not need an answer. Good luck, Martin P.S. If you are asking in the more abstract sense "why is that happening to me?", the answer is "because you are using an uncommon platform on which Python sees little or no testing". To work around, try a 32-bit build, or switch to Solaris, OS X, Debian Linux, or (heaven forbid) MS Windows :-) From __peter__ at web.de Wed May 30 13:54:11 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 30 May 2007 19:54:11 +0200 Subject: print bypasses calling write method for objects inheriting from file? References: <1180508789.556984.204520@o11g2000prd.googlegroups.com> Message-ID: Gabriel Genellina wrote: > En Wed, 30 May 2007 04:24:30 -0300, Peter Otten <__peter__ at web.de> > escribi?: > >>> I created an object that inherits from file and was a bit surprised to >>> find that print seems to bypass the write method for objects >>> inheriting from file. An optimization I suppose. Does this surprise >>> anyone else at all or am I missing something? >> >> No, your analysis is correct, though I'd consider optimization an >> euphemism >> for bug here. Noone was annoyed enough to write a patch, it seems. > > A one-line patch, I guess, PyFile_CheckExact instead of PyFile_Check. Or a > few lines, checking if the write method is still the builtin one. As this > is the third time I see this question I'll try to submit the patch. Good idea ;) Don't know if it is still applicable, but here's a patch by Jeff Epler: http://groups.google.com/group/comp.lang.python/msg/91d46ff2e05e1476 Peter From tijs_news at artsoftonline.com Wed May 30 10:54:56 2007 From: tijs_news at artsoftonline.com (Tijs) Date: Wed, 30 May 2007 16:54:56 +0200 Subject: xmlrpclib hangs execution References: <45AC0631.8080601@ctw.utwente.nl> <465890FB.4030405@utwente.nl> <465A9DC7.2010708@gmail.com> Message-ID: <465d9040$0$326$e4fe514c@news.xs4all.nl> Arno Stienen wrote: > Arno Stienen wrote: >> Perhaps I should be a bit more specific. When using this code to connect >> to a remote XML-RPC server (C++, xmlrpc++0.7 library): >> >> import xmlrpclib >> server = xmlrpclib.Server("http://10.10.101.62:29500") >> print server.Connection_Request("roberto") >> >> the Python command line 'hangs' until I kill the server. Then, the >> correct output is suddenly displayed: >> >> {'state': 0, 'id_session': '2Z3EUSLJFA13', 'port': 29501, >> 'str': 'Connection accepted. Session attached.'} >> >> Yet a slightly simpler call works flawlessly: >> >> import xmlrpclib >> server = xmlrpclib.Server("http://10.10.101.62:29500") >> print server.Info_RT('Master') >> >> {'state': 0, 'str': 'Info_RT'} >> After having a quick look at your files, I conclude that the problem is in a combination of two problems: 1. Your server is crap. It answers an HTTP/1.0 request by an HTTP/1.1 response without specifying any Connection header and without closing the connection. Normally, a simple client that is not HTTP/1.1-aware expects the connection to close. HTTP/1.1 leaves the connection open by default. 2. The Python implementation of xmlrpc is not very robust. It just waits for the connection to close. A well-written client (like your Java client) would detect the presence of a Content-Length header and use that. The other request is OK because the server closes the connection after having sent the response. Why the difference? Don't know, but it is something server-side. Try to force the server to send HTTP/1.0 responses, or turn off keep-alive, or something like that. Otherwise, adapt xmlrpclib.py to robustly handle 1.1 responses. -- Regards, Tijs From rurpy at yahoo.com Sun May 20 19:51:04 2007 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 20 May 2007 16:51:04 -0700 Subject: docs patch: dicts and sets In-Reply-To: <1179652368.412078.303890@k79g2000hse.googlegroups.com> References: <1178934092.773288.31830@o5g2000hsb.googlegroups.com> <1179100338.610239.299180@k79g2000hse.googlegroups.com> <1179652368.412078.303890@k79g2000hse.googlegroups.com> Message-ID: <1179705063.976309.240660@z24g2000prd.googlegroups.com> On May 20, 3:12 am, Raymond Hettinger wrote: > On May 13, 4:52 pm, r... at yahoo.com wrote: > > Dismissing this as not a "real problem" is both wrong > > and offensive to people taking the time to actually > > propose improvements. > > I should have elaborated on what I meant by saying that there is not a > real problem. Another way to put it is that the docs are sufficient > when they say that set ordering is arbitrary. That should be a cue to > not have *any* expectations about the internal ordering of sets and > dicts. I disagree. When reading the docs, the reader will always have and need assumtions because the docs can't describe all behavior from first priciples. Every programmer will bring and apply his or her understanding of how computers and computer programs operate under the hood. For example, nowhere in the "file" object documentation does is say the files are read starting from byte 0. It relies on the fact that the reader will have that expectation based on previous experience with computers. The are two basics principles that I think most programmers apply sans explicit contradictory information: * That documentation about behavior applies within the bounds of a single execution. * That computers are fundamentaly deterministic (with a possible exception for code running in Microsoft OSes. :-) When I read that sets return items in arbitrary order (and the docs aren't even that specific), I make a natural assumption that, no information provided to the contrary, within a single program execution the order will be arbitrary. Since it says nothing about between execution, the very strong general rule applies: that if no obvious source of volatilty or dependence on environment exist, the same program should produce the same results. > Any further documentation of behavior would be a mistake because it > would of necessity expose implementation specific details. You don't need to make promises to explain surprising behavior. (The word "may" is amazingly useful in these cases :-) A "for example" that exposes implementation details make no promises yet can make clear non-intuative behavior. A concise but clear noting of the surprising behavior seen by the OP would improve the clarity of the documentation, not harm it. > For > instance, there is another intentionally undocumented observable > behavior that sets and dicts change their internal order as new > members are added. It is also intentional that Python makes almost no > promises about the location of objects in memory. IIRC, the only > guarantees made about object identity are that "a is a" is always true > and None can be tested with "is". One last comment. While I treat opinions from Python experts on Python technical details with great respect and appreciation, opinions on documentation should be viewed with much greater skepticism. It can be difficult for an expert to view Python with the same eyes as a non-guru level programmer, yet the latter is (or should be) the target audience of the documentation. [And please, let's not start the reference vs tutorial thing!] From lyoshaM at gmail.com Wed May 23 15:20:04 2007 From: lyoshaM at gmail.com (Lyosha) Date: 23 May 2007 12:20:04 -0700 Subject: Inheriting from Python list object(type?) In-Reply-To: <1179947267.368622.92350@m36g2000hse.googlegroups.com> Message-ID: <1179948003.972160.140910@r19g2000prf.googlegroups.com> On May 23, 12:07 pm, Mangabasi wrote: > On May 23, 1:43 pm, "Jerry Hill" wrote: > > > > > On 23 May 2007 11:31:56 -0700, Mangabasi wrote: > > > > When I modified this to: > > > > class Point(list): > > > def __init__(self,x,y): > > > super(Point, self).__init__([x, y]) > > > self.x = x > > > self.y = y > > > > It worked. > > > Are you sure? > > > >>> p = Point(10, 20) > > >>> p > > [10, 20] > > >>> p.x > > 10 > > >>> p.x = 15 > > >>> p > > [10, 20] > > >>> p[0] > > 10 > > >>> p.x > > 15 > > > That doesn't look like what you were asking for in the original post. > > I'm afraid I don't know anything about numpy arrays or what special > > attributes an object may need to be put into a numpy array though. > > > -- > > Jerry > > This is the winner: > > class Point(list): > def __init__(self, x, y, z = 1): > super(Point, self).__init__([x, y, z]) > self.x = x > self.y = y > self.z = z [...] http://docs.python.org/dev/whatsnew/node3.html announces named tuples in python2.6. This is not what you want since tuples are immutable, but you might get some inspiration from their implementation. Or maybe not. From bj_666 at gmx.net Mon May 14 14:25:09 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 14 May 2007 20:25:09 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: In , Michel Claveau wrote: > And Il1 O0 ? Hm, we should ban digits from identifier names. :-) Ciao, Marc 'BlackJack' Rintsch From aleax at mac.com Wed May 2 10:54:38 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 2 May 2007 07:54:38 -0700 Subject: Why are functions atomic? References: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> <1178044821.864741.235260@o5g2000hsb.googlegroups.com> <1178063341.779617.289690@o5g2000hsb.googlegroups.com> <1178065685.161372.81790@y80g2000hsf.googlegroups.com> <1178083318.404304.76100@q75g2000hsh.googlegroups.com> Message-ID: <1hxh78n.1dtxf9b1vd8r04N%aleax@mac.com> Michael wrote: > Is there a reason for using the closure here? Using function defaults > seems to give better performance: What measurements show you that...? brain:~ alex$ cat powi.py def powerfactory1(exponent): def inner(x): return x**exponent return inner def powerfactory2(exponent): def inner(x, exponent=exponent): return x**exponent return inner brain:~ alex$ python -mtimeit -s'import powi; p=powi.powerfactory1(3)' 'p(27)' 1000000 loops, best of 3: 0.485 usec per loop brain:~ alex$ python -mtimeit -s'import powi; p=powi.powerfactory2(3)' 'p(27)' 1000000 loops, best of 3: 0.482 usec per loop Alex From DustanGroups at gmail.com Thu May 17 08:51:24 2007 From: DustanGroups at gmail.com (Dustan) Date: 17 May 2007 05:51:24 -0700 Subject: try In-Reply-To: References: <1179350291.106871.25640@e65g2000hsc.googlegroups.com> Message-ID: <1179406284.859454.167400@k79g2000hse.googlegroups.com> On May 16, 4:22 pm, Robert Kern wrote: > HMS Surprise wrote: > > I read in the ref man that try-except-finally did not work in earlier > > versions, I am using jython 2.2. Does this imply that try-except > > without finally does not work either? I get a syntax error on the else > > below. Some of the functions embedded in the try section try to > > convert strings to ints, etc and may fail on bad data, thus try seemed > > like a good start for a workaround. > > > Thanks, > > > jh > > > #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > def restoreDevice(self, deviceId, closeTime = time()): > > self.logon() > > try: > > lst = self.getLastUpdatedDevice(deviceId) > > lastUpdated = lst[0] > > incidentId = lst[1] > > print 'L', lastUpdated, 'I', incidentId > > self.restore(incidentId, lastUpdated) > > except: > > else: > > print "couldn't find incident" > > The except: block still needs something in it, even if it is just "pass". For sake of demonstration: def restoreDevice(self, deviceId, closeTime = time()): self.logon() try: lst = self.getLastUpdatedDevice(deviceId) lastUpdated = lst[0] incidentId = lst[1] print 'L', lastUpdated, 'I', incidentId self.restore(incidentId, lastUpdated) except: pass else: print "couldn't find incident" > -- > 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 mtobis at gmail.com Tue May 22 16:56:40 2007 From: mtobis at gmail.com (Michael Tobis) Date: 22 May 2007 13:56:40 -0700 Subject: NOOOOB In-Reply-To: <1179829763.464614.123920@a26g2000pre.googlegroups.com> References: <1179829763.464614.123920@a26g2000pre.googlegroups.com> Message-ID: <1179867400.167030.152910@w5g2000hsg.googlegroups.com> Different strokes for different folks. You might get better advice about where to start if you tell us a bit about yourself. Do you have any other programming experience? Do you have specific goals in mind as a programmer? mt From rahulnag22 at yahoo.com Tue May 8 11:34:48 2007 From: rahulnag22 at yahoo.com (rahulnag22 at yahoo.com) Date: 8 May 2007 08:34:48 -0700 Subject: tkinter - label widget text selection In-Reply-To: <87lkg1r98v.fsf@merkury.smsnet.pl> References: <1178478118.170827.196310@e65g2000hsc.googlegroups.com> <87lkg1r98v.fsf@merkury.smsnet.pl> Message-ID: <1178638488.915459.135080@o5g2000hsb.googlegroups.com> On May 6, 2:24 pm, Rob Wolfe wrote: > rahulna... at yahoo.com writes: > > Hi, > > I guess this is a very trivial question -- > > I am using a label widget to display text (black font in a white > > background color). I am trying to use my mouse to scroll over the > > displayed text to select it, buttkinterdoes not allow me to do it. > > Is there a method/option to do this. > > Try to use an entry widget in read-only state: > > > importTkinteras Tk > root = Tk.Tk() > > ent = Tk.Entry(root, state='readonly', readonlybackground='white', fg='black') > var = Tk.StringVar() > var.set('Some text') > ent.config(textvariable=var, relief='flat') > ent.pack() > root.mainloop() > > > -- > HTH, > Rob Thanks Rob I will try it out...Rahul From rupole at hotmail.com Sun May 6 17:32:00 2007 From: rupole at hotmail.com (Roger Upole) Date: Sun, 6 May 2007 17:32:00 -0400 Subject: WebBrowser: How to cast the document object References: <1178482264.678509.58730@p77g2000hsh.googlegroups.com> Message-ID: <1178487689_43155@sp12lax.superfeed.net> "zdp" wrote in message news:1178482264.678509.58730 at p77g2000hsh.googlegroups.com... > Hi, all, > > My project is based on wxPython, and I need an IE control (i.e. > WebBrowser ActiveX control). Although the wxPython implements a > wrapped version (wx.lib.iewin.IEHtmlWindow), but it doesn't meet all > my demands, because I need to custom many behaviors of the control. > So I thought I should use it through ActiveXWrapper directly. > > So I use makepy to make the typelib of "Microsoft Internet Controls" > and "Microsoft HTML Object Library". Now I can get the document object > of the WebBrowser, and I can cast it into any interface I need like > IHtmlDocument2, IHtmlDocument3... So far, so good. > > The document object also implements a COM interface > IPersistStreamInit, which has a *Load* method. Calling this method can > load any stream into the browser control. Here is the a example using > this method in visual c++: > > IPersistStreamInit* spPSI = NULL; > CStreamOnCString stream(szHTML); > if (m_pHtmlDoc) { > m_hResult = m_pHtmlDoc->QueryInterface(IID_IPersistStreamInit, > (void**)&spPSI); > if( SUCCEEDED(m_hResult) && spPSI ) { > m_hResult = spPSI->Load(static_cast(&stream)); > spPSI->Release(); > } > } > > Now I need to call this method on my document object, my code is just > like > > stream = win32com.client.CastTo(doc, "IPersistStreamInit") > stream.Load(somestr) > > But I got an error: > > ValueError: The interface name 'IPersistStreamInit' does not appear in > the same > library as object ' Library.DispHTMLDocume > nt instance at 0x46359096>' > > I googled and someones says only interfaces inherit from IDispatch can > be used by pythoncom. But IPersistStreamInit interface inherits from > IUnknown. But I just need to use > this interface. Many non-IDispatch interfaces are supported by pythoncom, IPersistStreamInit among them. You should be able to use QueryInterface just as the c++ code does. Try something like stream=doc._oleobj_.QueryInterface(pythoncom.IID_IPersistStreamInit) hth Roger ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From john at datavoiceint.com Tue May 8 12:29:45 2007 From: john at datavoiceint.com (HMS Surprise) Date: 8 May 2007 09:29:45 -0700 Subject: Atttribute error Message-ID: <1178641784.974581.14000@p77g2000hsh.googlegroups.com> The snippet below causes an attribute error. AttributeError: module 'urllib' has no attribute 'urlopen' I am using python 2.2.3. According to the documentation at C: \Python22\Doc\lib urllib has a function called urlopen. #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ import urllib class login(CompactTest): # Recorded test actions. def runTest(self): f = urllib.urlopen("http://www.python.org/") f.read() From jfabiani at yolo.com Mon May 28 10:15:53 2007 From: jfabiani at yolo.com (johnf) Date: Mon, 28 May 2007 07:15:53 -0700 Subject: gui application on cross platform References: <1180332092.551838.258440@z28g2000prd.googlegroups.com> Message-ID: james_027 wrote: > Hi, > > I am using delphi to develop gui application, and wish to make a shift > to python. here are some of my question/concern... > > 1. is python develop gui application a cross platform? just like java > swing? > 2. delphi makes things easy for me like coding for a specific event on > a specific component, could it be the same for python? > 3. are there cool library of component like in delphi available for > python that will make database application more usesable? > 4. where do I start the learning curve? I did some research and I > don't know which one to take among wxwdiget, pygtk, and etc. > > > Thanks > james May I suggest you take a close look at Dabo (www.dabodev.com). Dabo was designed from the ground up to do exact what you are asking for. Take a look at the Dabo screencast (http://leafe.com/screencasts/dataenvironment1.html) which will provide an easy review of most of what Dabo can do. Johnf From zdenekmaxa at yahoo.co.uk Tue May 29 05:03:57 2007 From: zdenekmaxa at yahoo.co.uk (Zdenek Maxa) Date: Tue, 29 May 2007 11:03:57 +0200 Subject: multiline regular expression (replace) Message-ID: <465BEC7D.4080604@yahoo.co.uk> Hi all, I would like to perform regular expression replace (e.g. removing everything from within tags in a XML file) with multiple-line pattern. How can I do this? where = open("filename").read() multilinePattern = "^ .... <\/tag>$" re.search(multilinePattern, where, re.MULTILINE) Thanks greatly, Zdenek From stefan.behnel-n05pAM at web.de Wed May 16 04:29:20 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 16 May 2007 10:29:20 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179288668.417582.210470@u30g2000hsc.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476081.7080609@web.de> <46498514$0$6402$9b4e6d93@newsspool2.arcor-online.net> <1179288668.417582.210470@u30g2000hsc.googlegroups.com> Message-ID: <464AC0E0.3040107@web.de> sjdevnull at yahoo.com wrote: > I even sometimes > read code snippets on email lists and websites from my handheld, which > is sadly still memory-limited enough that I'm really unlikely to > install anything approaching a full set of Unicode fonts. One of the arguments against this PEP was that it seemed to be impossible to find either transliterated identifiers in code or native identifiers in Java code using a web search. So it is very unlikely that you will need to upgrade your handheld as it is very unlikely for you to stumble into such code. Stefan From rene at korteklippe.de Tue May 15 05:58:35 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 15 May 2007 11:58:35 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46476F6B.2000501@web.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476081.7080609@web.de> <46476F6B.2000501@web.de> Message-ID: <4649844b$0$6402$9b4e6d93@newsspool2.arcor-online.net> Stefan Behnel schrieb: > I agree that code posted to comp.lang.python should use english identifiers > and that it is worth considering to use english identifiers in open source > code that is posted to a public OS project site. Note that I didn't say "ASCII > identifiers" but plain english identifiers. All other code should use the > language and encoding that fits its environment best. Unless you are 150% sure that there will *never* be the need for a person who does not know your language of choice to be able to read or modify your code, the language that "fits the environment best" is English. I simply doubt that the problem which this PEP wants to solve actually exists. If you know so little English that you really need non-ASCII identifiers, you will have a very hard time programming Python anyway. My native language is German, and in code I cooperate on with other Germans, I still use English identifiers, even if I am "quite sure" that no non-German will ever have to read the code. It also makes it easier and more beautiful for me if my code uses the same natural language as the stdlib and third party modules do. I do not need non-ASCII characters in Python identifiers. -- Ren? From aleax at mac.com Fri May 4 22:26:17 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 4 May 2007 19:26:17 -0700 Subject: Looping over lists References: Message-ID: <1hxlsky.tgi88sj7tfrN%aleax@mac.com> Tommy Grav wrote: > I have a list: > > a = [1., 2., 3., 4., 5.] > > I want to loop over a and then > loop over the elements in a > that is to the right of the current > element of the first loop > > In C this would be equivalent to: > > for(i = 0; i < n; i++) { > for(j=i+1; j < n; j++) { > print a[i], a[j] > > and should yield: > 1. 2. > 1. 3. > 1. 4. > 1. 5. > 2. 3. > 2. 4. > 2. 5. > 3. 4. > 3. 5. > 4. 5. > > Can anyone help me with the right approach for this > in python? Closes to the C++ code would be: for i in range(n): for j in range(i+1, n): print a[i], a[j] Alex From neokosmos at gmail.com Mon May 7 06:49:09 2007 From: neokosmos at gmail.com (Paul Miller) Date: 7 May 2007 03:49:09 -0700 Subject: Bastion/rexec use cases? Message-ID: <1178534949.324994.60870@l77g2000hsb.googlegroups.com> Bastion and rexec have been deprecated since Python 2.2, so it seems we (the Python community) have gotten along well enough without them. Have these modules not been reimplemented because: a) There are no valid use cases for them. b) Doing so would be difficult and prone to breakage as new features are introduced into the language. c) Nobody has any idea how to do it. d) Nobody cares. e) Guido thinks it's a bad idea. or, some combination of these? From maney at two14.net Sat May 19 13:00:01 2007 From: maney at two14.net (Martin Maney) Date: Sat, 19 May 2007 17:00:01 +0000 (UTC) Subject: zipfile [module and file format, both] stupidly broken References: Message-ID: Larry Bates bristled: > Are you serious? A zipfile with a comment > 4Kbytes. I've never encountered > such a beast. If I hadn't run into one I would never have had a clue that Python's zipfile module had this silly bug. > As with any open source product it is much better to roll up your sleeves > and pitch in to fix a problem than to rail about "how it is stupidly > broken". You are welcome to submit a patch or at the very least a good > description of the problem and possible solutions. If you have gotten a > lot of value out of Python, you might consider this "giving back". You > haven't paid anything for the value it has provided. Ah yes, the old "well, if you found it you should fix it" meme - another reason I found it pretty easy to stop reading this group. It's as stupid a position as it ever was (and FWIW I don't believe I've ever seen any of the real Python developers mouth this crap). Now, I have learned somewhat more than I knew (or ever wanted to know) about zipfiles since I smacked headfirst into this bug, and I've changed the subject line to reflect my current understanding. :-/ Back then it had already occurred to me that *just* changing the size of the step back seemed an incomplete fix: after all, that leaves you scanning through random binary glop looking for the signature. With the signature being four bytes, okay, it will *nearly* always work (just as the exisiting 4K scan does), but... well, from what I've read in the format specs that's about as good as it gets. The alternative, some sort of backwards scan, would avoid the binary glop but has much the same problem, in principle, with finding the signature embedded in the archive comment. Even worse, arguably, since that comment is apparently entirely up to the archive creator, so if there's a way to use a fake central directory for nefarious purposes, that would make it trivial to do. Which is the point where I decided that the file format itself is broken... (oh, and then I came across something from the info-zip crew that said much the same thing, though they didn't mention this particular design, uhm, shortcoming.) So I guess that perhaps the stupidly obvious fix: - END_BLOCK = min(filesize, 1024 * 4) + END_BLOCK = min(filesize, 1024 * 64 + 22) is after all about the best that can be done. (the lack of the size-of-End-Of-Central-Directory-record in the existing code isn't a separate bug, but if we're going to pretend we accomodate all valid zipfiles it wouldn't do to overlook it) So now you may imagine that your rudeness has had the result you intended after all, and I guess it has, though at a cost - well, you probably never cared what I thought about you anyway. BTW, thanks for the pointer someone else gave to the proper place for posting bugs. I'd had the silly idea that I would be able to find that easily at www.python.org, but if I had then I'd not have posted here and had so much fun. -- The most effective way to get information from usenet is not to ask a question; it is to post incorrect information. -- Aahz's Law Apparently denigrating the bug reporter can sometimes result in a patch, too, but I don't think that's in the same spirit. From john at datavoiceint.com Wed May 9 23:08:54 2007 From: john at datavoiceint.com (HMS Surprise) Date: 9 May 2007 20:08:54 -0700 Subject: EOL character Message-ID: <1178766534.648282.166080@e65g2000hsc.googlegroups.com> I have two files apparently identical until I open them with winMerge which reports that they use different EOL characters. They are both jython scripts built using the maxq tool. When the one would not work I stripped it down to bare minimums and then duplicated it. The duplicate works, the original gives an error message stating method closeInc not found. Parts of the original file may have been edited in a python shell, notepad, or even openOffice writer. Thought all would use the Windows default. Your thoughts please. Thanks, jh #Works: # Generated by MaxQ [com.bitmechanic.maxq.generator.JythonCodeGenerator] from PyHttpTestCase import PyHttpTestCase from com.bitmechanic.maxq import Config global validatorPkg if __name__ == 'main': validatorPkg = Config.getValidatorPkgName() # Determine the validator for this testcase. exec 'from '+validatorPkg+' import Validator' class closeInc(PyHttpTestCase): print 'closeInc' def runTest(self): print 'runTest' # ^^^ Insert new recordings here. (Do not remove this line.) # Code to load and run the test if __name__ == 'main': test = closeInc("closeInc") test.runTest() #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #Doesn't work. # Generated by MaxQ [com.bitmechanic.maxq.generator.JythonCodeGenerator] from PyHttpTestCase import PyHttpTestCase from com.bitmechanic.maxq import Config global validatorPkg if __name__ == 'main': validatorPkg = Config.getValidatorPkgName() # Determine the validator for this testcase. exec 'from '+validatorPkg+' import Validator' class closeInc(PyHttpTestCase): print 'closeInc' def runTest(self): print 'runTest' # ^^^ Insert new recordings here. (Do not remove this line.) # Code to load and run the test if __name__ == 'main': test = closeInc("closeInc") test.runTest() From rw at smsnet.pl Fri May 18 14:46:25 2007 From: rw at smsnet.pl (Rob Wolfe) Date: Fri, 18 May 2007 20:46:25 +0200 Subject: emacs python debugging: pydb or pdb fringe interaction References: <87k5v61qpc.fsf@rudin.co.uk> Message-ID: <87veeqnf5q.fsf@merkury.smsnet.pl> Paul Rudin writes: > I can't get the gdb fringe interaction functionality to work with > either pdb or pydb. Any hints as to versions or incantations I should > try? It works for me on Debian Etch and GNU Emacs 21.4.1. I'm using this settings: (setq pdb-path '/usr/lib/python2.4/pdb.py gud-pdb-command-name (symbol-name pdb-path)) (defadvice pdb (before gud-query-cmdline activate) "Provide a better default command line when called interactively." (interactive (list (gud-query-cmdline pdb-path (file-name-nondirectory buffer-file-name))))) -- HTH, Rob From claird at lairds.us Fri May 18 12:45:29 2007 From: claird at lairds.us (Cameron Laird) Date: Fri, 18 May 2007 16:45:29 +0000 Subject: Python-URL! - weekly Python news and links (May 16) References: <1179408898.460231.292340@k79g2000hse.googlegroups.com> Message-ID: <9q11i4-mgf.ln1@lairds.us> In article , Steve Holden wrote: >Steve Holden wrote: >> Beliavsky wrote: >>> On May 16, 2:45 pm, "Cameron Laird" wrote: >>>> QOTW: "Sometimes you just have to take the path of least distaste". - Grant >>>> Edwards >>>> >>>> "I want to choose my words carefully here, so I'm not misunderstood. >>> >>> >>> I think Cameron Laird does a good job with the Python digest but >>> blundered here. Why did he highlight a foul comment having nothing to >>> do with Python? >>> >> In fact it *is* peripherally related, since Gartner are currently doing >> a "survey" on dynamic languages, and there was a considerable effort >> exerted just to make sure that most of the questions actually allowed >> sensible comparisons between the various languages. >> >Please accept my apology: it's Forrester who are currently undertaking >the study on dynamic languages. Anyone interested in helping might look at > >http://python-advocacy.blogspot.com/2007/05/need-help-in-preparing-for-study-of.html > >and (now the study is underway) > >http://python-advocacy.blogspot.com/2007/05/seeking-four-code-samples-for-forrester.html . . . I'll make a few personal comments. I knew the choice of quotes was in questionable taste. I was out to be provocative without being offensive, though. My apologies to Mr. Beliavsky and anyone else I disappointed. On the whole, I still think I constructed the QOTWs appropriately. I have very little patience with The Analysts as a category. I have friends and acquaintances in the business, and I respect them individually. I am VERY skeptical about the sausage they produce at an institutional level, and can only experience its making for a few minutes at a time. I know Gartner and Forrester are different--they really are. For me, the differences pale in comparison to the dreary simi- larities. Many of the questions Forrester asks are ones that recur here in comp.lang.python (and elsewhere). I think it's a *great* time to comment on them in a lasting way, and I've set up to encourage that. From showell30 at yahoo.com Sun May 27 11:36:28 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 27 May 2007 08:36:28 -0700 (PDT) Subject: ten small Python programs In-Reply-To: <1180269944.944150.135930@q66g2000hsg.googlegroups.com> Message-ID: <462102.34958.qm@web33505.mail.mud.yahoo.com> --- BartlebyScrivener wrote: > > For the person new to programming (doesn't come from > C or other > languages), I think you need to add a separate > explanation of string > formatting and how it works, or at least add a > comment that tells them > you are using string formatting so that they can > search and find out > how it works. If your aim is to teach simple > programming concepts, why > confuse them so early on with fancy interpolation? > It's a thought provoking question, and I think my aim here is not exactly to teach simple programming concepts, but more to expose people to what Python looks like. I'm not really intending this page to be a tutorial, as several good tutorials already exist. I'm really targeting a particular niche of people. There are folks that know how to program, but don't know anything about Python, and they really just want to see a bunch of small examples all in one place, without a lot of explanation cluttering their presentation. That may sound like I'm narrowing my audience too much, but I do think it's a niche group that's not adequately addressed. I do hope, though, that folks more in a teaching role can reuse the examples, add better explanation, etc., as needed. Also, I wouldn't mind at all to add a little link called "Read more..." after each example. ____________________________________________________________________________________Ready for the edge of your seat? Check out tonight's top picks on Yahoo! TV. http://tv.yahoo.com/ From showell30 at yahoo.com Mon May 28 13:39:46 2007 From: showell30 at yahoo.com (Steve Howell) Date: Mon, 28 May 2007 10:39:46 -0700 (PDT) Subject: itertools.groupby In-Reply-To: <1180358275.3152.17.camel@localhost.localdomain> Message-ID: <166272.23665.qm@web33501.mail.mud.yahoo.com> --- Carsten Haese wrote: > On Sun, 2007-05-27 at 18:12 -0700, Steve Howell > wrote: > > [...] there is no way > > that "uniquekeys" is a sensible variable [...] > > That's because the OP didn't heed the advice from > the docs that > "Generally, the iterable needs to already be sorted > on the same key > function." > It was I who was complaining about the variable name uniquekeys, because the example itself didn't incorporate a call to sorted(). I would have proposed two solutions to prevent people from falling into the trap/pitfall: 1) Add a call to sorted() in the example. 2) Rename the variable to not_necessarily_unique_keys or something like that. Raymond did the former, so I'm happy. Although I do think, of course, that people need to read docs carefully, I think it was a big trap/pitfall that people might assume the semantics of the SQL "group by" syntax, so I'm glad that Raymond now calls out the pitfall, and compares it to the Unix "uniq" command, which has more similar semantics. > Suppose hypothetically you wanted to show off a > really neat example that > involves chain, izip, and groupby. It's hypothetical for itertools, but I can understand your premise for other modules, where you do more typically need multiple functions from the module to provide meaningful examples. > If the examples > were forced into the > page of function synopses, you'd have to duplicate > it in all three > functions, or randomly pick one function for which > your example is an > example. There's no reason why all three functions couldn't link to the same example on the Examples page, though. > Having a separate examples page that is not > arbitrarily > sectioned by function name makes more sense. > I'd propose a separate examples page that is not arbitrarily sectioned by function name, or not by function name, but which is organized according to the best way to help users use the module. In the case of itertools, I'd see the benefit of a separate section with many examples of groupby(), since it's a very rich function in its capabilities, and it doesn't really require anything else from itertools to write useful programs. ____________________________________________________________________________________Boardwalk for $500? In 2007? Ha! Play Monopoly Here and Now (it's updated for today's economy) at Yahoo! Games. http://get.games.yahoo.com/proddesc?gamekey=monopolyherenow From aleax at mac.com Mon May 28 17:12:32 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 28 May 2007 14:12:32 -0700 Subject: itertools.groupby References: <1180295221.3163.9.camel@localhost.localdomain> <1180313441.598026.198230@d30g2000prg.googlegroups.com> <7x8xb939ut.fsf@ruckus.brouhaha.com> <1180330198.466144.197620@j4g2000prf.googlegroups.com> <7xveed1mnk.fsf@ruckus.brouhaha.com> Message-ID: <1hytsy4.18fwrl71gwf3cgN%aleax@mac.com> Steve Howell wrote: ... > for has_chars, frags in itertools.groupby(lines, > lambda x: len(x) > 0): Hmmm, it appears to me that itertools.groupby(lines, bool) should do just the same job, just a bit faster and simpler, no? Alex From arkanes at gmail.com Fri May 4 16:07:52 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 4 May 2007 15:07:52 -0500 Subject: Why are functions atomic? In-Reply-To: <1178308503.420603.158120@e65g2000hsc.googlegroups.com> References: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> <1178044821.864741.235260@o5g2000hsb.googlegroups.com> <1178063341.779617.289690@o5g2000hsb.googlegroups.com> <1178065685.161372.81790@y80g2000hsf.googlegroups.com> <1178083318.404304.76100@q75g2000hsh.googlegroups.com> <1178260571.160570.299160@p77g2000hsh.googlegroups.com> <1178308503.420603.158120@e65g2000hsc.googlegroups.com> Message-ID: <4866bea60705041307i676946adv499f13bb827503e1@mail.gmail.com> On 4 May 2007 12:55:03 -0700, Michael wrote: > On May 4, 5:49 am, "Chris Mellon" wrote: > > You aren't getting "bit" by any problem with closures - this is a > > syntax problem. > > I understand that it is not closures that are specifically biting me. > However, I got bit, it was unplesant and I don't want to be bit > again;-) > > Thus, whenever I need to pass information to a function, I use default > arguments now. Is there any reason not to do this other than the fact > that it is a bit more typing? > There are different semantics when the thing you're passing is mutable. There's also different semantics when it's rebound within the calling scope, but then the default argument technique is probably what you want. > Michael > > -- > http://mail.python.org/mailman/listinfo/python-list > From gigs at hi.t-com.hr Thu May 3 10:07:37 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Thu, 03 May 2007 16:07:37 +0200 Subject: pyscripter to slow Message-ID: I have some problem with pyscripter. Sometimes when I type pyscripter get to slow (i type 10 chars and pyscripter needs 5 seconds to complete this). This happens mostly on deleting some chars. It is very frustrating. Does someone have same situation? btw My comp is amd athlon x2 4000 2mb cache sapphire am2rd580adv 3200 ati chipset 2GB corsair xm2 sapphire x1650 pro 256mb windows vista From duncan.booth at invalid.invalid Mon May 28 06:14:31 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 28 May 2007 10:14:31 GMT Subject: Can python create a dictionary from a list comprehension? References: <1180299312.207986.4340@k79g2000hse.googlegroups.com> <465a90a8$0$55856$dbd43001@news.wanadoo.nl> <465a94a0$0$98669$dbd4f001@news.wanadoo.nl> Message-ID: "Wim Vogelaar" wrote: > >> >> why this output isn't ordered, giving: >> {2: 3, 4: 5, 6: 7, 8: 9, 10: 11 } >> >> > > I made the original list two elements longer: a = > [1,2,3,4,5,6,7,8,9,10,11,12] > > and to my surprise the output is now ordered, giving: {2: 3, 4: 5, 6: > 7, 8: 9, 10: 11, 12: 13} > ... and it will become unordered again when you get up to storing 32 in the dictionary, and ordered again when you get up to 44. It is an unfortunate side-effect of the way that Python dictionaries work that it often appears when you store small integers as though they are being stored sorted. In fact the order depends on the order in which you inserted the values into the dictionary, the current size allocated to the dictionary, and whether any slots have previously been occupied by other values. In your original output: {8: 9, 2: 3, 4: 5, 10: 11, 6: 7} the keys 2, 4, and 6 are inserted into the 2nd, 4th, 6th slots of the dictionary (counting from 0 and there are initially 8 slots), 8 goes into the 0th slot, 10 would go into the 2nd slot except that is filled so it ends up in the 5th slot. When you insert 12, the initial dictionary is too full (it never fills all the slots), so it is resized to have 32 slots. Again the 32 wraps round to the 0th slot and higher values all collide with filled slots so they end up in less obvious positions: >>> for i in range(12,42,2): print dict.fromkeys(range(2,i,2)) {8: None, 2: None, 4: None, 10: None, 6: None} {2: None, 4: None, 6: None, 8: None, 10: None, 12: None} {2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 14: None} {2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 14: None, 16: None} {2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 14: None, 16: None, 18: None} {2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 14: None, 16: None, 18: None, 20: None} {2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 14: None, 16: None, 18: None, 20: None, 22: None} {2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 14: None, 16: None, 18: None, 20: None, 22: None, 24: None} {2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 14: None, 16: None, 18: None, 20: None, 22: None, 24: None, 26: None} {2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 14: None, 16: None, 18: None, 20: None, 22: None, 24: None, 26: None, 28: None} {2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 14: None, 16: None, 18: None, 20: None, 22: None, 24: None, 26: None, 28: None, 30: None} {32: None, 2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 14: None, 16: None, 18: None, 20: None, 22: None, 24: None, 26: None, 28: None, 30: None} {32: None, 2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 34: None, 14: None, 16: None, 18: None, 20: None, 22: None, 24: None, 26: None, 28: None, 30: None} {32: None, 2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 34: None, 14: None, 16: None, 18: None, 20: None, 22: None, 24: None, 36: None, 26: None, 28: None, 30: None} {32: None, 2: None, 4: None, 38: None, 6: None, 8: None, 10: None, 12: None, 34: None, 14: None, 16: None, 18: None, 20: None, 22: None, 24: None, 36: None, 26: None, 28: None, 30: None} The fact that integers hash to themselves may be unlikely to change, but the sizes of the hash tables, or the conflict resolution strategy when an insertion hits an already used slot could all vary in other versions of Python. From mail at timgolden.me.uk Thu May 10 05:37:44 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 10 May 2007 10:37:44 +0100 Subject: How to convert Unicode string to raw string escaped with HTML Entities In-Reply-To: <1178789127.182810.153040@o5g2000hsb.googlegroups.com> References: <1178787272.922167.79480@q75g2000hsh.googlegroups.com> <1178789127.182810.153040@o5g2000hsb.googlegroups.com> Message-ID: <4642E7E8.1010405@timgolden.me.uk> ldng wrote: > On 10 mai, 11:03, Tim Golden wrote: >> Probably worth having a look at this: >> >> http://effbot.org/zone/unicode-convert.htm > > Great ! You made my day :-) > > Thanks. That's all right, but it's the effbot you need to thank. (Hope Fredrik's reading this). TJG From brandon.mcginty at gmail.com Thu May 31 01:45:01 2007 From: brandon.mcginty at gmail.com (Brandon McGinty) Date: Wed, 30 May 2007 22:45:01 -0700 Subject: Parsing Rdf (Rewrite) Message-ID: <465e60a8.30f4919a.5746.3e3f@mx.google.com> Hi All, I'm trying to parse the rdf catalog at: http://www.gutenberg.org/feeds/catalog.rdf.bz2 I've put it into an _ElementTree as follows: import time import xml.etree.cElementTree as et tree = et.parse('c:/tmp/catalog2.rdf') root = tree.getroot() I would think that I could do: etexts=tree.findall('pgterms:etext') (or something like that), Which would pull out each etext record in the file. I could then do: for book in etexts: print book.get('id') This isn't yielding anything for me, no matter how I write it. Any thoughts on this? What am I doing wrong, or am I even in the realm of possibility, trying to get thee elements by name? Thanks, Brandon -- Brandon McGinty McGinty Soft Ltd. Website design, configuration, and maintenance Python and PHP coder Email:brandon.mcginty at gmail.com MSN:brandon_mcginty at hotmail.com Phone:(480)-202-5790 -------------- next part -------------- An HTML attachment was scrubbed... URL: From frederic.pica at gmail.com Thu May 31 12:02:11 2007 From: frederic.pica at gmail.com (frederic.pica at gmail.com) Date: 31 May 2007 09:02:11 -0700 Subject: Python memory handling In-Reply-To: References: <1180611604.247696.149060@h2g2000hsg.googlegroups.com> Message-ID: <1180627331.756615.132650@k79g2000hse.googlegroups.com> On 31 mai, 17:29, "Josh Bloom" wrote: > If the memory usage is that important to you, you could break this out > into 2 programs, one that starts the jobs when needed, the other that > does the processing and then quits. > As long as the python startup time isn't an issue for you. > > On 31 May 2007 04:40:04 -0700, frederic.p... at gmail.com > > wrote: > > Greets, > > > I've some troubles getting my memory freed by python, how can I force > > it to release the memory ? > > I've tried del and gc.collect() with no success. > > Here is a code sample, parsing an XML file under linux python 2.4 > > (same problem with windows 2.5, tried with the first example) : > > #Python interpreter memory usage : 1.1 Mb private, 1.4 Mb shared > > #Usinghttp://www.pixelbeat.org/scripts/ps_mem.pyto get memory > > information > > import cElementTree as ElementTree #meminfo: 2.3 Mb private, 1.6 Mb > > shared > > import gc #no memory change > > > et=ElementTree.parse('primary.xml') #meminfo: 34.6 Mb private, 1.6 Mb > > shared > > del et #no memory change > > gc.collect() #no memory change > > > So how can I free the 32.3 Mb taken by ElementTree ?? > > > The same problem here with a simple file.readlines() > > #Python interpreter memory usage : 1.1 Mb private, 1.4 Mb shared > > import gc #no memory change > > f=open('primary.xml') #no memory change > > data=f.readlines() #meminfo: 12 Mb private, 1.4 Mb shared > > del data #meminfo: 11.5 Mb private, 1.4 Mb shared > > gc.collect() # no memory change > > > But works great with file.read() : > > #Python interpreter memory usage : 1.1 Mb private, 1.4 Mb shared > > import gc #no memory change > > f=open('primary.xml') #no memory change > > data=f.read() #meminfo: 7.3Mb private, 1.4 Mb shared > > del data #meminfo: 1.1 Mb private, 1.4 Mb shared > > gc.collect() # no memory change > > > So as I can see, python maintain a memory pool for lists. > > In my first example, if I reparse the xml file, the memory doesn't > > grow very much (0.1 Mb precisely) > > So I think I'm right with the memory pool. > > > But is there a way to force python to release this memory ?! > > > Regards, > > FP > > > -- > >http://mail.python.org/mailman/listinfo/python-list Yes it's a solution, but I think it's not a good way, I did'nt want to use bad hacks to bypass a python specific problem. And the problem is everywhere, every python having to manage big files. I've tried xml.dom.minidom using a 66 Mb xml file => 675 Mb of memory that will never be freed. But that time I've got many unreachable object when running gc.collect() Using the same file with cElementTree took me 217 Mb, with no unreachable object. For me it's not a good behavior, it's not a good way to let the system swap this unused memory instead of freeing it. I think it's a really good idea to have a memory pool for performance reason, but why is there no 'free block' limit ? Python is a really really good language that can do many things in a clear, easier and performance way I think. It has always feet all my needs. But I can't imagine there is no good solution for that problem, by limiting the free block pool size or best, letting the user specify this limit and even better, letting the user completely freeing it (with also the limit manual specification) Like: import pool pool.free() pool.limit(size in megabytes) Why not letting the user choosing that, why not giving the user more flexibility ? I will try later under linux with the latest stable python Regards, FP From newsgroups at nospam.demon.co.uk Thu May 31 14:40:04 2007 From: newsgroups at nospam.demon.co.uk (Douglas Woodrow) Date: Thu, 31 May 2007 19:40:04 +0100 Subject: c[:]() References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> Message-ID: On Thu, 31 May 2007 07:49:22, Warren Stringer wrote >> >>def a(): return 'b' >> >>def b(): print 'polly! wakey wakey' >> >>c = {} >> >>c['a'] = b >> >>c[a()]() #works! >> > >> > >> >(typo correction for other easily-confused newbies like myself) >> > >> >I think you mean [...] >Hey Douglas, > >Perhaps I was being too abstract? Here goes: > >,------------------------------- >| def selector(): >| ... >| return funcKey #get down get down >| >| def func(): >| ... >| funcSwitch = {} >| funcSwitch[funcKey] = func >| ... >| funcSwitch[selector()]() Thanks Warren, I was merely pointing out the typing mistake you made in your first example. And yes, your abstract names made it difficult to guess the intention of the original code. With the meaningful names you've just provided, I can see immediately that you intended to write the 2nd working code alternative I suggested: >> Oh no, I get it, you meant... >> ,---- >> | c['b'] = b >> | c[a()]() #works! >> `---- -- Doug Woodrow From george.sakkis at gmail.com Wed May 16 08:54:23 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 16 May 2007 05:54:23 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46473267$0$31532$9b622d9e@news.freenet.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <1179320063.870224.25220@p77g2000hsh.googlegroups.com> On May 13, 11:44 am, "Martin v. L?wis" wrote: > (snipped) > > So, please provide feedback, e.g. perhaps by answering these > questions: > - should non-ASCII identifiers be supported? why? Initially I was on -1 but from this thread it seems that many closed (or semi-closed) environments would benefit from such a change. I'm still concerned though about the segregation this feature encourages. In my (admittedly limited) experience on non-english-speaking environments, everyone used to have some basic command of english and was encouraged to use proper english identifiers; OTOH, the hodgepodge of english keywords/stdlib/3rd party symbols with transliterated to ascii application identifiers was being looked down as clumsy and in fact less readable. Bottom line, -0. > - would you use them if it was possible to do so? in what cases? No, and I would refuse to maintain code that did use them*. George * Unless I start teaching programming to preschoolers or something. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed May 9 14:33:49 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 09 May 2007 20:33:49 +0200 Subject: Inheritance problem References: <1178734168.255175.248800@e51g2000hsg.googlegroups.com> Message-ID: <5aeigdF2p1oghU1@mid.individual.net> amidzic.branko at gmail.com wrote: > class longList(shortList): > > def __init__(self): > > shortList.setList() > > self.setList() Addition: Always call the base class __init__ in your constructor if there exists one, i. e. class longList(shortList) def __init__(self): shortlist.__init__() # [...] Regards, Bj?rn -- BOFH excuse #108: The air conditioning water supply pipe ruptured over the machine room From __peter__ at web.de Mon May 28 05:04:07 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 28 May 2007 11:04:07 +0200 Subject: Can python create a dictionary from a list comprehension? References: <1180299312.207986.4340@k79g2000hse.googlegroups.com> <1180299814.129770.93220@o11g2000prd.googlegroups.com> <1180342133.550619.124250@o11g2000prd.googlegroups.com> Message-ID: half.italian at gmail.com wrote: > Do you think we just shouldn't use list comprehensions to build > dictinaries at all? Or is Stefan's solution acceptable (and pythonic)? Use list comprehensions where you need the resulting list; if you want nothing but the side effects, use a for loop. [Stefan Sonnenberg-Carstens] > a = [1,2,3,4,5,6,7,8,9,10] > aDict = dict([(x,x+1) for x in a if x%2==0]) Stefan's example meets the above criterion, so yes, it's acceptable. In Python 2.5 you would use a generator expression, though: aDict = dict((x, x+1) for x in a if x % 2 ==0) Peter From rene at korteklippe.de Tue May 15 06:01:57 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 15 May 2007 12:01:57 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476081.7080609@web.de> Message-ID: <46498514$0$6402$9b4e6d93@newsspool2.arcor-online.net> Marc 'BlackJack' Rintsch schrieb: > You find it in the sources by the line number from the traceback and the > letters can be copy'n'pasted if you don't know how to input them with your > keymap or keyboard layout. Typing them is not the only problem. They might not even *display* correctly if you don't happen to use a font that supports them. -- Ren? From half.italian at gmail.com Wed May 2 01:31:43 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 1 May 2007 22:31:43 -0700 Subject: os.path.join In-Reply-To: References: <1178072869.844914.59010@u30g2000hsc.googlegroups.com> Message-ID: <1178083903.677905.32710@c35g2000hsg.googlegroups.com> On May 1, 9:23 pm, Elliot Peele wrote: > On Tue, 2007-05-01 at 19:27 -0700, 7stud wrote: > > On May 1, 7:36 pm, Elliot Peele wrote: > > > Why does os.path.join('/foo', '/bar') return '/bar' rather than > > > '/foo/bar'? That just seems rather counter intuitive. > > > > Elliot > > > join( path1[, path2[, ...]]) > > Join one or more path components intelligently. If any component is an > > absolute path, all previous components (on Windows, including the > > previous drive letter, if there was one) are thrown away... > > Yes, but that still doesn't answer my question as to why os.path.join > works that way. I understand that that is how it is written, but why? > > Elliot It makes perfect sense. You are joining two paths that both begin at the root directory. The second path is overwriting the first because they can't both begin at the root and also be parts of one path. A better question is why this doesn't work. >>> pathparts = ["/foo", "bar"] >>> os.path.join(pathparts) ['/foo', 'bar'] This should return a string in my opinion. ~Sean From __peter__ at web.de Sat May 5 02:00:27 2007 From: __peter__ at web.de (Peter Otten) Date: Sat, 05 May 2007 08:00:27 +0200 Subject: Looping over lists References: <64D2C5F9-2896-47C3-8606-B021DB9D378A@mac.com> Message-ID: prad wrote: > On Friday 04 May 2007 18:40:53 Tommy Grav wrote: >> Can anyone help me with the right approach for this >> in python? > > for each in a: > for item in a[a.index(each)+1:]: > print each,item > > will produce > > 1 2 > 1 3 > 1 4 > 1 5 > 2 3 > 2 4 > 2 5 > 3 4 > 3 5 > 4 5 > > a.index(each) gives the index of the each value in the a list. > then you just add 1 to it so you start at the index value beside each's > index. If there are equal items you may not get what you expect: >>> items = [1, 2, 1.0] >>> for a in items: ... for b in items[items.index(a)+1:]: ... print a, b ... 1 2 1 1.0 2 1.0 1.0 2 1.0 1.0 Peter From fabiofz at gmail.com Tue May 15 08:14:33 2007 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Tue, 15 May 2007 09:14:33 -0300 Subject: Pydev 1.3.3 Released Message-ID: Hi All, Pydev and Pydev Extensions 1.3.3 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: ----------------------------------------------------------------- * Quick-fix: When an import is added from the auto-import quick-fix, a code-analysis is requested right after it. * Minor bugs fixed. Release Highlights in Pydev: ---------------------------------------------- * Performance: Optimizations in the code-completion structure. * Debugger: Performance improvements (it will only actually trace contexts that have breakpoints -- it was doing that in a module context before). * Debugger: Step over correctly stops at the previous context. * Debugger: Breakpoint labels correct when class/function name changes. * Quick-Fix: Move import to global scope would not be correct if the last line was a multi-line import. * Outline: Syntax errors will show in the outline. * Outline: Selection on import nodes is now correct. * Outline: Link with editor created. * Outline: Show in outline added to the pydev perspective. * Find Previous Problem: action created (Ctrl+Shift+.). * Extract method refactoring: end line delimiters are gotten according to the document (it was previously fixed to \n). * Extension-points: Documentation added for some of the extension points available. * Perspective: The pydev package explorer has been set as the preferred browser in the pydev perspective. 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 apatheticagnostic at gmail.com Fri May 25 21:01:57 2007 From: apatheticagnostic at gmail.com (kaens) Date: Fri, 25 May 2007 21:01:57 -0400 Subject: Large Amount of Data In-Reply-To: References: Message-ID: <163f0ce20705251801h226aeff6rd7aa92ed2386875c@mail.gmail.com> On 5/25/07, Jack wrote: > I need to process large amount of data. The data structure fits well > in a dictionary but the amount is large - close to or more than the size > of physical memory. I wonder what will happen if I try to load the data > into a dictionary. Will Python use swap memory or will it fail? > > Thanks. > > > -- > http://mail.python.org/mailman/listinfo/python-list > Could you process it in chunks, instead of reading in all the data at once? From ggrabler at gmail.com Tue May 15 15:42:39 2007 From: ggrabler at gmail.com (Georg Grabler) Date: Tue, 15 May 2007 19:42:39 +0000 Subject: Pyrex char *x[] Message-ID: Hello everybody. I finally decided to use pyrex for my tasks wrapping and creating new python objects. Anyway, i ran into struggles. I want an array to be passed to a function, so basically i started the function as follows: def addToList (self, char *array[]): .... This throws an error compiling: "Cannot convert Python object argument to type 'char(*(*))'" So, what i want: Basically, it's a function called by python. This function shall step trough the elements of the array, and call another function: def addList(self, char *str): ... Calling the addList function directly works properly, the function extends a C list for the object. Now i want a function adding the whole array to a the list, using the 2nd function. Does anyone of you have an idea how to archive this? Thank you, Georg From carsten at uniqsys.com Wed May 23 08:07:18 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 23 May 2007 08:07:18 -0400 Subject: Can I reference 1 instance of an object by more names ? rephrase In-Reply-To: References: Message-ID: <1179922038.3409.62.camel@dot.uniqsys.com> On Wed, 2007-05-23 at 12:55 +0200, stef wrote: > Is there another way, without using the dummy index, to achieve the same > results ? > > thanks, > Stef Mientki > > > class cpu_ports(object): > def __init__(self, value=0): > self._d = value > def __setitem__(self, index, value): > print 'vv' > self._d = value > def __getitem__(self, index): > return self._d > def __repr__(self): > return str(self._d) > > name1 = cpu_ports() # create an instance > name2 = name1 # refer with a second name to the same instance > print name1, name2 # test ok > > name1[0] = 25 # assign a value to the instance > print name1, name2 # both references are OK > > name2[0] = 26 # assign another value through the other name > print name1, name2 # both reference are OK > > name2[0] = name1[0] + 13 # use both names at either side of an assignment > print name1, name2 # both references still OK > An assignment without a dummy index or attribute, i.e. a "plain" assignment to name1 or name2, will never do what you want, for two reasons: 1) Assignments modify namespaces, not objects. 2) Assignments can not be overridden. The reason why the code with dummy indexes works is that those are not actually namespace-modifying assignments; they are shorthand notations for __setitem__ method calls. You could achieve the same effect by using an attribute instead: >>> class A(object): pass ... >>> name1 = A() >>> name2 = name1 >>> name1.value = 25 >>> print name1.value, name2.value 25 25 >>> name2.value = 26 >>> print name1.value, name2.value 26 26 >>> name2.value = name1.value + 13 >>> print name1.value, name2.value 39 39 The first statement modifies the namespace by binding the name "name1" to a newly created instance of class A. The second statement modifies the namespace by binding the name "name2" to the very same instance. Until either name1 or name2 are reassigned, the object known as name1 is now *identical* to the object known as name2. Not equal, not indistinguishable, but identical. name1 and name2 are two different names for the same thing. None of the statements that follow are assignments. They are disguised __setattr__ method calls on that one object that is known by two names. Those calls will modify that object (not the namespace), and any changes made to the object known as name1 are immediately visible in the object known as name2, because it's the same object. Hope this helps, -- Carsten Haese http://informixdb.sourceforge.net From nospam at invalid.com Sun May 27 13:51:46 2007 From: nospam at invalid.com (Jack) Date: Sun, 27 May 2007 10:51:46 -0700 Subject: What's the best way to iniatilize a function Message-ID: <7NmdncRrFaG3WMTbnZ2dnUVZ_gWdnZ2d@comcast.com> I have a set of functions to wrap a library. For example, mylib_init() mylib_func() mylib_exit() or handle = mylib_init() mylib_func(handle) mylib_exit(handle) In order to call mylib_func(), mylib_init() has to be called once. When it's done, or when program exits, mylib_exit() should be called once to free resources. I can list all three functions in a module and let the application manage the init call and exit call. Or, better, to have the wrapper function manage these calls. I'm currently using a singleton class (see below.) It seems to work fine. My questions here are: 1. every time I call the function: MyLib().func() part of the object creation code is called, at least to check if there is an existing instance of the class, then return it. So it may not be very efficient. Is there a better way? 2. what's the right way to call mylib_exit()? I put it in __del__(self) but it is not being called in my simple test. STATUS_UNINITIALIZED = 0 STATUS_INITIALIZED = 1 STATUS_ERROR = 2 class MyLib (object): instance = None status = STATUS_UNINITIALIZED def __new__(cls, *args, **kargs): if cls.instance is None: cls.instance = object.__new__(cls, *args, **kargs) return cls.instance def __init__(self): if self.status == STATUS_UNINITIALIZED: mylib_init() self.status = STATUS_INITIALIZED def func(self): return mylib_func() def __del__(self): mylib_exit() From kirk at jobspam/mapssluder.net Sat May 12 17:40:03 2007 From: kirk at jobspam/mapssluder.net (Kirk Job Sluder) Date: Sat, 12 May 2007 17:40:03 -0400 Subject: Basic question References: <1178986686.510137.195490@p77g2000hsh.googlegroups.com> Message-ID: "Cesar G. Miguel" writes: > I've been studying python for 2 weeks now and got stucked in the > following problem: > > for j in range(10): > print j > if(True): > j=j+2 > print 'interno',j > > What happens is that "j=j+2" inside IF does not change the loop > counter ("j") as it would in C or Java, for example. Granted this question has already been answered in parts, but I just wanted to elaborate. Although the python for/in loop is superficially similar to C and Java for loops, they work in very different ways. Range creates a list object that can create an iterator, and the for/in construct under the hood sets j to the results of iterator.next(). The equivalent completely untested java would be something like: public ArrayList range(int n){ a = new ArrayList; //Java 1.5 addition I think. for(int x=0,x > Am I missing something? > > []'s > Cesar > -- Kirk Job Sluder From lyoshaM at gmail.com Fri May 18 03:52:00 2007 From: lyoshaM at gmail.com (Lyosha) Date: 18 May 2007 00:52:00 -0700 Subject: How to convert a number to binary? In-Reply-To: <87lkfm64ry.fsf@benfinney.id.au> References: <1179444832.775573.55830@y80g2000hsf.googlegroups.com> <1179445546.307017.275850@p77g2000hsh.googlegroups.com> <87lkfm64ry.fsf@benfinney.id.au> Message-ID: <1179474720.810650.10510@l77g2000hsb.googlegroups.com> On May 17, 11:10 pm, Ben Finney wrote: [...] > > That's way too complicated... Is there any way to convert it to a > > one- liner so that I can remember it? > > You put in a module so you don't *have* to remember it. > > Then, you use it in this one-liner: > > foo = to_base(15, 2) > > Carrying a whole lot of one-liners around in your head is a waste of > neurons. Neurons are far more valuable than disk space, screen lines, > or CPU cycles. While I agree with this general statement, I think remembering a particular one-liner to convert a number to a binary is more valuable to my brain than remembering where I placed the module that contains this function. I needed the one-liner not to save disk space or screen lines. It's to save time, should I need to convert to binary when doing silly little experiments. I would spend more time getting the module wherever it is I stored it (and rewriting it if it got lost). It's fun, too. From tartifola at gmail.com Thu May 24 12:48:11 2007 From: tartifola at gmail.com (Tartifola) Date: Thu, 24 May 2007 18:48:11 +0200 Subject: No file from stdin Message-ID: <20070524184811.6e439221.tartifola@gmail.com> Hi, suppose a script of python is waiting for a file from the stdin and none is given. How can I make the script to stop and, for example, print an error message? Sorry for the n00b question and thanks From sjmachin at lexicon.net Mon May 14 06:27:42 2007 From: sjmachin at lexicon.net (John Machin) Date: 14 May 2007 03:27:42 -0700 Subject: Element tree errors In-Reply-To: <1179136577.691598.229270@o5g2000hsb.googlegroups.com> References: <1179136577.691598.229270@o5g2000hsb.googlegroups.com> Message-ID: <1179138462.203683.327630@h2g2000hsg.googlegroups.com> On May 14, 7:56 pm, saif.shak... at gmail.com wrote: > HI, > The following code is for replacing the strings localid with > "datapackageid" in an xml document.: > > from xml.etree.ElementTree import ElementTree as et Note there are *two* occurrences of ElementTree in what you have above. The first is the *module* with the parse function that that you are looking for. The second is a *class*. Try this: import xml.etree.ElementTree as et input_xml = open(file_input,'r') tree = et.parse(input_xml) or this: from xml.etree.ElementTree import parse input_xml = open(file_input,'r') tree = parse(input_xml) From nsjmetzger at gmail.com Wed May 2 19:15:08 2007 From: nsjmetzger at gmail.com (minitotoro) Date: 2 May 2007 16:15:08 -0700 Subject: Cannot execute Windows commands via Python in 64-bit In-Reply-To: References: <1178143060.952025.85520@h2g2000hsg.googlegroups.com> <1178145527.014102.11480@l77g2000hsb.googlegroups.com> Message-ID: <1178147703.568351.95740@e65g2000hsc.googlegroups.com> On May 2, 3:46 pm, Larry Bates wrote: > minitotoro wrote: > > On May 2, 3:07 pm, Larry Bates wrote: > >> nsjmetz... at gmail.com wrote: > >>> I have a script that runs fine in Windows 2003 (32-bit). It basically > >>> calls the Windows defrag command. When I try the exact same code on > >>> Windows 2003 (64-bit) I get the following message: > >>> C:\Scripts>autodefrag.py > >>> Starting defragment: defrag -v C: >>c:/Scripts/DEFRAG20070502.log > >>> 'defrag' is not recognized as an internal or external command, > >>> operable program or batch file. > >>> I have tried defrag.exe and even giving it the full path to > >>> defrag.exe. Always the same result. Here is the python code that is > >>> generating this error: > >>> cmd = "defrag -v C: >>c:/Scripts/DEFRAG20070502.log" > >>> print "Starting defragment: ", cmd > >>> errorlevel = os.system(cmd) > >>> Anyone know what the heck is going on and how to fix it? This code > >>> works fine on my 32-bit windows machines. > >>> Thanks. > >> Sounds like system can't find defrag. Usually this is because of a path > >> issue. Are you running the script in the foreground or scheduled? Can > >> you open a command prompt and enter the command and have it work? If > >> you give full path, this shouldn't be the problem. > > >> -Larry > > > I have tried foreground and scheduled (neither works). I can run > > defrag from the command prompt with no problem. If I give it the full > > path in the script it still fails. I am completely befuddled. Help. > > Copy and paste the traceback here for us. > > -Larry I'm sorry, but I'm not familiar with traceback. How do I use it? Thanks. From solisgb at gmail.com Sat May 19 07:55:36 2007 From: solisgb at gmail.com (luis) Date: 19 May 2007 04:55:36 -0700 Subject: dislin titlin and string decode In-Reply-To: <1179572181.557824.213350@k79g2000hse.googlegroups.com> References: <1179572181.557824.213350@k79g2000hse.googlegroups.com> Message-ID: <1179575736.755320.218370@p47g2000hsd.googlegroups.com> the code is: #!/usr/bin/env python def try_dislin(): ...import dislin ...dislin.metafl ('WMF') ...dislin.errdev ('FILE') ...dislin.disini () ...dislin.errmod('PROTOCOL','ON') ...dislin.hwfont () ...dislin.pagera () ...dislin.pagfll (255) ...dislin.color('BLACK') ...dislin.axspos (500, 1600) ...dislin.axslen (2200, 1200) ... ...dislin.name...('x','X') ...dislin.name...('y','Y') ... ...dislin.ticks (10, 'X') ...dislin.ticks (10, 'Y') ...dislin.labels ('FLOAT','X') ...dislin.labels ('FLOAT','Y') ...dislin.incmrk(1) ...dislin.hsymbl (15) ...dislin.chacod('STANDARD') ...dislin.polcrv('LINEAR') ...x=[1.,2.,3.] ...y=[1.,2.,3.] ......... ...a=unicode("Ram?n y Andr?s",'Latin-1') ...dislin.titlin (a.encode('Latin-1'), 1) ... ...min_x_axis=1. ...max_x_axis=3. ...min_y_axis=1. ...max_y_axis=3.... ... ...xstep=(max_x_axis - min_x_axis)/10. ...ystep=(max_y_axis - min_y_axis)/10. ...dislin.graf (min_x_axis,max_x_axis,min_x_axis,xstep \ ......,min_y_axis,max_y_axis,min_y_axis,ystep) ... ...dislin.title() ... ...dislin.curve(x,y, len(x)) ...dislin.color ('foreground') ...dislin.dash...() ...dislin.xaxgit () ...dislin.disfin () try_dislin() print 'end' From joel.hedlund at gmail.com Wed May 23 14:28:30 2007 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Wed, 23 May 2007 20:28:30 +0200 Subject: Slightly OT: Why all the spam? In-Reply-To: <1358ov765ociib4@corp.supernews.com> References: <3bb44c6e0705220008y10f5deb7v86ed82d3f8241761@mail.gmail.com> <1358lu17h16a96e@corp.supernews.com> <1358ov765ociib4@corp.supernews.com> Message-ID: > Then they aren't expired. If they were expired, you wouldn't > see them. Alright, so the solution is not to browse c.l.p articles newer than a week while the boss is behind your back then. :-) Thanks for educating a usenet white belt though! /Joel From iddw at hotmail.com Tue May 8 16:34:28 2007 From: iddw at hotmail.com (Dave Hansen) Date: 8 May 2007 13:34:28 -0700 Subject: Suggestions for how to approach this problem? In-Reply-To: <4640d69b$0$31446$c3e8da3@news.astraweb.com> References: <4640ca5b$0$23392$c3e8da3@news.astraweb.com> <4640d69b$0$31446$c3e8da3@news.astraweb.com> Message-ID: <1178656468.602613.4740@y80g2000hsf.googlegroups.com> On May 8, 3:00 pm, John Salerno wrote: > Marc 'BlackJack' Rintsch wrote: > > I think I have vague idea how the input looks like, but it would be > > helpful if you show some example input and wanted output. > > Good idea. Here's what it looks like now: > > 1. Levy, S.B. (1964) Isologous interference with ultraviolet and X-ray > irradiated > bacteriophage T2. J. Bacteriol. 87:1330-1338. > 2. Levy, S.B. and T. Watanabe (1966) Mepacrine and transfer of R > factor. Lancet 2:1138. > 3. Takano, I., S. Sato, S.B. Levy and T. Watanabe (1966) Episomic > resistance factors in > Enterobacteriaceae. 34. The specific effects of the inhibitors of DNA > synthesis on the > transfer of R factor and F factor. Med. Biol. (Tokyo) 73:79-83. Questions: 1) Do the citation numbers always begin in column 1? 2) Are the citation numbers always followed by a period and then at least one whitespace character? If so, I'd probably use a regular expression like ^[0-9]+\.[ \t] to find the beginning of each cite. then I would output each cite through a state machine that would reduce consecutive whitespace characters (space, tab, newline) into a single character, separating each cite with a newline. Final formatting can be done with paragraph styles in Word. HTH, -=Dave From noagbodjivictor at gmail.com Thu May 3 21:39:07 2007 From: noagbodjivictor at gmail.com (noagbodjivictor at gmail.com) Date: 3 May 2007 18:39:07 -0700 Subject: How do I import a variable from another module? In-Reply-To: <1178242561.677032.4440@y80g2000hsf.googlegroups.com> References: <1178242032.254096.316860@o5g2000hsb.googlegroups.com> <1178242561.677032.4440@y80g2000hsf.googlegroups.com> Message-ID: <1178242747.807572.226360@h2g2000hsg.googlegroups.com> On May 3, 9:36 pm, Andy Terrel wrote: > are you sure your variable isn't in some code block that wouldn't be > read on import? Such as: > > if __name__ == "__main___": > actions = 1 No Andy, I have not put the variable in any code block From kevin.haynes at auxilior.co.uk Wed May 2 20:42:23 2007 From: kevin.haynes at auxilior.co.uk (Kevin Haynes) Date: Thu, 3 May 2007 01:42:23 +0100 Subject: Microsoft's Dynamic Languages Runtime (DLR) In-Reply-To: <1178151313.421106.43130@o5g2000hsb.googlegroups.com> References: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> <1178151313.421106.43130@o5g2000hsb.googlegroups.com> Message-ID: <200705030142.23790.kevin.haynes@auxilior.co.uk> Isn't python cross platform? On Thursday 3 May 2007, Kaz Kylheku wrote: > On May 2, 11:22 am, sturlamolden wrote: > > On Monday Microsoft announced a new runtime for dynamic languages, > > Kindly refrain from creating any more off-topic, cross-posted threads. > Thanks. From bbxx789_05ss at yahoo.com Thu May 3 13:26:17 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 3 May 2007 10:26:17 -0700 Subject: sqlite for mac? In-Reply-To: <6Wn_h.6573$Ut6.1759@newsread1.news.pas.earthlink.net> References: <1177993261.572563.70370@n76g2000hsh.googlegroups.com> <5f56302b0705010308h5c3f64a8ka05cd92de879f6bd@mail.gmail.com> <1178165109.102244.188860@c35g2000hsg.googlegroups.com> <6Wn_h.6573$Ut6.1759@newsread1.news.pas.earthlink.net> Message-ID: <1178213177.120129.58650@o5g2000hsb.googlegroups.com> Per the pysqlite installation instructions, this is the test I ran to confirm that pysqlite installed correctly >from pysqlite2 import test >test.test() and I got output similar to what the docs say should happen: >ran 101 tests in 0.182s My python book, "Beginning Python: From Novice to Professional"(2005), after giving some brief installation instructions for SQLite and pysqlite, says: "Once you have pysqlite installed, you can import it as a module, under the name sqlite." and then the author provides this example: >>>import sqlite >>>conn = sqlite.connect('somedatabase.db') >>>curs = conn.cursor() This cursor can then be used to make SQL queries... >>>conn.commit() >>>conn.close() So that is what I tried. Then I changed "sqlite" to "sqlite2" and "sqlite3" as well. From saif.shakeel at gmail.com Thu May 10 04:55:30 2007 From: saif.shakeel at gmail.com (saif.shakeel at gmail.com) Date: 10 May 2007 01:55:30 -0700 Subject: replacing string in xml file--revisited In-Reply-To: <1178786570.875630.6820@l77g2000hsb.googlegroups.com> References: <1178783809.444544.79640@w5g2000hsg.googlegroups.com> <1178786570.875630.6820@l77g2000hsb.googlegroups.com> Message-ID: <1178787330.478164.310550@n59g2000hsh.googlegroups.com> On May 10, 1:42 pm, half.ital... at gmail.com wrote: > On May 10, 12:56 am, saif.shak... at gmail.com wrote: > > > > > > > Hi, > > I need to replace a string in xml file with something else.Ex > > > - > > rate > > rate > > > > > > > > - > > > Here i have opened an xml > > file(small part is pasted here).I want to replace the word 'localId' > > with 'dataPackageID' wherever it comes in xml file.I have asked this > > before and got a code: > > input_file = open(filename) > > xmlcontents = input_file.read() > > input_file.close() > > xmlcontents = xmlcontents.replace("spam", "eggs") > > output_file = open(filename,"w") > > output_file.write(xmlcontents) > > output_file.close() > > > Although this works alone it is nto > > working when i handle multiple file I/O.Is there a alternative to do > > this.(maybe without read() operation) > > Thanks > > try this... > > #!/usr/bin/env python > > from elementtree import ElementTree as et > tree = et.parse("testxml.xml") > > for t in tree.getiterator("SERVICEPARAMETER"): > t.set("Semantics", "localId") > > tree.write("output.xml") > > ~Sean- Hide quoted text - > > - Show quoted text - #!/usr/bin/env python from elementtree import ElementTree as et tree = et.parse("testxml.xml") for t in tree.getiterator("SERVICEPARAMETER"): t.set("Semantics", "localId") tree.write("output.xml") Is this code complete,where are you replacing the localid with "datapackageid",and where is the new xml being stored. Thanks for the replies From fruels at gmail.com Wed May 2 04:46:17 2007 From: fruels at gmail.com (whitewave) Date: 2 May 2007 01:46:17 -0700 Subject: DiffLib Question Message-ID: <1178095577.190066.158960@y80g2000hsf.googlegroups.com> Hi Guys, I'm a bit confused in difflib. In most cases, the differences found using difflib works well but when I have come across the following set of text: >>> d1 = '''In addition, the considered problem does not have a meaningful traditional type of adjoint ... problem even for the simple forms of the differential equation and the nonlocal conditions. Due to these facts, some serious difficulties arise in the application of the classical methods to such a problem.''' >>> d2 = '''In addition, the considered problem does not have a meaningful traditional type of ... adjoint problem even for the simple forms of the differential equation and the nonlocal conditions. Due ... to these facts, some serious difficulties arise in the application of the classical methods to such a ... problem. ''' Using this line of code: >>> a = difflib.Differ().compare(d1,d2) >>> dif =[] >>> for i in a: ... dif.append(i) ... s = ''.join(dif) I get the following output: ' I n a d d i t i o n , t h e c o n s i d e r e d p r o b l e m d o e s n o t h a v e a m e a n i n g f u l t r a d i t i o n a l t y p e o f- + \n a d j o i n t+ + p+ r+ o+ b+ l+ e+ m+ + e+ v+ e+ n+ + f+ o+ r+ + t+ h+ e+ + s+ i+ m+ p+ l+ e+ + f+ o+ r+ m+ s+ + o+ f+ + t+ h+ e+ + d+ i+ f+ f+ e+ r + e+ n+ t+ i+ a+ l+ + e+ q+ u+ a+ t+ i+ o+ n+ + a+ n+ d+ + t+ h+ e + + n+ o+ n+ l+ o+ c+ a+ l+ + c+ o+ n+ d+ i+ t+ i+ o+ n+ s+ .+ + D+ u+ e \n+ t+ o+ + t+ h+ e+ s+ e+ + f+ a+ c+ t+ s+ ,+ + s+ o+ m+ e+ + s+ e+ r+ i+ o+ u+ s+ + d+ i+ f+ f+ i+ c+ u+ l+ t+ i+ e+ s+ + a+ r+ i+ s+ e+ + i+ n+ + t+ h+ e+ + a+ p+ p+ l+ i+ c+ a+ t+ i+ o+ n+ + o + f+ + t+ h+ e+ + c+ l+ a+ s+ s+ i+ c+ a+ l+ + m+ e+ t+ h+ o+ d+ s + + t+ o+ + s+ u+ c+ h+ + a+ \n p r o b l e m- - e- v- e- n- - f- o- r- - t- h- e- - s- i- m- p- l- e- - f- o- r- m- s- - o- f- - t- h- e- - d- i- f- f- e- r- e- n- t- i- a- l- - e- q- u- a- t- i- o- n- - a- n- d- - t- h- e- - n- o- n- l- o- c- a- l- - c- o- n- d- i- t- i- o- n- s . - D- u- e- - t- o- - t- h- e- s- e- - f- a- c- t- s- ,- - s- o- m- e- - s- e- r- i- o- u- s- - d- i- f- f- i- c- u- l- t- i- e- s- - a- r- i- s- e- - i- n- - t- h- e- - a- p- p- l- i- c- a- t- i- o- n- - o- f- - t- h- e- - c- l- a- s- s- i- c- a- l- - m- e- t- h- o- d- s- - t- o- - s- u- c- h- - a- - p- r- o- b- l- e- m- .' How come the rest of the text after the "adjoint" word is marked as an additional text (while others is deleted) while in fact those text are contained in both d1 and d2?The only difference is that it has a newline. I'm I missing something? Is there a way for me to disregard the newlines and spaces? Python 2.3 WINXP Thanks. Jen From apatheticagnostic at gmail.com Wed May 30 02:27:14 2007 From: apatheticagnostic at gmail.com (kaens) Date: Wed, 30 May 2007 02:27:14 -0400 Subject: Key Listeners In-Reply-To: <1180491273.446164.281990@q75g2000hsh.googlegroups.com> References: <1180491273.446164.281990@q75g2000hsh.googlegroups.com> Message-ID: <163f0ce20705292327k3caff940y82c8f85699d3084a@mail.gmail.com> On 29 May 2007 19:14:33 -0700, Mike wrote: > Are there key listeners for Python? Either built in or third party? > > -- > http://mail.python.org/mailman/listinfo/python-list > I'm pretty sure pygame's got some, don't know about built-ins. From nufuhsus at gmail.com Wed May 9 15:21:16 2007 From: nufuhsus at gmail.com (nufuhsus at gmail.com) Date: 9 May 2007 12:21:16 -0700 Subject: preferred windows text editor? In-Reply-To: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> References: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> Message-ID: <1178738476.023202.63820@o5g2000hsb.googlegroups.com> On May 9, 2:06 pm, "T. Crane" wrote: > Right now I'm using Notepad++. What are other people using? I am very noob to this Python game (though it has been around since 1995 me thinks) and currently (I was using ActivePython and then IDLE) I have been using a combination of Notepad2 and the interpreter (Python 2.5) on a Windblows X[crement]P[roblem] SP2 machine. http://www.flos-freeware.ch/notepad2.html I like IDLE but it seems to stop working after the first few times and I would then re-install it and it would work a few times more. ActivePython was cool but I could not find a version of it that used Python 2.5 (as far as I can see, it only uses 2.4) Notepad2 allows you to launch your script directly from the editor (just like IDLE) and has configurable code highlighting. And it is FREE. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed May 9 10:28:25 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 09 May 2007 16:28:25 +0200 Subject: Simulating simple electric circuits References: <5a9838F2nlbanU1@mid.individual.net> Message-ID: <5ae44aF2ku9rtU1@mid.individual.net> Dave Baum wrote: > Are you trying to do logic simulation (digital) or analog circuit > simulation? Mh, a mix of both :) I want to simulate (in principle simple) magnetic relay circuits. The only "evil tricks" that are used are - shortcuts (e. g. a relay coil is bypassed and thus the relay gets no voltage and it relaxes) - low currents (so a relay has current but doesn't switch) > I don't want to go into too much more detail about this one > because I have a hunch you are really looking at digital, but if > you're interested in the analog approach let me know and I'll fill > in more of the details. Good hunch :) But thanks for the explanations. The fully analog network approach is definitely overkill here. > For digital: > > Event based simulation is typical here. These simulations > generally are concerned with voltage, not current. A circuit > consists of signals and devices. At any given time, each signal > has a certain state (high/low, on/off, 9 level logic, whatever). > Devices are connected to one another by signals. You'll also need > events (a signal, a time, and a new state), and an event queue > (events sorted by time). This is easier if each signal is driven > by at most one device: > > 1) pop the next event off the queue > 2) if the event's signal's state is the same as the new state, go > to 1 > 3) set the event's signal's state to the new state > 4) for each device that is attached to the signal, run the > device's code, which should look at all of its inputs, and post > new events to the queue for any outputs (do this even if the > computed output is the same as the current output). These events > are usually posted for some time in the future (1 > simulation 'tick' is fine). > 5) go to 1 > > This approach is pretty simple to do in Python. I wrote a sample > digital simulator a while back and the core of the simulator was > around 50 lines of code. Rounded out with some basic logic gates > and helper functions to probe the simulation, it was around 150 > lines. It was only 2 level logic and signals could only be driven > by a single device. > > The devices that you want to model (switches, loads, etc) don't > have explicit inputs and outputs, and you'll need to deal with a > signal being driven from multiple sources, so it will get a bit > more complicated. You will probably also need 9 level logic (or > something equivalent) to deal with the fact that ground beats a > source through a load when determining a node's state. > > The basic idea is that each signal has multiple drivers, each of > which has an internal state. When a device wants to set an > output, it only changes its driver's state. The signal then has > code that looks at the state of all drivers and combines them in > some way (this is called a resolution function). That combined > state is what devices see when they read the signal. > > It isn't *that* complicated to implement, but if you can turn your > problem into one with 2 level logic and no multiple drivers, then > it will be easier to write and debug. Sounds more familiar than the analog approach. Maybe I misunderstood something ... but I can't transfer my problem to this way of thinking yet. My biggest problem is the fact that relays aren't really interested in voltage, but current. Also, I find it difficult to transfer this circuit logic to boolean logic I can contruct logic gates from. Sometimes, electric circuits are used in different directions. This is how far I've come with my first approach yet: I set up the mentioned "controller" which, at the beginning, tries out all possible ways through the network and saves them. So, for every possible circuit it knows which switches must be closed and which relays will work if it's "on". In theory, it should now be possible to try out every path, tell the relays if they have voltage/current, and let the relays report back in to the controller if their status changes so it can again test the circuits that may have changed. I haven't tried out the last step, but I will in the next days. Is there any logic error in my strategy? Regards, Bj?rn -- BOFH excuse #122: because Bill Gates is a Jehovah's witness and so nothing can work on St. Swithin's day. From bdesth.quelquechose at free.quelquepart.fr Mon May 21 17:30:44 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 21 May 2007 23:30:44 +0200 Subject: Python Web Programming - looking for examples of solid high-traffic sites In-Reply-To: <1179769189.351376.151440@z24g2000prd.googlegroups.com> References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> <1179769189.351376.151440@z24g2000prd.googlegroups.com> Message-ID: <4652051e$0$19313$426a34cc@news.free.fr> Ivan Tikhonov a ?crit : > Use php. I am lead programmer/maintainer of big website with a lot of > interactive stuff in user's backoffice and with a lot of interraction > to our non-web apps. > > PHP is a crap, but programming for web in python is a pain in the ass. Strange enough, MVHO on this is that PHP is crap *and* that programming "for the web" with it is a king-size PITA, *specially* compared to Python. > And php programmers are cheaper. "cheaper", yes. On an hourly basis. TCO is another problem... > Especialy avoid mod_python. Unless you have to deeply integrate with (and are willing to be forever tied to) Apache, I totally agree on this last one. From ronpro at cox.net Thu May 31 17:29:36 2007 From: ronpro at cox.net (Ron Provost) Date: Thu, 31 May 2007 17:29:36 -0400 Subject: implementing callback function Message-ID: <008a01c7a3ca$cabf1470$6701a8c0@aristotle> Within an application I'm working on. The app is written in multiple layers such that lower layers provided services to higher layers. Ideally in such an architecture, the high-level objects know about lower-level ones, but lower-level objects know nothing about the higher-level ones. There's only one problem. When this software was originally wirtten, one of the low-level objects was given knowledge of a higher-level object. This creates a really ugly dependency that I want to eliminate. My solution (at least what I'm trying to implement) is a classic one. When a low-level routine needs info from a higher-level routine, let the higher-level routine provide a callback which the lower-level routine can call. In this way, the lower-level routine knows nothing about higher-level routines. However, Python is complaining about my implementation. It raises an exception: TypeError: unbound method fn_impl() must be called with X instance as first argument (got int instance instead) For simplicity, I've narrowed it down to a bit of sample code. class X is my low-level service. class X( object ): fn = None @staticmethod def callX( n ): return X.fn( n ) Now, the following global stuff represents my higher-level routines: def fn_impl( n ): # my callback return n + 1 X.fn = fn_impl # register my callback Now I can do something which forces my callback (fn_impl) to get called print X.callX( 3 ) I think I would get '4' printed but instead get the above error. What am I doing wrong? Thanks, Ron -------------- next part -------------- An HTML attachment was scrubbed... URL: From carl at personnelware.com Thu May 24 10:07:07 2007 From: carl at personnelware.com (Carl K) Date: Thu, 24 May 2007 09:07:07 -0500 Subject: installing cx_Oracle. In-Reply-To: References: Message-ID: Getting closer, thanks Bill and Diez. $ export ORACLE_HOME $ ORACLE_HOME=/usr/lib/oracle/xe/app/oracle/product/10.2.0/client $ python setup.py build $ sudo python setup.py install $ python -c "import cx_Oracle" Traceback (most recent call last): File "", line 1, in ? ImportError: libclntsh.so.10.1: cannot open shared object file: No such file or directory guessing I need to add /usr/lib/oracle/xe/app/oracle/product/10.2.0/client/lib/ to some path? btw - anyone know of a .deb that will install this? Carl K From chris-list-python at shenton.org Tue May 29 11:22:12 2007 From: chris-list-python at shenton.org (Chris Shenton) Date: Tue, 29 May 2007 11:22:12 -0400 Subject: RSA SecurID token authentication? Message-ID: <86odk3sli3.fsf@PECTOPAH.shenton.org> Anyone doing python application authentication using RSA SecurID tokens? We have a Pylons app that needs this. I've written code against RSA's API and found the docs terrible and the libraries painful to use. RSA has a RADIUS server fronting their server so I expect I could use that instead, might be easier. This is on Solaris10 x86 which supports PAM but I've never accessed PAM from Python, any pointers? I've done RADIUS before (Cistron, Ascend, FreeRADIUS) but not with Python. Any suggestions? I see a pyrad library, last updated in March 2006; any experience with it? Any other suggestions? Thanks. From theller at ctypes.org Thu May 31 15:48:39 2007 From: theller at ctypes.org (Thomas Heller) Date: Thu, 31 May 2007 21:48:39 +0200 Subject: FAQ: how to vary the byte offset of a field of a ctypes.Structure In-Reply-To: <1180634138.944362.88590@d30g2000prg.googlegroups.com> References: <1180634138.944362.88590@d30g2000prg.googlegroups.com> Message-ID: p.lavarre at ieee.org schrieb: > How do I vary the byte offset of a field of a ctypes.Structure? > > How do I "use the dynamic nature of Python, and (re-)define the data > type after the required size is already known, on a case by case > basis"? > > \\\ > > For example, suppose sometimes I receive the value '\x03hi' + \x04bye' > for the struct: > > class Struct34(ctypes.Structure): > _pack_ = 1 > _fields_ = [('first', 3 * ctypes.c_ubyte), > ('second', 4 * ctypes.c_ubyte)] > > but then sometimes instead I receive the value '\x05left' + \x06right' > for the struct: > > class Struct56(ctypes.Structure): > _pack_ = 1 > _fields_ = [('first', 5 * ctypes.c_ubyte), > ('second', 6 * ctypes.c_ubyte)] > > Thus in general I receive (0xFF ** 2) possible combinations of field > lengths. > > /// > > How do I declare all those hugely many simply regular combinations as > one CTypes.structure? > > I also need to do series of 3 or 4 or 5 strings, not just 2 strings. > But always the byte offsets of the subsequent fields vary when the > byte sizes of the preceding fields vary. The byte size of the > enclosing packed struct varies as the length of the packed bytes it > contains. Often it helps to ask yourself the question: How would I do this in C? IMO, the answer to this question, applied to your problem, would be: *Not* by using a structure. A structure is fine if the definition is fixed, or at most has *one* variable sized field at the very end. Nothing is true for your problem. Thomas From JoeSalmeri at hotmail.com Thu May 31 20:26:11 2007 From: JoeSalmeri at hotmail.com (Joe Salmeri) Date: Thu, 31 May 2007 20:26:11 -0400 Subject: Python 2.5.1 broken os.stat module References: <1180648618.295955.68600@x35g2000prf.googlegroups.com> Message-ID: Hi Tony, I still believe there is a problem. I was searching for os.stat problems so I hadn't seen that one yet. (THANKS) I just read that thread but it seems that the conclusion was that this was a bug in a Microsoft c runtime library. Here's why I think there is still a problem: I created a file and specifically set the created date, last accessed date and last write date to 01/02/2003 12:34:56 After setting the date and time on the file I verified the following: The dir /tc command shows the correct Create date of 01/02/2003 12:34 The dir /ta command shows the correct Access date of 01/02/2003 12:34 The dir /tw command shows the correct Write date of 01/02/2003 12:34 Looking at the properties of the file in Windows Explorer also shows that all 3 dates match. When Python 2.4.2 os.stat is used to get those timestamps all 3 are CORRECT When Python 2.5.1 os.stat is used to get those timestamps all 3 are WRONG and they are off by exact 1 hour 01/02/2003 11:34:56 instead of 01/02/2003 12:34:56 In the case of my above test I know exactly what the timestamp on the file is because I manually set it so that all 3 timestamps are the same. Since Python 2.5.1 does not return the known values for that files timestamps how can it not be a Python 2.5.1 bug? Further testing shows that the results are somewhat inconsistent, many times the create and access date are correct but the Last Write timestamp is wrong. It is generally off by one hour but I have seen situations where it was +1 hour and other situations where it was -1 hour. I even found situations where the python timestamp was 1 minute later. (I know about the 2 second timestamps on FAT, all my filesystems are NTFS). I just found a situation where the python timestamp was 02:51 PM and the windows timestamp was 02:12 PM. DST or timezone changes are not going to make the results be off by 39 minutes? (My timezone is GMT - 5:00). As an additional test I wrote the following Python program which takes a directory name as a paramater. It retrieves all 3 dates for all files in all directories and subdirectories for the specified directory name. First it gets the dates using Python and os.stat, then it runs the dir /tc, dir /ta, and dir /tw commands on the file. Finally it compares the dates and times returned by Python against the dates and times that the Windows dir command is reporting. If you run the program using Python 2.4.2 then ALL dates and times returned by Python 2.4.2 correctly match the dates and times that Windows reports. If you run the program using Python 2.5.1 against the same directory then you get intermittient results. As a quick test I ran it against a directory on my home directory. Python 2.4.2 all dates matched between what the Windows dir command reported and what Python 2.4.2 reported. Python 2.5.1 had the following differences (more than 50% of the time it was wrong) Total Files Processed : 149 Matched All 3 Dates : 70 Did NOT Match All 3 Dates: 79 Matched Create Date : 69 Did NOT Match Create Date: 10 Matched Access Date : 59 Did NOT Match Access Date: 20 Matched Write Date : 11 Did NOT Match Write Date : 68 Here's the source for the check_dates.py program. Run it for youself and see what your results are. import os import stat import sys import time if len(sys.argv) == 1: print print '%s path_to_check' % (sys.argv[0]) print raise SystemExit else: path_to_check = sys.argv[1] file_count = 0 file_match_count = 0 file_no_match_count = 0 create_match_count = 0 create_no_match_count = 0 access_match_count = 0 access_no_match_count = 0 write_match_count = 0 write_no_match_count = 0 for root, dirs, files in os.walk(r'%s' % path_to_check): for file in files: file_count = file_count + 1 file_name = os.path.join(root, file) create_ts_match = False access_ts_match = False write_ts_match = False file_stats = os.stat(file_name) python_create_ts = time.strftime('%m/%d/%Y %I:%M %p', time.localtime(file_stats[stat.ST_CTIME])) python_access_ts = time.strftime('%m/%d/%Y %I:%M %p', time.localtime(file_stats[stat.ST_ATIME])) python_write_ts = time.strftime('%m/%d/%Y %I:%M %p', time.localtime(file_stats[stat.ST_MTIME])) win_create_ts = os.popen('dir /a /tc "%s"' % (file_name)).readlines()[5][0:20] win_access_ts = os.popen('dir /a /ta "%s"' % (file_name)).readlines()[5][0:20] win_write_ts = os.popen('dir /a /tw "%s"' % (file_name)).readlines()[5][0:20] if python_create_ts == win_create_ts: create_ts_match = True if python_access_ts == win_access_ts: access_ts_match = True if python_write_ts == win_write_ts: write_ts_match = True if create_ts_match and access_ts_match and write_ts_match: # All timestamps match file_match_count = file_match_count + 1 else: file_no_match_count = file_no_match_count + 1 print print 'File Name : %s' % (file_name) print if create_ts_match: create_match_count = create_match_count + 1 else: create_no_match_count = create_no_match_count + 1 print 'python_create_ts: %s' % (python_create_ts) print 'win_create_ts : %s' % (win_create_ts) print if access_ts_match: access_match_count = access_match_count + 1 else: access_no_match_count = access_no_match_count + 1 print 'python_access_ts: %s' % (python_access_ts) print 'win_access_ts : %s' % (win_access_ts) print if write_ts_match: write_match_count = write_match_count + 1 else: write_no_match_count = write_no_match_count + 1 print 'python_write_ts : %s' % (python_write_ts) print 'win_write_ts : %s' % (win_write_ts) print # # Show Count Results # print 'Total Files Processed : %s' % (file_count) print print 'Matched All 3 Dates : %s' % (file_match_count) print 'Did NOT Match All 3 Dates: %s' % (file_no_match_count) print print 'Matched Create Date : %s' % (create_match_count) print 'Did NOT Match Create Date: %s' % (create_no_match_count) print print 'Matched Access Date : %s' % (access_match_count) print 'Did NOT Match Access Date: %s' % (access_no_match_count) print print 'Matched Write Date : %s' % (write_match_count) print 'Did NOT Match Write Date : %s' % (write_no_match_count) print "Tony Meyer" wrote in message news:1180648618.295955.68600 at x35g2000prf.googlegroups.com... > On Jun 1, 9:16 am, "Joe Salmeri" wrote: >> I just upgraded from Python 2.4.2 to Python 2.5.1 and have found some >> unexpected behavior that appears to be a bug in the os.stat module. > > Have you read this thread? > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/890eef2197c6f045/5466283a8253cafb?lnk=gst&q=getmtime&rnum=3#5466283a8253cafb > > I suspect that it explains your problem. > > Cheers, > Tony > From larry.bates at websafe.com Fri May 4 16:05:53 2007 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 04 May 2007 15:05:53 -0500 Subject: how to find a lable quickly? In-Reply-To: References: Message-ID: wang frank wrote: > Hi, > > I am a new user on Python and I really love it. > I have a big text file with each line like: > > label 3 > teststart 5 > endtest 100 > newrun 2345 > > I opened the file by uu=open('test.txt','r') and then read the data as > xx=uu.readlines() > > In xx, it contains the list of each line. I want to find a spcefic > labels and read the data. Currently, I > do this by > for ss in xx: > zz=ss.split( ) > if zz[0] = endtest: > index=zz[1] > > Since the file is big and I need find more lables, this code runs > slowly. Are there anyway to speed up the process? I thought to convert > the data xx from list to a dictionay, so I can get the index quickly > based on the label. Can I do that effeciently? > > Thanks > > Frank > > _________________________________________________________________ > ??????????????????2???????????????? > http://campaign.live.jp/dizon/ Are the labels unique? That is, labels are never repeated in the file. If not you are going to need to do some processing because dictionary keys must be unique. Do you have control over the format of the test.txt file. If so a small change would put it into a format that the ConfigParser module can handle which would make it faster because it uses dictionaries. [labels] label=3 teststart=5 endtest=100 newrun=2345 With this you can have different sections [section] with labels under each section. Use configParser to read this and then get options with geting(section, option). -Larry From claird at lairds.us Tue May 1 20:35:56 2007 From: claird at lairds.us (Cameron Laird) Date: Wed, 2 May 2007 00:35:56 +0000 Subject: How can I get the ascii code of a charter in python? References: <1178053581.390873.65850@n76g2000hsh.googlegroups.com> <1178060108.853490.318050@h2g2000hsg.googlegroups.com> Message-ID: In article <1178060108.853490.318050 at h2g2000hsg.googlegroups.com>, John Machin wrote: >On May 2, 7:06 am, "tedpot... at gmail.com" wrote: > >> How can I get the ascii code of a charter in python? > >E.g. download from here: >http://www.gutenberg.org/ebooks/10000 >then in Python, use: >text = open("the_file.txt").read() . . . Humorist. From arimaeug at gmail.com Thu May 10 14:36:07 2007 From: arimaeug at gmail.com (Eugenio Arima) Date: Thu, 10 May 2007 14:36:07 -0400 Subject: Working with Excel Inside Python Message-ID: <251ec7c0705101136p4b7139ffsa5543cf535ee3883@mail.gmail.com> Try # to save dbf3 set file format = 8 excel.ActiveSheet.SaveAs(Filename = "D:\AN00GALL.dbf", FileFormat = 8) -------------- next part -------------- An HTML attachment was scrubbed... URL: From maxm at mxm.dk Mon May 14 09:25:02 2007 From: maxm at mxm.dk (Max M) Date: Mon, 14 May 2007 15:25:02 +0200 Subject: Basic question In-Reply-To: References: <1178986686.510137.195490@p77g2000hsh.googlegroups.com> <1178991933.421386.58500@u30g2000hsc.googlegroups.com> <1178992910.318929.77790@e51g2000hsg.googlegroups.com> Message-ID: <46486330$0$52098$edfadb0f@dread11.news.tele.dk> Dmitry Dzhus skrev: >> Actually I'm trying to convert a string to a list of float numbers: >> str = '53,20,4,2' to L = [53.0, 20.0, 4.0, 2.0] > > str="53,20,4,2" > map(lambda s: float(s), str.split(',')) > > Last expression returns: [53.0, 20.0, 4.0, 2.0] The lambda is not needed there, as float is a callable. map(float, str.split(',')) -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From gagsl-py2 at yahoo.com.ar Mon May 7 03:12:22 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 07 May 2007 04:12:22 -0300 Subject: DiffLib Question References: <1178095577.190066.158960@y80g2000hsf.googlegroups.com> <1178097127.286181.216520@y80g2000hsf.googlegroups.com> <1178097973.516943.248720@y80g2000hsf.googlegroups.com> <1178272004.263635.146300@n59g2000hsh.googlegroups.com> <1178509938.636725.154730@w5g2000hsg.googlegroups.com> Message-ID: En Mon, 07 May 2007 00:52:18 -0300, whitewave escribi?: > I am currently doing the third option. Doing file.read() to both file > to be compared then feed the result to the compare function. > > Let me give you a brief sample of what I want to achieve. > > Using this code >>>> diffline=[] >>>> fileDiff = difflib.Differ().compare(f1, f2) >>>> diffline = list(fileDiff) >>>> finStr = ''.join(diffline) So you are concerned with character differences, ignoring higher order structures. Use a linejunk filter function to the Differ constructor -as shown in my post last Wednesday- to ignore "\n" characters when matching. That is: def ignore_eol(c): return c in "\r\n" fileDiff = difflib.Differ(linejunk=ignore_eol).compare(f1, f2) print ''.join(fileDiff) you get: - T h e s o l v a b+ i l- e+ i+ t+ y c o n d i t i o n s a n d t h e G r e e n ' s f u n c t i o n s o f l i n e a r b o u n d a r y v a l u e- + p r o b l e m s f o r o r d i n a r y- + d i f f e r e n t i a l e q u a t i o n s w i t h s u f f i c i e n t l y s m o o t h c o e f f i c i e n t s h a v e b e e n- + i n v e s t i g a t e d i n d e t a i l b y + m+ a+ n+ y+ - o- t- h- e- r- a u t h o r s \ c i t e { C R 1 , C R 2 , C R 3 , C R 4 , C R 5 } . -- Gabriel Genellina From thomas.guest at gmail.com Mon May 21 11:52:17 2007 From: thomas.guest at gmail.com (thomas.guest at gmail.com) Date: 21 May 2007 08:52:17 -0700 Subject: doctest environment question Message-ID: <1179762737.153434.143030@b40g2000prd.googlegroups.com> I'm not making progress with the following and would appreciate any help. Here's an interpreted Python session. >>> import sys >>> def f(): pass ... >>> this_module = sys.modules[__name__] >>> delattr(this_module, 'f') >>> f() Traceback (most recent call last): File "", line 1, in NameError: name 'f' is not defined Suppose I want to doctest this behaviour. I cut and paste the above into a file "test.txt" then run: python -c "import doctest; doctest.testfile('test.txt')" This gives me unexpected test failures: python -c "import doctest; doctest.testfile('test.txt')" ********************************************************************** File "test.txt", line 5, in test.txt Failed example: delattr(this_module, 'f') Exception raised: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/doctest.py", line 1212, in __run compileflags, 1) in test.globs File "", line 1, in delattr(this_module, 'f') AttributeError: f ********************************************************************** File "test.txt", line 6, in test.txt Failed example: f() Expected: Traceback (most recent call last): File "", line 1, in NameError: name 'f' is not defined Got nothing ********************************************************************** 1 items had failures: 2 of 5 in test.txt ***Test Failed*** 2 failures. From jiang.haiyun at gmail.com Tue May 1 01:55:23 2007 From: jiang.haiyun at gmail.com (jiang.haiyun at gmail.com) Date: 30 Apr 2007 22:55:23 -0700 Subject: Problem with PyQt4 In-Reply-To: <1177943540.857556.235210@y80g2000hsf.googlegroups.com> References: <1177943540.857556.235210@y80g2000hsf.googlegroups.com> Message-ID: <1177998923.287208.93060@y80g2000hsf.googlegroups.com> I rebuild them from source now. Hope this can help me. From kyosohma at gmail.com Wed May 9 14:19:11 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 9 May 2007 11:19:11 -0700 Subject: path stuff In-Reply-To: <1178734266.858048.311740@y5g2000hsa.googlegroups.com> References: <1178734266.858048.311740@y5g2000hsa.googlegroups.com> Message-ID: <1178734751.270516.9230@y5g2000hsa.googlegroups.com> On May 9, 1:11 pm, fscked wrote: > I am walking some directories looking for a certain filename pattern. > This part works fine, but what if I want to exclude results from a > certain directory being printed? > > eg > > d:\dir\mydir1\filename.txt <----------I want to > see this one > d:\dir\mydir2\archived\filename.txt <----------I don't want to > see anything in the "archived" directory > d:\dir\mydir2\filename.txt <----------Again, I do > want to see this one > > I am having a bit of trouble figuring out how to use the path module > to hack up the path to determine if I am in a subdir I care about. So > either don show me the results from a certain directory or just plain > skip a certain directory. Hi, One way to do it would be to grab just the directory path like this: dirPath = os.path.dirname(path) and then use and if: if 'archived' in dirPath: # skip this directory That should get you closer to the answer anyway. Mike From jzgoda at o2.usun.pl Sun May 13 16:01:18 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Sun, 13 May 2007 22:01:18 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46476AB1.7010001@web.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476AB1.7010001@web.de> Message-ID: Stefan Behnel napisa?(a): >> While I can read the code with Hebrew, Russian or Greek names >> transliterated to ASCII, I would not be able to read such code in native. > > Then maybe it was code that was not meant to be read by you? OK, then. As a code obfuscation measure this would fit perfectly. -- Jarek Zgoda http://jpa.berlios.de/ From Tonicopm at yahoo.com Sat May 5 03:47:09 2007 From: Tonicopm at yahoo.com (Tonico) Date: 5 May 2007 00:47:09 -0700 Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? In-Reply-To: <08qk33t594ih0ulmjmev90d22lkfnotgoe@4ax.com> References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> <08qk33t594ih0ulmjmev90d22lkfnotgoe@4ax.com> Message-ID: <1178351229.212479.237050@l77g2000hsb.googlegroups.com> On May 4, 2:08 am, quasi wrote: > On Fri, 04 May 2007 09:37:37 +1200, Gib Bogle > > wrote: > >Ah, so the firefighters were in on the conspiracy! > > No, but the firefighters are very much aware that there is more to > 9/11 than has been officially revealed. > > This is even more true at Pentagon. The firefighters there brought > dogs trained to search for survivors and/or remains and found nothing. > > quasi **************************************************** Ah, Quasi, Midex and the other conspiratorers! You're the living proof that (gullible) idiots don't disappear: there just are new ones every time. Regards Tonio From nogradi at gmail.com Mon May 14 05:21:59 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Mon, 14 May 2007 11:21:59 +0200 Subject: Asyncore Help? In-Reply-To: <60e9f3330705132151q75f2bc2bt25aa04cff93f5b82@mail.gmail.com> References: <60e9f3330705132151q75f2bc2bt25aa04cff93f5b82@mail.gmail.com> Message-ID: <5f56302b0705140221w430281dex33f1b7043fd96891@mail.gmail.com> > I am working on the networking code for a small Multiplayer RPG I'm > working on. I currently have some basic code using threads, but it > seems like asyncore would be far better suited for my needs. However, > I have trouble finding a solid example for what I need. Python.org and > other sites provide simple examples, but they appear more intended for > servers that simply send one peice of data to the client. > > I want to have a server program that is willing to accept commands > sent from the client, and repeatedly wait for data and respond. > Maintaining a long term connection until the client is done playing. > > Besides this I am also stuck with dealing with TCP data streams. I can > receive and send the data (using threads, not yet with asynocore), but > I am unsure how to deal with the streamlike nature of TCP (and would > prefer to use TCP over UDP). I would like to have it so that the > client sends the server a command (such as update position), and then > the data, and have the server update that information on its side > accordingly. > > While basic socket work was rather easy to deal with, this has proved > significantly more difficult. Are there any good free sources for > information on Asyncore, and dealing with TCP? The twisted project might also be a good place for anything related to python and networking: http://twistedmatrix.com/trac/ From ahaas at airmail.net Sun May 13 22:13:52 2007 From: ahaas at airmail.net (Art Haas) Date: Sun, 13 May 2007 21:13:52 -0500 Subject: [ANNOUNCE] Thirty-sixth release of PythonCAD now available Message-ID: <20070514021352.GA10397@artsapartment.org> Hi. I'm pleased to announce the thirty-sixth development release of PythonCAD, a CAD package for open-source software users. As the name implies, PythonCAD is written entirely in Python. The goal of this project is to create a fully scriptable drafting program that will match and eventually exceed features found in commercial CAD software. PythonCAD is released under the GNU Public License (GPL). PythonCAD requires Python 2.2 or newer. The interface is GTK 2.0 based, and uses the PyGTK module for interfacing to GTK. The design of PythonCAD is built around the idea of separating the interface from the back end as much as possible. By doing this, it is hoped that both GNOME and KDE interfaces can be added to PythonCAD through usage of the appropriate Python module. Addition of other PythonCAD interfaces will depend on the availability of a Python module for that particular interface and developer interest and action. The thirty-sixth release of PythonCAD is primarily a bug-fix release. A number or bugs relating to saving and loading user preferences that appeared in the thirty-fifth release have been fixed. Also, several number of bugs involving entity redrawing have been corrected, as well as bugs regarding the typing of various commands within the text entry box in the display. A mailing list for the development and use of PythonCAD is available. Visit the following page for information about subscribing and viewing the mailing list archive: http://mail.python.org/mailman/listinfo/pythoncad Visit the PythonCAD web site for more information about what PythonCAD does and aims to be: http://www.pythoncad.org/ Come and join me in developing PythonCAD into a world class drafting program! Art Haas -- Man once surrendering his reason, has no remaining guard against absurdities the most monstrous, and like a ship without rudder, is the sport of every wind. -Thomas Jefferson to James Smith, 1822 From half.italian at gmail.com Wed May 23 15:35:32 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 23 May 2007 12:35:32 -0700 Subject: Parallel/distributed generator In-Reply-To: <1179943256.575473.62610@q66g2000hsg.googlegroups.com> Message-ID: <1179948932.314833.34930@a35g2000prd.googlegroups.com> On May 23, 11:00 am, George Sakkis wrote: > I'm looking for any existing packages or ideas on how to implement the > equivalent of a generator (in the Python sense, i.e.http://www.python.org/dev/peps/pep-0255/) in a parallel/distributed > way. As a use case, imagine a function that generates a range of > primes. I'd like to be able to do something along the following lines: > > def iterprimes(start=1, end=None): > # ... > yield prime > > # rpc-related initialization > ... > rpc_proxy = some_rpc_lib(iterprimes, start=1e6, end=1e12) > for prime in proxy: > print prime > > Is there any module out there that does anything close to this ? > > George Parellel Python? http://www.parallelpython.com/content/view/17/31/#SUM_PRIMES I've never used it, but looks like it does what you are looking for. ~Sean From SuperM at ssiveBlackHoleAtTheCenterOfTheMilkyWayGalaxy.org Wed May 2 23:20:30 2007 From: SuperM at ssiveBlackHoleAtTheCenterOfTheMilkyWayGalaxy.org (SuperM at ssiveBlackHoleAtTheCenterOfTheMilkyWayGalaxy.org) Date: Wed, 02 May 2007 20:20:30 -0700 Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> Message-ID: <57li33hegq8g81bbcru09gagbpqp6eq3cp@4ax.com> On 2 May 2007 20:05:23 -0700, Midex Gave us: >100% EVIDENCE You AND Rosie are fucking retarded! From jzgoda at o2.usun.pl Fri May 25 03:41:06 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 25 May 2007 09:41:06 +0200 Subject: Reading (and writing?) audio file tags In-Reply-To: <1180025144.752607.63350@h2g2000hsg.googlegroups.com> References: <1180021454.086004.126170@p47g2000hsd.googlegroups.com> <1180025144.752607.63350@h2g2000hsg.googlegroups.com> Message-ID: Paul Moore napisa?(a): >> Anyway, what you want is Mutagen. It handles both Flac and Mp3 tags, as well >> as many others:http://www.sacredchao.net/quodlibet/wiki/Development/Mutagen > > Excellent! The web page you mentioned gave "access denied", but I got > to it via Google's cache, and the download link still worked :-) Guys from QuodLibet seem still block access for MSIE users. Anyway, you may try to get Mutagen source from subversion: $ svn co http://svn.sacredchao.net/svn/quodlibet/trunk/mutagen -- Jarek Zgoda "We read Knuth so you don't have to." From no at spam.here Fri May 4 02:03:43 2007 From: no at spam.here (coyote) Date: Fri, 04 May 2007 02:03:43 -0400 Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? In-Reply-To: <6v1l33tht11glj7fpd1q36qo46ev7i5dvv@4ax.com> References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> <1178162456.929395.139390@q75g2000hsh.googlegroups.com> <4639ce3e$0$29937$afc38c87@news.optusnet.com.au> <4639DB53.397D6243@hotmail.com> <6v1l33tht11glj7fpd1q36qo46ev7i5dvv@4ax.com> Message-ID: The Great Attractor wrote: > On Thu, 03 May 2007 13:53:39 +0100, Eeyore > wrote: > >> >> Peter Webb wrote: >> >>>> Ask yourself WHY havn't I seen this footage before? >>>> >>>> **************************** >>> OK, why haven't you seen this footage before? >> Nice response ! >> >> Graham >> > You're an utter retard. You are terribly repetitive. Don't you know any other insults other that "retard", "nitwit", "cunt", "twit" and variations on *tard? It is very hard to believe you're a grown man, the way you sputter schoolyard insults. - Im starting to think this "Great Attractor" is a pre-adolescent lad simmering with rage and hormones, an active imagination, and a limited vocabulary. Given his fascination with lame double entendre like "Massive Attractor" and his fixation on cunts Id say he's likely a virgin as well, and very, very frustrated about it too. -- ~coyote From rurpy at yahoo.com Tue May 15 18:00:07 2007 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 15 May 2007 15:00:07 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <4649dd55$0$23144$9b4e6d93@newsspool1.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649dd55$0$23144$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <1179266407.687569.222810@y80g2000hsf.googlegroups.com> On May 15, 10:18 am, Ren? Fleschenberg wrote: > Carsten Haese schrieb: > > > Allowing people to use identifiers in their native language would > > definitely be an advantage for people from such cultures. That's the use > > case for this PEP. It's easy for Euro-centric people to say "just suck > > it up and use ASCII", but the same people would probably starve to death > > if they were suddenly teleported from Somewhere In Europe to rural China > > which is so unimaginably different from what they know that it might > > just as well be a different planet. "Learn English and use ASCII" is not > > generally feasible advice in such cultures. > > This is a very weak argument, IMHO. How do you want to use Python > without learning at least enough English to grasp a somewhat decent > understanding of the standard library? Let's face it: To do any "real" > programming, you need to know at least some English today, and I don't > see that changing anytime soon. And it is definitely not going to be > changed by allowing non-ASCII identifiers. snip Another way of framing this discussion could be, "should Python continue to maintain a barrier to it's use by non-English speakers if it is not necessary?" Virtually every guide to programming style I have ever read stresses the importance of variable naming. For example, the Wikipedia article "programming style" mentions variable naming right after layout (indentation, etc) in importance: "Appropriate choices for variable names are seen as the keystone for good style. Poorly-named variables make code harder to read and understand" Even when English-as-non-native-language speakers can understand English words, the level and speed of compression is often far below that of their native language. Denying the ability to use native language identifiers puts these people at a significant disadvantage compared to English speakers with regard to reading (their own!) code. And the justification for this is the hypothetical case that someone who doesn't understand that language *might* *someday* have to read it. Besides the large number of programs that will never be public (far larger than most of the worriers think is my guess), even in public programs this is not necessarily a disaster. A public application written in "Chinese Python" might work perfectly and be completely usable by me, even if it is difficult for me to understand. And why should my difficulty count for more than a Chinese person's difficultly in understanding my "English Python" application? That Python keywords are English is unimportant -- they are a small finite set that can be memorized. Identifiers are a large unbounded set that can't be. That the standard library code and documentation is in English is irrelevant. One shouldn't need to read the standard library code to use it. (That one sometimes has to is a Python flaw that should be fixed -- not bandaided by requiring Python programmers to know English). There is no need to understand english to use the standard library. Documentation has and will (as Python becomes more popular) be translated into native languages. Here is Python standard library documentation in Japanese: http://www.python.jp/doc/release/lib/ While encouraging English in shared/public code is fine, trying by enforce it by continuing to enforce ascii-only identifiers smacks to me of a "whites only country club" mentality. Making Python more accessible to the world (the vast majority of whom do not speak English) can only advance Python. From frank at chagford.com Wed May 30 10:42:44 2007 From: frank at chagford.com (Frank Millman) Date: 30 May 2007 07:42:44 -0700 Subject: Windows build of PostgreSQL library for 2.5 In-Reply-To: <1180534505.421166.83700@q66g2000hsg.googlegroups.com> References: <1180534505.421166.83700@q66g2000hsg.googlegroups.com> Message-ID: <1180536164.370773.183140@q69g2000hsb.googlegroups.com> On May 30, 4:15 pm, Ben Sizer wrote: > I've been looking for a Windows version of a library to interface to > PostgreSQL, but can only find ones compiled under Python version 2.4. > Is there a 2.5 build out there? > > -- > Ben Sizer Is this what you are looking for? http://stickpeople.com/projects/python/win-psycopg/ Frank Millman From half.italian at gmail.com Thu May 10 04:42:50 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 10 May 2007 01:42:50 -0700 Subject: replacing string in xml file--revisited In-Reply-To: <1178783809.444544.79640@w5g2000hsg.googlegroups.com> References: <1178783809.444544.79640@w5g2000hsg.googlegroups.com> Message-ID: <1178786570.875630.6820@l77g2000hsb.googlegroups.com> On May 10, 12:56 am, saif.shak... at gmail.com wrote: > Hi, > I need to replace a string in xml file with something else.Ex > > - > rate > rate > > > > - > > Here i have opened an xml > file(small part is pasted here).I want to replace the word 'localId' > with 'dataPackageID' wherever it comes in xml file.I have asked this > before and got a code: > input_file = open(filename) > xmlcontents = input_file.read() > input_file.close() > xmlcontents = xmlcontents.replace("spam", "eggs") > output_file = open(filename,"w") > output_file.write(xmlcontents) > output_file.close() > > Although this works alone it is nto > working when i handle multiple file I/O.Is there a alternative to do > this.(maybe without read() operation) > Thanks try this... #!/usr/bin/env python from elementtree import ElementTree as et tree = et.parse("testxml.xml") for t in tree.getiterator("SERVICEPARAMETER"): t.set("Semantics", "localId") tree.write("output.xml") ~Sean From solisgb at gmail.com Sat May 19 17:28:51 2007 From: solisgb at gmail.com (luis) Date: 19 May 2007 14:28:51 -0700 Subject: dislin titlin and string decode In-Reply-To: <1179572181.557824.213350@k79g2000hse.googlegroups.com> References: <1179572181.557824.213350@k79g2000hse.googlegroups.com> Message-ID: <1179610131.799695.244180@p77g2000hsh.googlegroups.com> On 19 mayo, 12:56, luis wrote: > Hello! > > I have an unespectedn result with dislin titlin > > dislin.metafl ('WMF') > dislin.disini () > > .... > a="Andr?s or Ram?n" > dislin.titlin (a.encode("Latin-1"), 1) > # not error raised, is ok > .... > > dislin.disfin () > > In the output file all is ok but the title is > > Andr s or Ram n > > Thanks in advance! The problem was the value of dislin.chacod. This must be 'ISO1' not the default ('STANDAR') From grante at visi.com Wed May 30 14:30:02 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 30 May 2007 18:30:02 -0000 Subject: Appending a log file and see progress as program executes References: Message-ID: <135rgla7efk37da@corp.supernews.com> On 2007-05-30, Karim Ali wrote: > Hi, > > I am writing a program that will take several days to execute :) and would > like to append to a log file but be able to open that file at any time and > see the errors that have occured. > > So this is what I am doing: > > ---------------------------------------------- > flog = open('out.log', 'a') > .... > when needed: > sys.stdout=flog > print "error message" sys.stdout.flush() -- Grant Edwards grante Yow! Do I have a lifestyle at yet? visi.com From sickcodemonkey at gmail.com Thu May 10 13:11:05 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Thu, 10 May 2007 13:11:05 -0400 Subject: append In-Reply-To: <1178816546.689849.255070@y5g2000hsa.googlegroups.com> References: <1178816546.689849.255070@y5g2000hsa.googlegroups.com> Message-ID: <2adc542f0705101011y3164db06n3447c4263ae15249@mail.gmail.com> http://docs.python.org/tut/node7.html Yes there is a pop function. "An example that uses most of the list methods: >>> a = [66.25, 333, 333, 1, 1234.5] >>> print a.count(333), a.count(66.25), a.count('x') 2 1 0 >>> a.insert(2, -1) >>> a.append(333) >>> a [66.25, 333, -1, 333, 1, 1234.5, 333] >>> a.index(333) 1 >>> a.remove(333) >>> a [66.25, -1, 333, 1, 1234.5, 333] >>> a.reverse() >>> a [333, 1234.5, 1, 333, -1, 66.25] >>> a.sort() >>> a [-1, 1, 66.25, 333, 333, 1234.5] " On 10 May 2007 10:02:26 -0700, HMS Surprise wrote: > > Trying not to be a whiner but I sure have trouble finding syntax in > the reference material. I want to know about list operations such as > append. Is there a pop type function? I looked in tutorial, language > reference, and lib for list, append, sequence. Is there a place where > us doofi ( who may not have our heads out in the sunlight) may find > all related syntax grouped together? > > thanx, > > jh > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fsckedagain at gmail.com Thu May 3 11:03:13 2007 From: fsckedagain at gmail.com (fscked) Date: 3 May 2007 08:03:13 -0700 Subject: _csv.Error: string with NUL bytes Message-ID: <1178204593.280648.208040@c35g2000hsg.googlegroups.com> Anyone have an idea of what I might do to fix this? I have googled adn can only find some random conversations about it that doesn't make sense to me. I am basically reading in a csv file to create an xml and get this error. I don't see any empty values in any fields or anything... From metaperl at gmail.com Thu May 17 05:02:19 2007 From: metaperl at gmail.com (metaperl) Date: 17 May 2007 02:02:19 -0700 Subject: Seeking author of script which generated HTML pages from pictures of them Message-ID: <1179392539.203491.153900@u30g2000hsc.googlegroups.com> On reddit.com, many moons ago, I downloaded some code which generated a page using HTML tables from a picture of the page you wanted. However, I dont have any author information in the code and wanted to stay in touch which she/he... does anyone know who wrote this code below? # Box geometry. class Box(object): def __init__(self, x, y, right, bottom): self.x, self.y, self.right, self.bottom = x, y, right, bottom def box_x_delimeters(boxes): return sorted(set(box.right for box in boxes)) def box_y_delimiters(boxes): return sorted(set(box.bottom for box in boxes)) def box_rowspans(boxes): rowspans = dict((box, 0) for box in boxes) for delim in box_y_delimiters(boxes): for box in boxes: if box.y < delim and box.bottom >= delim: rowspans[box] += 1 return rowspans def box_colspans(boxes): colspans = dict((box, 0) for box in boxes) for delim in box_x_delimeters(boxes): for box in boxes: if box.x < delim and box.right >= delim: colspans[box] += 1 return colspans def box_rows(boxes): rows, boxes_left = [], set(boxes) for delim in box_y_delimiters(boxes): boxes_in_row = set(box for box in boxes_left if box.y < delim) boxes_left -= boxes_in_row rows.append(sorted(boxes_in_row, key=lambda box: box.x)) return rows # Rendering and parsing tables. def render_html_table(boxes): rowspans, colspans = box_rowspans(boxes), box_colspans(boxes) table = '\n' for row in box_rows(boxes): table += ' \n' for box in row: table += ' \n' % (rowspans[box], colspans[box], 'blank
    ' * (box.bottom - box.y)) table += ' \n' table += '
    %s
    \n' return table def parse_ascii_table(table): def char(x, y): if 0 <= y < len(grid) and 0 <= x < len(grid[y]): return grid[y][x] else: return " " def box_right(x, y): for right in range(x, len(grid[y + 1])): if char(right + 1, y + 1) == '|': return right raise RuntimeError("Unterminated box.") def box_bottom(x, y): for bottom in range(y, len(grid)): if char(x + 1, bottom + 1) == '-': return bottom raise RuntimeError("Unterminated box.") grid = table.splitlines() boxes = [] for y in range(len(grid)): for x in range(len(grid[y])): if char(x, y) in ('-', '|') and char(x, y + 1) == '|' and char(x + 1, y) == '-': boxes.append(Box(x, y, box_right(x, y), box_bottom(x, y))) return boxes # Tests. table = \ """ ----------------------------------------------------------------------------- | adsafasf | | | | | | | | ----------------------------------------------------------------------------- | | | | | | | | | ----------------------------------------------------------------------------- | | | | | | | | | ----------------------------------------------------------------------------- """ open("test.html", "w").write('\n\n%s\n\n' % (render_html_table(parse_ascii_table(table)),)) From nyamatongwe+thunder at gmail.com Thu May 17 18:33:47 2007 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Thu, 17 May 2007 22:33:47 GMT Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464CD15A.9070409@v.loewis.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <464C5382.6080403@v.loewis.de> <1179423799.254286.294930@w5g2000hsg.googlegroups.com> <464CD15A.9070409@v.loewis.de> Message-ID: Martin v. L?wis: > ... regardless of whether this PEP gets accepted > or not (which it just did). Which version can we expect this to be implemented in? Neil From bbxx789_05ss at yahoo.com Thu May 24 23:50:33 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 24 May 2007 20:50:33 -0700 Subject: sockets, gethostname() changing In-Reply-To: <1180063489.535893.182970@x35g2000prf.googlegroups.com> References: <1180062244.266857.300830@m36g2000hse.googlegroups.com> <1180063489.535893.182970@x35g2000prf.googlegroups.com> Message-ID: <1180065033.520142.37050@q66g2000hsg.googlegroups.com> Thanks for the response. On May 24, 9:24 pm, half.ital... at gmail.com wrote: > I can't imagine why your hostname would be changing, unless you > installed some of their proprietary software thats messing around with > things. When I first started using Terminal, I noticed that the prompt in Terminal changed when I was connected to the internet. > What is the hostname set to in Sys Prefs->Sharing? My Name's Computer > Try > setting it there. What are the before and after connection names you > get? > If I add the line: host = socket.gethostname() print host #<---------- and I'm not connected to the internet and I run the program, I get: my-names-computer.local When I'm connected to the internet, I get: dialup-9.999.999.999.dial9.xxxxxxx.level9.net From steve at holdenweb.com Thu May 31 16:39:54 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 31 May 2007 16:39:54 -0400 Subject: Using PIL to find separator pages In-Reply-To: References: Message-ID: Larry Bates wrote: > I have a project that I wanted to solicit some advice > on from this group. I have millions of pages of scanned > documents with each page in and individual .JPG file. > When the documents were scanned the people that did > the scanning put a colored (hot pink) separator page > between the individual documents. I was wondering if > there was any way to utilize PIL to scan through the > individual files, look at some small section on the > page, and determine if it is a separator page by > somehow comparing the color to the separator page > color? I realize that this would be some sort of > percentage match where 100% would be a perfect match > and any number lower would indicate that it was less > likely that it was a coverpage. > > Thanks in advance for any thoughts or advice. > I suspect the easiest way would be to select a few small patches of each image and average the color values of the pixels, then normalize to hue rather than RGB. Close enough to the hue you want (and you could include saturation and intensity too, if you felt like it) across several areas of the page would be a hit for a separator. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From hq4ever at gmail.com Sat May 5 19:27:46 2007 From: hq4ever at gmail.com (Maxim Veksler) Date: Sun, 6 May 2007 02:27:46 +0300 Subject: Init style output with python? Message-ID: Hi list, I'm working on writing sanity check script, and for aesthetic reasons I would like the output be in the formatted like the gentoo init script output, that is: """ Check for something .................................. [OK] Check for something else ..........................[FAIL] """ Is there are frame work or something in python that would allow me to do this (quickly) ? If not, ideas how I should I be getting this boring task of: 1. get screen width 2. get output string length 3. get out status length 4. calculate space 5. print string, print space, print status, print newline what happens if user changes textual terminal "resolution" ? p.s. I would also like to "OK" and "FAIL" output to be colored. I haven't found anything for python to would allow to to output to ansi (linux, rxvt, xterm). Here's a quick class I've written (in the hope it proves to be useful to the next guy). """ #!/usr/bin/env python """ This stuff is under GPL, as always""" class ColorTerm: def __init__(self, Mono = False): pass def __get_tput_color_value__(colorcode): from commands import getoutput return getoutput('tput setaf ' + colorcode) BLACK_FG = __get_tput_color_value__('0') RED_FG = __get_tput_color_value__('1') GREEN_FG = __get_tput_color_value__('2') YELLOW_FG = __get_tput_color_value__('3') BLUE_FG = __get_tput_color_value__('4') MAGENTA_FG = __get_tput_color_value__('5') CYAN_FG = __get_tput_color_value__('6') WHITE_FG = __get_tput_color_value__('7') def black(self, msg): return self.BLACK_FG + msg + self.BLACK_FG def red(self, msg): return self.RED_FG + msg + self.BLACK_FG def green(self, msg): return self.GREEN_FG + msg + self.BLACK_FG def yellow(self, msg): return self.YELLOW_FG + msg + self.BLACK_FG def blue(self, msg): return self.BLUE_FG + msg + self.BLACK_FG def magenta(self, msg): return self.MAGENTA_FG + msg + self.BLACK_FG def cyan(self, msg): return self.CYAN_FG + msg + self.BLACK_FG def white(self, msg): return self.WHITE_FG + msg + self.BLACK_FG cc = ColorTerm() print cc.red('Cool!') + cc.yellow('?'), cc.green('Sure is!!!') print "Now setting your terminal text color to blue" + cc.BLUE_FG print "well don't be blue about this, here let me set it back for you" print cc.BLACK_FG + "see, nothing to worry about" """ -- Cheers, Maxim Veksler "Free as in Freedom" - Do u GNU ? From S.Mientki-nospam at mailbox.kun.nl Tue May 1 18:37:28 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Wed, 02 May 2007 00:37:28 +0200 Subject: Python for Windows other way to getting it? In-Reply-To: <1178055837.723546.228980@n59g2000hsh.googlegroups.com> References: <1178051916.033367.205320@h2g2000hsg.googlegroups.com> <59pp42F2jtk6gU2@mid.uni-berlin.de> <1178055837.723546.228980@n59g2000hsh.googlegroups.com> Message-ID: <1fa8b$4637c091$d443bb3a$12645@news.speedlinq.nl> noagbodjivictor at gmail.com wrote: > On May 1, 5:17 pm, "Diez B. Roggisch" wrote: >> noagbodjivic... at gmail.com schrieb: >> >>> Hello >>> I don't have permission to install new application on the PC I'm >>> using, I need a zipped version of python that I can copy on my >>> external drive. Where can I get a zip version? >> http://www.voidspace.org.uk/python/movpy/ >> >> Diez > > Thank you Diez, as a student I was hoping for an open source version. > There are none [good project for an experienced programmer]. But I > have however found an old stand alone version here : > http://arctrix.com/nas/python/standalone.html > If you're a student you might be interested in the Scientific Package from Enthought, look for the "Enstaller" version, or try Portable SciPy, is an easy installer of SciPy for M$ windows users. http://oase.uci.kun.nl/~mientki/data_www/pic/jalcc/python/portable_scipy.html cheers, Stef Mientki From mccredie at gmail.com Tue May 22 14:30:40 2007 From: mccredie at gmail.com (Matimus) Date: 22 May 2007 11:30:40 -0700 Subject: Create an XML document In-Reply-To: <1179846012.972391.160800@z28g2000prd.googlegroups.com> References: <1179846012.972391.160800@z28g2000prd.googlegroups.com> Message-ID: <1179858640.808299.178690@y2g2000prf.googlegroups.com> > How do I get Python to put values into the elements by tag name? The same way you create put in new elements. Only, you use 'doc.createTextNode' instead of 'doc.createElement' to create it. from xml.dom.minidom import Document doc = Document() zappt = doc.createElement('zAppointments') zappt.setAttribute('reminder', '15') doc.appendChild(zappt) appt = doc.createElement('appointment') zappt.appendChild(appt) begin = doc.createElement('begin') begincont = doc.createTextElement('1179775800') begin.appendChild(begincont) appt.appendChild(begin) duration = doc.createElement('duration') durationcont = doc.createTextElement('1800') duration.appendChild(durationcont) appt.appendChild(duration) f = file(r'path\to\file.xml', 'w') f.write(doc.toprettyxml(indent=' ')) f.close() From aisaac at american.edu Tue May 15 12:31:37 2007 From: aisaac at american.edu (Alan Isaac) Date: Tue, 15 May 2007 16:31:37 GMT Subject: docs patch: dicts and sets Message-ID: This discussion ended abruptly, and I'd like to see it reach a conclusion. I will attempt to synthesize Bill and Carsten's proposals. There are two proposed patches. The first is to http://docs.python.org/lib/typesmapping.html where it is proposed for footnote (3) to state: Keys and values are listed in an arbitrary order. This order is indeterminate and generally depends on factors outside the scope of the containing program. However, if items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond. The second is for http://docs.python.org/lib/types-set.html where the proposal is to append a new sentence to the 2nd paragraph: Iteration over a set returns elements in an indeterminate order,which generally depends on factors outside the scope of the containing program. Alan Isaac From aisaac at american.edu Sat May 5 19:00:12 2007 From: aisaac at american.edu (Alan Isaac) Date: Sat, 05 May 2007 23:00:12 GMT Subject: change of random state when pyc created?? References: <1178388186.631422.290580@w5g2000hsg.googlegroups.com> Message-ID: <008%h.379$HR1.364@trnddc01> I have documented this behavior on two completely different systems (Win 2000 and Win XP SP2), using Python 2.5.1. It two modules where this happens, as described before. If it should not happen, there is a bug. I am looking for potential explanation, since I realize that finding bugs is unlikely. Alan Isaac From gagsl-py2 at yahoo.com.ar Tue May 8 20:12:11 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 08 May 2007 21:12:11 -0300 Subject: Atttribute error References: <1178641784.974581.14000@p77g2000hsh.googlegroups.com> <1178643271.048991.83730@u30g2000hsc.googlegroups.com> Message-ID: En Tue, 08 May 2007 13:54:31 -0300, HMS Surprise escribi?: >> print urllib.__file__ >> print dir(urllib) >> > > C:\maxq\bin\testScripts\.\urllib.py > ['__doc__', '__file__', '__name__', 'string'] Perhaps you get an import error and it got unnoticed? I think earlier Python versions could leave a partially initialized module in sys.modules, and Jython could suffer that. Because the first thing urllib does is to import string, and the second, to import socket. Maybe it can't find socket.py or its dependencies (that's not surprising, if Jython could not find urllib.py in the first place). So copying individual modules from the library isn't a good solution - you'd have to copy a lot of things in order to fulfill the growing import requirements. Best is to make Jython find its library - if Jython was installed on C:\Jython, it should be at C:\Jython\Lib. Follow the advice from John Machin on the other thread. -- Gabriel Genellina From grante at visi.com Wed May 2 14:08:23 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 02 May 2007 18:08:23 -0000 Subject: Time functions References: <1178125256.640115.26480@o5g2000hsb.googlegroups.com> <1178126501.245493.210150@y80g2000hsf.googlegroups.com> <1178128753.140811.228620@u30g2000hsc.googlegroups.com> Message-ID: <133hksn172i4a43@corp.supernews.com> On 2007-05-02, Matimus wrote: >> I think I have an import misconception. >> >> I use >> import from time localtime, strftime >> t = strftime('%m/%d/%Y %H:%M', localtime()) >> >> This works. How would one use it with the module name pre-pended? > > I would think that what you have written there shouldn't work at > all... It doesn't. > it would need to be: > > [code] > from time import localtime, strftime > [/code] > > to use the prepended module name just do this instead: > > [code] > import time > t = time.strftime('%m/%d/%Y %H:%M', time.localtime()) > [/code] or just this t = time.strftime('%m/%d/%Y %H:%M') time.strftime() has used the localtime() value by default for a while now. -- Grant Edwards grante Yow! There's enough money at here to buy 5000 cans of visi.com Noodle-Roni! From cedric.louyot at gmail.com Wed May 9 03:36:48 2007 From: cedric.louyot at gmail.com (redcic) Date: 9 May 2007 00:36:48 -0700 Subject: Plot with scipy In-Reply-To: <1178542249.948480.270930@y5g2000hsa.googlegroups.com> References: <1178283196.755609.241790@n59g2000hsh.googlegroups.com> <1178287027.434242.230170@h2g2000hsg.googlegroups.com> <1178542249.948480.270930@y5g2000hsa.googlegroups.com> Message-ID: <1178696208.190294.196190@e65g2000hsc.googlegroups.com> Thank you all for your answers. Setting "interactive : True" is often suggested to me but it does not solve my problem. I tried different other things (following your advices) but I still have the same problem. Maybe the source of my problem is the fact that I use the SciTE editor. What do you think about that ? Any other idea ? Thanks again, C?dric On 7 mai, 14:50, "bernhard.vo... at gmail.com" wrote: > On 4 Mai, 15:57, redcic wrote: > > > I've already got this package. I just wanted to try something new. > > > However, since you talk about it, I've got a question regarding this > > package. The execution of the code stops after the line: > > pylab.show() > > which is off course the last line of my code. My problem is that I > > have to close the figure window in order to launch my program another > > time. I'd like to be able to launch my program many times with > > different parameters without having to close the figure windows before > > each launch. > > Just so you know, I'm using TkAgg backend. > > > Any hint ? > > There's an option in your matplotlibrc file (personal lives in > $HOME/.matplotlib, default in $PYTHONPATH/matplotlib/mpl-data): > > #### CONFIGURATION BEGINS HERE > # the default backend; one of GTK GTKAgg GTKCairo FltkAgg QtAgg TkAgg > # Agg Cairo GD GDK Paint PS PDF SVG Template > backend : TkAgg > numerix : numpy # numpy, Numeric or numarray > interactive : True # seehttp://matplotlib.sourceforge.net/interactive.html > ..... > > Take a look at the quoted webpage for details and troubleshooting. > > Bernhard From p.f.moore at gmail.com Thu May 24 12:45:44 2007 From: p.f.moore at gmail.com (Paul Moore) Date: 24 May 2007 09:45:44 -0700 Subject: Reading (and writing?) audio file tags In-Reply-To: References: <1180021454.086004.126170@p47g2000hsd.googlegroups.com> Message-ID: <1180025144.752607.63350@h2g2000hsg.googlegroups.com> On 24 May, 17:22, darren kirby wrote: > quoth the Paul Moore: > > > I'd like to write some scripts to analyze and manipulate my music > > files. The files themselves are in MP3 and FLAC format (mostly MP3, > > but FLAC where I ripped original CDs and wanted a lossless format). > > I've no idea what form of tags are used in the files (ID3v1, ID3v2, > > OGG, APE, ...) > > Flac files use Vorbis comments, the same that Ogg Vorbis files use. As for > MP3, they use ID3v2 or ID3v1, or both. > > Anyway, what you want is Mutagen. It handles both Flac and Mp3 tags, as well > as many others:http://www.sacredchao.net/quodlibet/wiki/Development/Mutagen Excellent! The web page you mentioned gave "access denied", but I got to it via Google's cache, and the download link still worked :-) It does seem to build a Windows installer quite happily, so that's a great start. I'll see how it goes tonight. Thanks for the pointer. Paul. From http Sun May 13 14:06:50 2007 From: http (Paul Rubin) Date: 13 May 2007 11:06:50 -0700 Subject: GUI tutorial References: Message-ID: <7x1whka98l.fsf@ruckus.brouhaha.com> John K Masters writes: > Can someone point me in the direction of a good tutorial on programming > python with a GUI? I'm just starting out with python and have written a > few scripts successfully but would like to add a graphical front end to > them to make it easier for my work colleagues, most of whom have never > used a command line, to use. http://infohost.nmt.edu/tcc/help/pubs/tkinter/ is pretty good. You could alternatively consider writing your script as a web server or web app, so the gui would be a browser. That puts some limitations on the gui design but it makes development and deployment both simpler. Develoment is simpler because you just use regular HTML instead of weird libraries and callbacks and threads and all that crap. Deployment is simpler because you can install and run the program on one machine, send the url to your colleagues, and update the program as needed without having to get your colleagues constantly installing new versions. For security reasons, be careful to not expose the web interface to the public internet until you know what you're doing. From tinaweb at bestemselv.com Wed May 16 07:17:46 2007 From: tinaweb at bestemselv.com (Tina I) Date: Wed, 16 May 2007 13:17:46 +0200 Subject: Distributing programs depending on third party modules. In-Reply-To: <1179305458.664062.121800@l77g2000hsb.googlegroups.com> References: <53357$4649c4a6$4275d90a$20775@FUSE.NET> <-J6dnUQxANzMB9fbRVnzvAA@telenor.com> <1179305458.664062.121800@l77g2000hsb.googlegroups.com> Message-ID: <9rmdnV0Xpe_HddfbRVnzvAA@telenor.com> David Boddie wrote: > On May 16, 7:44 am, Tina I wrote: > >> A binary would be ideal. I'll look into the freeze modules and >> Pyinstaller. Even if they don't handle huge things like Qt it would be a >> step in the right direction if it handles smaller third part modules. >> And maybe the smartest thing to do would be to dump PyQt and just >> go for tkinter, however ugly it is :/ > > It's may be worth reading this message before making such a drastic > decision: > > http://www.riverbankcomputing.com/pipermail/pyqt/2007-May/016092.html > > David ;-) > Oh... now I feel stupid... I'm on the PyQt list but somehow missed that topic. Thanks! Tina From kinch1967 at gmail.com Sat May 19 13:21:59 2007 From: kinch1967 at gmail.com (bullockbefriending bard) Date: 19 May 2007 10:21:59 -0700 Subject: regex matching question Message-ID: <1179595319.239229.262160@l77g2000hsb.googlegroups.com> first, regex part: I am new to regexes and have come up with the following expression: ((1[0-4]|[1-9]),(1[0-4]|[1-9])/){5}(1[0-4]|[1-9]),(1[0-4]|[1-9]) to exactly match strings which look like this: 1,2/3,4/5,6/7,8/9,10/11,12 i.e. 6 comma-delimited pairs of integer numbers separated by the backslash character + constraint that numbers must be in range 1-14. i should add that i am only interested in finding exact matches (doing some kind of command line validation). this seems to work fine, although i would welcome any advice about how to shorten the above. it seems to me that there should exist some shorthand for (1[0-4]|[1-9]) once i have defined it once? also (and this is where my total beginner status brings me here looking for help :)) i would like to add one more constraint to the above regex. i want to match strings *iff* each pair of numbers are different. e.g: 1,1/3,4/5,6/7,8/9,10/11,12 or 1,2/3,4/5,6/7,8/9,10/12,12 should fail to be matched by my final regex whereas 1,2/3,4/5,6/7,8/9,10/11,12 should match OK. any tips would be much appreciated - especially regarding preceding paragraph! and now for the python part: results = "1,2/3,4/5,6/7,8/9,10/11,12" match = re.match("((1[0-4]|[1-9]),(1[0-4]|[1-9])/){5}(1[0-4]|[1-9]), (1[0-4]|[1-9])", results) if match == None or match.group(0) != results: raise FormatError("Error in format of input string: %s" % (results)) results = [leg.split(',') for leg in results.split('/')] # => [['1', '2'], ['3', '4'], ['5', '6'], ['7', '8'], ['9', '10'], ['11', '12']] . . . the idea in the above code being that i want to use the regex match as a test of whether or not the input string (results) is correctly formatted. if the string results is not exactly matched by the regex, i want my program to barf an exception and bail out. apart from whether or not the regex is good idiom, is my approach suitably pythonic? TIA for any help here. From dustin at v.igoro.us Sat May 5 13:28:51 2007 From: dustin at v.igoro.us (dustin at v.igoro.us) Date: Sat, 5 May 2007 12:28:51 -0500 Subject: Python regular expressions just ain't PCRE In-Reply-To: <1178380335.646708.260540@h2g2000hsg.googlegroups.com> References: <1178323901.381993.47170@e65g2000hsc.googlegroups.com> <1178380335.646708.260540@h2g2000hsg.googlegroups.com> Message-ID: <20070505172851.GR5734@v.igoro.us> On Sat, May 05, 2007 at 08:52:15AM -0700, Wiseman wrote: > > I believe the current Python re module was written to replace the Python > > wrapping of pcre in order to support unicode. > > I don't know how PCRE was back then, but right now it supports UTF-8 > Unicode patterns and strings, and Unicode character properties. Maybe > it could be reintroduced into Python? I would say this is a case for "rough consensus and working code". With something as big and ugly[1] as a regexp library, I think the "working code" part will be the hard part. So, if you have a patch, there's a decent chance such a thing would be adopted. I'm not sure what your skill level is, but I would suggest studying the code, starting in on a patch for one or more of these features, and then corresponding with the module's maintainers to improve your patch to the point where it can be accepted. Dustin From christopherlmarshall at yahoo.com Thu May 31 13:45:04 2007 From: christopherlmarshall at yahoo.com (christopherlmarshall at yahoo.com) Date: 31 May 2007 10:45:04 -0700 Subject: pack() and the division of vertical space Message-ID: <1180633504.182393.20960@o5g2000hsb.googlegroups.com> I am trying to figure out how to stack two widgets in a frame vertically so that they both expand horizontally and during vertical expansion, the top one sticks to the top of the frame and the bottom one consumes the remaining vertical space. I thought this would do it but it doesn't. What am I missing? from Tkinter import * class AFrame(Frame): def __init__(self,master,**config): Frame.__init__(self,master,config) size=50 self.l1= Label(text="abc",relief="groove") self.l1.pack(side=TOP,expand=YES,fill=X,anchor=N) self.l2= Label(text="abc",relief="groove") self.l2.pack(side=TOP,expand=YES,fill=BOTH) af= AFrame(None) af.pack(side=TOP,expand=YES,fill=BOTH) mainloop() From sjmachin at lexicon.net Tue May 15 06:22:01 2007 From: sjmachin at lexicon.net (John Machin) Date: 15 May 2007 03:22:01 -0700 Subject: Iron Python In-Reply-To: References: <464981fa$0$8759$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: <1179224521.550517.271820@e51g2000hsg.googlegroups.com> On May 15, 8:05 pm, Jarek Zgoda wrote: > Jon Harrop napisa?(a): > > > Anybody tried it? > > Me. > Me too. From hpj at urpla.net Thu May 10 08:52:39 2007 From: hpj at urpla.net (Hans-Peter Jansen) Date: Thu, 10 May 2007 14:52:39 +0200 Subject: trouble with generators Message-ID: Hi Pythonistas, I'm stuck in a maze of new style classes and generators. While I love the concepts, I obviously didn't grok them throughout. I'm trying to generate a bunch of similar classes, where some are contained in list attributes of others, e.g.: class A: def __init__(self): self.id = 'A1' self.b = [instances of B] class B: def __init__(self): self.id = 'B1' Here's the test code, I have: #!/usr/bin/env python # -*- coding: utf8 -*- class A(object): "A" def __init__(self): self.id = None self.b = [] class B(object): "B" def __init__(self): self.id = None class Gen(object): def records(self, cls): for i in range(3): setattr(cls, "id", "%s%s" % (cls.__doc__, i)) yield cls def display(self, rec): for i in rec.__dict__.keys(): if not i.startswith("_"): print "%s: %s: %s" % (rec.__doc__, i, rec.__dict__[i]) class GenA(Gen): def __init__(self): self.genB = GenB() def records(self): for a in Gen.records(self, A()): for b in self.genB.records(): #self.genB.display(b) a.b.append(b) #self.display(a) yield a class GenB(Gen): def records(self): return Gen.records(self, B()) # testing.. aRecs = [] bRecs = [] for i, r in enumerate(GenB().records()): bRecs.append(r) print i, r.id, r for i, r in enumerate(GenA().records()): aRecs.append(r) print i, r.id, r for b in r.b: print b.id, b Here's the commented output: # even if I keep a reference to each rec, the object is reused: 0 B0 <__main__.B object at 0xb7bd0f8c> 1 B1 <__main__.B object at 0xb7bd0f8c> 2 B2 <__main__.B object at 0xb7bd0f8c> # same here, with additional quadratic behavior, I do not understand 0 A0 <__main__.A object at 0xb7bd206c> B2 <__main__.B object at 0xb7bd210c> B2 <__main__.B object at 0xb7bd210c> B2 <__main__.B object at 0xb7bd210c> 1 A1 <__main__.A object at 0xb7bd206c> B2 <__main__.B object at 0xb7bd210c> B2 <__main__.B object at 0xb7bd210c> B2 <__main__.B object at 0xb7bd210c> B2 <__main__.B object at 0xb7bd20ec> B2 <__main__.B object at 0xb7bd20ec> B2 <__main__.B object at 0xb7bd20ec> 2 A2 <__main__.A object at 0xb7bd206c> B2 <__main__.B object at 0xb7bd210c> B2 <__main__.B object at 0xb7bd210c> B2 <__main__.B object at 0xb7bd210c> B2 <__main__.B object at 0xb7bd20ec> B2 <__main__.B object at 0xb7bd20ec> B2 <__main__.B object at 0xb7bd20ec> B2 <__main__.B object at 0xb7bd0f8c> B2 <__main__.B object at 0xb7bd0f8c> B2 <__main__.B object at 0xb7bd0f8c> I expected to get 3 different class objects from both sections, with each A containing 3 different Bs in the latter section, but obviously got something else. Could some kind soul help me to distangle my mind twist here? Am I healable? TIA, Pete From noagbodjivictor at gmail.com Tue May 1 18:05:19 2007 From: noagbodjivictor at gmail.com (noagbodjivictor at gmail.com) Date: 1 May 2007 15:05:19 -0700 Subject: Python for Windows other way to getting it? In-Reply-To: <1178056230.282600.199660@l77g2000hsb.googlegroups.com> References: <1178051916.033367.205320@h2g2000hsg.googlegroups.com> <59pp42F2jtk6gU2@mid.uni-berlin.de> <1178055837.723546.228980@n59g2000hsh.googlegroups.com> <1178056230.282600.199660@l77g2000hsb.googlegroups.com> Message-ID: <1178057119.061494.235150@l77g2000hsb.googlegroups.com> On May 1, 5:50 pm, Tal Einat wrote: > On May 2, 12:43 am, noagbodjivic... at gmail.com wrote: > > > > > On May 1, 5:17 pm, "Diez B. Roggisch" wrote: > > > > noagbodjivic... at gmail.com schrieb: > > > > > Hello > > > > I don't have permission to install new application on the PC I'm > > > > using, I need a zipped version of python that I can copy on my > > > > external drive. Where can I get a zip version? > > > >http://www.voidspace.org.uk/python/movpy/ > > > > Diez > > > Thank you Diez, as a student I was hoping for an open source version. > > There are none [good project for an experienced programmer]. But I > > have however found an old stand alone version here :http://arctrix.com/nas/python/standalone.html > > Check out Portable Python:http://www.portablepython.com/ > > Still in beta status, but quite up-to-date, and free. > > - Tal Einat thanks Tal From larry.bates at websafe.com Thu May 3 12:05:20 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 03 May 2007 11:05:20 -0500 Subject: pyscripter to slow In-Reply-To: References: Message-ID: Gigs_ wrote: > I have some problem with pyscripter. > Sometimes when I type pyscripter get to slow (i type 10 chars and > pyscripter needs 5 seconds to complete this). This happens mostly on > deleting some chars. > > It is very frustrating. > > Does someone have same situation? > > btw > My comp is > > amd athlon x2 4000 2mb cache > sapphire am2rd580adv 3200 ati chipset > 2GB corsair xm2 > sapphire x1650 pro 256mb > > windows vista I see this when pyscripter is trying to resolve autocomplete to show me the underlying arguments to a function. You should probably post back to their website instead of here. -Larry From exarkun at divmod.com Sat May 5 11:55:41 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sat, 5 May 2007 11:55:41 -0400 Subject: Non blocking sockets with select.poll() ? In-Reply-To: Message-ID: <20070505155541.19381.801734577.divmod.quotient.8711@ohm> On Sat, 5 May 2007 15:37:31 +0300, Maxim Veksler wrote: >On 5/4/07, Jean-Paul Calderone wrote: >> >""" >> >#!/usr/bin/env python >> >import socket >> >import select >> > >> >class PollingSocket(socket.socket): >> > Usually there's no particularly good reason to subclass socket. In this case you did it to add a poll method, it seems. However... >> > >> > def __init__(self, port_number): >> > self.__poll = select.poll() >> > self.tcp_port_number = port_number >> > >> > socket.socket.__init__(self, socket.AF_INET, socket.SOCK_STREAM) >> > self.setblocking(0) >> > self.bind(('0.0.0.0', self.tcp_port_number)) >> > self.listen(5) >> > self.__poll.register(self) Creating one poll object per socket isn't necessary. You only need one overall. >> > >> > def poll(self, timeout = 0): >> > return self.__poll.poll(timeout) Polling with a zero timeout is just busy looping. You want to poll with a large (or infinite) timeout, and on more than one socket at a time. >> > >> >def debugPollingSocket(port_num): >> > print "BIND TO PORT: ", port_num >> > return PollingSocket(port_num) >> > >> >all_sockets = map(debugPollingSocket, xrange(10000, 19169)) >> > >> >print "We have this in stock:" >> >for nb_active_socket in all_sockets: >> > print nb_active_socket.tcp_port_number >> > >> >while 1: >> > for nb_active_socket in all_sockets: >> > print "Asking", nb_active_socket.tcp_port_number >> > if nb_active_socket.poll(0): >> > print "Found", nb_active_socket.tcp_port_number >> > conn, addr = nb_active_socket.accept() >> > while 1: >> > data = conn.recv(1024) >> > if not data: break >> > conn.send(data) >> > conn.close() >> >""" >> > Instead of looping over all the sockets repeatedly and asking each one if it has any data, you want to create one poll object, register every socket with it, and ask it which sockets have data. You also want to put the accepted sockets into non-blocking mode and also poll them, reading from whichever ones have data when they have data. Even if you don't want to use Twisted, it might be beneficial to read how it is implemented to learn how to do this. Jean-Paul From gagsl-py2 at yahoo.com.ar Fri May 25 07:08:19 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 25 May 2007 08:08:19 -0300 Subject: Find the closest relative References: <1180074710.011260.276830@n15g2000prd.googlegroups.com> <1180078850.074308.286570@p77g2000hsh.googlegroups.com> <1180080540.316522.67020@a35g2000prd.googlegroups.com> Message-ID: En Fri, 25 May 2007 05:09:00 -0300, jm.suresh at no.spam.gmail.com escribi?: > Vehicle > | > |--- Two Wheeler > | | > | |--- BatteryPowered > | |--- PetrolPowered > | |--- DieselPowered > | > |--- Three Wheeler > | | > | |--- AutoRicksaw > | > |--- Four Wheeler > | | > | |--- GeneralTrans > | | |--- Car > | | |--- Car1 > | | |--- Car2 > | | |--- Car3 > | | > | |--- PublicTrans > | | |--- Bus > | | |--- Bus1 > | | |--- Bus2 > | |--- Goods > | |--- Lorry > |--- Lorry1 > |--- Lorry2 > |--- Lorry3 > > Now given one instance of some type, I want to choose between second > and third, whichever > is closest relative to the first object. > Eg. > Instance(Car1), Instance(Lorry1), Instance(AutoRicksaw) => > Instance(Lorry1) If your classes actually form a tree (you have only single inheritance) then you may use the mro(): Car1.mro() = [Car, GeneralTrans, FourWheeler, Vehicle, object] Lorry1.mro() = [Lorry, Goods, FourWheeler, Vehicle, object] AutoRicksaw.mro() = [ThreeWeeler, Vehicle, object] Now you have to find the first item in Lorr1.mro that appears also in Car1.mro, and the same for AutoRicksaw.mro; the least index on Car1.mro wins (Or the least index in the other list; or the least sum; that depends on your exact definition of "closest relative"). (Under the Argentinian law, you measure how "close" two relatives are, starting with one person, going up the tree until you find a common ancestor, and going down to the other person. That is, summing up the indices on both "mro" lists for the common ancestor). -- Gabriel Genellina From stephen at theboulets.net Tue May 15 08:49:14 2007 From: stephen at theboulets.net (Stephen_B) Date: 15 May 2007 05:49:14 -0700 Subject: pyshell and unum hint Message-ID: <1179233354.305517.56720@y80g2000hsf.googlegroups.com> I like to have unum units imported automatically on my PYTHONSTARTUP since I'm always converting things, and I also like to use pyshell. They conflict for some reason I don't understand (pyshell doesn't like the Unum.as method, maybe since it will be a keyword): 1.0*IN.as(M) File "", line 1 1.0*IN.as(M) ^ SyntaxError: invalid syntax Instead I put this in my PYTHONSTARTUP: from unum.tools.calc import * Unum.to = Unum.as Which gives: 1.0*IN.to(M) 0.0253999368687 [m] Stephen From researchbase at gmail.com Mon May 7 02:55:53 2007 From: researchbase at gmail.com (krishnakant Mane) Date: Mon, 7 May 2007 12:25:53 +0530 Subject: problem with quoted strings while inserting into varchar field of database. In-Reply-To: <1178475772.423687.118800@e65g2000hsc.googlegroups.com> References: <1178475772.423687.118800@e65g2000hsc.googlegroups.com> Message-ID: On 6 May 2007 11:22:52 -0700, Daniele Varrazzo > > Every serious database driver has a complete and solid SQL escaping > mechanism. This mechanism tipically involves putting placeholders in > your SQL strings and passing python data in a separate tuple or > dictionary. Kinda > > cur.execute("INSERT INTO datatable (data) VALUES (%s);", > (pickled_data,)) > I will try doing that once I get back to the lab. mean while I forgot to mention in my previous email that I use MySQLdb for python-mysql connection. I did not find any such reference to storing pickled objects in the API. any Idea what could be done with the mysql python module I am using? regards, Krishnakant. From aboudouvas at panafonet.gr Tue May 22 17:57:04 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 22 May 2007 14:57:04 -0700 Subject: 'int' object is not callable in an threaded app In-Reply-To: References: Message-ID: <1179871024.178930.93180@q66g2000hsg.googlegroups.com> > It appears that worker.start gets set to the result of > count.ui.spFrom.value(). If that result is an int, then worker.start() is > going to generate the TypeError you received. Did you actually mean to call > worker.run() instead? > > --- > -Bill Hamilton Some friend pointed out to me an hour ago, it was indeed that damn variable... Anyway, thanks Bill! From lokesh.jagasia at gmail.com Mon May 7 07:04:00 2007 From: lokesh.jagasia at gmail.com (lokesh.jagasia at gmail.com) Date: 7 May 2007 04:04:00 -0700 Subject: N00b question on Py modules In-Reply-To: References: <1178521238.333095.111370@h2g2000hsg.googlegroups.com> Message-ID: <1178535840.526299.126700@e65g2000hsc.googlegroups.com> Thanks a lot for the responses ppl. Python's treatment of global variables was an eye-opener. I have coded in Java & C/C++ in the past and there the behaviour is diametrically opposite. Cheers From sjmachin at lexicon.net Thu May 24 17:49:57 2007 From: sjmachin at lexicon.net (John Machin) Date: 24 May 2007 14:49:57 -0700 Subject: Changing Unicode object to Tuple Type In-Reply-To: <5blhn0F2u4ii7U2@mid.uni-berlin.de> References: <1180007144.514744.188090@q75g2000hsh.googlegroups.com> <5bldo8F2tlcqfU1@mid.uni-berlin.de> <1180010621.001281.268800@g4g2000hsf.googlegroups.com> <5blhn0F2u4ii7U2@mid.uni-berlin.de> Message-ID: <1180043397.278491.28010@a35g2000prd.googlegroups.com> On May 24, 11:19 pm, "Diez B. Roggisch" wrote: > laxmikiran.ba... at gmail.com schrieb: > > > > > On May 24, 5:11 pm, "Diez B. Roggisch" wrote: > >> laxmikiran.ba... at gmail.com schrieb: > > >>> Can we have change a unicode string Type object to a Tuple type > >>> object.. If so how ???? > >> Why? Are you getting an error that makes you think that's a good idea? > > >> Tuples are basically structs, unicode objects are strings. There is no > >> canonical way to convert them. Tell us more about the problem you want > >> to be solved, and we might help you better. > > >> diez > > > ********** > > > I have to get few strings from an application(strings of different > > languages..ex: korean,japanese,french etc.,). The data returned by the > > application was in the format of the xml. > > Hence I was using pyRXP to get the data. I was not able to get all the > > strigs in different languages. Now I wanted to use pyRXPU to get all > > the strings of that application.When Iam using pyRXPU iam getting the > > following error. > > > Traceback (most recent call last): > > File "D:\LanguageScripts\Screens.py", line 106, in > > test_1_01_DoSomething > > TitlenSoftkeyfn() > > File "D:\LanguageScripts\EventLog_Screens.py", line 66, in > > TitlenSoftkeyfn > > titleBar = root.TitleBar.currentText > > File "D:\LanguageScripts\XmlWrapper.py", line 35, in __getattr__ > > tagName, attrs, children, spare = child > > ValueError: need more than 1 value to unpack > > > Here the child is of the format unicode.. > > > When pyRXP is used it was of the format tuple... I was just trying to > > find out if there is some way that I make this code work. > > I don't know pyRXP and pyRXPU, and especially not how you use them. > Who's responsible for writing that "XmlWrapper.py"? He or she obviously > expected a tuple returned that was basically a DOM-tree (tag, attrs, > childs and something called spare) > > But changing to pyRXPU seems to break the protocol here. But I can't > judge that without seeing more code. > Looks like the OP needs to RTFM. Here's an excerpt from an article by David Mertz (http://www.ibm.com/developerworks/library/x- matters29.html): """ pyRXP's tuple tree data structure pyRXP (and RXP itself) uses an efficient, lightweight tree representation of XML documents. Each node in a pyRXP tree is simply a tuple of the form: (tagname, attr_dict, child_list, reserved) No specialized Python classes are used in the representation -- just tuples, dicts, lists, and strings (and None in the reserved position). Perhaps surprisingly, this form is adequate to represent all the information in an XML document. The tagname is a straightforward string; the attribute dictionary is a dictionary that maps attributes to values, as you would expect. ***The child list is more subtle: Strings can be interleaved with tuples in the list, indicating a mixed content element.*** Moreover, an element that has no content is represented by an empty child list, but a self-closed tag is represented by None. """ "subtle" is not the word I would have used :-) From cedric.louyot at gmail.com Fri May 4 09:57:07 2007 From: cedric.louyot at gmail.com (redcic) Date: 4 May 2007 06:57:07 -0700 Subject: Plot with scipy In-Reply-To: References: <1178283196.755609.241790@n59g2000hsh.googlegroups.com> Message-ID: <1178287027.434242.230170@h2g2000hsg.googlegroups.com> I've already got this package. I just wanted to try something new. However, since you talk about it, I've got a question regarding this package. The execution of the code stops after the line: pylab.show() which is off course the last line of my code. My problem is that I have to close the figure window in order to launch my program another time. I'd like to be able to launch my program many times with different parameters without having to close the figure windows before each launch. Just so you know, I'm using TkAgg backend. Any hint ? Thanks, C?dric On 4 mai, 15:49, Lou Pecora wrote: > In article <1178283196.755609.241... at n59g2000hsh.googlegroups.com>, > > > > redcic wrote: > > Hi all, > > > I've just downloaded scipy v 0.5.2 and I would like to be able to draw > > plots. I've tried: > > import scipy.gplt > > import scipy.plt > > import scipy.xplt > > > and none of them work. Are these modules still included in scipy ? If > > not, where can I find them ? > > > Thanks for your answers, > > > C?dric > > You really want matplotlib and PyLab the library built on top of it. > Search on the python.org site for examples. Google will turn up a lot. > Matplotlib w/ PyLab is a nice, easy plotting package. From beliavsky at aol.com Tue May 15 13:29:23 2007 From: beliavsky at aol.com (Beliavsky) Date: 15 May 2007 10:29:23 -0700 Subject: Trying to choose between python and java In-Reply-To: References: Message-ID: <1179250163.596672.321480@o5g2000hsb.googlegroups.com> On May 15, 1:30 am, Anthony Irwin wrote: > #5 someone said that they used to use python but stopped because the > language changed or made stuff depreciated (I can fully remember > which) and old code stopped working. Is code written today likely to > still work in 5+ years or do they depreciate stuff and you have to update? Because Python 3 will change the syntax of print to disallow print "Hello, world." a substantial fraction of Python programs in existence, including all of my programs, will be broken. Draw your own conclusions. From mtobis at gmail.com Wed May 9 18:38:54 2007 From: mtobis at gmail.com (Michael Tobis) Date: 9 May 2007 15:38:54 -0700 Subject: interesting exercise In-Reply-To: <1178739676.565009.35590@u30g2000hsc.googlegroups.com> References: <1178595952.641173.76540@y80g2000hsf.googlegroups.com> <1178601624.812907.23550@u30g2000hsc.googlegroups.com> <1178661305.063868.130730@e65g2000hsc.googlegroups.com> <1178661851.606885.104330@p77g2000hsh.googlegroups.com> <1178670691.209680.119330@o5g2000hsb.googlegroups.com> <46416674$0$83110$c30e37c6@lon-reader.news.telstra.net> <1178739676.565009.35590@u30g2000hsc.googlegroups.com> Message-ID: <1178750334.391599.237410@q75g2000hsh.googlegroups.com> On May 9, 2:41 pm, castiro... at gmail.com wrote: > On May 9, 1:13 am, Charles Sanders > wrote: > > or even this monstrosity ... > > > def permute2( s, n ): > > return [ ''.join([ s[int(i/len(s)**j)%len(s)] > > for j in range(n-1,-1,-1)]) > > for i in range(len(s)**n) ] > > > print "permute2('abc',2) =", permute2('abc',2) > > print "len(permute2('13579',3)) =", len(permute2('13579',3)) > > > permute2('abc',2) = ['aa', 'ab', 'ac', 'ba', 'bb', 'bc', > > 'ca', 'cb', 'cc'] > > len(permute2('13579',3)) = 125 > > > Charles > > Could you explain, this one, actually? Don't forget StopIteration. Heh, it's cute. Not sure what the issue is with StopIteration. He is modeling the problem as casting an integer to base N. It's terse, but it does way too much arithmetic and isn't very readable. The following uses the same idea more readably and (I expect, untested) more efficiently, if less tersely. It actually is not too bad for real code, though I much prefer your recursive list comprehension and will use that. def getdigits(number,base,length,alphabet): residual = number result = "" for column in range(length): residual,digit = divmod(residual,base) result = alphabet[digit] + result return result def permu(alphabet,wordlength): total = len(alphabet)**wordlength return [getdigits(index,len(alphabet),wordlength,alphabet) for index in range(total)] if __name__ == "__main__": print permu("abc",2) print len(permu("13579",3)) mt From paul at boddie.org.uk Fri May 25 14:35:46 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 25 May 2007 11:35:46 -0700 Subject: webbrowser module bug? In-Reply-To: References: Message-ID: <1180118146.617722.300670@g4g2000hsf.googlegroups.com> On 25 May, 00:03, Ron Adam wrote: > Is anyone else having problems with the webbrowser module? > > Python 2.5.1c1 (release25-maint, Apr 12 2007, 21:00:25) > [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import webbrowser > >>> webbrowser.open('http://www.python.org') > True > >>> > > It opens firefox as expected, but the url is ... > > file:///home/ron/%22http://www.python.org%22 Since %22 is the URL-encoded double-quote character ("), I can only imagine that something is quoting the URL for the shell, resulting in the following command: firefox '"http://www.python.org/"' Or something similar, at least. Firefox 1.5 seems to refuse to open such URLs, though. Paul From mfmorss at aep.com Mon May 21 09:31:36 2007 From: mfmorss at aep.com (Mark Morss) Date: 21 May 2007 06:31:36 -0700 Subject: Python compared to other language In-Reply-To: <4650acf1$0$4867$426a74cc@news.free.fr> References: <1179540061.598417.13870@y80g2000hsf.googlegroups.com> <1hybvdz.1qnlesglcv0vcN%aleax@mac.com> <1179556574.341550.229190@q23g2000hsg.googlegroups.com> <4650acf1$0$4867$426a74cc@news.free.fr> Message-ID: <1179754295.942394.218230@n15g2000prd.googlegroups.com> On May 20, 5:02 pm, Bruno Desthuilliers >Ruby is probably far better than Python at sys-admin tasks. Why, pray tell? I don't know much about Ruby, but I know that Python is the language that Gentoo uses for package management, which certainly qualifies as a sys-admin task. From kkylheku at gmail.com Wed May 2 20:15:13 2007 From: kkylheku at gmail.com (Kaz Kylheku) Date: 2 May 2007 17:15:13 -0700 Subject: Microsoft's Dynamic Languages Runtime (DLR) In-Reply-To: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> References: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> Message-ID: <1178151313.421106.43130@o5g2000hsb.googlegroups.com> On May 2, 11:22 am, sturlamolden wrote: > On Monday Microsoft announced a new runtime for dynamic languages, Kindly refrain from creating any more off-topic, cross-posted threads. Thanks. From paul at boddie.org.uk Thu May 31 09:52:56 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 31 May 2007 06:52:56 -0700 Subject: HTML Form/Page and Navigation with multiple buttons In-Reply-To: <1180617750.709628.180070@p77g2000hsh.googlegroups.com> References: <1180617750.709628.180070@p77g2000hsh.googlegroups.com> Message-ID: <1180619576.752444.87250@h2g2000hsg.googlegroups.com> On 31 May, 15:22, mosscliffe wrote: > [Multiple submit buttons in HTML forms] > How can I identify which button has been pressed. Do I need a > separate form for each button and hide all the relevant session fields > in each form or is there a way of identifying which button has been > pressed on the page. When you define the buttons like this... When the user selects one of the buttons, you should get an entry for the field representing the button in the FieldStorage object. So, if the user presses the "next" button, there should be an entry mapping that name ("next") to some value ("Next" in the above example) in the FieldStorage object. Paul From kw at codebykevin.com Sat May 12 20:17:05 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Sat, 12 May 2007 20:17:05 -0400 Subject: Licence for webchecker module? Message-ID: I want to use webchecker.py (distributed in Tools/webchecker of the Python source code tarball) in a project, but there is no license listed in any of the scripts that I can see. Is this code covered by the standard Python license? -- Kevin Walzer Code by Kevin http://www.codebykevin.com From rene at korteklippe.de Tue May 15 06:21:04 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 15 May 2007 12:21:04 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46479eec$0$4166$ba624c82@nntp02.dk.telia.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <46478694$0$1412$426a34cc@news.free.fr> <1hy252p.1anf7sr1p4yp12N%aleax@mac.com> <46479eec$0$4166$ba624c82@nntp02.dk.telia.net> Message-ID: <46498990$0$6441$9b4e6d93@newsspool2.arcor-online.net> Anders J. Munch schrieb: > There's any number of things to be done about that. > 1. # -*- encoding: ascii -*- This would limit comments and string literals to ASCII, too. I use "-*- coding: utf-8 -*-" in all of my code and I am still against this PEP. It is useful to be able to spell my own name correctly in a comment. It is not useful to do so in a Python identifier. -- Ren? From mattheww at chiark.greenend.org.uk Thu May 31 17:03:46 2007 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 31 May 2007 22:03:46 +0100 (BST) Subject: Python memory handling References: <1180611604.247696.149060@h2g2000hsg.googlegroups.com> Message-ID: <6xh*m48Lr@news.chiark.greenend.org.uk> Josh Bloom wrote: > If the memory usage is that important to you, you could break this out > into 2 programs, one that starts the jobs when needed, the other that > does the processing and then quits. > As long as the python startup time isn't an issue for you. And if python startup time is an issue, another possibility is to fork before each job and do the work in the child. -M- From afriere at yahoo.co.uk Mon May 21 23:46:59 2007 From: afriere at yahoo.co.uk (Asun Friere) Date: 21 May 2007 20:46:59 -0700 Subject: Types in Python (was: managed lists?) In-Reply-To: <87bqgdg0ry.fsf@benfinney.id.au> References: <87bqgdg0ry.fsf@benfinney.id.au> Message-ID: <1179803148.505334.136230@z24g2000prd.googlegroups.com> On May 22, 10:28 am, Ben Finney wrote: > "Jorgen Bodde" writes: > > Right now i have a list in a class that I export as a member > > variable to the outside world, it is a standard list (e.g. [] ) but > > I wish to have a stronger type checking when adding objects, that > > only some objects are allowed and others are not. > > This is a poor idiom in Python. The object system allows powerful > polymorphism: the only thing that your application should be checking > is if the objects *can be used* in a particular way, not that they > belong to a specific subset of the type hierarchy. And this very succintly sums up the nature of Python's polymorphism by interface (duck-typing). An understanding of this is central to groking the way typing and OO are done in python. "Jorgen Bodde" writes: > I solved it now, by using isinstance() and giving the class name as > argument to the list There may be some situations in which testing for class (or inheritance) are appropriate, however in the vast majority of cases doing so is a mistake. The object should itself know what to do in any given situation (or throw an exception if it doesn't). Similarly your program should be responding to exceptions rather than checking before hand whether its OK to go on. Instead of reaching for 'isinstance()' you should probably be using 'try : ... except: ...' > and it sometimes frustates me to no end that a wrongly given > argument explodes somewhere deep inside my application without > giving any clue why it blew up in the first place.. If by 'explode' you mean spitting out feedback (as opposed to hanging), you should find at least a few clues. At the very least, you now know one of the exceptions your code will need to handle. Asun From notro at tronnes.org Wed May 9 14:58:38 2007 From: notro at tronnes.org (Noralf Trřnnes) Date: Wed, 9 May 2007 20:58:38 +0200 Subject: ctypes: Problems using Windows-DLL from VB example code References: <4641fd20$1@news.broadpark.no> <4642091d$1@news.broadpark.no> Message-ID: <464219f2$1@news.broadpark.no> Thank you very much! That did the trick. Noralf. From maric at aristote.info Wed May 30 08:11:23 2007 From: maric at aristote.info (Maric Michaud) Date: Wed, 30 May 2007 14:11:23 +0200 Subject: Rats! vararg assignments don't work In-Reply-To: References: <1180496033.608791.35840@g37g2000prf.googlegroups.com> <1180496542.955320.5430@m36g2000hse.googlegroups.com> Message-ID: <465D69EB.3020400@aristote.info> samwyse a ?crit : > George Sakkis wrote: >> On May 29, 11:33 pm, Matimus wrote: >> >> >>> Your attemtp: >>> >>> [code] >>> first, rest = arglist[0], arglist[1:] >>> [/code] >>> >>> Is the most obvious and probably the most accepted way to do what you >>> are looking for. As for adding the fucntionality you first suggested, >>> it isn't likely to be implemented. The first step would be to write a >>> PEP though. >> >> The time machine did it again: http://www.python.org/dev/peps/pep-3132/. > > Thanks! Now I just need to wait for Py3K and all of my problems will be > solved. ;-) > > Actually, I'm surprised that the PEP does as much as it does. If tuples > are implemented as S-expressions, then something like this: > car, *cdr = tuple > while leaving cdr a tuple would be trivial to implement. Of course, I'm > an old-school LISPer, so what I consider surprising behavior doesn't > always surprise anyone else, and vice versa. Remember all these are copies of the original sequence, the lisp equivalent to car/cdr is feasible with an iterator : it = iter(seq) car, cdr = it.next(), it From paul at boddie.org.uk Wed May 16 11:52:43 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 16 May 2007 08:52:43 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de><464762B6.701@web.de> <46478694$0$1412$426a34cc@news.free.fr> <1hy252p.1anf7sr1p4yp12N%aleax@mac.com> <464988a4$0$20289$9b4e6d93@newsspool3.arcor-online.net> <464aaee8$0$10188$9b4e6d93@newsspool4.arcor-online.net> <464afa8d$0$10200$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <1179330761.676441.302650@p77g2000hsh.googlegroups.com> On 16 May, 15:49, Carsten Haese wrote: > > [*] And if you respond that they must know "some" English in the form of > keywords and such, the answer is no, they need not. It is not hard for > Europeans to learn to visually recognize a handful of simple Chinese > characters without having to learn their pronunciation or even their > actual meaning. By the same token, a Chinese person can easily learn to > recognize "if", "while", "print" and so on visually as symbols, without > having to learn anything beyond what those symbols do in a Python > program. I think this is a crucial point being made here. Taking a page from the python.jp site, from which an example was posted elsewhere in the discussion, we see a sprinkling of Latin-based identifiers much like a number of other Japanese sites: http://www.python.jp/Zope/pythondoc_jp/ I know hardly anything about the Japanese language and have heard only anecdotal tales of English proficiency amongst Japanese speakers, but is it really likely that readers of that page (particularly newcomers) know the special pronunciation of "LaTeX" (or even most English readers unfamiliar with that technology) and the derivation of that name, that "Q" specifically means "question", that "HTML" specifically means "Hypertext Markup Language", and so on? It seems to me that modern Japanese culture and society is familiar with such "symbols" without there being any convincing argument to suggest that this is only the case because "they all must know English". Consequently, Python's keywords and even the standard library can exist with names being "just symbols" for many people. It would be interesting to explore the notion of localised versions of the library; the means of providing interoperability between programs and library versions in different languages would be one of the many challenges involved. Paul From mcPas.De.Spam at mclaveauPas.De.Spam.com Mon May 14 11:53:18 2007 From: mcPas.De.Spam at mclaveauPas.De.Spam.com (Michel Claveau) Date: Mon, 14 May 2007 17:53:18 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: Hi ! > - should non-ASCII identifiers be supported? why? > - would you use them if it was possible to do so? in what cases? Yes. And, more: yes yes yes Because: 1) when I connect Python to j(ava)Script, if the pages "connected" contains objects with non-ascii characters, I can't use it ; snif... 2) when I connect Python to databases, if there are fields (columns) with emphatic letters, I can't use class properties for drive these fields. Exemples: "cit?" (french translate of "city") "t?l?phone" (for phone) And, because non-ASCII characters are possible, they are no-obligatory ; consequently guys (snobs?) want stay in pure-ASCII dimension will can. * sorry for my bad english * -- @-salutations Michel Claveau From mike4ty4 at yahoo.com Fri May 4 04:27:45 2007 From: mike4ty4 at yahoo.com (mike3) Date: 4 May 2007 01:27:45 -0700 Subject: Firefighters at the site of WTC7 "Move away the building is going to blow up, get back the building is going to blow up." In-Reply-To: <1178172877.755445.101340@q75g2000hsh.googlegroups.com> References: <1178161820.731367.264500@y80g2000hsf.googlegroups.com> <1178163974.007362.13870@c35g2000hsg.googlegroups.com> <1178172877.755445.101340@q75g2000hsh.googlegroups.com> Message-ID: <1178267265.378650.250200@l77g2000hsb.googlegroups.com> On May 3, 12:14 am, malibu wrote: > On May 2, 9:46 pm, Eric Gisse wrote: > > > On May 2, 7:10 pm, Midex wrote: > > > [...] > > > I guess the explanation that people were looking at the building and > > watching its' structure deform is too rational. > > Also, that was a Larry Silverstein impostor who > said they were going to 'pull it'. > And the only reason he took out huge amounts > of extra insurance on the buildings two months > before this happened was because of global > warming, because we all know a little bit of heat > will bring down steel buildings. > > John Pull = pull out the firefighters. Also, did you know that when they used "pull" to refer to pulling WTC6 it was because they were going to _pull it over_ not blow it up? http://www.debunking911.com/pull.htm From stargaming at gmail.com Thu May 3 19:21:14 2007 From: stargaming at gmail.com (Stargaming) Date: Fri, 04 May 2007 01:21:14 +0200 Subject: How do I get type methods? In-Reply-To: <1178220806.664557.245780@c35g2000hsg.googlegroups.com> References: <1178220806.664557.245780@c35g2000hsg.googlegroups.com> Message-ID: yavannadil at yahoo.com schrieb: > Hello! > > If I do > > import uno > localContext=uno.getComponentContext() > > then localContext is of type > I guess it's a new type provided by PyUNO extension. > localContext.__class__ is None > Is there any way to list all methods of that new type, via Python C > API or through interpreter (other then dir(localContext) )? What's wrong about `dir()`? > What I want is to call localContext's methods like in the tutorial > example: > > x=MyClass() > MyClass.f(x) I'd prefer:: x = MyClass() x.f() > > Thank you, > Dmitri > From apardon at forel.vub.ac.be Thu May 3 08:33:45 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 3 May 2007 12:33:45 GMT Subject: Lazy evaluation: overloading the assignment operator? References: <1178133344.415521.118710@n76g2000hsh.googlegroups.com> <59scumF2lqg76U1@mid.uni-berlin.de> <4639636b$0$14016$c30e37c6@lon-reader.news.telstra.net> <1178185184.795457.253500@h2g2000hsg.googlegroups.com> Message-ID: On 2007-05-03, sturlamolden wrote: > On May 3, 6:22 am, Charles Sanders > wrote: > >> y = a*b+c*d # Returns a proxy object >> >> x = y[4] # Computes x = a[4]*b[4] + c[4]*d[4] >> >> v = y.eval() # Evaluates all elements, returning Xarray >> >> z = ((a+b)*(c+d)).eval() # Also evaluates all elements > > When I suggested this on the NumPy mailing list, I too suggested using > the indexing operator to trigger the computations. But I am worried > that if an expression like > > y = a*b+c*d > > returns a proxy, it is somehow possible to mess things up by creating > cyclically dependent proxies. I may be wrong about this, in which case > __getitem__ et al. will do the job. How do you expect to handle the following kind of situation: while : x = y a = ... b = ... y = a * x + b -- Antoon Pardon From stefan.behnel-n05pAM at web.de Sun May 13 15:10:46 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sun, 13 May 2007 21:10:46 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46473267$0$31532$9b622d9e@news.freenet.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <464762B6.701@web.de> Martin v. L?wis schrieb: > PEP 1 specifies that PEP authors need to collect feedback from the > community. As the author of PEP 3131, I'd like to encourage comments > to the PEP included below, either here (comp.lang.python), or to > python-3000 at python.org > > In summary, this PEP proposes to allow non-ASCII letters as > identifiers in Python. If the PEP is accepted, the following > identifiers would also become valid as class, function, or > variable names: L?ffelstiel, chang?, ??????, or ??? > (hoping that the latter one means "counter"). > > I believe this PEP differs from other Py3k PEPs in that it really > requires feedback from people with different cultural background > to evaluate it fully - most other PEPs are culture-neutral. > > So, please provide feedback, e.g. perhaps by answering these > questions: > - should non-ASCII identifiers be supported? why? > - would you use them if it was possible to do so? in what cases? To make it clear: this PEP considers "identifiers written with non-ASCII characters", not "identifiers named in a non-english language". While the first is already allowed as long as the transcription uses only ASCII characters, the second is currently forbidden and is what this PEP is about. Now, I am not a strong supporter (most public code will use English identifiers anyway) but we should not forget that Python supports encoding declarations in source files and thus has much cleaner support for non-ASCII source code than, say, Java. So, introducing non-ASCII identifiers is just a small step further. Disallowing this does *not* guarantee in any way that identifiers are understandable for English native speakers. It only guarantees that identifiers are always *typable* by people who have access to latin characters on their keyboard. A rather small advantage, I'd say. The capability of a Unicode-aware language to express non-English identifiers in a non-ASCII encoding totally makes sense to me. Stefan From rdm at rcblue.com Thu May 10 07:56:47 2007 From: rdm at rcblue.com (Dick Moores) Date: Thu, 10 May 2007 04:56:47 -0700 Subject: preferred windows text editor? In-Reply-To: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> References: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> Message-ID: <20070510115651.824A21E400C@bag.python.org> At 11:06 AM 5/9/2007, T. Crane wrote: >Right now I'm using Notepad++. What are other people using? Ulipad. Dick Moores From __peter__ at web.de Fri May 4 03:14:31 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 04 May 2007 09:14:31 +0200 Subject: urllib.quote fails on Unicode URL References: Message-ID: John Nagle wrote: > The code in urllib.quote fails on Unicode input, when > called by robotparser. > > That bit of code needs some attention. > - It still assumes ASCII goes up to 255, which hasn't been true in > Python > for a while now. > - The initialization may not be thread-safe; a table is being > initialized > on first use. The code is too clever and uncommented. > > "robotparser" was trying to check if a URL, > "http://www.highbeam.com/DynamicContent/%E2%80%9D/mysaved/privacyPref.asp%22" > could be accessed, and there are some wierd characters in there. Unicode > URLs are legal, so this is a real bug. > > Logged in as Bug #1712522. There has been a related discussion: http://groups.google.com/group/comp.lang.python/browse_thread/thread/b331dc3625dbfc41/ce6e6a3c0635e340 IIRC the outcome was that while UTF-8 is recommended urllib.quote()/unquote() should not guess the encoding. What changes that would imply for robotparser I don't know... Peter From aleax at mac.com Thu May 31 11:06:23 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 31 May 2007 08:06:23 -0700 Subject: Good Python style? References: Message-ID: <1hyywcm.1xykj1n1ybfnzrN%aleax@mac.com> Andreas Beyer wrote: > Hi, > > I found the following quite cryptic code, which basically reads the > first column of some_file into a set. > In Python I am used to seeing much more verbose/explicit code. However, > the example below _may_ actually be faster than the usual "for line in ..." > Do you consider this code good Python style? Or would you recommend to > refrain from such complex single-line code?? > > Thanks! > Andreas > > inp = resource(some_file) > # read first entries of all non-empty lines into a set > some_set = frozenset([line.split()[0] for line in \ > filter(None, [ln.strip() for ln in inp])]) Sparse is better than dense, and this code is far from the fastest one could write -- it builds useless lists comprehensions where genexps would do, it splits off all whitespace-separated words (rather than just the first one) then tosses all but the first away, etc. frozenset(first_word_of_line for line in input_file for first_word_of_line in line.split(None, 1)[:1] ) does not sacrifice any speed (on the contrary), yet achieves somewhat better clarity by clearer variable names, reasonable use of whitespace for formatting, and avoidance of redundant processing. If this set didn't have to be frozen, building it in a normal for loop (with a .add call in the nested loop) would no doubt be just as good in terms of both clarity and performance; however, frozen sets (like tuples) don't lend themselves to such incremental building "in place" (you'd have to build the mutable version, then "cast" it at the end; the alternative of making a new frozenset each time through the loop is clearly unpleasant), so I can see why one would want to avoid that. A good, readable, and only slightly slower alternative is to write a named generator: def first_words(input_file): for line in input_file: first_word_if_any = line.split(None, 1) if first_word_if_any: yield first_word_if_any[0] ff = frozenset(first_words(input_file)) A full-fledged generator gives you more formatting choices, an extra name to help, and the possibility of naming intermediate variables. Whether it's worth it in this case is moot -- personally I find the "slice then for-loop" idiom (which I used in the genexp) just as clear as the "test then index" one (which I used in first_words) to express the underlying notion "give me the first item if any, but just proceed without giving anything if the list is empty"; but I can imagine somebody else deciding that the test/index idiom is a more direct expression of that notion. You could use it in a genexp, too, of course: frozenset(first_word_if_any[0] for line in input_file for first_word_if_any in [line.split(None, 1)] if first_word_if_any ) but this requires the "for x in [y]" trick to simulate the "x=y" assigment of an intermediate variable in a genexp or LC, which is never an elegant approach, so I wouldn't recommend it. Alex From bscrivener42 at gmail.com Wed May 9 18:21:41 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: 9 May 2007 15:21:41 -0700 Subject: preferred windows text editor? In-Reply-To: References: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> Message-ID: <1178749301.768963.278070@w5g2000hsg.googlegroups.com> On May 9, 1:26 pm, "Looney, James B" wrote: > I'm using Vim (http://www.vim.org/). I too vote for VIM. I use it on both Windows XP and Debian Etch. I can't find anything it doesn't do. rd From dotancohen at gmail.com Sat May 5 10:47:04 2007 From: dotancohen at gmail.com (Dotan Cohen) Date: Sat, 5 May 2007 17:47:04 +0300 Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? In-Reply-To: <0k8p33h90bp5tfajedb4bmd2eik8gfi2ho@4ax.com> References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> <08qk33t594ih0ulmjmev90d22lkfnotgoe@4ax.com> <463C2A3A.8332D211@hotmail.com> <0k8p33h90bp5tfajedb4bmd2eik8gfi2ho@4ax.com> Message-ID: <880dece00705050747j30ba2084r87d58868d8d76903@mail.gmail.com> I missed the relevancy to Python in this thread. Could someone, preferably the OP, please quote it? Thanks in advance. Dotan Cohen http://lyricslist.com/ http://what-is-what.com/ From gagsl-py2 at yahoo.com.ar Thu May 10 21:36:19 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 10 May 2007 22:36:19 -0300 Subject: How to find C source References: <1178844459.271906.92560@o5g2000hsb.googlegroups.com> Message-ID: En Thu, 10 May 2007 21:47:39 -0300, escribi?: > How do I get to the source for parser.suite()? Are you looking for function parser_suite in parsermodule.c? -- Gabriel Genellina From rtw at freenet.co.uk Sun May 6 14:23:11 2007 From: rtw at freenet.co.uk (Rob Williscroft) Date: Sun, 06 May 2007 13:23:11 -0500 Subject: Error when using Custom Exception defined in a different python module. References: <1178475284.092656.103710@e65g2000hsc.googlegroups.com> Message-ID: wrote in news:1178475284.092656.103710 at e65g2000hsc.googlegroups.com in comp.lang.python: > Hi, > > I am hitting this error consistently and don't know why it's > happening. I would like to define all exceptions for my project in one > file and use them across the project. Here's a sample - > > exceptions.py - > from exceptions import * > raise MyException("Raise custom error") > > When the above is run, I get the following error - > NameError: global name 'MyException' is not defined When you get this kind of error, goto a python prompt (type python at a command prompt, or click on IDLE) and try this: >>> import exceptions >>> help( exceptions ) I got this response (clipped): Help on built-in module exceptions: NAME exceptions - Python's standard exception class hierarchy. Another common module name to avoid is "test". Rob. -- http://www.victim-prime.dsl.pipex.com/ From bumtool at gmail.com Mon May 28 07:56:41 2007 From: bumtool at gmail.com (kilnhead) Date: 28 May 2007 04:56:41 -0700 Subject: pyAntTasks Message-ID: <1180353401.548751.110330@p77g2000hsh.googlegroups.com> I am trying to use pyAntTasks in Eclipse. I have followed the example in the ibm doc, but I get the following error: [taskdef] Could not load definitions from resource pyAntTasks.properties. It could not be found. I have added pyAntTasks to my classpath and AntHome directory. Anybody have any ideas? From duncan.booth at invalid.invalid Wed May 2 14:10:37 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 May 2007 18:10:37 GMT Subject: Need Help in Preparing for Study of Python by Forrester Research References: Message-ID: Jeff Rush wrote: > Initially, they'd like feedback (not yet the answers themselves) from > us regarding their proposed evaluation criteria - questions to add or > that give no value, rewording to make them more clear. I've posted > their draft criteria, which came as a spreadsheet at: > > http://dfwpython.org/uploads/ForresterPrep/DynamicLanguagesCriteria.x > ls > That's a somewhat weird definition of polymorphism: > Polymorphism > Does the language support polymorphic behavior? > Measured by support for polymorphics behavior 5 = functions/methods > can be overridden and the developer can define identical function > names with different parameter sets. 1 = functions cannot be > overridden but identical function names with different parameter sets > can be defined 0 = functions cannot be overridden and only one > function can be defined with a given function name Polymorphism means you can write a single function which operates with different data types, not that you can override methods or write multiple functions with the same name (that is known as overloading). Overriding and overloading are different things than polymorphism. If you want a separate question about overriding then your criteria are still a bit strange: Python methods can be overridden but not overloaded[*] so none of your possible answers applies. [*] Unless you write some code to support overloading, which is easy enough to do but not something most people bother with. From gh at gregor-horvath.com Wed May 16 05:59:58 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Wed, 16 May 2007 11:59:58 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179307776.953405.207680@l77g2000hsb.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179289167.723990.223890@u30g2000hsc.googlegroups.com> <464abd12$0$23364$426a34cc@news.free.fr> <1179307776.953405.207680@l77g2000hsb.googlegroups.com> Message-ID: sjdevnull at yahoo.com schrieb: > code on the (GUI-less) production servers over a terminal link. They > have to use all kinds of environments where they can't install the > latest and greatest fonts. Promoting code that becomes very hard to > read and debug in real situations seems like a sound negative to me. If someone wants to debug a Chinese program, he has in almost all cases obviously already installed the correct fonts and his machine can handle unicode. Maybe yours and mine not, but I doubt that we are going to debug a chinese program. I have debugged German programs (not python) with unicode characters in it for years and had no problem at all, because all customers and me have obviously German machines. Gregor From gabor.urban at siemens.com Fri May 4 08:45:11 2007 From: gabor.urban at siemens.com (Urban, Gabor) Date: Fri, 4 May 2007 14:45:11 +0200 Subject: unittest dependencies In-Reply-To: <1178140170.849347.79190@h2g2000hsg.googlegroups.com> References: <1178140170.849347.79190@h2g2000hsg.googlegroups.com> Message-ID: <38F58D7B92CB20438DF49D28B572CC6FE3B3B7@budgw09a.ww300.siemens.net> Hullo! I have several questions about this problem. Do you have more test scripts using the unittest framework? My blind idea would be the following: run test b first, and go forward when no errors are found. To do this you could change the TestRunner component. The official documentation is good enough. Good luck, Gabor Urban NMC - ART -----Original Message----- From: python-list-bounces+gabor.urban=siemens.com at python.org [mailto:python-list-bounces+gabor.urban=siemens.com at python.org] On Behalf Of urielka Sent: 2007. m?jus 2. 23:10 To: python-list at python.org Subject: unittest dependencies i am using unittest to test a project,and one thing i really want is a way to say that test a depends on test b,so it need to run before it and be successful in order to run this test. i just wanted to know if anyone have done it before(i searched for it but didn`t find something useful),i think it can be done easily using a decorator that will run the test which is depend on and mark it as successful,the only problem will be detecting circular test dependencies,but that can be fixed by keeping all the functions that the decorator have seen. what do you guys think? did someone did it before? -- http://mail.python.org/mailman/listinfo/python-list From bbxx789_05ss at yahoo.com Sat May 19 13:23:48 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 19 May 2007 10:23:48 -0700 Subject: Beginner question: module organisation In-Reply-To: <1179593109.409934.193690@l77g2000hsb.googlegroups.com> References: <1179148188.698342.317080@w5g2000hsg.googlegroups.com> <1179593109.409934.193690@l77g2000hsb.googlegroups.com> Message-ID: <1179595428.485794.160300@q75g2000hsh.googlegroups.com> On May 19, 10:45 am, 7stud wrote: > > refineModule.py: > --------------- > def refine(userfunc, mesh): > #process mesh > func(mesh) > The last line should be: userfunc(mesh) From enleverlesX.XmcX at XmclaveauX.com Wed May 2 01:31:19 2007 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Wed, 2 May 2007 07:31:19 +0200 Subject: Tcl-tk 8.5? Message-ID: <46382248$0$5105$ba4acef3@news.orange.fr> Hi! See http://wiki.tcl.tk/10630 Any plan to integrate Tcl 8.5 in standard Python? @+ MCI From ptmcg at austin.rr.com Thu May 17 20:14:09 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 17 May 2007 17:14:09 -0700 Subject: How to convert a number to binary? In-Reply-To: <1179445546.307017.275850@p77g2000hsh.googlegroups.com> References: <1179444832.775573.55830@y80g2000hsf.googlegroups.com> <1179445546.307017.275850@p77g2000hsh.googlegroups.com> Message-ID: <1179447249.556198.77780@q75g2000hsh.googlegroups.com> "".join([('0','1')[bool(n & 2**i)] for i in range(20) if n>2**i] [::-1]) Still only valid up to 2**20, though. -- Paul From gregcorradini at gmail.com Tue May 8 15:21:39 2007 From: gregcorradini at gmail.com (Greg Corradini) Date: Tue, 8 May 2007 12:21:39 -0700 (PDT) Subject: 1.#QNAN Solution In-Reply-To: <1341e74982jkr46@corp.supernews.com> References: <10379999.post@talk.nabble.com> <1341e74982jkr46@corp.supernews.com> Message-ID: <10382201.post@talk.nabble.com> Thanks for you help Grant Grant Edwards wrote: > > On 2007-05-08, Greg Corradini wrote: > >> I'm running descriptive stats on mileages from a database >> (float numbers, about a million records). My sum returns >> 1.#QNAN, which I understand from searching this forum is an >> error. > > Not necessarily. You've ended up with a floating point "not a > number" value (AKA a NaN). That might or might not be an > error. Whether it's an error not not depends on your input > data and your algorithm. > >> While I'm looking for help in solving this problem, I'm more >> interested in a general explanation about the cause of this >> problem. > > If you're asking how you end up with a NaN, there are several > ways to generate a NaN: > > 0/0 > > Inf*0 > > Inf/Inf > > Inf-Inf > > Almost any operation on a NaN > > http://en.wikipedia.org/wiki/NaN > http://steve.hollasch.net/cgindex/coding/ieeefloat.html > > -- > Grant Edwards grante Yow! Spreading peanut > at butter reminds me of > visi.com opera!! I wonder why? > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/1.-QNAN-Solution-tf3710941.html#a10382201 Sent from the Python - python-list mailing list archive at Nabble.com. From fadereu at gmail.com Mon May 28 01:17:11 2007 From: fadereu at gmail.com (DJ Fadereu) Date: 27 May 2007 22:17:11 -0700 Subject: ten small Python programs In-Reply-To: References: Message-ID: <1180329431.346676.256000@a26g2000pre.googlegroups.com> > > You could try this wiki page: > > http://rosettacode.org/wiki/Main_Page > > It has a fair amount of Python examples as well as many more other > languages (doing the same algorithm). > > Hope this helps. > > Adonis THIS IS GREAT :) Thanx! From bhoel at despammed.com Mon May 21 15:24:55 2007 From: bhoel at despammed.com (Berthold =?utf-8?Q?H=C3=B6llmann?=) Date: Mon, 21 May 2007 21:24:55 +0200 Subject: Moving class used in pickle References: Message-ID: Jeffrey Barish writes: > I have a class derived from string that is used in a pickle. In the new > version of my program, I moved the module containing the definition of the > class. Now the unpickle fails because it doesn't find the module. I was > thinking that I could make the unpickle work by putting a copy of the > module in the original location and then redefine the class by sticking a > __setstate__ in the class thusly: > > def __setstate__(self, state): > self.__dict__.update(state) > self.__class__ = NewClassName > > My plan was to specify the new location of the module in NewClassName. > However, when I do this I get the message "'class' object layout differs > from 'class'". I don't think that they do as the new module is a copy of > the old one. I suspect that I am not allowed to make the class assignment > because my class is derived from string. What is the best way to update > the pickle? The only thought I have is to read all the data with the old > class module, store the data in some nonpickle format, and then, with > another program, read the nonpickle-format file and rewrite the pickle with > the class module in the new location. You can fiddle with the file class used reading the pickled file. I.e. the "read()" method could replace each instance of "foo.myclass" by "greatnewmodule.mynewclass" could bring you back in the game. Porting some applications of my from 32 to 64 bit i discovered that my Numeric int arrays really had to be int32. So i opened the (binary) pickled files and replaced the occurences of "'l'" by "'i'". Later we replaced Numeric by numpy. I used the editor approach again to replace "Numeric" string by "numpy" or "numpy.oldnumeric". A collegue of mine wrote a small reader class implementing the approach working on the input stream. Regards Berthold -- From howe.steven at gmail.com Tue May 8 23:29:49 2007 From: howe.steven at gmail.com (Steven Howe) Date: Tue, 08 May 2007 20:29:49 -0700 Subject: SEO - Search Engine Optimization - Seo Consulting In-Reply-To: References: <1177808356.681710.42980@n76g2000hsh.googlegroups.com> <#O8fXGAjHHA.3700@TK2MSFTNGP06.phx.gbl> <1178160448.699851.227600@p77g2000hsh.googlegroups.com> Message-ID: <4641402D.2020701@gmail.com> Steve Holden wrote: > Steven D'Aprano wrote: > >> On Wed, 02 May 2007 19:47:28 -0700, Huck Phin wrote: >> > [a request for peace, love and understanding, concluding with] > >>> We all should be a little more considerate of each other. >>> >> And if the hippy hug fest fails to stop spamming, perhaps we'll be allowed >> to hunt them down like rabid dogs and stick their heads up on pikes as a >> warning to others. >> >> Hey, a man can dream can't he??? *wink* >> >> >> > Yeah, just ONE day a year when we could roast them on spits over open > fires ... just to discourage the survivors, you understand. > > regards > Steve > Man Steven, you really need someone to give you a huge and possibly some sex. You're way too mean and aggressive for a site where people are looking for help. Yes, some messages are out of place, but 'burning the witch' talk is just way, way out there. I suggest you join the Republican party and lose some more brain cell (i.e. program in Visual Basic) or better yet, learn to filter your e-mail. That's a thought; I think I'll filter you. :) sph -- HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -------------- next part -------------- An HTML attachment was scrubbed... URL: From jstroud at mbi.ucla.edu Sat May 12 00:20:51 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 11 May 2007 21:20:51 -0700 Subject: name capitalization of built-in types, True, and False In-Reply-To: <1178915868.650553.219430@h2g2000hsg.googlegroups.com> References: <1178915868.650553.219430@h2g2000hsg.googlegroups.com> Message-ID: cbtube03 at gmail.com wrote: > I see that naming conventions are such that classes usually get named > CamelCase. So why are the built-in types named all lowercase (like > list, dict, set, bool, etc.)? > > And names for instances of classes are usually written in lowercase, > like foo in ``foo = CamelCase()``. So why are True and False > (instances of bool) capitalized? Shouldn't they be "true" and "false"? > Same goes for None. > My guess is that TRUE, FALSE, and NONE are fairly unbecoming and all lowercase would not do justice to their status as language constants. From erikwickstrom at gmail.com Sun May 27 16:55:12 2007 From: erikwickstrom at gmail.com (erikcw) Date: 27 May 2007 13:55:12 -0700 Subject: Can python create a dictionary from a list comprehension? Message-ID: <1180299312.207986.4340@k79g2000hse.googlegroups.com> Hi, I'm trying to turn o list of objects into a dictionary using a list comprehension. Something like entries = {} [entries[int(d.date.strftime('%m'))] = d.id] for d in links] I keep getting errors when I try to do it. Is it possible? Do dictionary objects have a method equivalent to [].append? Maybe a lambda? Thanks for your help! Erik From john at datavoiceint.com Thu May 17 13:35:56 2007 From: john at datavoiceint.com (HMS Surprise) Date: 17 May 2007 10:35:56 -0700 Subject: Declaring variables In-Reply-To: <134oq09mlrqju81@corp.supernews.com> References: <1179334649.990688.73320@o5g2000hsb.googlegroups.com> <134mea4o0svae73@corp.supernews.com> <1179342961.494519.103620@u30g2000hsc.googlegroups.com> <134oq09mlrqju81@corp.supernews.com> Message-ID: <1179423356.372250.115080@u30g2000hsc.googlegroups.com> On May 17, 9:34 am, Grant Edwards wrote: > On 2007-05-16, HMS Surprise wrote: > > > No haven't had to endure Pascal. Mostly C/C++, Tcl, and assembler. > > I must have you mixed up with somebody else who recently > mentioned having Pascal as their first real language. > > -- > Grant Edwards grante Yow! It's OKAY -- I'm an > at INTELLECTUAL, too. > visi.com That's OK. I am easily mixed up. From __peter__ at web.de Fri May 18 05:08:24 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 May 2007 11:08:24 +0200 Subject: Unusual i/o problems References: <1179325595.708882.289510@e65g2000hsc.googlegroups.com> <1179471578.531264.51220@u30g2000hsc.googlegroups.com> <1179478960.749659.258480@q75g2000hsh.googlegroups.com> Message-ID: saif.shakeel at gmail.com wrote: > On May 18, 1:01 pm, Peter Otten <__pete... at web.de> wrote: >> saif.shak... at gmail.com wrote: >> > I am running the exe from command prompt,but i am not able to see >> > the error as it goes off very quickly. >> >> http://effbot.org/pyfaq/how-do-i-run-a-python-program-under-windows.htm >> >> > How do i capture the error (traceback).I tried putting an input prompt >> > after the expected line of error but wont work.Is there a command to >> > capture the error. >> >> You can redirect stderr to a file: >> >> http://www.microsoft.com/resources/documentation/windows/xp/all/prodd... >> >> Peter > > ok i traced the error for above code.It says something like this: > Traceback (most recent call last): > File "C:\Projects\ODX Import\code_ini\odxparse_mod.py", line 294, in > > input_xml_sec = open(output_file,'r') > TypeError: coercing to Unicode: need string or buffer, file found > Can someone help me in this. > Thanks I already pointed you to the error in my first post in this thread. output_file is a file, but open() expects a file name. Peter From padhia at yahoo.com Mon May 21 17:45:11 2007 From: padhia at yahoo.com (P. Adhia) Date: 21 May 2007 14:45:11 -0700 Subject: Invalid pointer when accessing DB2 using python scripts Message-ID: <1179783911.116870.54360@a26g2000pre.googlegroups.com> Hello, I was wondering if anyone is successfully using using Python(2.5)+DB2+pydb2. I get an error in all situations. It seems that this problem might be limited to python 2.5. A quick Google search suggests that with Python 2.5, memory model has become more stringent and mixing various types of memory calls are likely to produce this error. I am not familiar with writing Python C extensions, but from what I can tell, pydb2 extension is using only one type of memory call. Any workaround besides falling back to python 2.4? It seems pydb2 project isn't very active. I think IBM officially supports only PHP, ruby and perl, does IBM have any plans to support python bindings for DB2? Thanks P Adhia Environment: Ubuntu : Fiesty Fawn Python 2.5.1c1 (release25-maint, Apr 12 2007, 21:00:25) DB2 9.1.2 Error: *** glibc detected *** python: free(): invalid pointer: 0xppppppp *** A simple program to reproduce this error. #! /usr/bin/env python import DB2 con = DB2.connect('ANYDB', 'xxxxxx', 'xxxxxx') csr = con.cursor() csr.close() con.close() From puffjacket67 at hotmail.com Mon May 21 18:00:27 2007 From: puffjacket67 at hotmail.com (ddddddddd dddddddddddddd) Date: Tue, 22 May 2007 02:00:27 +0400 Subject: Python Web Programming - looking for examples of solid high-traffic sites Message-ID: [Bruno Desthuilliers]> John, I'm really getting tired of your systemic and totally > unconstructive criticism. If *you* are not happy with Python, by all > means use another language. You are saying bad things about my darling! Python is my baby! Shame on you John Nagle, if you do it again I'll really beat you up and if I can't I'll call my brother who really knows CS!!!!! Side note: John Nagle contributed several bug reports, bug fixes and discussion about general features of python, pro and con. He is not a brainless fanboy, that is true :)[John Nagle]>> YouTube's home page is PHP. Try "www.youtube.com/index.php".>> That works, while the obvious alternatives don't.>> If you look at the page HTML, you'll see things like>>>> > onclick="_hbLink('LogIn','UtilityLinks');">Log In>>>> So there's definitely PHP inside YouTube.[Bruno Desthuilliers]> What about learning more on web servers configuration ?> http://zope.alostnet.eu/index.php> > "definitively php", hu ?What about reading what the person you are replying to actually wrote in this thread 3 days ago?http://mail.python.org/pipermail/python-list/2007-May/441376.htmlYou just gotta love the brainless fanboys that breed around each and every programming language :)Puff _________________________________________________________________ Connect to the next generation of MSN Messenger? http://imagine-msn.com/messenger/launch80/default.aspx?locale=en-us&source=wlmailtagline -------------- next part -------------- An HTML attachment was scrubbed... URL: From bbxx789_05ss at yahoo.com Wed May 23 13:52:25 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 23 May 2007 10:52:25 -0700 Subject: f.readline(), for line in f Message-ID: <1179942745.407006.113410@o5g2000hsb.googlegroups.com> Hi, 1) Does this make any sense: """ Thus, the loop: for line in f: iterates on each line of the file. Due to buffering issues, interrupting such a loop prematurely(e.g. with break), or calling f.next() instead of f.readline(), leaves the files position set to an arbitrary value. """ The docs say: """ next( ) A file object is its own iterator, for example iter(f) returns f (unless f is closed). When a file is used as an iterator, typically in a for loop (for example, for line in f: print line), the next() method is called repeatedly. This method returns the next input line, or raises StopIteration when EOF is hit. 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 experimented with this test code: f = open("aaa.txt", "w") for i in range(1000): f.write("line " + str(i) + "\n") f.close() f = open("aaa.txt", "r") for line in f: print f.next() print f.readline() break print f.next() print f.readline() f.close() and the output was: line 1 922 line 2 line 923 So, it looks like f.readline() is what messes things up--not f.next(). "for line in f" appears to be reading a chunk of the file into a buffer, and then readline() gets the next line after the chunk. 2) Does f.readline() provide any buffering? It doesn't look like it when I run this code and examine the output: f = open("aaa.txt", "w") for i in range(3000): f.write("line " + str(i) + "\n") f.close() f = open("aaa.txt", "r") for line in f: print f.next() print f.readline() f.close() The first few lines of the the output are: line 1 922 line 3 line 923 line 5 line 924 (I assume the skipping from 1 to 3 to 5 is caused by the automatic call to f.next() when the for loop begins in addition to the explicit call to f.next() inside the loop.) I interpret the output to mean that the chunk of the file put in the buffer by "for line in f", ends in the middle of line 922, and "print f.readline()" is printing the first line past the buffer. Scrolling down to where "print f.next()" reaches line 922, I see this: line 919 line 1381 line 921 line 1382 line 1384 <-----** line 2407 <-----** which means that when the buffer that was created by "for line in f" is empty, the next chunk starting directly after the current position of the readline() file position is put in the buffer. That indicates that readline() provides no buffering. Then, the next call to readline() jumps to a position after the chunk that was used to replenish the buffer. From see.signature at no.spam Wed May 30 04:04:56 2007 From: see.signature at no.spam (Eric Brunel) Date: Wed, 30 May 2007 10:04:56 +0200 Subject: Tkinter Listbox - Different Text colors in one listbox References: <1180458123.139727.182500@d30g2000prg.googlegroups.com> Message-ID: On Tue, 29 May 2007 19:02:03 +0200, wrote: > Hi, > Is it possible to have different items in a listbox in different > colors? Or is it just one color for all items in a listbox? > Thanks > Rahul > AFAIK, this is not possible with a listbox. You can however quite easily emulate the behaviour of a listbox with a text widget, which allows to mix fonts and colors in any way you like. I did it once by creating a sub-class of Tkinter.Text (cannot post the code here - closed source, sorry...) and all I had to do was: - make sure the text widget had its state to DISABLED all the time, except when modifying it; - removing all the bindings defined in the text widgets (use widget.bind_class('Text') to get all the events, then widget.bind(event, lambda e: 'break') to remove them); - define a new binding for a button click selecting the line under the cursor; - define the insert, delete and getcurselection methods, taking care of treating the special index END. All in all, this was just a few dozen lines. HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From stefan.behnel-n05pAM at web.de Mon May 14 07:49:41 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 14 May 2007 13:49:41 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179142941.222428.113150@w5g2000hsg.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179142941.222428.113150@w5g2000hsg.googlegroups.com> Message-ID: <46484CD5.8070304@web.de> Marco Colombo wrote: > I suggest we keep focused on the main issue here, which is "shoud non- > ascii identifiers be allowed, given that we already allow non-ascii > strings literals and comments?" > > Most arguments against this proposal really fall into the category > "ascii-only source files". If you want to promote code-sharing, then > you should enfore quite restrictive policies: > - 7-bit only source files, so that everyone is able to correctly > display and _print_ them (somehow I feel that printing foreign glyphs > can be harder than displaying them) ; > - English-only, readable comments _and_ identifiers (if you think of > it, it's really the same issue, readability... I know no Coding Style > that requires good commenting but allows meaningless identifiers). > > Now, why in the first place one should be allowed to violate those > policies? One reason is freedom. Let me write my code the way I like > it, and don't force me writing it the way you like it (unless it's > supposed to be part of _your_ project, then have me follow _your_ > style). > > Another reason is that readability is quite a relative term... > comments that won't make any sense in a real world program, may be > appropriate in a 'getting started with' guide example: > > # this is another way to increment variable 'a' > a += 1 > > we know a comment like that is totally useless (and thus harmful) to > any programmer (makes me think "thanks, but i knew that already"), but > it's perfectly appropriate if you're introducing that += operator for > the first time to a newbie. > > You could even say that most string literals are best made English- > only: > > print "Ciao Mondo!" > > it's better written: > > print _("Hello World!") > > or with any other mean to allow the i18n of the output. The Italian > version should be implemented with a .po file or whatever. > > Yet, we support non-ascii encodings for source files. That's in order > to give authors more freedom. And freedom comes at a price, of course, > as non-ascii string literals, comments and identifiers are all harmful > to some extents and in some contexts. > > What I fail to see is a context in which it makes sense to allow non- > ascii literals and non-ascii comments but _not_ non-ascii identifiers. > Or a context in which it makes sense to rule out non-ascii identifiers > but not string literals and comments. E.g. would you accept a patch > with comments you don't understand (or even that you are not able to > display correctly)? How can you make sure the patch is correct, if you > can't read and understand the string literals it adds? > > My point being that most public open source projects already have > plenty of good reasons to enforce an English-only, ascii-only policy > on source files. I don't think that allowing non-ascii indentifiers at > language level would hinder thier ability to enforce such a policy > more than allowing non-ascii comments or literals did. > > OTOH, I won't be able to contribute much to a project that already > uses, say, Chinese for comments and strings. Even if I manage to > display the source code correctly here, still I won't understand much > of it. So I'm not losing much by allowing them to use Chinese for > identifiers too. > And whether it was a mistake on their part not to choose an "English > only, ascii only" policy it's their call, not ours, IMHO. Very well written. +1 Stefan From python at hope.cz Wed May 23 04:11:54 2007 From: python at hope.cz (Johny) Date: 23 May 2007 01:11:54 -0700 Subject: httpd: Syntax error on line 54 In-Reply-To: <1179817058.576484.135570@y2g2000prf.googlegroups.com> References: <1179817058.576484.135570@y2g2000prf.googlegroups.com> Message-ID: <1179907914.742099.279980@g4g2000hsf.googlegroups.com> On May 22, 8:57 am, deepak wrote: > I installed apache 2.2.4 and modPython 3.3.1 on Fc6 > while starting the apache server the following error occurs: > > httpd: Syntax error on line 54 of /usr/local/apache2/conf/httpd.conf: > Cannot load /usr/local/apache2/modules/mod_python.so into server: /usr/ > local/apache2/modules/mod_python.so: cannot restore segment prot after > reloc: Permission denied > > help plz Can Apache start wo/mod_python? If so, check mod_python( permissions) installation From gagsl-py2 at yahoo.com.ar Mon May 7 02:48:18 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 07 May 2007 03:48:18 -0300 Subject: default test method name in unittest framework References: <271115400705061817u3c8ee950u3c7b0ec7ddcf6576@mail.gmail.com> Message-ID: En Sun, 06 May 2007 22:17:44 -0300, Vyacheslav Maslov escribi?: > i have question related to python's unit testing framework. > > Take a look at unittest.TestCase class. The main method which contains > all > code related to test case execution have name "run". But in the same time > constructor of unittest.TestCase class have param methodName with default > value "runTest", not "run"! Why? This leads to AttributeError exception > if i > do not explicitly set methodName to "run" during TestCase initialization. No: method run is used by the framework, it internally calls the setUp, tearDown, etc. You don't have to override run (you must not override run!), instead, you provide the runTest method in your class. Furthermore, instead of many similar TestCase classes, you can write a single class with many methods named testXXX, and they will be found and used by a TestLoader. -- Gabriel Genellina From duncan.booth at invalid.invalid Tue May 15 03:38:38 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 15 May 2007 07:38:38 GMT Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> <4648294F.2000704@web.de> <46487a6c$0$2400$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Stefan Behnel a ?crit : >> Bruno Desthuilliers wrote: >>> but CS is english-speaking, period. >> >> That's a wrong assumption. > > I've never met anyone *serious* about programming and yet unable to > read and write CS-oriented technical English. > I don't believe that Python should be restricted to people *serious* about programming. Recently there has been quite a bit of publicity about the One Laptop Per Child project. The XO laptop is just beginning rollout to children and provides two main programming environments: Squeak and Python. It is an exciting thought that that soon there will be millions of children in countries such as Nigeria, Brazil, Uruguay or Nepal[*] who have the potential to learn to program, but tragic if the Python community is too arrogant to consider it acceptable to use anything but English and ASCII. Yes, any sensible widespread project is going to mandate a particular language for variable names and comments, but I see no reason at all why they all have to use English. [*] BTW, I see OLPC Nepal is looking for volunteer Python programmers this Summer: if anyone fancies spending 6+ weeks in Nepal this Summer for no pay, see http://www.mail-archive.com/devel at laptop.org/msg04109.html From gagsl-py2 at yahoo.com.ar Thu May 10 19:58:46 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 10 May 2007 20:58:46 -0300 Subject: Newbie look at Python and OO References: <1178812734.860473.236370@y80g2000hsf.googlegroups.com> <1178832102.256466.235020@l77g2000hsb.googlegroups.com> Message-ID: En Thu, 10 May 2007 18:21:42 -0300, escribi?: > These conversations are funny to me. I use Python every day and I > have never actually thought about the implications of binding objects > to names, or two names pointing to the same object. Problems of this > sort just never come up in actual programming for me. It just works. > > Python was my virgin language, so maybe that just makes it natural to > me, but it seems like people coming from other languages get hung up > on testing out the differences and theories rather than just > programming in it. Alas, maybe I have yet to get deep enough to run > into these kinds of problems. Certainly, learning Python as a first language has some advantages. But I think you'd feel a bit shocked if you had to program in C++ someday; these rather innocent lines might not do what you think: a = 0; b = a; From a C++ point of view, it would be natural that: - a is not 0, and it might not even be a number. - (a==0) may be false, and (b==0) too. - b is not the same thing as a, may be a totally different type, and if it were something like Python's "mutable containers", mutating b would have no effect on a. Simple things have so complex and ugly rules that... ugh, enough for now. But people coming from other languages/backgrounds may think Python syntax a bit strange at first - just for a while, but if they can pass the "Gimme my curly braces back!" stage, most end loving Python. -- Gabriel Genellina From robert.kern at gmail.com Thu May 31 20:07:58 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 31 May 2007 19:07:58 -0500 Subject: call function in console without paranthesis In-Reply-To: <465f3dbc$0$52092$edfadb0f@dread11.news.tele.dk> References: <465f3dbc$0$52092$edfadb0f@dread11.news.tele.dk> Message-ID: Troels Thomsen wrote: > Hello, > > I am wondering if I can write some code, that allows me to call functions in > the console , IDLE, without using the paranthesis notation. Like print. > This will improve "intreractive'ness" > > serialOpen() # some magic is issued here !!! > tx Hello > > instead of > serialObj = mySerial(....) > serialObj.Tx("Hello") Take a look at IPython. It has an autocall mode that allows this. http://ipython.scipy.org/moin/ In [1]: %autocall? Type: Magic function Base Class: Namespace: IPython internal File: /Users/rkern/svn/ipython/IPython/Magic.py Definition: %autocall(self, parameter_s='') Docstring: Make functions callable without having to type parentheses. Usage: %autocall [mode] The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the value is toggled on and off (remembering the previous state). In [2]: %autocall 2 Automatic calling is: Full In [3]: def f(*args): ...: print args ...: ...: In [4]: f ------> f() () In [5]: f 1 ------> f(1) (1,) In [7]: f 'Foo', 'bar' ------> f('Foo', 'bar') ('Foo', 'bar') In [9]: f 1, 2, 3 ------> f(1, 2, 3) (1, 2, 3) In [13]: x = 1 In [14]: f x -------> f(x) (1,) -- 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 mikeminer53 at hotmail.com Wed May 23 12:43:47 2007 From: mikeminer53 at hotmail.com (mkPyVS) Date: 23 May 2007 09:43:47 -0700 Subject: Resizing listbook's listview pane In-Reply-To: <1179932659.180278.72990@w5g2000hsg.googlegroups.com> Message-ID: <1179938627.088816.28910@p77g2000hsh.googlegroups.com> Sorry, copied from wxpython submit as well.. I'm using wxpython 2.8... Primariy I want the resize to happen programatically during object creation/post creation... I can worry about app size changes later. Thanks, From arkanes at gmail.com Wed May 2 11:00:54 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 2 May 2007 10:00:54 -0500 Subject: Is it possible to determine what a function needs for parameters - In-Reply-To: <1178115727.932794.100390@h2g2000hsg.googlegroups.com> References: <1178115727.932794.100390@h2g2000hsg.googlegroups.com> Message-ID: <4866bea60705020800u47445cb6r2dc18cbe46db5f99@mail.gmail.com> On 2 May 2007 07:22:07 -0700, rh0dium wrote: > Hi all, > > Below is a basic threading program. The basic I idea is that I have a > function which needs to be run using a queue of data. Early on I > specified my function needed to only accept basic parameters ( no > postional *args or *kwargs ) but now I am re-writing it and I want to > accept these. Is there anyway to determine what parameters are needed > by a given function and format the arguments given appropriately. My > problem is that I feel my "Kludge"section is just that - a kludge. > While it works for most cases it won't work for all (Try running this > on function4 for example...). I guess I have a problem with multiple > if statements and I think it should just look to see what parameters > are accepted and format them appropriately. Thoughts? > > If I am really screwing this up - please help me get back on the right > track. I appreciate all of the help I get and it's great to learn from > the experts. > > import random > import threading > import Queue > > class WorkerB(threading.Thread): > > def __init__(self, *args, **kwargs): > self.id = kwargs.get('id', 0) > self.requestQ = kwargs.get('requestQ', None) > self.function = kwargs.get('function', None) > threading.Thread.__init__(self, name=self.__class__.__name__ > +"."+str(self.id)) > > def run(self): > while 1: > input = self.requestQ.get() > if input is None: break > > # How do I look at the function and determine what it > requires then apply that as an input? > > # -------- Start Kludge ---------- > tu=dic=False > if isinstance(input, tuple): > try: > if isinstance(input[0], tuple): tu = True > elif isinstance(input[0], list): tu=True > except: pass > try: > if isinstance(input[1], dict):dic = True > except: pass > if tu and dic: > print " -Tuple and list found" > result = self.function(*input[0], **input[1]) > elif tu and not dic: > print " -Tuple found" > result = self.function(*input[0]) > elif isinstance(input, list): > print " -list only found" > result = self.function(*input) > else: > print " -Unknown" > result = self.function(input) > > # -------- End Kludge ---------- > > def function1(arg1): > print arg1 > > def function2(*a ): > print "args", a > > def function3(*a, **kw): > print "args", a > print "kwargs", kw > > def function4(arg1, *a, **kw): > print arg1 > print "args", a > print "kwargs", kw > > def main(): > > > lod = 2 > myQ=Queue.Queue() > > # A basic example > print "\n== Example 1" > for x in range(lod):myQ.put( random.random() ) > myQ.put(None) > a=WorkerB(requestQ=myQ, function=function1).start() > > # Throw at is some args > print "\n== Example 2" > for x in range(lod):myQ.put(["a","b","c"]) > myQ.put(None) > a=WorkerB(requestQ=myQ, function=function2).start() > > # Throw at it both args and kwargs > print "\n== Example 3" > for x in range(lod):myQ.put(((1,2,3), > {"input":random.random(),"loglevel":10})) > myQ.put(None) > a=WorkerB(requestQ=myQ, function=function3).start() > > # Throw at it both args and kwargs > print "\n== Example 4 Does nothing!!" > for x in range(lod):myQ.put(("alpha",(1,2,3), > {"input":random.random(),"loglevel":10})) > myQ.put(None) > a=WorkerB(requestQ=myQ, function=function4).start() > > > if __name__ == '__main__': > main() > This is far more work than you need. Push an (args, kwargs) tuple into your arguments queue and call self.function(*args, **kwargs). From johnjsal at NOSPAMgmail.com Wed May 9 11:36:51 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 09 May 2007 11:36:51 -0400 Subject: Suggestions for how to approach this problem? In-Reply-To: <4640ca5b$0$23392$c3e8da3@news.astraweb.com> References: <4640ca5b$0$23392$c3e8da3@news.astraweb.com> Message-ID: <4641ea34$0$6823$c3e8da3@news.astraweb.com> John Salerno wrote: > So I need to remove the line breaks too, but of course not *all* of them > because each reference still needs a line break between it. After doing a bit of search and replace for tabs with my text editor, I think I've narrowed down the problem to just this: I need to remove all newline characters that are not at the end of a citation (and replace them with a single space). That is, those that are not followed by the start of a new numbered citation. This seems to involve a look-ahead RE, but I'm not sure how to write those. This is what I came up with: \n(?=(\d)+) (I can never remember if I need parentheses around '\d' or if the + should be inside it or not! From jm.suresh at gmail.com Fri May 25 04:09:00 2007 From: jm.suresh at gmail.com (jm.suresh@no.spam.gmail.com) Date: 25 May 2007 01:09:00 -0700 Subject: Find the closest relative In-Reply-To: <1180078850.074308.286570@p77g2000hsh.googlegroups.com> References: <1180074710.011260.276830@n15g2000prd.googlegroups.com> <1180078850.074308.286570@p77g2000hsh.googlegroups.com> Message-ID: <1180080540.316522.67020@a35g2000prd.googlegroups.com> On May 25, 12:40 pm, 7stud wrote: > On May 25, 12:31 am, "jm.sur... at no.spam.gmail.com" > > > > wrote: > > This is how I implemented; I guess there must be elegant way to do > > this... > > > def find_closest_relative(a,b,c): > > c1 = b.__class__ > > c2 = b.__class__ > > > while True: > > if isinstance(a, c1): > > return b > > if isinstance(a, c2): > > return c > > c1 = c1.__base__ > > c2 = c1.__base__ > > > - > > Suresh > > I can't see how your code does what you describe. > > > Now, given one of the instance, I want to find the > > closest relative of the other two. > > What influence would an object have over the closest relative of two > other objects? The closet relative of two other objects is > independent of any third object. Do you want to find the closest > relative of 3 objects? If so, this might work: > > import inspect > > class A(object): pass > class X(object): pass > > class B(A, X): pass #an object of this class has A as a base class > class C(A, X): pass > class D(A, X): pass > > class E(C): pass #an object of this class has A as a base class > class F(D): pass #an object of this class has A as a base class > > def closestRelative(x, y, z): > b1 = inspect.getmro(x.__class__) > b2 = inspect.getmro(y.__class__) > b3 = inspect.getmro(z.__class__) > > for elmt in b1: > if elmt in b2 and elmt in b3: > return elmt > return None > > b = B() > e = E() > f = F() > > print closestRelative(b, e, f) > > However, you should probably post an example of a class structure and > describe what you want to happen when you have three instance of the > various classes. Vehicle | |--- Two Wheeler | | | |--- BatteryPowered | |--- PetrolPowered | |--- DieselPowered | |--- Three Wheeler | | | |--- AutoRicksaw | |--- Four Wheeler | | | |--- GeneralTrans | | |--- Car | | |--- Car1 | | |--- Car2 | | |--- Car3 | | | |--- PublicTrans | | |--- Bus | | |--- Bus1 | | |--- Bus2 | |--- Goods | |--- Lorry |--- Lorry1 |--- Lorry2 |--- Lorry3 Now given one instance of some type, I want to choose between second and third, whichever is closest relative to the first object. Eg. Instance(Car1), Instance(Lorry1), Instance(AutoRicksaw) => Instance(Lorry1) From wagnergc at itautec.com Wed May 23 14:10:12 2007 From: wagnergc at itautec.com (Wagner Garcia Campagner) Date: Wed, 23 May 2007 15:10:12 -0300 Subject: Web Archtecture using tow layers in Phyton Message-ID: SGVsbG8sDQoNCkkgbmVlZCB0byBkZXZlbG9wIGFuIHdlYiBhcHBsaWNhdGlvbnMgdGhhdCBt ZWV0IHRoZSBmb2xsb3dpbmcgcmVxdWlyZW1lbnRzOg0KDQotIDIgbGF5ZXJzOiB0aGUgZmly c3Qgb25lIGlzIHRoZSB1c2VyIGludGVyZmFjZSAoYnJvd3NlcikgYW5kIHRoZSBzZWNvbmQg b25lIGlzIHRoZSBpbnRlcmFjdGlvbiB3aXRoIHRoZSBvcGVyYWNpb25hbCBzeXN0ZW0gb2Yg dGhlDQpzZXJ2ZXIuDQotIHRoZSBzZWNvbmQgbGF5ZXIgbXVzdCBiZSBkZXZlbG9wZWQgdXNp bmcgUHl0aG9uLg0KDQpJJ2QgbGlrZSB0byBrbm93IGlmIGl0IGlzIHBvc3NpYmxlIHRvIGlt cGxlbWVudCB0aGlzIHN5c3RlbS4uLiBtYWtpbmcgdGhlIHNlY29uZCBsYXllciB1c2luZyBw eXRob24gYW5kIHRoZSBmaXJzdCBsYXllciB1c2luZw0KYW5vdGhlciB3ZWIgdGVjaG5vbG9n aWVzIGxpa2UgQUpBWCBmb3IgZXhhbXBsZS4NCg0KRG9lcyBhbnlib2R5IGhhdmUgYW55IGV4 cGVyaWVuY2UgaW4gZGV2ZWxvcGluZyBweXRob24gd2ViIGFwcGxpY2F0aW9ucz8gTWF5YmUg c2VuZCBtZSBzb21lIGxpbmtzIG9yIGRvY3VtZW50YXRpb24gYWJvdXQgaXQuLi4NCg0KVGhl IGZpbmFsIGdvYWwgaXMgdG8gbWFrZSBkaWZlcmVudCB1c2VyIGludGVyZmFjZXMgKGxheWVy IDEpIHRoYXQgY2FuIGludGVncmF0ZSB3aXRoIHRoZSBzZWNvbmQgbGF5ZXIuLi4gZm9yIGV4 YW1wbGUsIG9uZSB3ZWINCmludGVyZmFjZSBhbmQgb25lIGxvY2FsIGludGVyZmFjZSB1c2lu ZyBweXRob24rcXQgKGV4YW1wbGUpLi4uIGkgZG9uJ3Qga25vdyBpZiB0aGlzIGlzIHBvc3Np YmxlIGFuZCBob3cgY2FuIHRoaXMgYmUgaW1wbGVtZW50ZWQuLi4NCmFueSBoZWxwIGlzIGFw cnJlY2lhdGVkLi4uDQoNClRoYW5rcyBpbiBhZHZhbmNlLA0KV2FnbmVyLg0KDQotLS0tLS0t LS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0t LS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tCkFWSVNPIExFR0FMOiBFc3RhIG1lbnNhZ2VtIGVs ZXRy9G5pY2EgKGUgcXVhbHF1ZXIgYW5leG8pIOkgY29uZmlkZW5jaWFsIGUgZW5kZXJl52Fk YSBhbyhzKSBpbmRpdu1kdW8ocykgcmVmZXJpZG9zIGFjaW1hIGUgYSBvdXRyb3MgcXVlIHRl bmhhbSBzaWRvIGV4cHJlc3NhbWVudGUgYXV0b3JpemFkb3Mg4CByZWNlYmUtbGEuIFNlIHZv Y+ogbuNvIOkgbyBkZXN0aW5hdOFyaW8oYSkgZGVzdGEgbWVuc2FnZW0sIHBvciBmYXZvciBu 428gY29waWUsIHVzZSBvdSBkaXZ1bGd1ZSBzZXUgY29udGX6ZG8g4CBvdXRyb3MuIENhc28g dm9j6iB0ZW5oYSByZWNlYmlkbyBlc3RhIG1lbnNhZ2VtIGVxdWl2b2NhZGFtZW50ZSwgcG9y IGZhdm9yIGFwYWd1ZSBlc3RhIG1lbnNhZ2VtIGUgZXZlbnR1YWlzIGNvcGlhcy4KCkxFR0FM IE5PVElDRTogVGhpcyBlLW1haWwgY29tbXVuaWNhdGlvbiAoYW5kIGFueSBhdHRhY2htZW50 cykgaXMgY29uZmlkZW50aWFsIGFuZCBpcyBpbnRlbmRlZCBvbmx5IGZvciB0aGUgaW5kaXZp ZHVhbChzKSBuYW1lZCBhYm92ZSBhbmQgb3RoZXJzIHdobyBoYXZlIGJlZW4gc3BlY2lmaWNh bGx5IGF1dGhvcml6ZWQgdG8gcmVjZWl2ZSBpdC4gSWYgeW91IGFyZSBub3QgdGhlIGludGVu ZGVkIHJlY2lwaWVudCwgcGxlYXNlIGRvIG5vdCByZWFkLCBjb3B5LCB1c2Ugb3IgZGlzY2xv c2UgdGhlIGNvbnRlbnRzIG9mIHRoaXMgY29tbXVuaWNhdGlvbiB0byBvdGhlcnMuIFBsZWFz ZSB0aGVuIGRlbGV0ZSB0aGUgZS1tYWlsIGFuZCBhbnkgY29waWVzIG9mIGl0LiAKCkFWSVNP IExFR0FMOiBFc3RlIG1lbnNhamUgZWxlY3Ry825pY28gKHkgY3VhbHF1aWVyIGFuZXhvKSBl cyBjb25maWRlbmNpYWwgeSBlc3ThIGRpcmlnaWRvIGV4Y2x1c2l2YW1lbnRlIGEgc3Uocykg ZGVzdGluYXRhcmlvKHMpIGFycmliYSBpbmRpY2Fkb3MgeSBhcXVlbGxvcyBxdWUgaGF5YW4g c2lkbyBleHByZXNhbWVudGUgYXV0b3JpemFkb3MgYSByZWNpYmlybG8uIFNpIHVzdGVkIG5v IGVzIGVsIGRlc3RpbmF0YXJpbyhzKSBkZSBlc3RlIG1lbnNhamUsIHBvciBmYXZvciBubyBj b3BpZSwgdXNlIG8gZGl2dWxndWUgZWwgY29udGVuaWRvIGEgdGVyY2Vyb3MuIEVuIGNhc28g cXVlIHVzdGVkIGhheWEgcmVjaWJpZG8gZXN0ZSBtZW5zYWplIHBvciBlcnJvciwgcG9yIGZh dm9yIHByb2NlZGEgYSBzdSBkZXN0cnVjY2nzbiB5IGFsIGRlIGxhcyBwb3NpYmxlcyBjb3Bp YXMuDQo= -------------- next part -------------- An HTML attachment was scrubbed... URL: From chad.rhyner at gmail.com Wed May 2 22:47:28 2007 From: chad.rhyner at gmail.com (Huck Phin) Date: 2 May 2007 19:47:28 -0700 Subject: SEO - Search Engine Optimization - Seo Consulting In-Reply-To: References: <1177808356.681710.42980@n76g2000hsh.googlegroups.com> <#O8fXGAjHHA.3700@TK2MSFTNGP06.phx.gbl> Message-ID: <1178160448.699851.227600@p77g2000hsh.googlegroups.com> I understand how top posting is annoying, and when you check any usenet group message, everyone seems to just jump at the chance to yell at someone for doing it. What I do not understand is how everyone is attacking the top poster, and not the spammer. It seems that the real issue of this post is not being addressed. There are many usenet groups available to talk about what you should talk about, and this is not an advertising booth, it is a gathering where others can learn from each other, and teach each other what they know. That is what usenet is for. We all should be a little more considerate of each other. From tjreedy at udel.edu Thu May 24 15:45:59 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 24 May 2007 15:45:59 -0400 Subject: of destructors, open files and garbage collection References: <1180021256.619953.80500@q66g2000hsg.googlegroups.com> Message-ID: "massimo s." wrote in message news:1180021256.619953.80500 at q66g2000hsg.googlegroups.com... | Hi, | | Python 2.4, Kubuntu 6.06. I'm no professional programmer (I am a ph.d. | student in biophysics) but I have a fair knowledge of Python. | | I have a for loop that looks like the following : | | for item in long_list: | foo(item) | | def foo(item): | item.create_blah() #<--this creates item.blah; by doing that it | opens a file and leaves it open until blah.__del__() is called | | Now, what I thought is that if I call | | del(item) | | it will delete item No, it removes the association between the name 'item' and the object it is currently bound to. In CPython, removing the last such reference will cause the object to be gc'ed. In other implementations, actual deletion may occur later. You probably should close the files directly and arrange code so that you can do so before too many are open. tjr From john at datavoiceint.com Thu May 10 13:11:17 2007 From: john at datavoiceint.com (HMS Surprise) Date: 10 May 2007 10:11:17 -0700 Subject: append In-Reply-To: <1178816546.689849.255070@y5g2000hsa.googlegroups.com> References: <1178816546.689849.255070@y5g2000hsa.googlegroups.com> Message-ID: <1178817077.591054.318230@e51g2000hsg.googlegroups.com> Found list popping at http://en.wikibooks.org/wiki/Python_Programming/Lists :) From http Fri May 4 11:32:14 2007 From: http (Paul Rubin) Date: 04 May 2007 08:32:14 -0700 Subject: Lisp for the C21 References: <1178155239.007219.205020@y5g2000hsa.googlegroups.com> <1178219732.127815.3260@y80g2000hsf.googlegroups.com> <1178269626.886617.214390@u30g2000hsc.googlegroups.com> Message-ID: <7x1whwwqo1.fsf@ruckus.brouhaha.com> Mark Tarver writes: > See my remarks on the Lisp for the Twenty First Century > http://www.lambdassociates.org/lC21.htm Anyone who didn't love lisp in the 20th century has no heart. Anyone who still loves it in the 21st, has no head. From carsten at uniqsys.com Thu May 10 00:34:07 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 10 May 2007 00:34:07 -0400 Subject: change of random state when pyc created?? In-Reply-To: References: <5ae25fF2oggbqU1@mid.uni-berlin.de> Message-ID: <20070510034207.M59225@uniqsys.com> On Thu, 10 May 2007 02:50:49 GMT, Alan Isaac wrote > "Carsten Haese" wrote in message > news:mailman.7498.1178763619.32031.python-list at python.org... > > Knowing that maps don't have reproducible ordering is one thing. > > Realizing that that's the cause of the problem that's arbitrarily and > > wrongly attributed to the 'random' module, in a piece of code that's not > > posted to the public, and presumably not trimmed down to the shortest > > possible example of the problem, is quite another. > > There is no reason to be unfriendly about this. I did not mean this to be unfriendly. I'm sorry if you got that impression. I was simply pointing out all the ways in which you made it difficult for the community to explain your problem. > > I'll venture the guess that most Python programmers with a modicum of > > experience will, when asked point blank if it's safe to rely on a > > dictionary to be iterated in a particular order, answer no. > > Again, that misses the point. This is clearly documented. > I would have said the same thing: no, that's not safe. But > the question is whether the same people will be surprised when > *unchanged* code rerun with an *unchanged* implementation > produces *changed* results. That only means that a program can behave non-deterministically if you're not carefully restricting it to functions that are guaranteed to be deterministic. No experienced software engineer, whether they are experienced in Python or some other programming language should be surprised by this notion. I don't think that the cause of non-determinism in your case was exceptionally subtle, you just made it harder to find. > The docs > should not be useful only to the most sophisticated users. Please feel free to suggest specific wording changes to make the documentation more useful. > > It does, at least for dicts: "Keys and values are listed in an arbitrary > > order." If this wording is not present for sets, something to this > > effect should be added. > > Even Robert did not claim that *that* phrase was adequate. > I note that you cut off "which is non-random"! In my opinion, that phrase is adequate. I did cut off the non-random part because it's irrelevant. Non-random doesn't mean deterministic. Regards, Carsten. From claird at lairds.us Sat May 26 11:49:45 2007 From: claird at lairds.us (Cameron Laird) Date: Sat, 26 May 2007 15:49:45 +0000 Subject: Muzzle Velocity (was: High resolution sleep (Linux) References: <1178274122.142071.91740@y5g2000hsa.googlegroups.com> Message-ID: In article , Hendrik van Rooyen wrote: . . . >2) That the old NATO round (.308 Winchester) travels at >around 2500 fps. - and this was some forty years ago, >when I did my stint of military duty. > >So being an idle bugger, I just naturally assumed that the >speed would have doubled in the intervening time since >I was last involved in this subject. - hence the 5000. . . . Ha! It's interesting, especially for "computerists", to consider how some technologies "plateau": steam car speeds, fresco paint- ing, dry-stone walls, ... From stefan.behnel-n05pAM at web.de Wed May 16 03:59:46 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 16 May 2007 09:59:46 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464ab64f$0$10185$9b4e6d93@newsspool4.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649dd55$0$23144$9b4e6d93@newsspool1.arcor-online.net> <464a25e9$0$10188$9b4e6d93@newsspool4.arcor-online.net> <1179291296.561359.286230@h2g2000hsg.googlegroups.com> <464ab64f$0$10185$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <464AB9F2.60906@web.de> Ren? Fleschenberg wrote: > rurpy at yahoo.com schrieb: >> I'm not sure how you conclude that no problem exists. >> - Meaningful identifiers are critical in creating good code. > > I agree. > >> - Non-english speakers can not create or understand >> english identifiers hence can't create good code nor >> easily grok existing code. > > I agree that this is a problem, but please understand that is problem is > _not_ solved by allowing non-ASCII identifiers! Well, as I said before, there are three major differences between the stdlib and keywords on one hand and identifiers on the other hand. Ignoring arguments does not make them any less true. So, the problem is partly tackled by the people who face it by writing degenerated transliterations and language mix in identifiers, but it would be *solved* by means of the language if Unicode identifiers were available. Stefan From bj_666 at gmx.net Mon May 21 10:00:05 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 21 May 2007 16:00:05 +0200 Subject: Python compared to other language References: <1179753682.661307.186540@y18g2000prd.googlegroups.com> Message-ID: In <1179753682.661307.186540 at y18g2000prd.googlegroups.com>, user2048 at yahoo.com wrote: >> Python is a strongly typed but dynamic language ... > > In the "A few questions" thread, John Nagle's summary of Python begins > "Python is a byte-code interpreted untyped procedural dynamic > language with implicit declaration. " > > Is Python strongly typed or untyped? Strongly typed. Ciao, Marc 'BlackJack' Rintsch From joeedh at gmail.com Sun May 13 16:58:17 2007 From: joeedh at gmail.com (joeedh at gmail.com) Date: 13 May 2007 13:58:17 -0700 Subject: PyRun_String and related functions causing garbage when calling a parsed function from C. Message-ID: <1179089897.569954.110370@n59g2000hsh.googlegroups.com> Hi I'm getting extremely odd behavior. First of all, why isn't PyEval_EvalCode documented anywhere? Anyway, I'm working on blender's python integration (it embeds python, as opposed to python embedding it). I have a function that executes a string buffer of python code, fetches a function from its global dictionary then calls it. When the function code returns a local variable, PyObject_Call() appears to be returning garbage. Strangely this is only happening with internal blender types, yet try however I might I can't find any refcounting errors to account for this. The initial implementation used the same dictionary for the global and local dicts. I tried using separate dicts, but then the function wasn't being called at all (or at least I tested it by putting a "print "bleh"" in there, and it didn't work). Also, when I printed the refcount of the garbage data, it was garbage as well (so the entire piece of memory is bad, not just the data portion). I've tested with both python 2.4 and 2.5. Mostly with 2.4. This bug may be cropping up in other experimental blender python code as well. Here's the code in the string buffer: #BPYCONSTRAINT from Blender import * from Blender.Mathutils import * print "d" def doConstraint(inmat, tarmat, prop): a = Matrix() a.identity() a = a * TranslationMatrix(Vector(0, 0, 0)) print "t" a = tarmat return inmat print doConstraint(Matrix(), Matrix(), 0) Here's the code that executes the string buffer: PyObject *RunPython2( Text * text, PyObject * globaldict, PyObject *localdict ) { char *buf = NULL; /* The script text is compiled to Python bytecode and saved at text->compiled * to speed-up execution if the user executes the script multiple times */ if( !text->compiled ) { // if it wasn't already compiled, do it now buf = txt_to_buf( text ); text->compiled = Py_CompileString( buf, GetName( text ), Py_file_input ); MEM_freeN( buf ); if( PyErr_Occurred( ) ) { BPY_free_compiled_text( text ); return NULL; } } return PyEval_EvalCode( text->compiled, globaldict, localdict ); } . . .and heres the (rather long, and somewhat in a debugging state) function that calls the function in the script's global dictionary: void BPY_pyconstraint_eval(bPythonConstraint *con, float obmat[][4], short ownertype, void *ownerdata, float targetmat[][4]) { PyObject *srcmat, *tarmat, *idprop; PyObject *globals, *locals; PyObject *gkey, *gval; PyObject *retval; MatrixObject *retmat; Py_ssize_t ppos = 0; int row, col; if ( !con->text ) return; globals = CreateGlobalDictionary(); srcmat = newMatrixObject( (float*)obmat, 4, 4, Py_NEW ); tarmat = newMatrixObject( (float*)targetmat, 4, 4, Py_NEW ); idprop = BPy_Wrap_IDProperty( NULL, &con->prop, NULL); /* since I can't remember what the armature weakrefs do, I'll just leave this here commented out. Since this function was based on pydrivers. if( !setup_armature_weakrefs()){ fprintf( stderr, "Oops - weakref dict setup\n"); return result; } */ retval = RunPython2( con->text, globals, globals); if (retval) {Py_XDECREF( retval );} if ( retval == NULL ) { BPY_Err_Handle(con->text->id.name); ReleaseGlobalDictionary( globals ); /*free temp objects*/ Py_XDECREF( idprop ); Py_XDECREF( srcmat ); Py_XDECREF( tarmat ); return; } /*Now for the fun part! Try and find the functions we need.*/ while ( PyDict_Next(globals, &ppos, &gkey, &gval) ) { if ( PyString_Check(gkey) && strcmp(PyString_AsString(gkey), "doConstraint")==0 ) { if (PyFunction_Check(gval) ) { retval = PyObject_CallObject(gval, Py_BuildValue("OOO", srcmat, tarmat, idprop)); Py_XDECREF( retval ); } else { printf("ERROR: doConstraint is supposed to be a function!\n"); } break; } } if (!retval) { BPY_Err_Handle(con->text->id.name); /*free temp objects*/ ReleaseGlobalDictionary( globals ); Py_XDECREF( idprop ); Py_XDECREF( srcmat ); Py_XDECREF( tarmat ); return; } if (!PyObject_TypeCheck(retval, &matrix_Type)) { printf("Error in pyconstraint: Wrong return type for a pyconstraint!\n"); ReleaseGlobalDictionary( globals ); Py_XDECREF( idprop ); Py_XDECREF( srcmat ); Py_XDECREF( tarmat ); Py_XDECREF( retval ); return; } retmat = (MatrixObject*) retval; if (retmat->rowSize != 4 || retmat->colSize != 4) { printf("Error in pyconstraint: Matrix is the wrong size!\n"); ReleaseGlobalDictionary( globals ); Py_XDECREF( idprop ); Py_XDECREF( srcmat ); Py_XDECREF( tarmat ); Py_XDECREF( retval ); return; } //this is the reverse of code taken from newMatrix(). for(row = 0; row < 4; row++) { for(col = 0; col < 4; col++) { if (retmat->wrapped) obmat[row][col] = retmat->data.blend_data[row*4+col]; //[row][col]; else obmat[row][col] = retmat->data.py_data[row*4+col]; //[row][col]; } } /*clear globals*/ //ReleaseGlobalDictionary( globals ); /*free temp objects*/ //Py_XDECREF( idprop ); //Py_XDECREF( srcmat ); //Py_XDECREF( tarmat ); //Py_XDECREF( retval ); //PyDict_Clear(locals); //Py_XDECREF(locals); } Joe From afriere at yahoo.co.uk Tue May 22 02:42:06 2007 From: afriere at yahoo.co.uk (Asun Friere) Date: 21 May 2007 23:42:06 -0700 Subject: howto check does module 'asdf' exist? (is available for import) In-Reply-To: <1179753436.736228.321400@x35g2000prf.googlegroups.com> References: <1179753436.736228.321400@x35g2000prf.googlegroups.com> Message-ID: <1179816125.666430.222010@u36g2000prd.googlegroups.com> On May 21, 11:17 pm, dmitrey wrote: > howto check does module 'asdf' exist (is available for import) or no? try : import asdf del asdf except ImportError : #do stuff ... > (without try/cache of course) Oops sorry, you didn't want it the obvious way ... but why ever not? From castironpi at gmail.com Wed May 9 22:57:02 2007 From: castironpi at gmail.com (castironpi at gmail.com) Date: 9 May 2007 19:57:02 -0700 Subject: interesting exercise In-Reply-To: <46426c28$0$83121$c30e37c6@lon-reader.news.telstra.net> References: <1178595952.641173.76540@y80g2000hsf.googlegroups.com> <1178601624.812907.23550@u30g2000hsc.googlegroups.com> <1178661305.063868.130730@e65g2000hsc.googlegroups.com> <1178661851.606885.104330@p77g2000hsh.googlegroups.com> <1178670691.209680.119330@o5g2000hsb.googlegroups.com> <46416674$0$83110$c30e37c6@lon-reader.news.telstra.net> <1178739676.565009.35590@u30g2000hsc.googlegroups.com> <46426c28$0$83121$c30e37c6@lon-reader.news.telstra.net> Message-ID: <1178765822.649769.142490@e65g2000hsc.googlegroups.com> On May 9, 7:49 pm, Charles Sanders wrote: > castiro... at gmail.com wrote: > > On May 9, 1:13 am, Charles Sanders > > wrote: > [snip] > >> or even this monstrosity ... > > >> def permute2( s, n ): > >> return [ ''.join([ s[int(i/len(s)**j)%len(s)] > >> for j in range(n-1,-1,-1)]) > >> for i in range(len(s)**n) ] > > >> print "permute2('abc',2) =", permute2('abc',2) > >> print "len(permute2('13579',3)) =", len(permute2('13579',3)) > > >> permute2('abc',2) = ['aa', 'ab', 'ac', 'ba', 'bb', 'bc', > >> 'ca', 'cb', 'cc'] > >> len(permute2('13579',3)) = 125 > > >> Charles > > > Could you explain, this one, actually? Don't forget StopIteration. > > As Michael said, simple counting in base n with the > string as the digits. No attempt at clarity or efficiency (I > did say it was a "monstrosity"). > > Also, as a python beginner I didn't know about divmod, > and have no idea what you (castironpi) mean by "Don't forget > StopIteration." > > Charles Please disregard. I have just learned that: "If the generator exits without yielding another value, a StopIteration exception is raised." "exception StopIteration Raised by an iterator's next() method to signal that there are no further values." Means normal generator termination. From antroy at gmail.com Wed May 2 11:16:51 2007 From: antroy at gmail.com (Ant) Date: 2 May 2007 08:16:51 -0700 Subject: regexp match string with word1 and not word2 In-Reply-To: <1178093820.914883.113760@n76g2000hsh.googlegroups.com> References: <1177920984.247487.54620@c35g2000hsg.googlegroups.com> <9rGdnQGHaNy1mqvbnZ2dnUVZ_v_inZ2d@comcast.com> <1177946577.080567.73400@u30g2000hsc.googlegroups.com> <1178093820.914883.113760@n76g2000hsh.googlegroups.com> Message-ID: <1178119011.733528.110000@y5g2000hsa.googlegroups.com> On May 2, 9:17 am, Flyzone wrote: > On 30 Apr, 20:00, Steven Bethard wrote: ... > Maybe a right approach will be another if after the first one? Like: > for y in range(0, len(skip_lst) ): > if (re.search(skip_lst[y], line)): > if > (re.search(skip_lst_negative[y], line)): > skip=1 > break > and in the rule-file, i could add a new column and check to do the if > just if the second column is not empty. This is quite a common approach for this sort of matching problem - having includes and excludes patterns, and having the test return True if the include matches but not the exclude. Trying to roll the two into one requires pretty unreadable regexes if it is possible at all... From wildemar at freakmail.de Fri May 18 10:39:44 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Fri, 18 May 2007 16:39:44 +0200 Subject: (Modular-)Application Framework / Rich-Client-Platform in Python In-Reply-To: References: <878xbm5s56.fsf@benfinney.id.au> Message-ID: <464DBAB0.7060001@freakmail.de> Jarek Zgoda wrote: >> I've never used Eclipse (beyond proving that it runs on various >> computers). Can you please describe what behaviour you're looking for? >> > > The key is not "Eclipse" itself, but the whole Eclipse Platform. > > See http://wiki.eclipse.org/index.php/Rich_Client_Platform > Thank you for helping me out here. I'd just gone on and on about what my conception of a RCP is. I think that link just about clarifies it. W From bbxx789_05ss at yahoo.com Tue May 1 10:35:15 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 1 May 2007 07:35:15 -0700 Subject: Why are functions atomic? In-Reply-To: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> References: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> Message-ID: <1178030115.591931.137040@h2g2000hsg.googlegroups.com> On May 1, 5:06 am, Michael wrote: > Why are functions atomic? (I.e. they are not copied.) > > For example, I would like to make a copy of a function so I can change > the default values: > > >>> from copy import copy > >>> f = lambda x: x > >>> f.func_defaults = (1,) > >>> g = copy(f) > >>> g.func_defaults = (2,) > >>> f(),g() > > (2, 2) > > I would like the following behaviour: > > >>> f(),g() > > (1,2) > > I know I could use a 'functor' defining __call__ and using member > variables, but this is more complicated and quite a bit slower. (I > also know that I can use new.function to create a new copy, but I > would like to know the rational behind the decision to make functions > atomic before I shoot myself in the foot;-) > > Thanks, > Michael. Does deepcopy work? From tjreedy at udel.edu Thu May 24 15:59:17 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 24 May 2007 15:59:17 -0400 Subject: What is an instance and what isn't? References: Message-ID: "Gre7g Luterman" wrote in message news:HKedneXu0YpQMcjbnZ2dnUVZ_jCdnZ2d at bresnan.com... |I suppose I was lulled into complacency by how Python makes so many things | look like classes, but I'm starting to realize that they're not, are they? | | I'm writing a C program which handles Python objects in different ways based | on their type. I do a PyInstance_Check(PyObj) to determine if the PyObj is | an instance, but it is returning 0 on a lot of stuff that I thought would be | an instance. So I did the following simple test on three things that look | like instances: | | 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. | >>> class a: pass | ... | >>> type(a()) | | >>> type(Exception()) | | >>> class b(dict): pass | ... | >>> type(b()) | | | I was relieved that a() returns an instance, but I was surprised that | Exceptions aren't really instances at all. And what's the deal with derving | a class from a standard type like a dictionary? I thought for sure, that | would be an instance, but this shows it is a class?!? | | Can anyone explain the last one and/or give me a simple test I can do in C | to determine whether a Python object is "instance-like"? Your problem is mixing two different meanings of 'instance', one obsolete. Everything is an instance of its type/class. However, for old-style classes, all instances of user defined classes are instances of type 'instance' instead of their class. This is usually not very helpful. New style classes fix this. >>> class a(object): pass >>> type(a()) In 2.5, Exception changed from old-style to new. Terry Jan Reedy From resmith5 at yahoo.com Tue May 29 08:52:21 2007 From: resmith5 at yahoo.com (Simon) Date: 29 May 2007 05:52:21 -0700 Subject: python unix install, sqlite3 Message-ID: <1180443141.119281.304880@q66g2000hsg.googlegroups.com> I installed the source code on unix for python 2.5.1. The install went mainly okay, except for some failures regarding: _ssl, _hashlib, _curses, _curses_panel. No errors regarding sqlite3. However, when I start python and do an import sqlite3 I get: /ptmp/bin/> python Python 2.5.1 (r251:54863, May 29 2007, 05:19:30) [GCC 3.3.2] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 Traceback (most recent call last): File "", line 1, in File "/ptmp/Python-2.5.1/lib/python2.5/sqlite3/__init__.py", line 24, in from dbapi2 import * File "/ptmp/Python-2.5.1/lib/python2.5/sqlite3/dbapi2.py", line 27, in from _sqlite3 import * ImportError: No module named _sqlite3 From gagsl-py2 at yahoo.com.ar Wed May 16 05:12:32 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 16 May 2007 06:12:32 -0300 Subject: Interesting list Validity (True/False) References: <1178915791.584216.293130@l77g2000hsb.googlegroups.com> <1178918808.091358.233740@o5g2000hsb.googlegroups.com> <1179017740.656323.209590@e51g2000hsg.googlegroups.com> <1179020634.130689.171960@o5g2000hsb.googlegroups.com> <1179031812.090768.248750@l77g2000hsb.googlegroups.com> <1179168081.603409.39970@e51g2000hsg.googlegroups.com> <1179203827.881205.287910@l77g2000hsb.googlegroups.com> <1179248480.350553.4430@n59g2000hsh.googlegroups.com> <1179296218.969564.240220@k79g2000hse.googlegroups.com> Message-ID: En Wed, 16 May 2007 03:16:59 -0300, mensanator at aol.com escribi?: > On May 15, 7:07 pm, "Gabriel Genellina" > wrote: >> >>>> import gmpy >> >>>> a = 2**177149-1 >> >>>> b = gmpy.mpz(2**177149-1) >> >>>> a==b >> > True >> >>>> print '%d' % (b) >> >> > Traceback (most recent call last): >> > File "", line 1, in >> > print '%d' % (b) >> > TypeError: int argument required >> >> > So although the comparison operator is smart enough to realize >> > the equivalency of numeric types and do the type conversion, >> > the print statement isn't so smart. >> >> This is up to the gmpy designers/writers/maintainers. Anyone writing a >> class chooses which features to implement, which ones to omit, how to >> implement them, etc. The code may contain bugs, may not be efficient, >> may >> not behave exactly as the users expect, may not have anticipated all >> usage >> scenarios, a long etc. In this case, probably the gmpy writers have >> chosen >> not to allow to convert to int, and they may have good reasons to not do >> that (I don't know what platform are you working in, but I feel that >> your >> b object is somewhat larger than sys.maxint...). > > Then how does this work? > >>>> print '%d' % (long(gmpy.mpz(2**177149-1))) > 1454...<53320 digits snipped>...3311 > > I honestly don't understand why there's a problem here. > If print can handle arbitrary precision longs without > a problem, why does it fail on mpzs > sys.maxint? > If the gmpy writers are not allowing the conversion, > then why do small mpz values work? Something smells > inconsistent here. Python (builtin) "integral numbers" come on two flavors: int and long. ints correspond to the C `long` type usually, and have a limited range, at least from -2**31 to 2**31-1; most operations have hardware support (or at least it's up to the C compiler). Long integers are a totally different type, they have unlimited range but are a lot slower, and all operations must be done "by hand". See http://docs.python.org/ref/types.html If you say "%d" % something, Python first tries to see if `something` is a long integer -not to *convert* it to a long integer, just to see if the object *is* a long integer. If it's a long, it's formatted accordingly. If not, Python sees if `something` is a plain integer. If not, it sees if it's a number (in this context, that means that the structure describing its type contains a non-NULL tp_as_number member) and tries to *convert* it to an integer. Notice that if the object whas not originally a long integer, no attempt is made to convert it to a long using the nb_long member - just a plain integer conversion is attempted. It's at this stage that a large mpz object may fail - when its value can't fit in a plain integer, it raises an OverflowError and the "%d" formatting fails. If you force a conversion to long integer, using long(mpz(...)) as above, the % operator sees a long integer from start and it can be formatted without problems. I don't know if this asymmetric behavior is a design decision, a historic relic, a change in protocol (is nb_int allowed now to return a PyLongObject, but not before?), a "nobody cares" issue, or just a bug. Perhaps someone else can give an opinion - and certainly I may be wrong, I had never looked at the PyString_Format function internal details before (thanks for providing an excuse!). As a workaround you can always write "%d" % long(mpznumber) when you want to print them (or perhaps "%s" % mpznumber, which might be faster). > How is it that > >>>> print '%d' % (1.0) > 1 > > doesn't make a type mismatch? Obviously, the float > got changed to an int and this had nothing to do with > gmpy. Is it the print process responsible for doing > the conversion? Maybe I should say invoking the > conversion? Maybe the gmpy call tries to literally > convert to an integer rather than sneakily substitute > a long? Same as above: is the argument a long integer? no. is it a number? yes. Convert to int. No errors? Apply format. -- Gabriel Genellina From no at spam.here Wed May 2 23:51:37 2007 From: no at spam.here (coyote) Date: Wed, 02 May 2007 23:51:37 -0400 Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? In-Reply-To: <1178163851.199354.14450@n59g2000hsh.googlegroups.com> References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> <1178162456.929395.139390@q75g2000hsh.googlegroups.com> <1178163851.199354.14450@n59g2000hsh.googlegroups.com> Message-ID: Midex wrote: > On 3 maio, 00:20, Don Stockbauer wrote: >> Ask yourself WHY havn't I seen this footage before? >> >> **************************** >> >> "Don, why havent you seen this footage before?" he asked himself, self- >> referentially in the best tradition of Douglas R. Hofstadter. >> >> 'Er, because I haven't seen it before?" Don responded in a >> tautological fashion. >> >> (uproarius laughter ensues) > > You're that ignorant and brainwashed lost that you can't see that the > media didn't want youto see this footage and thus why you havn't seen > it before? If thisfootage was suppressed, why was it not destroyed? If hidden, how and why is it surfacing now? Where was it? Who got it back and published it? What was in it for the media to suppress it? -- ~coyote From michael at jedimindworks.com Tue May 1 17:14:20 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Tue, 1 May 2007 16:14:20 -0500 Subject: I wish that [].append(x) returned [x] In-Reply-To: <46379a41$0$25252$88260bb3@free.teranews.com> References: <46379a41$0$25252$88260bb3@free.teranews.com> Message-ID: <56C5DA13-6C46-4FF3-874C-6CB3CC873D07@jedimindworks.com> On May 1, 2007, at 3:45 PM, Tobiah wrote: > I wanted to do: > > query = "query text" % tuple() > > but the append() method returns none, so I did this: > > fields = rec[1:-1] > fields.append(extra) > query = "query text" % tuple(fields) > As you learned. .append() adds to an existing list rather than returning a new list. You might be happier with: query = "query text" % tuple(rec[1:-1] + [extra]) From bronger at physik.rwth-aachen.de Thu May 17 15:05:17 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 17 May 2007 21:05:17 +0200 Subject: Regexes: How to handle escaped characters Message-ID: <87tzubqniq.fsf@wilson.homeunix.com> Hall?chen! I need some help with finding matches in a string that has some characters which are marked as escaped (in a separate list of indices). Escaped means that they must not be part of any match. My current approach is to look for matches in substrings with the escaped characters as boundaries between the substrings. However, then ^ and $ in the patterns are treated wrongly. (Although I use startpos and endpos parameters for this and no slicing.) Another idea was to have a special unicode character that never takes part in a match. The docs are not very promising regarding such a thing, or did I miss something? Any other ideas? Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From basilisk96 at gmail.com Sat May 12 13:45:33 2007 From: basilisk96 at gmail.com (Basilisk96) Date: 12 May 2007 10:45:33 -0700 Subject: Basic question In-Reply-To: <1178986686.510137.195490@p77g2000hsh.googlegroups.com> References: <1178986686.510137.195490@p77g2000hsh.googlegroups.com> Message-ID: <1178991933.421386.58500@u30g2000hsc.googlegroups.com> On May 12, 12:18 pm, "Cesar G. Miguel" wrote: > I've been studying python for 2 weeks now and got stucked in the > following problem: > > for j in range(10): > print j > if(True): > j=j+2 > print 'interno',j > > What happens is that "j=j+2" inside IF does not change the loop > counter ("j") as it would in C or Java, for example. > > Am I missing something? > > []'s > Cesar What is your real intent here? This is how I understand it after reading your post: you want to create a loop that steps by an increment of 2. If that's the case, then: >>> for j in range(0,10,2): ... print j ... 0 2 4 6 8 would be a simple result. Cheers, -Basilisk96 From gatti at dsdata.it Mon May 14 10:42:37 2007 From: gatti at dsdata.it (gatti at dsdata.it) Date: 14 May 2007 07:42:37 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46473267$0$31532$9b622d9e@news.freenet.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <1179153757.844925.14230@p77g2000hsh.googlegroups.com> On May 13, 5:44 pm, "Martin v. L?wis" wrote: > In summary, this PEP proposes to allow non-ASCII letters as > identifiers in Python. If the PEP is accepted, the following > identifiers would also become valid as class, function, or > variable names: L?ffelstiel, chang?, ??????, or ??? > (hoping that the latter one means "counter"). I am strongly against this PEP. The serious problems and huge costs already explained by others are not balanced by the possibility of using non-butchered identifiers in non-ASCII alphabets, especially considering that one can write any language, in its full Unicode glory, in the strings and comments of suitably encoded source files. The diatribe about cross language understanding of Python code is IMHO off topic; if one doesn't care about international readers, using annoying alphabets for identifiers has only a marginal impact. It's the same situation of IRIs (a bad idea) with HTML text (happily Unicode). > - should non-ASCII identifiers be supported? why? No, they are useless. > - would you use them if it was possible to do so? in what cases? No, never. Being Italian, I'm sometimes tempted to use accented vowels in my code, but I restrain myself because of the possibility of annoying foreign readers and the difficulty of convincing every text editor I use to preserve them > Python code is written by many people in the world who are not familiar > with the English language, or even well-acquainted with the Latin > writing system. Such developers often desire to define classes and > functions with names in their native languages, rather than having to > come up with an (often incorrect) English translation of the concept > they want to name. The described set of users includes linguistically intolerant people who don't accept the use of suitable languages instead of their own, and of compromised but readable spelling instead of the one they prefer. Most "people in the world who are not familiar with the English language" are much more mature than that, even when they don't write for international readers. > The syntax of identifiers in Python will be based on the Unicode > standard annex UAX-31 [1]_, with elaboration and changes as defined > below. Not providing an explicit listing of allowed characters is inexcusable sloppiness. The XML standard is an example of how listings of large parts of the Unicode character set can be provided clearly, exactly and (almost) concisely. > ``ID_Start`` is defined as all characters having one of the general > categories uppercase letters (Lu), lowercase letters (Ll), titlecase > letters (Lt), modifier letters (Lm), other letters (Lo), letter numbers > (Nl), plus the underscore (XXX what are "stability extensions" listed in > UAX 31). > > ``ID_Continue`` is defined as all characters in ``ID_Start``, plus > nonspacing marks (Mn), spacing combining marks (Mc), decimal number > (Nd), and connector punctuations (Pc). Am I the first to notice how unsuitable these characters are? Many of these would be utterly invisible ("variation selectors" are Mn) or displayed out of sequence (overlays are Mn), or normalized away (combining accents are Mn) or absurdly strange and ambiguous (roman numerals are Nl, for instance). Lorenzo Gatti From JoeSalmeri at hotmail.com Thu May 31 17:16:07 2007 From: JoeSalmeri at hotmail.com (Joe Salmeri) Date: Thu, 31 May 2007 17:16:07 -0400 Subject: Python 2.5.1 broken os.stat module Message-ID: I just upgraded from Python 2.4.2 to Python 2.5.1 and have found some unexpected behavior that appears to be a bug in the os.stat module. My OS is Windows XP SP2 + all updates. I have several programs that have worked flawlessly on all previous Python versions for years and they are now producing incorrect results in the code that uses os.stat. Searching through the 2.5.1 release notes I found the following: Use Win32 API to implement os.stat/fstat. As a result, subsecond timestamps are reported, the limit on path name lengths is removed, and stat reports WindowsError now (instead of OSError). ********************* * Overview of the problem: ********************* Reviewing my code it seems that it should still work with the 2.5.1 os.stat changes however that does not appear to be the case. Timestamps reported by os.stat() are no longer correct and the results are not even consistent. In my first test case ALL 3 timestamps reported by Python are 1 hour less than the actual timestamp on the file. In my second test case the created and last accessed timestamps reported by Python are correct but the last write timestamp is 1 hour less than the actual timestamp on the file. As a third test I looked at the last write timestamps on approximately 21,000 files. Python determined wrong last write timestamp on approximately 1581 files. Assuming there is no error in the following code that prints out the timestamps using the new return value from os.stat() then it would appear that the 2.5.1 os.stat changes have a bug. print 'Creation Time: %s' % time.strftime('%m/%d/%Y %H:%M:%S', time.localtime(file_stats[stat.ST_CTIME])) print 'Last Access Time: %s' % time.strftime('%m/%d/%Y %H:%M:%S', time.localtime(file_stats[stat.ST_ATIME])) print 'Last Write Time: %s' % time.strftime('%m/%d/%Y %H:%M:%S', time.localtime(file_stats[stat.ST_MTIME])) ********************* * Detailed test results ********************* To demonstrate the problem I have created the following test. Here are the files that will be used in my test and their associated timestamps as reported the the dir command. 01/02/2003 12:34 PM 0 broke_test 03/06/2007 05:24 PM 3,497,177 broke_test2 05/31/2007 04:35 PM 254 runtest.cmd 05/31/2007 04:31 PM 513 broke.py The file named broke_test has a timestamp of 01/02/2003 12:34:56 (dir does not show seconds). The runtest.cmd script shows the created, last accessed, and last write timestamps as reported by the dir command (and also verified via right clicking on the file and selecting properties in Explorer. ------ >>> START runtest.cmd script <<<< @Echo Off echo Create TimeStamp reported by dir command dir /tc %1 echo Last Access TimeStamp reported by dir command dir /ta %1 echo Last Write TimeStamp reported by dir command dir /tw %1 echo Python 2.5.1 timestamp info broke.py %1 ------ >>> END runtest.cmd script <<<< The broke.py script prints out the created, last accessed, last write timestamps as Python sees them. ------ >>> START broke.py script <<<< import sys import os import stat import time file_name = sys.argv[1] file_stats = os.stat(file_name) print print 'File Name : %s' % (file_name) print print 'Creation Time: %s' % time.strftime('%m/%d/%Y %H:%M:%S', time.localtime(file_stats[stat.ST_CTIME])) print 'Last Access Time: %s' % time.strftime('%m/%d/%Y %H:%M:%S', time.localtime(file_stats[stat.ST_ATIME])) print 'Last Write Time: %s' % time.strftime('%m/%d/%Y %H:%M:%S', time.localtime(file_stats[stat.ST_MTIME])) print ------ >>> END broke.py script <<<< # # Test 1 on file broke_test # runtest broke_test Create TimeStamp reported by dir command 01/02/2003 12:34 PM 0 broke_test Last Access TimeStamp reported by dir command 01/02/2003 12:34 PM 0 broke_test Last Write TimeStamp reported by dir command 01/02/2003 12:34 PM 0 broke_test Python 2.5.1 timestamp info File Name : broke_test Creation Time: 01/02/2003 11:34:56 -- Python results are WRONG hours reported are 1 hour short Last Access Time: 01/02/2003 11:34:56 -- Python results are WRONG hours reported are 1 hour short Last Write Time: 01/02/2003 11:34:56 -- Python results are WRONG hours reported are 1 hour short # # Test 2 on file broke_test2 # runtest broke_test2 Create TimeStamp reported by dir command 05/31/2007 04:26 PM 3,497,177 broke_test2 Last Access TimeStamp reported by dir command 05/31/2007 04:26 PM 3,497,177 broke_test2 Last Write TimeStamp reported by dir command 03/06/2007 05:24 PM 3,497,177 broke_test2 Python 2.5.1 timestamp info File Name : broke_test2 Creation Time: 05/31/2007 16:26:36 -- Python results are correct Last Access Time: 05/31/2007 16:26:38 -- Python results are correct Last Write Time: 03/06/2007 16:24:21 -- Python results are WRONG hours reported are 1 hour short From andymac at bullseye.apana.org.au Fri May 25 07:08:26 2007 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Fri, 25 May 2007 22:08:26 +1100 Subject: Compiling python extension on amd64 for 32 bit In-Reply-To: References: Message-ID: <4656C3AA.4050007@bullseye.andymac.org> Mathias Waack wrote: > After switching my development environment to 64 bit I've got a problem with > a python extension for a 32 bit application. {...} > Ok, thats fine. So why is python complaining? Or even more interesting, what > do I have to do to compile the code? Is the Python your toolchain is referencing 32 or 64 bit? Based on what I can see in pyport.h, I'd guess that you're finding a 64 bit Python (ie SIZEOF_LONG == 8). -- ------------------------------------------------------------------------- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From armagan4celik at gmail.com Sat May 26 21:02:16 2007 From: armagan4celik at gmail.com (=?ISO-8859-9?Q?Arma=F0an_=C7elik?=) Date: Sun, 27 May 2007 04:02:16 +0300 Subject: binary search trees using classes Message-ID: <738900580705261802w4c2883d7tad86a9c6ec74edb8@mail.gmail.com> >* Have a nice day. Have a nice day. *>* Have a nice day. *>* Have a nice day. *>* *>* the output is *>* *>* a 4 *>* day 4 *>* have 4 *>* nice 4 can you send c++ code of this output .This my homework* -------------- next part -------------- An HTML attachment was scrubbed... URL: From ragnar at lysator.liu.se Tue May 29 17:02:36 2007 From: ragnar at lysator.liu.se (Ragnar Ouchterlony) Date: Tue, 29 May 2007 21:02:36 GMT Subject: how to print the GREEK CAPITAL LETTER delta under utf-8 encoding In-Reply-To: References: <1180414659.066482.236370@i38g2000prf.googlegroups.com> <465BBB49.6000803@v.loewis.de> <1180421212.151587.118020@r19g2000prf.googlegroups.com> <465BD0AA.9080805@v.loewis.de> <1180462611.5376.13.camel@localhost> Message-ID: <1180472556.5376.22.camel@localhost> tis 2007-05-29 klockan 16:08 -0300 skrev Gabriel Genellina: > >>>> sys.stdout = filewrapper(sys.stdout, 'utf-8') > >>>> print u"??? \N{GREEK CAPITAL LETTER DELTA}" > > > > Useful if you don't want to append .encode() to everything you print out > > that potentially can contain non-ascii letters. > > Isn't the same as codecs.EncodedFile? > No, codecs.EncodedFile() doesn't do exactly the same. If I understand it correctly, EncodedFile() takes a byte stream as input and produces another bytestream (with possibly different encoding) as output in both read and write. My function (as well as codecs.open()) decodes a byte stream for read and produces a unicode object or encodes a unicode object for write and produces a byte stream. At least, I were unable to create the same behaviour as my filewrapper() using EncodedFile(). If you are able to do that, I'm interested in how you do it. /Ragnar From tjandacw at yahoo.com Tue May 15 08:17:56 2007 From: tjandacw at yahoo.com (timw.google) Date: 15 May 2007 05:17:56 -0700 Subject: customary way of keeping your own Python and module directory in $HOME In-Reply-To: <1179190528.707235.324010@e65g2000hsc.googlegroups.com> References: <1179175513.896546.313500@y80g2000hsf.googlegroups.com> <1179190528.707235.324010@e65g2000hsc.googlegroups.com> Message-ID: <1179231476.298382.36530@u30g2000hsc.googlegroups.com> On May 14, 8:55 pm, jmg3... at gmail.com wrote: > On May 14, 6:00 pm, James Stroud wrote: > > > jmg3... at gmail.com wrote: > > [snip], but on *nix, > > you can compile python with the "--prefix=" option set to a directory in > > your home dir and install there. > > Check. > > > I recommend having your own python install if you want a comprehensive > > approach. > > Yup. I dropped the src in ~/src/Python-2.5.1, created a ~/py-2.5.1 > directory, and did > > ./configure --prefix=/home/me/py-2.5.1 > make > make install > > and it worked fine. The only other step after that was creating a > symlink: > > cd > ln -s py-2.5.1 py > > and adding /home/me/py/bin to my $PATH. > > > Doesn't seem like hyper-paranoid sysadmining is all that efficient, does it? > > Well, on a server with many other users, they've pretty much gotta > keep you confined to your home directory. > > My issues have been with keeping a ~/pylib directory for extra > modules, and reconciling that with setuptools / Easy Install. I'm > curious to hear how other folks manage their own local module > directory. I just do ./configure --prefix=$HOME;make;make install My PATH has $HOME/bin, and LD_LIBRARY_PATH has $HOME/lib before the system bin and lib directories. Everything works just fine. I do the same thing for everything else I download for personal use when I want to use a more up to date version of what's installed. For Windoze, Python gets installed in C:\Python24 (or C:\Python25 now, I guess) and you don't need admin rights for that. (Thank you, Python developers!) From grante at visi.com Fri May 11 10:45:30 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 11 May 2007 14:45:30 -0000 Subject: Newbie look at Python and OO References: <1178812734.860473.236370@y80g2000hsf.googlegroups.com> <1178832102.256466.235020@l77g2000hsb.googlegroups.com> Message-ID: <13490canfv56c9c@corp.supernews.com> On 2007-05-10, Gabriel Genellina wrote: > En Thu, 10 May 2007 18:21:42 -0300, escribi?: > >> These conversations are funny to me. I use Python every day and I >> have never actually thought about the implications of binding objects >> to names, or two names pointing to the same object. Problems of this >> sort just never come up in actual programming for me. It just works. >> >> Python was my virgin language, so maybe that just makes it natural to >> me, but it seems like people coming from other languages get hung up >> on testing out the differences and theories rather than just >> programming in it. Alas, maybe I have yet to get deep enough to run >> into these kinds of problems. > > Certainly, learning Python as a first language has some > advantages. But I think you'd feel a bit shocked if you had to > program in C++ someday; these rather innocent lines might not > do what you think: [...] > Simple things have so complex and ugly rules that... ugh, enough for now. http://www.ariel.com.au/jokes/An_Interview_with_Bjarne_Stroustrup.html Maybe BS thought he was joking, but IMO, it's true. "Stroustrup: Remember the length of the average-sized 'C' project? About 6 months. Not nearly long enough for a guy with a wife and kids to earn enough to have a decent standard of living. Take the same project, design it in C++ and what do you get? I'll tell you. One to two years." -- Grant Edwards grante Yow! I know how to do at SPECIAL EFFECTS!! visi.com From john at datavoiceint.com Fri May 11 14:01:08 2007 From: john at datavoiceint.com (HMS Surprise) Date: 11 May 2007 11:01:08 -0700 Subject: File modes In-Reply-To: <1178842276.692281.174370@e51g2000hsg.googlegroups.com> References: <1178830039.962239.245800@e51g2000hsg.googlegroups.com> <1178842276.692281.174370@e51g2000hsg.googlegroups.com> Message-ID: <1178906468.124923.107350@o5g2000hsb.googlegroups.com> On May 10, 7:11 pm, Jon Pentland wrote: > I don't really see the use for being able to do that. Have you tried > Well, I think I found a reason and it probably happens quite a bit. I open the file and read it into a list. I pop some elements from the list for processing and then write the shortened list back to disk to be available for other functions to access later, where later varies from seconds to days. There is no need to keep the file open till after the processing so I wish to write/flush/close right away. jvh From digimotif at gmail.com Thu May 24 15:15:02 2007 From: digimotif at gmail.com (digimotif) Date: 24 May 2007 12:15:02 -0700 Subject: need advice on building core code for python and PHP In-Reply-To: <1180028001.569139.317660@q66g2000hsg.googlegroups.com> References: <1180025115.704410.250890@a35g2000prd.googlegroups.com> <1180028001.569139.317660@q66g2000hsg.googlegroups.com> Message-ID: <1180034102.202337.23220@k79g2000hse.googlegroups.com> > > * simple and nice solution: > do not ever use php I'd like not to use it at all, but there's already been quite a bit of work done with it and I'm sure I won't be able to have it all removed at one time. I REALLY don't like debugging PHP especially after all the stuff I've done with Python. I find it much easier to test Python code as I go and I end up with fewer bugs to fix later. I'll work to remove the need for PHP a little at a time. Thanks for the tips, I'll look into it and I'm interested in any other ideas out there. Brian From mikael at isy.liu.se Thu May 31 04:51:48 2007 From: mikael at isy.liu.se (Mikael Olofsson) Date: Thu, 31 May 2007 10:51:48 +0200 Subject: c[:]() In-Reply-To: <002801c7a2eb$288a8750$240110ac@Muse> References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180504773.374529.161740@q66g2000hsg.googlegroups.com> <002801c7a2eb$288a8750$240110ac@Muse> Message-ID: <465E8CA4.4010506@isy.liu.se> Warren Stringer wrote: > I want to call every object in a tupple, like so: > [snip examples] > Why? Because I want to make Python calls from a cell phone. > Every keystroke is precious; even list comprehension is too much. If you are going to do this just a few times in your program, I cannot help. But: If you want to do it several times, perhaps you have space for an initial class definition, like so: class CallableList(list): def __call__(self,*args,**kwargs): return [f(*args,**kwargs) for f in self] def a(): return 'a called' def b(): return 'b called' c = CallableList([a,b])() You might want to trim the class to fit your needs, perhaps use a shorter name, and perhaps you don't need to handle arguments. Can the class be placed in a module, so that it only needs to be typed once in your application? /MiO From mail at timgolden.me.uk Wed May 9 11:26:34 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 09 May 2007 16:26:34 +0100 Subject: Specification for win32com.client package In-Reply-To: <1178723397.709258.50350@o5g2000hsb.googlegroups.com> References: <23617.87850.qm@web63415.mail.re1.yahoo.com> <1178715787.220103.245060@e65g2000hsc.googlegroups.com> <1178723397.709258.50350@o5g2000hsb.googlegroups.com> Message-ID: <4641E82A.6070604@timgolden.me.uk> kyosohma at gmail.com wrote: > On May 9, 8:25 am, Tim Golden wrote: >> kyoso... at gmail.com wrote: >>> The wiki idea sounds like a good one. I was thinking about doing some >>> kind of Python site about the modules and I think the popular 3rd >>> party ones would be a good place to start, maybe starting with win32. >>> How much information do you think would need to be on a site like this >>> to start out with? >> Someone did start a Python Win32 Wiki recently (check the >> python-win32 archives for location etc.) I did mean to put >> things on there myself, but real life has taken over. Often, >> these things just need someone with a bit of oomph to at >> least get the thing going. >> >> I think what's needed (if you're offering :) is for someone >> to put a *framework* in place on such a site which would >> make it easy for anyone to come along and fill in the gaps >> with their particular 3rd-party app or brand of knowledge. >> As I say, someone did start something, but I've not heard >> anything from him since then and I haven't found the time >> myself. If you were to kick something off and actually get >> it going I wouldn't say no. >> >> TJG > > I think I found the thread you were talking about: > http://mail.python.org/pipermail/python-win32/2007-March/005585.html > > I went to the site listed: www.wazoozle.com and I see nothing related > to python there. In fact, James (the poster) doesn't appear to be > listed anywhere either. Very weird. Strange. Maybe he gave up and hosted something else instead. It's not as though the name was related :) > While I am not a wiki wizard, I will look into it. I might be able to > bamboozle some free space on my friend's hosting service for such a > project. If so, I'll let you know. Personally, if only to save startup pain, I'd be inclined to use the main Python wiki, at least to get going. I know I said at the time that I was willing to kick something off, but days led to weeks... and you can guess the rest. Why not corner an area on http://wiki.python.org/moin/ and put headings in place? I'm not a great fan of MoinMoin, but it's there and it carries a (certain) measure of authority. That said, if you want to set up on your own space, I'm not objecting. I'll do my best (this time) to supply info and keep things going. TJG From robert.kern at gmail.com Thu May 24 16:51:10 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 24 May 2007 15:51:10 -0500 Subject: Newsgroups and mailing lists (was Re: Slightly OT: Why all the spam?) In-Reply-To: References: <3bb44c6e0705220008y10f5deb7v86ed82d3f8241761@mail.gmail.com> Message-ID: Aahz wrote: > These days, because of the cancelbot wars, ... Heh. Sounds like a particularly dire episode of Doctor Who. -- 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 tiarno at sas.com Wed May 16 10:05:12 2007 From: tiarno at sas.com (Tim Arnold) Date: Wed, 16 May 2007 10:05:12 -0400 Subject: Quote aware split References: Message-ID: "Ondrej Baudys" wrote in message news:mailman.7721.1179276620.32031.python-list at python.org... > Hi, > > After trawling through the archives for a simple quote aware split > implementation (ie string.split-alike that only splits outside of > matching quote) and coming up short, I implemented a quick and dirty > function that suits my purposes. Take a look at pyparsing--you'll like it I think. esp. http://pyparsing.wikispaces.com/Examples --Tim Arnold From timr at probo.com Wed May 16 03:18:42 2007 From: timr at probo.com (Tim Roberts) Date: Wed, 16 May 2007 07:18:42 GMT Subject: Iron Python References: <464981fa$0$8759$ed2619ec@ptn-nntp-reader02.plus.net> <1179224521.550517.271820@e51g2000hsg.googlegroups.com> <1179231778.899533.78590@u30g2000hsc.googlegroups.com> Message-ID: BartlebyScrivener wrote: >On May 15, 5:22 am, John Machin wrote: >> > > Anybody tried it? >> >> > Me. >> >> Me too. > >Anybody like it? I think it is a fascinating development, but it is aiming in a different direction. To a certain extent, you have to separate the Python language from the Python standard library. IronPython has the entire Python language, and it will run most (but not all) of the standard library we're all accustomed to, but the real fun of IronPython is that you have the entire .NET class framework available from Our Favorite Language. Considering all of the junk that regularly comes out of Redmond, I think that the Windows Presentation Foundation (formerly called "Avalon") is one of the most interesting things they've produced in a long time. IronPython will give me the opportunity to really dig into WPF without having to drink the C# kool-aid. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From john at datavoiceint.com Tue May 1 16:06:54 2007 From: john at datavoiceint.com (HMS Surprise) Date: 1 May 2007 13:06:54 -0700 Subject: Using python with MySQL In-Reply-To: References: <1178048415.272711.261930@n59g2000hsh.googlegroups.com> Message-ID: <1178050014.027397.324780@n59g2000hsh.googlegroups.com> On May 1, 2:58 pm, "Greg Donald" wrote: > On 1 May 2007 12:40:20 -0700, HMS Surprise wrote: > > > I need to peform some simple queries via MySQL. Searching the list I > > see that folks are accessing it with python. I am very new to python > > and pretty new to MySQL too. Would appreciate it if you could point me > > to some documentation for accessing MySQL via python. Something of the > > "Python and MySQL for Dummies" caliber would be about my speed, but of > > course I will be thankful for anything offered. > > http://mysql-python.sourceforge.net/ > > -- > Greg Donaldhttp://destiney.com/ Most excellent! Many thanks, Greg. I'll get started reading pronto. jvh From kw at codebykevin.com Tue May 15 16:47:05 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Tue, 15 May 2007 16:47:05 -0400 Subject: Distributing programs depending on third party modules. In-Reply-To: <464a1617$0$14328$426a74cc@news.free.fr> References: <53357$4649c4a6$4275d90a$20775@FUSE.NET> <464a1617$0$14328$426a74cc@news.free.fr> Message-ID: <62bee$464a1c4a$4275d90a$14962@FUSE.NET> Bruno Desthuilliers wrote: >> What platform are you doing this on? On the Linux platform, >> "dependency hell" of this sort is pretty much unavoidable, > > Yes it is. EasyInstall works just fine. You can install a beast like PyQt with easy_install? Meaning, that it will download and build/install not just the PyQt bits, but also Qt itself, sip, and all the other foundational components? If easy_install handles all that, I'm impressed. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From gagsl-py2 at yahoo.com.ar Thu May 10 21:08:48 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 10 May 2007 22:08:48 -0300 Subject: path stuff References: <1178734266.858048.311740@y5g2000hsa.googlegroups.com> <1178818879.239014.152210@e65g2000hsc.googlegroups.com> <1178826330.282268.132350@p77g2000hsh.googlegroups.com> <1178829783.996168.48250@u30g2000hsc.googlegroups.com> <1178834670.518728.102920@e65g2000hsc.googlegroups.com> Message-ID: En Thu, 10 May 2007 19:04:30 -0300, fscked escribi?: > ok, I lied, it is still doing the archived folders. Here is the code: > > import os, sys > from path import path > > myfile = open("boxids.txt", "r", 0) > for line in myfile: > d = 'D:\\Dir\\' + path(line.strip()) > for f in d.walkfiles('*Config*.xml'): > for dirpath, dirnames, filenames in os.walk(d): > if "Archived" in dirnames: > dirnames.remove("Archived") #skip this directory > print f > print 'Done' > > > when it does the print f it still shows me the dirs i don't want to > see. You are walking the directory structure *twice*, using two different methods at the same time. Also, there is no standard `path` module, and several implementations around, so it would be a good idea to tell us which one you use. If you want to omit a directory, and include just filenames matching a pattern: import os, sys, os.path, fnmatch def findinterestingfiles(root_dir): for dirpath, dirnames, filenames in os.walk(root_dir): if "Archived" in dirnames: dirnames.remove("Archived") for filename in fnmatch.filter(filenames, '*Config*.xml'): fullfn = os.path.join(dirpath, filename) print fullfn myfile = open("boxids.txt", "r") for line in myfile: dirname = os.path.join('D:\\Dir\\', line.strip()) findinterestingfiles(dirname): myfile.close() -- Gabriel Genellina From dborne at gmail.com Fri May 18 09:57:17 2007 From: dborne at gmail.com (Dave Borne) Date: Fri, 18 May 2007 08:57:17 -0500 Subject: A best approach to a creating specified http post body In-Reply-To: <1179486210.398916.251970@o5g2000hsb.googlegroups.com> References: <1179486210.398916.251970@o5g2000hsb.googlegroups.com> Message-ID: <6e42ec490705180657h1a7d8777qe2c1fb2b6ac7fe7b@mail.gmail.com> > I need to build a special http post body that consists of : > name=value +\r\n strings. > Problem is that depending on operations the number of name,value > pairs can increase and decrease. > Values need to be initialized at runtime, so storing premade text > files is not possible. I'm not completely understanding your problems here. Can you explain why urllib.urlencode wouldn't work? (http://docs.python.org/lib/module-urllib.html) Thanks, -Dave From larry.bates at websafe.com Tue May 22 10:19:13 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 22 May 2007 09:19:13 -0500 Subject: Printing dots in sequence ('...') In-Reply-To: <1179820951.288587.142670@h2g2000hsg.googlegroups.com> References: <1179820951.288587.142670@h2g2000hsg.googlegroups.com> Message-ID: beertje wrote: > This is a very newbie question for my first post, perhaps > appropriately. > > I want to print '....' gradually, as a progress indicator. I have a > for-loop that every 10 steps executes: > print '.', > > This results in something like 'Loading. . . .', whereas I want > 'Loading....' > > A pet peeve, I can't for the life of me figure out how to get this > desired output. How do I print dots - or anything for that matter - in > sequence without a space being inserted in between? > > Thanks. > Bj?rn > See example here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/299207 -Larry From rahulnag22 at yahoo.com Thu May 17 10:57:48 2007 From: rahulnag22 at yahoo.com (rahulnag22 at yahoo.com) Date: 17 May 2007 07:57:48 -0700 Subject: tkFileDialog.askopenfilename() In-Reply-To: References: Message-ID: <1179413868.285499.235540@o5g2000hsb.googlegroups.com> On May 16, 6:21 am, "Hamilton, William " wrote: > > From: rahulna... at yahoo.com > > > Hi, > > When I call tkFileDialog.askopenfilename() , the dialog box opens with > > the current directory as the default directory. Is it possible to open > > the dialog box with a directory other than the current directory. Can > > we pass in a user defined starting directory. > > Thanks > > Rahul > > This link has a decent amount of info about the various dialog modules.http://www.pythonware.com/library/tkinter/introduction/x1164-data-ent... > > --- > -Bill Hamilton Thanks for the links ppl. That helped.... From __peter__ at web.de Thu May 10 12:53:17 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 10 May 2007 18:53:17 +0200 Subject: keyword checker - keyword.kwlist References: Message-ID: tom at finland.com wrote: > Still no go. I just can't get it right. My current script: > > #!usr/bin/env python > import keyword > > myInput = raw_input('Enter identifier to check >> ') > if myInput in keyword.kwlist: > print myInput, "is keyword" > > else: > print myInput, "is not keyword" > > print keyword.kwlist > print keyword.__file__ > > And the output: > > Enter identifier to check >> else > else > is not keyword > ['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', > 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', > 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', > 'raise', 'return', 'try', 'while', 'with', 'yield'] > F:\Ohjelmat\Python25\Lib\keyword.pyc Does myInput = raw_input("...").strip() # ... work? Your raw_input() seems to be broken and includes the trailing newline. Peter From bj_666 at gmx.net Thu May 3 10:36:34 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 03 May 2007 16:36:34 +0200 Subject: ascii to unicode line endings References: <1178191837.424765.51090@o5g2000hsb.googlegroups.com> <1178196326.926359.187930@p77g2000hsh.googlegroups.com> Message-ID: In <1178196326.926359.187930 at p77g2000hsh.googlegroups.com>, fidtz wrote: >>>> import codecs >>>> testASCII = file("c:\\temp\\test1.txt",'w') >>>> testASCII.write("\n") >>>> testASCII.close() >>>> testASCII = file("c:\\temp\\test1.txt",'r') >>>> testASCII.read() > '\n' > Bit pattern on disk : \0x0D\0x0A >>>> testASCII.seek(0) >>>> testUNI = codecs.open("c:\\temp\\test2.txt",'w','utf16') >>>> testUNI.write(testASCII.read()) >>>> testUNI.close() >>>> testUNI = file("c:\\temp\\test2.txt",'r') >>>> testUNI.read() > '\xff\xfe\n\x00' > Bit pattern on disk:\0xff\0xfe\0x0a\0x00 > Bit pattern I was expecting:\0xff\0xfe\0x0d\0x00\0x0a\0x00 >>>> testUNI.close() Files opened with `codecs.open()` are always opened in binary mode. So if you want '\n' to be translated into a platform specific character sequence you have to do it yourself. Ciao, Marc 'BlackJack' Rintsch From deets at nospam.web.de Tue May 1 16:20:51 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 01 May 2007 22:20:51 +0200 Subject: Grabbing the output of a long-winded shell call (in GNU/Linux) In-Reply-To: <46379600.3060502@yahoo.com> References: <46378364$1@news.bezeqint.net> <1178047885.767785.35320@h2g2000hsg.googlegroups.com> <46379600.3060502@yahoo.com> Message-ID: <59plp3F2l64obU1@mid.uni-berlin.de> Efrat Regev schrieb: > draghuram at gmail.com wrote: >> On May 1, 2:23 pm, Efrat Regev wrote: >> >>> So my question is if there's a way to "grab" the output as it's being >>> generated. It doesn't matter if the solution is blocking (as opposed to >>> callback based), since threads can handle this. I just don't know how to >>> "grab" the output. I appreciate your time in reading (and answering >>> this), as I've been googling several hours for this. >> >> There may be more pythonic solution than what I suggest here but this >> is what I have done when I needed similar functionality. Basically run >> your command in the background and redirect its stdout/err to a temp >> file. You may run the command either in the background or in a >> separate thread. You can then run the command "tail --retry -- >> pid= -n+0 -F " and grab the output. The tail command >> exits once the real command is done. Or instead use the python subprocess module and read the commands stdin/out/err from the Popen-object. Diez From paul.rudin at ntlworld.com Fri May 18 15:09:35 2007 From: paul.rudin at ntlworld.com (Paul Rudin) Date: Fri, 18 May 2007 20:09:35 +0100 Subject: emacs python debugging: pydb or pdb fringe interaction References: <87k5v61qpc.fsf@rudin.co.uk> <87veeqnf5q.fsf@merkury.smsnet.pl> Message-ID: <87sl9u9ceo.fsf@rudin.co.uk> Rob Wolfe writes: > Paul Rudin writes: > >> I can't get the gdb fringe interaction functionality to work with >> either pdb or pydb. Any hints as to versions or incantations I should >> try? > > It works for me on Debian Etch and GNU Emacs 21.4.1. > I'm using this settings: > > (setq pdb-path '/usr/lib/python2.4/pdb.py > gud-pdb-command-name (symbol-name pdb-path)) > > (defadvice pdb (before gud-query-cmdline activate) > "Provide a better default command line when called interactively." > (interactive > (list (gud-query-cmdline pdb-path > (file-name-nondirectory buffer-file-name))))) Unfortunately this doesn't make any difference for me, with either emacs 22 or 21. I guess I'll just have to dig deeper into the code. From webbfamily at DIESPAMDIEoptusnet.com.au Thu May 3 07:57:42 2007 From: webbfamily at DIESPAMDIEoptusnet.com.au (Peter Webb) Date: Thu, 3 May 2007 21:57:42 +1000 Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? In-Reply-To: <1178162456.929395.139390@q75g2000hsh.googlegroups.com> References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> <1178162456.929395.139390@q75g2000hsh.googlegroups.com> Message-ID: <4639ce3e$0$29937$afc38c87@news.optusnet.com.au> > Ask yourself WHY havn't I seen this footage before? > > **************************** OK, why haven't you seen this footage before? From mensanator at aol.com Fri May 11 16:09:50 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 11 May 2007 13:09:50 -0700 Subject: Interesting list Validity (True/False) In-Reply-To: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> Message-ID: <1178914190.166662.285410@p77g2000hsh.googlegroups.com> On May 11, 2:28 pm, nufuh... at gmail.com wrote: > Hello all, > > First let me appologise if this has been answered but I could not find > an acurate answer to this interesting problem. > > If the following is true: > C:\Python25\rg.py>python > 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. > >>> [] == [] > True > >>> ['-o'] == [] > False > >>> ['-o'] == False > False > >>> > > Then why do I get the following results: > C:\Python25\rg.py>help.py -o > print arg ['-o'] > type(arg): > arg is True? False > help.py version 1.0 Copyright RDEG (c) 2007 > ['-o'] is an unrecognized option. > Progam Exit (0) > > > import sys > > _ver_ = 1.00 > > if '-h' in sys.argv or '--help' in sys.argv: > print > print " help.py Version", _ver_, "Copyright RDEG (c) 2007" > print ''' > > Options : -h, --help -- display this message > Progam Exit (0)''' > sys.exit(0) > else: > arg = sys.argv[1:] > print 'print arg', arg > print 'type(arg):', type(arg) > print 'arg is True?', arg == True > print " help.py version", _ver_, "Copyright RDEG (c) 2007" > print " ", arg, "is an unrecognized option." > print " Progam Exit (0)" > sys.exit(0) > Does this clear things up? import sys _ver_ = 1.00 if '-h' in sys.argv or '--help' in sys.argv: print print " help.py Version", _ver_, "Copyright RDEG (c) 2007" print ''' Options : -h, --help -- display this message Progam Exit (0)''' sys.exit(0) else: arg = sys.argv[1:] print 'print arg', arg print 'type(arg):', type(arg) print 'arg is True?', arg == True print if arg: print 'was True' else: print 'was False' print print " help.py version", _ver_, "Copyright RDEG (c) 2007" print " ", arg, "is an unrecognized option." print " Progam Exit (0)" sys.exit(0) ## C:\python25\user>python arghhh!.py -o ## print arg ['-o'] ## type(arg): ## arg is True? False ## ## was True ## ## help.py version 1.0 Copyright RDEG (c) 2007 ## ['-o'] is an unrecognized option. ## Progam Exit (0) ## C:\python25\user>python arghhh!.py ## print arg [] ## type(arg): ## arg is True? False ## ## was False ## ## help.py version 1.0 Copyright RDEG (c) 2007 ## [] is an unrecognized option. ## Progam Exit (0) From desertlinux at netscape.net Wed May 16 09:46:30 2007 From: desertlinux at netscape.net (Brian) Date: Wed, 16 May 2007 06:46:30 -0700 Subject: Newbie Question: Getting a list of files In-Reply-To: References: Message-ID: Hi Steven, Thanks for all of the good advice! Much appreciated. Dusty --- Steven D'Aprano wrote: > On Tue, 15 May 2007 17:12:01 -0700, Brian wrote: > >> How do I, in Python, obtain a recursive list of files in a specified >> directory, including the subdirectories, etc? For example, in the old >> MS-DOS days, we could specify at the command prompt "DIR /S" and this >> would provide a listing of all files, including those in subdirectories, >> no matter how far down the branch they were. How can this be done with >> Python? > > In MS DOS days, you were dealing with a small number of files. Python has > to deal with file systems that could contain billions of files. If each > file name has an average of eight characters, your recursive list of > files could require a gigabyte of memory just to hold the file names. (It > might not, of course -- it depends on the file system in use.) > > I suggest you have a look at the os module, in particular os.listdir and > os.walk. > > From rahulnag22 at yahoo.com Mon May 14 16:46:32 2007 From: rahulnag22 at yahoo.com (rahulnag22 at yahoo.com) Date: 14 May 2007 13:46:32 -0700 Subject: tkinter button state = DISABLED In-Reply-To: References: <1179163831.016938.79840@w5g2000hsg.googlegroups.com> Message-ID: <1179175592.011635.103980@e51g2000hsg.googlegroups.com> On May 14, 12:01 pm, Peter Otten <__pete... at web.de> wrote: > rahulna... at yahoo.com wrote: > > I have created a button widget with a button click binding. The button > > initially has a state=disabled. I can see the greyed out version of > > the button in the GUI. But If I click on the button it still invokes > > the callback/binding function. > > > Any suggestions as to why the callback is being invoked even though > > the button has a disabled state. It looks like- > > > b=Button(frame, text = "Button", state = 'disabled') > > > b.bind("", > > lambda > > event : > > function() > > ) > > Well, the /mouse/ button /was/ released. Do you know about the alternative? > > b = Button(..., command=function) # no bind(), no lambda > > It behaves like you expect. > > Peter So, then is it right to say that for a widget like button widget on occurance of a 'event' the function which is bound to this event is invoked, even if the button widget has its 'state' option set to 'disabled'. I was assuming that if the button widget has state = 'disabled' then even on a button event the binding function wont be invoked. I will take a look at the alternative code you suggested above too. Thanks Rahul From jim at reallykillersystems.com Tue May 8 17:32:52 2007 From: jim at reallykillersystems.com (James Beck) Date: Tue, 8 May 2007 17:32:52 -0400 Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> <08qk33t594ih0ulmjmev90d22lkfnotgoe@4ax.com> <463C2A3A.8332D211@hotmail.com> <0k8p33h90bp5tfajedb4bmd2eik8gfi2ho@4ax.com> <4640CB37.907C9988@earthlink.net> Message-ID: In article <4640CB37.907C9988 at earthlink.net>, mike.terrell at earthlink.net says... > James Beck wrote: > > > > Yep, you must have access to better drugs than I do. > > You get to hallucinate your stuff up. > > Don't forget to adjust your tin beanie! > > > Its not a beanie. He had his head tin plated. :( > I just the "How it's Made" that showed how they make bronzed baby shoes. Maybe they can adapt that process to tin plate heads. Would save these guys thousands of $$$ on foil. Jim From steve at holdenweb.com Sat May 19 22:53:06 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 19 May 2007 22:53:06 -0400 Subject: What is deployment? In-Reply-To: <7x4pm8tf6v.fsf@ruckus.brouhaha.com> References: <68m4i4-9a4.ln1@lairds.us> <7x4pm8tf6v.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > claird at lairds.us (Cameron Laird) writes: >> What might C. mean? Say I install a program, but I still have to worry >> about how I'm going to configure it within the cluster where I intend to >> use it, AND I need to co-ordinate its configuration with the central >> database on which it depends, AND I have to tie it in to our license- >> management system, AND there are issues with users sharing data and also >> protecting data from each other, AND ...--well, all those things that >> happen after narrow-sense installation are still part of "deployment". > > Deployment also refers to pre-installation issues, like buying the > hardware that you're going to install on. You *install* programs. You *deploy* "solutions" ;-) 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From nagle at animats.com Thu May 3 13:47:16 2007 From: nagle at animats.com (John Nagle) Date: Thu, 03 May 2007 17:47:16 GMT Subject: My Python annoyances In-Reply-To: References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> Message-ID: Ben Collver wrote: > I rewrote my code in Python and I found myself running into many of the > same hassles that I run into with other languages: inaccurate and > incomplete documentation, a maze of little platform-specific quirks to > work around in the base classes, and a macho community of users. That's about typical. I've had much the same experiences, but with a completely different set of external packages. I was doing a web application in Linux; this user was doing a desktop app on Windows. Yet he's reporting much the same kinds of quality problems I noticed. In general, the libraries outside of the core are not well maintained. The user communities are small and bug reports can take years to resolve. > I tried to write portable Python code. The zlib CRC function returned > different results on architectures between 32 bit and 64 bit > architectures. I filed a bug report. It was closed, without a comment > from the person who closed it. I get the unspoken message: bug reports > are not welcome. That's the problem with bug reporting systems which let developers close bugs arbitrarily. Defect reporting systems should have a status for "developer in denial". Bug handling in loosely managed projects tends to follow the same path as the "stages of grief": denial, anger, bargaining, depression, and acceptance. Getting through the process requires a year or so. There's an integration problem with the CPython implementation. The mechanism for supporting extensions in other languages does not have a tightly defined API which remains constant across versions. Thus, C extensions are tied to a specific version of CPython compiled with a specific compiler. There's no effort by the core Python development group to keep third-party extensions in sync with the core, so whenever a new core version comes out, many third party extensions are unusuable with it for some months. The integration problem is dumped on the third party extension developers. Most of the items the user here is complaining about fall into that category. > In short, there is plenty of room for improvement. Admittedly these are > not problems with the language definition. But I downloaded a Python > distribution, and the problems are Python specific. That's the usual observation. The language is in good shape, but the libraries are not. Python is better than Perl, but CPAN is better than Cheese Shop. John Nagle From Carlos.Hanson at gmail.com Mon May 7 12:22:13 2007 From: Carlos.Hanson at gmail.com (Carlos Hanson) Date: 7 May 2007 09:22:13 -0700 Subject: ftplib acting weird In-Reply-To: <1178275384.656955.269830@h2g2000hsg.googlegroups.com> References: <1178275384.656955.269830@h2g2000hsg.googlegroups.com> Message-ID: <1178554933.176915.64770@e51g2000hsg.googlegroups.com> On May 4, 3:43 am, Merrigan wrote: > Hi All, > > I have written a little script to upload some files to an ftp folder. > The problem is as follows : > > I wrote the script on my windows laptop, and I want to run it from > mylinux server. Everything worked fine so I uploaded it to my linux > machine. Every time I tun the script I get the following error: > > *************************************************************************************************************************** > > [root at moses ftpsync]# python ftpsync.py > !!!!!!!!!! > The Connection to the Server Could not be established. > Please Check all neccesary settings and run the script again. > Thank you > !!!!!!!!!! > Traceback (most recent call last): > File "ftpsync.py", line 194, in ? > ftplisting() > File "ftpsync.py", line 83, in ftplisting > ftpconn.cwd(remotedir) #This changes to the remote directory > File "/usr/lib64/python2.4/ftplib.py", line 494, in cwd > return self.voidcmd(cmd) > File "/usr/lib64/python2.4/ftplib.py", line 245, in voidcmd > self.putcmd(cmd) > File "/usr/lib64/python2.4/ftplib.py", line 175, in putcmd > self.putline(line) > File "/usr/lib64/python2.4/ftplib.py", line 170, in putline > self.sock.sendall(line) > AttributeError: 'NoneType' object has no attribute 'sendall' > [root at moses ftpsync]# > > *************************************************************************************************************************** > > When I copy the same piece of scripting and run it from the python > command shell, it works... > > what am I doing wrong? I have double checked everything about a > million times, but to no avail. > > Blessings! Can you show the code? -- Carlos Hanson From bbxx789_05ss at yahoo.com Tue May 1 00:21:01 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 30 Apr 2007 21:21:01 -0700 Subject: sqlite for mac? Message-ID: <1177993261.572563.70370@n76g2000hsh.googlegroups.com> Does sqlite come in a mac version? Thanks. From XX.XmcX at XX.XmclaveauX.com Thu May 17 09:14:32 2007 From: XX.XmcX at XX.XmclaveauX.com (MC) Date: Thu, 17 May 2007 15:14:32 +0200 Subject: Sending a JavaScript array to Python script? References: <1179405295.865954.241740@e65g2000hsc.googlegroups.com> Message-ID: Hi! Which context? I know to do interact Python <=> Jscript, with Internet-Explorer+COM ; but I don't know with others environment. -- @-salutations Michel Claveau From gagsl-py2 at yahoo.com.ar Mon May 14 02:38:16 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 14 May 2007 03:38:16 -0300 Subject: PyRun_String and related functions causing garbage when calling a parsed function from C. References: <1179089897.569954.110370@n59g2000hsh.googlegroups.com> Message-ID: En Sun, 13 May 2007 17:58:17 -0300, escribi?: > Hi I'm getting extremely odd behavior. First of all, why isn't > PyEval_EvalCode documented anywhere? Anyway, I'm working on > blender's > python integration (it embeds python, as opposed to python embedding > it). I have a function that executes a string buffer of python code, > fetches a function from its global dictionary then calls it. Why don't you use a documented function like PyRun_String or similar, as in the subject line? > /*Now for the fun part! Try and find the functions we need.*/ > while ( PyDict_Next(globals, &ppos, &gkey, &gval) ) { > if ( PyString_Check(gkey) && strcmp(PyString_AsString(gkey), > "doConstraint")==0 ) { > if (PyFunction_Check(gval) ) { > retval = PyObject_CallObject(gval, > Py_BuildValue("OOO", > srcmat, tarmat, idprop)); > Py_XDECREF( retval ); > } else { > printf("ERROR: doConstraint is supposed to be a > function!\n"); > } > break; > } > } I'd use PyDict_Get_Item_String (iterating over a dict just to locate a key is rather silly). And, if you are going to use the return value from PyObject_CallObject (retval), don't decref it!!! (you even decref it twice). -- Gabriel Genellina From pete.losangeles at gmail.com Tue May 15 19:38:14 2007 From: pete.losangeles at gmail.com (MisterPete) Date: 15 May 2007 16:38:14 -0700 Subject: inherit from file and create stdout instance? In-Reply-To: <1179270178.281061.34860@k79g2000hse.googlegroups.com> References: <1179267498.154549.58370@h2g2000hsg.googlegroups.com> <1179270178.281061.34860@k79g2000hse.googlegroups.com> Message-ID: <1179272294.058634.140760@k79g2000hse.googlegroups.com> > Your code works for me: > > import sys > > class Output(file): > def __init__(self, file=sys.stdout, verbosity=1): > self.verbosity = verbosity > self.file = file > > def write(self, string, messageVerbosity=1): > if messageVerbosity <= self.verbosity: > self.file.write(string) > > o = Output() > o.write("this goes to a console window") > > f = open("aaa.txt", "w") > o = Output(f) > o.write("this goes to a file") I could make wrappers around all of the file methods but that kind of defeats the purpose of inheriting from file. It's kind of odd to inherit from file but then keep a file object (although then it would at least pass any isinstance(object, file) tests at least) and overwrite every single method. I'd prefer that I inherit from file and just get flush and next and everything for free (and any new methods if they were added). What I'm really looking for is to make a copy of the sys.stdout object but make it an Output object. If the file object just had a __dict__ with a buffer I could grab or something like that it wouldn't be too tough. Unfortunately I don't even know how I could make a copy of sys.stdout since the copy module doesn't work for file objects. Thanks, Pete From DustanGroups at gmail.com Fri May 4 07:13:14 2007 From: DustanGroups at gmail.com (Dustan) Date: 4 May 2007 04:13:14 -0700 Subject: Why are functions atomic? In-Reply-To: <1178260571.160570.299160@p77g2000hsh.googlegroups.com> References: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> <1178044821.864741.235260@o5g2000hsb.googlegroups.com> <1178063341.779617.289690@o5g2000hsb.googlegroups.com> <1178065685.161372.81790@y80g2000hsf.googlegroups.com> <1178083318.404304.76100@q75g2000hsh.googlegroups.com> <1178260571.160570.299160@p77g2000hsh.googlegroups.com> Message-ID: <1178277194.559817.143360@o5g2000hsb.googlegroups.com> On May 4, 1:36 am, Michael wrote: > On May 2, 6:08 am, Carsten Haese wrote: > > > On Tue, 2007-05-01 at 22:21 -0700, Michael wrote: > > > Is there a reason for using the closure here? Using function defaults > > > seems to give better performance:[...] > > > It does? Not as far as I can measure it to any significant degree on my > > computer. > > I agree the performance gains are minimal. Using function defaults > rather than closures, however, seemed much cleaner an more explicit to > me. For example, I have been bitten by the following before: > > >>> def f(x): > > ... def g(): > ... x = x + 1 > ... return x > ... return g>>> g = f(3) > >>> g() > > Traceback (most recent call last): > File "", line 1, in > File "", line 3, in g > UnboundLocalError: local variable 'x' referenced before assignment > > If you use default arguments, this works as expected:>>> def f(x): > > ... def g(x=x): > ... x = x + 1 > ... return x > ... return g > >>> g = f(3) > >>> g() > > 4 >>> g() 4 >>> g() 4 >>> g() # what is going on here???? 4 > The fact that there also seems to be a performance gain (granted, it > is extremely slight here) led me to ask if there was any advantage to > using closures. It seems not. > > > An overriding theme in this thread is that you are greatly concerned > > with the speed of your solution rather than the structure and > > readability of your code. > > Yes, it probably does seem that way, because I am burying this code > deeply and do not want to revisit it when profiling later, but my > overriding concern is reliability and ease of use. Using function > attributes seemed the best way to achieve both goals until I found out > that the pythonic way of copying functions failed. Here was how I > wanted my code to work: > > @define_options(first_option='abs_tol') > def step(f,x,J,abs_tol=1e-12,rel_tol=1e-8,**kwargs): > """Take a step to minimize f(x) using the jacobian J. > Return (new_x,converged) where converged is true if the tolerance > has been met. > """ > > return (x + dx, converged) > > @define_options(first_option='min_h') > def jacobian(f,x,min_h=1e-6,max_h=0.1): > """Compute jacobian using a step min_h < h < max_h.""" > > return J > > class Minimizer(object): > """Object to minimize a function.""" > def __init__(self,step,jacobian,**kwargs): > self.options = step.options + jacobian.options > self.step = step > self.jacobian = jacobian > > def minimize(self,f,x0,**kwargs): > """Minimize the function f(x) starting at x0.""" > step = self.step > jacobian = self.jacobian > > step.set_options(**kwargs) > jacobian.set_options(**kwargs) > > converged = False > while not converged: > J = jacobian(f,x) > (x,converged) = step(f,x,J) > > return x > > @property > def options(self): > """List of supported options.""" > return self.options > > The idea is that one can define different functions for computing the > jacobian, step etc. that take various parameters, and then make a > custom minimizer class that can provide the user with information > about the supported options etc. > > The question is how to define the decorator define_options? > > 1) I thought the cleanest solution was to add a method f.set_options() > which would set f.func_defaults, and a list f.options for > documentation purposes. The docstring remains unmodified without any > special "wrapping", step and jacobian are still "functions" and > performance is optimal. > > 2) One could return an instance f of a class with f.__call__, > f.options and f.set_options defined. This would probably be the most > appropriate OO solution, but it makes the decorator much more messy, > or requires the user to define classes rather than simply define the > functions as above. In addition, this is at least a factor of 2.5 > timese slower on my machine than option 1) because of the class > instance overhead. (This is my only real performance concern because > this is quite a large factor. Otherwise I would just use this > method.) > > 3) I could pass generators to Minimize and construct the functions > dynamically. This would have the same performance, but would require > the user to define generators, or require the decorator to return a > generator when the user appears to be defining a function. This just > seems much less elegant. > > ... > @define_options_generator(first_option='min_h') > def jacobian_gen(f,x,min_h=1e-6,max_h=0.1): > """Compute jacobian using a step min_h < h < max_h.""" > > return J > > class Minimizer(object): > """Object to minimize a function.""" > def __init__(self,step_gen,jacobian_gen,**kwargs): > self.options = step_gen.options + jacobian_gen.options > self.step_gen = step_gen > self.jacobian_gen = jacobian_gen > > def minimize(self,f,x0,**kwargs): > """Minimize the function f(x) starting at x0.""" > step = self.step_gen(**kwargs) > jacobian = self.jacobian_gen(**kwargs) > > converged = False > while not converged: > J = jacobian(f,x) > (x,converged) = step(f,x,J) > > return x > ... > > 4) Maybe there is a better, cleaner way to do this, but I thought that > my option 1) was the most clear, readable and fast. I would > appreciate any suggestions. The only problem is that it does use > mutable functions, and so the user might be tempted to try: > > new_step = copy(step) > > which would fail (because modifying new_step would also modify step). > I guess that this is a pretty big problem (I could provide a custom > copy function so that > > new_step = step.copy() > > would work) and I wondered if there was a better solution (or if maybe > copy.py should be fixed. Checking for a defined __copy__ method > *before* checking for pre-defined mutable types does not seem to break > anything.) > > Thanks again everyone for your suggestions, it is really helping me > learn about python idioms. > > Michael. From george.sakkis at gmail.com Tue May 29 12:51:09 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 29 May 2007 09:51:09 -0700 Subject: Storing tracebacks In-Reply-To: <1180446376.879439.55840@m36g2000hse.googlegroups.com> References: <1180410412.643608.30050@q66g2000hsg.googlegroups.com> <1180446376.879439.55840@m36g2000hse.googlegroups.com> Message-ID: <1180457469.296553.291590@x35g2000prf.googlegroups.com> On May 29, 9:46 am, kyoso... at gmail.com wrote: > On May 28, 10:46 pm, George Sakkis wrote: > > > > > I'm reading the docs on sys.exc_info() but I can't tell for sure > > whether I'm using it safely to get a snapshot of an exception and > > reraise it later. The use case is a class which acts like a deferred > > callable, a callable that will be called at some point in the future > > (possibly in a different thread) and whose result or raised exception > > is to be stored as an attribute. This will be available by calling the > > result() method, which returns the original result or reraises the > > exception: > > > class JobRequest(object): > > > def __init__(self, *args, **kwds): > > self.args = args > > self.kwds = kwds > > self._exc_info = None > > > def __call__(self): > > raise NotImplementedError('Abstract method') > > > def process(self): > > try: > > self._result = self(*self.args, **self.kwds) > > except: > > self._exc_info = sys.exc_info() > > else: > > self._exc_info = None > > > def result(self): > > if self._exc_info is not None: > > type,exception,traceback = self._exc_info > > raise type,exception,traceback > > try: return self._result > > except AttributeError: > > raise UnprocessedRequestError() > > > class UnprocessedRequestError(RuntimeError): > > pass > > > So far it seems it works as expected but I'd like to know if this is > > error-prone and why. > > > George > > I don't know enough about this method of getting tracebacks, but why > wouldn't the traceback module work for you? It sounds like it uses the > sys.exc_info() method you refer to. > > http://python.active-venture.com/lib/module-traceback.html The traceback module is handy if you want a text representation of the traceback, not the actual traceback. The reason I want to store the actual traceback is to make the exception transparent to the user, i.e. not be able to tell whether the exception was thrown in the current stack frame or in another thread or even process. Unfortunately tracebacks are not pickleable, otherwise I could just pickle them in process() and unpickle them in result(). George From python at rcn.com Tue May 29 06:02:33 2007 From: python at rcn.com (Raymond Hettinger) Date: 29 May 2007 03:02:33 -0700 Subject: itertools.groupby In-Reply-To: <6Y6dnb0mTLsaCsbbnZ2dnUVZ_hCdnZ2d@comcast.com> References: <1180286272.100790.131670@q75g2000hsh.googlegroups.com> <7xveecr5xx.fsf@ruckus.brouhaha.com> <6Y6dnb0mTLsaCsbbnZ2dnUVZ_hCdnZ2d@comcast.com> Message-ID: <1180432953.210575.144900@n15g2000prd.googlegroups.com> On May 28, 8:02 pm, Gordon Airporte wrote: > "Each" seems to imply uniqueness here. Doh! This sort of micro-massaging the docs misses the big picture. If "each" meant unique across the entire input stream, then how the heck could the function work without reading in the entire data stream all at once. An understanding of iterators and itertools philosophy reveals the correct interpretation. Without that understanding, it is a fools errand to try to inject all of the attendant knowledge into the docs for each individual function. Without that understanding, a user would be *much* better off using list based functions (i.e. using zip() instead izip() so that they will have a thorough understanding of what their code actually does). The itertools module necessarily requires an understanding of iterators. The module has a clear philosophy and unifying theme. It is about consuming data lazily, writing out results in small bits, keeping as little as possible in memory, and being a set of composable functional-style tools running at C speed (often making it possible to avoid the Python eval-loop entirely). The docs intentionally include an introduction that articulates the philosophy and unifying theme. Likewise, there is a reason for the examples page and the recipes page. Taken together, those three sections and the docs on the individual functions guide a programmer to a clear sense of what the tools are for, when to use them, how to compose them, their inherent strengths and weaknesses, and a good intuition about how they work under the hood. Given that context, it is a trivial matter to explain what groupby() does: it is an itertool (with all that implies) that emits groups from the input stream whenever the key(x) function changes or the stream ends. Without the context, someone somewhere will find a way to get confused no matter how the individual function docs are worded. When the OP said that he hadn't read the examples, it is not surprising that he found a way to get confused about the most complex tool in the toolset.* Debating the meaning of "each" is sure sign of ignoring context and editing with tunnel vision instead of holistic thinking. Similar issues arise in the socket, decimal, threading and regular expression modules. For users who do not grok those module's unifying concepts, no massaging of the docs for individual functions can prevent occasional bouts of confusion. Raymond * -- FWIW, the OP then did the RightThing (tm) by experimenting at the interactive prompt to observe what the function actually does and then posted on comp.lang.python in a further effort to resolve his understanding. From rurpy at yahoo.com Thu May 17 13:45:19 2007 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 17 May 2007 10:45:19 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464C34DB.4010903@v.loewis.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179258692.237438.110860@p77g2000hsh.googlegroups.com> <464ad4a2$0$23143$9b4e6d93@newsspool1.arcor-online.net> <464C34DB.4010903@v.loewis.de> Message-ID: <1179423919.521335.24150@k79g2000hse.googlegroups.com> On May 17, 4:56 am, "Martin v. L?wis" wrote: ... > (look me in the eye and tell me that "def" is > an English word, or that "getattr" is one) That's not quite fair. They are not english words but they are derived from english and have a memonic value to english speakers that they don't (or only accidently) have for non-english speakers. From john at datavoiceint.com Thu May 10 13:02:26 2007 From: john at datavoiceint.com (HMS Surprise) Date: 10 May 2007 10:02:26 -0700 Subject: append Message-ID: <1178816546.689849.255070@y5g2000hsa.googlegroups.com> Trying not to be a whiner but I sure have trouble finding syntax in the reference material. I want to know about list operations such as append. Is there a pop type function? I looked in tutorial, language reference, and lib for list, append, sequence. Is there a place where us doofi ( who may not have our heads out in the sunlight) may find all related syntax grouped together? thanx, jh From mailmaverick666 at gmail.com Thu May 31 01:39:49 2007 From: mailmaverick666 at gmail.com (rishi pathak) Date: Thu, 31 May 2007 11:09:49 +0530 Subject: Usage of the __and__ method In-Reply-To: <1180588305.004419.127680@d30g2000prg.googlegroups.com> References: <1180588305.004419.127680@d30g2000prg.googlegroups.com> Message-ID: <180b672e0705302239p7d03fb4g70ee4b54eacd00ee@mail.gmail.com> This works perfectly well. class Person: def __init__(self,name): self.name = name def print_name(self): print self.name def __and__(self,other): print "self.name : ",self.name print "other.name : ",other.name self.name = '%s AND %s' %(self.name,other.name) return self.name p = Person("John") q = Person("George") print Person.__and__(p,q) On 30 May 2007 22:11:45 -0700, theju wrote: > > Hello all, > I've two objects (both instances of a class called Person) and I want > to use the __and__ method and print the combined attributes of the two > instances. > > To be precise, here is my code.... > > class Person: > def __init__(self,name): > self.name = name > def print_name(self): > print self.name > def __and__(self,other): > self.name = '%s AND %s' %(self.name,other.name) > return self.name > > p = Person("John") > q = Person("George") > > r = p and q > print r.print_name() > > Output: > ----------- > George > None > > I've also tried this: > class Person: > def __init__(self,name): > self.name = name > def print_name(self): > print self.name > def __and__(self,other): > a = Person() > a.name = '%s AND %s' %(self.name,other.name) > return a > > p = Person("John") > q = Person("George") > > r = p and q > print r.print_name() > > Output: > ----------- > George > None > > The above output in both cases is giving me a doubt if __and__ method > is over-ridable or not? > > The output that I am accepting is: > John AND George > > What are the changes if to be made? > > Thanking You > Thejaswi Puthraya > http://thejuhyd.blogspot.com > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Regards-- Rishi Pathak National PARAM Supercomputing Facility Center for Development of Advanced Computing(C-DAC) Pune University Campus,Ganesh Khind Road Pune-Maharastra -------------- next part -------------- An HTML attachment was scrubbed... URL: From bdesth.quelquechose at free.quelquepart.fr Wed May 2 19:41:19 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 03 May 2007 01:41:19 +0200 Subject: How to check if a string is empty in python? In-Reply-To: <1178139155.260722.153750@n59g2000hsh.googlegroups.com> References: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> <1178138964.503290.254060@o5g2000hsb.googlegroups.com> <1178139155.260722.153750@n59g2000hsh.googlegroups.com> Message-ID: <463917d1$0$2415$426a74cc@news.free.fr> mensanator at aol.com a ?crit : > On May 2, 3:49 pm, Basilisk96 wrote: > >>A simple >> >>if s: >> print "not empty" >>else: >> print "empty" >> >>will do. > > > How do you know that s is a string? Why do you want to know if it's a string ? From michael.forbes at gmail.com Tue May 1 07:06:18 2007 From: michael.forbes at gmail.com (Michael) Date: 1 May 2007 04:06:18 -0700 Subject: Why are functions atomic? Message-ID: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> Why are functions atomic? (I.e. they are not copied.) For example, I would like to make a copy of a function so I can change the default values: >>> from copy import copy >>> f = lambda x: x >>> f.func_defaults = (1,) >>> g = copy(f) >>> g.func_defaults = (2,) >>> f(),g() (2, 2) I would like the following behaviour: >>> f(),g() (1,2) I know I could use a 'functor' defining __call__ and using member variables, but this is more complicated and quite a bit slower. (I also know that I can use new.function to create a new copy, but I would like to know the rational behind the decision to make functions atomic before I shoot myself in the foot;-) Thanks, Michael. From grante at visi.com Thu May 31 19:14:02 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 31 May 2007 23:14:02 -0000 Subject: c[:]() References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <135tobve86qj808@corp.supernews.com> <135tru124pie2b3@corp.supernews.com> <135tv1bjqgbmsc9@corp.supernews.com> <003301c7a3ab$f2bdf960$240110ac@Muse> <001801c7a3cc$e9f0b270$240110ac@Muse> Message-ID: <135ullqco8qds4b@corp.supernews.com> On 2007-05-31, Jerry Hill wrote: > On 5/31/07, Warren Stringer wrote: >> In summation: >> I started this thread asking why c[:]() wouldn't work > > Because it's not part of the language. It's got nothing to do with the OP's usage, but it will work if you define a class which returns something callable from its __getitem__ method when passed a slice, right? It just won't work for the built-in sequence types which always return a sequence when you pass ':' to their __getitem__ method. I think. Or am I not understanding how slices and __getitem__ works. In any case, that would be different that creating a sequence class that can be called. -- Grant Edwards grante Yow! Not SENSUOUS ... only at "FROLICSOME" ... and in visi.com need of DENTAL WORK ... in PAIN!!! From Dicky.Links7 at gmail.com Mon May 21 16:16:15 2007 From: Dicky.Links7 at gmail.com (Dicky.Links7 at gmail.com) Date: 21 May 2007 13:16:15 -0700 Subject: ^? Boobies Tities all under 16yr old chicks! Message-ID: <1179778575.115179.56100@u36g2000prd.googlegroups.com> http://nudepicks.blogspot.com - Download these girls for free boobies! From knipknap at gmail.com Tue May 22 10:02:56 2007 From: knipknap at gmail.com (Samuel) Date: 22 May 2007 07:02:56 -0700 Subject: omniORBpy: Error 0x41540002 In-Reply-To: <5bg7e8F2svqcaU1@mid.uni-berlin.de> References: <1179833439.210564.191810@x18g2000prd.googlegroups.com> <5bg7e8F2svqcaU1@mid.uni-berlin.de> Message-ID: <1179842575.923614.257240@b40g2000prd.googlegroups.com> On May 22, 2:53 pm, "Diez B. Roggisch" wrote: > Please see my answer to your first post. Gaa, Google's web client reported an error where there was none. Sorry about the repost. -Samuel From steven at REMOVE.THIS.cybersource.com.au Wed May 23 01:13:55 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 23 May 2007 05:13:55 GMT Subject: Can I reference 1 instance of an object by more names ? References: Message-ID: On Wed, 23 May 2007 01:44:22 +0200, Stef Mientki wrote: > Now I want to assign a more logical name to that port, (In JAL: "var > byte My_New_Name IS port_D") > > Is that possible ? > > I think the answer is "no", > because the object itself is not mutable. Am I right ? > > But I read: "An object can have any number of names, or no name at all." > So am I wrong ? > > Sorry this has been discussed before, but I'm totally confused. # oops, we misspelled a name in the official API # can't change it, so alias it mispeled_name = IO_port('D') fixed_name = IO_port('D') correct_name = mispeled_name You can test if two names point to the same object with the is operator: >>> mispeled_name is correct_name True >>> mispeled_name is fixed_name False But make sure you really care that they are the same object. In general, testing for equality is more sensible. >>> 1 == 1.0 True >>> 1 is 1.0 False >>> "hello world" == ("hello " + "world") True >>> "hello world" is ("hello " + "world") False -- Steven. From luc.saffre at gmail.com Mon May 7 17:00:06 2007 From: luc.saffre at gmail.com (luc.saffre at gmail.com) Date: 7 May 2007 14:00:06 -0700 Subject: invoke user's standard mail client In-Reply-To: References: <1178266064.922925.125760@y80g2000hsf.googlegroups.com> <1178513538.133114.81940@p77g2000hsh.googlegroups.com> Message-ID: <1178571606.190151.233580@y5g2000hsa.googlegroups.com> On May 7, 10:28 am, "Gabriel Genellina" wrote: > > Get the pywin32 package (Python for Windows extensions) from sourceforge, > install it, and look into the win32comext\mapi\demos directory. Thanks for the hint, Gabriel. Wow, that's heavily spiced code! When I invoke mapisend.py I get: Traceback (most recent call last): File "mapisend1.py", line 85, in SendEMAPIMail(SendSubject, SendMessage, SendTo, MAPIProfile=MAPIProfile) File "mapisend1.py", line 23, in SendEMAPIMail mapi.MAPIInitialize(None) pywintypes.com_error: (-2147467259, 'Unspecified error', None, None) But what is a MAPI profile? I left this variable blank. Do I need MS Exchange Server to run this demo? From rrr at ronadam.com Thu May 24 18:03:11 2007 From: rrr at ronadam.com (Ron Adam) Date: Thu, 24 May 2007 17:03:11 -0500 Subject: webbrowser module bug? Message-ID: Is anyone else having problems with the webbrowser module? Python 2.5.1c1 (release25-maint, Apr 12 2007, 21:00:25) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import webbrowser >>> webbrowser.open('http://www.python.org') True >>> It opens firefox as expected, but the url is ... file:///home/ron/%22http://www.python.org%22 Which of course doesn't do what is expected. Any ideas? Ron From Leisure.208 at gmail.com Tue May 8 05:26:39 2007 From: Leisure.208 at gmail.com (Leisure.208 at gmail.com) Date: 8 May 2007 02:26:39 -0700 Subject: Download FireFox with the New Google Toolbar Message-ID: <1178616399.719425.255980@n59g2000hsh.googlegroups.com> http://www.mysearchenginewatch.com/ - Bookmark us for your search needs and keep informed on all the new occurances in the Search Industry Updated Daily. Try the new Google Firefox with Google PageRank toolbar. From stefaan.himpe at gmail.com Fri May 18 06:58:25 2007 From: stefaan.himpe at gmail.com (stefaan) Date: 18 May 2007 03:58:25 -0700 Subject: (Modular-)Application Framework / Rich-Client-Platform in Python In-Reply-To: References: Message-ID: <1179485905.764950.124000@p77g2000hsh.googlegroups.com> > To make it short: Is there something like this already? To keep it short: yes. To make it longer: not sure about its status... i've never tried it myself. To make it short again: http://code.enthought.com/ets/ I also know some people are trying to create something called pyxides, but also there I am not sure about the status: http://pyxides.stani.be/ Best regards, Stefaan. From brenNOSPAMbarn at NObrenSPAMbarn.net Sun May 27 03:30:46 2007 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: Sun, 27 May 2007 07:30:46 GMT Subject: Is PEP-8 a Code or More of a Guideline? References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> Message-ID: Paul McGuire wrote: > I was under the impression that lower_case_with_underscores was a > dated recommendation, and that recent practice is more inclusive of > mixedCase style identifiers. On the contrary, Steven Bethard > straightened me out, saying that PEP-8 used to accept either style, > but has been amended to accept only lower_case_with_underscores. Underscores are harder to type than any alphanumeric character. Thus I support their use in situations where difficulty of typing is desirable (e.g., magic method names) and I detest them in all other situations. -- --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 tjreedy at udel.edu Thu May 10 13:18:34 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 10 May 2007 13:18:34 -0400 Subject: Towards faster Python implementations - theory References: <1210i.7468$2v1.2505@newssvr14.news.prodigy.net> <1178804728.527486.196400@y80g2000hsf.googlegroups.com> Message-ID: "sturlamolden" wrote in message news:1178804728.527486.196400 at y80g2000hsf.googlegroups.com... | Franz, CMUCL, SBCL and GCL teams made Lisp almost as fast as C. A | dynamic language can be fast if the implementation is good. | | If you look at SBCL and GCL, no code is interpreted. It's all compiled | on the fly to native machine code. Unfortunately, native machine code depends on the machine, or at least the machine being emulated by the hardware. Fortunately or not, the dominance of the x386 model makes this less of a problem. | The compiler begins with some code | and some input data, and compiles as much as it can. Then the RT | executes the machine code, compiles again, etc. Often long stretches | of code can be compiled without break, and tight performance critical | loops are usually compiled only once. In addition to this, one needs | an efficient system to cache compiled code, in order to do the | compilation work only once. making a dynamic language fast is not | rocket science. This sound somewhat similar to Psyco. If a code section is entered with different machine types, recompilation is needed. One of the problems with Psyco is that its efficient caching of multiple versions of compiled code is space-hungry. | We should have somthing like "GPython", a Python RT on top of a GCC | backend, similar to what the GCL team did for Lisp. There is no | obvious reason as to why Lisp should have better performance than | Python. In the 1980s, during the Lisp/AI boom, perhaps a billion dollars was put into making Lisp run faster. Plus decades of work in Computer Science departments. Other than that, I agree. Now, Python is slowly making inroads into academia as a subject of research and theses, and the PyPy group got at least one large EU grant. Terry Jan Reedy From jgodoy at gmail.com Mon May 7 19:31:58 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Mon, 07 May 2007 20:31:58 -0300 Subject: No module named urllib References: <1178575589.059564.226060@q75g2000hsh.googlegroups.com> <87tzuop8s2.fsf@gmail.com> <1178577562.498615.222340@e51g2000hsg.googlegroups.com> <87ps5cp816.fsf@gmail.com> <1178578923.067315.14440@q75g2000hsh.googlegroups.com> <1178580280.902179.248000@w5g2000hsg.googlegroups.com> Message-ID: <87hcqop5w1.fsf@gmail.com> HMS Surprise writes: > Since sys.path = ['.', 'C:\\maxq\\lib\\Lib', 'C:\\maxq\\jython'] I > copied urllib to c:\maxq\lib\Lib. > > Now I get the error - > > Traceback (innermost last): > File "", line 5, in ? > File "C:\maxq\lib\Lib\urllib.py", line 1148 > _hextochr = dict(('%02x' % i, chr(i)) for i in range(256)) > ^ > SyntaxError: invalid syntax >>> dict(1, 1) Traceback (most recent call last): File "", line 1, in TypeError: dict expected at most 1 arguments, got 2 >>> dict(a=1) {'a': 1} >>> -- Jorge Godoy From mail at timgolden.me.uk Fri May 25 03:41:12 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 25 May 2007 08:41:12 +0100 Subject: File monitoring for all drive In-Reply-To: <1180049186.804822.5060@a26g2000pre.googlegroups.com> References: <1180049186.804822.5060@a26g2000pre.googlegroups.com> Message-ID: <46569318.8000704@timgolden.me.uk> rohit wrote: > hi > i want to detect all file change operations(rename,delete,create....) > on ALL THE DRIVES of the hard disk But to go a little further than your question... are you sure you want to do this? It's going to put quite a load on your system and be not-very-scaleable. I haven't yet had a chance to look into the NTFS Change Journal, but that might be a better way to go. Search this group for previous suggestions of this sort (from me and others). TJG From novin01 at gmail.com Wed May 9 06:15:03 2007 From: novin01 at gmail.com (Dave) Date: Wed, 9 May 2007 10:15:03 +0000 (UTC) Subject: view workspace, like in MatLab ? References: <46418D90.6030207@mailbox.kun.nl> Message-ID: Stef Mientki mailbox.kun.nl> writes: > > hello, > > is there a function / library / IDE that displays all the user defined > variables, like the workspace in MatLab ? > > thanks, > Stef Mientki Using ipython (which I would highly recommend!) you can use the %whos 'magic' function. This works as follows (with automagic (no % needed) on and pylab imported): In [1]: x = 10 In [2]: y = rand(3) In [3]: z = 'astring' In [4]: whos Variable Type Data/Info ------------------------------- x int 10 y ndarray [ 0.57395635 0.92184657 0.16277339] z str astring In [5]: reset Once deleted, variables cannot be recovered. Proceed (y/[n])? y In [6]: whos Interactive namespace is empty. In [7]: Note: the %reset 'magic' function works like the Matlab clear all command. HTH, Dave From juan-manuel.behrendt at siemens.com Wed May 9 03:46:26 2007 From: juan-manuel.behrendt at siemens.com (juan-manuel.behrendt at siemens.com) Date: 9 May 2007 00:46:26 -0700 Subject: error in the if, elif, else statement ? Message-ID: <1178696786.705128.320750@l77g2000hsb.googlegroups.com> Hello together, I wrote a script for the engineering software abaqus/CAE. It worked well until I implemented a selection in order to variate the variable "lGwU" through an if elif, else statement. I am going to post the first 82 lines of the script, since the error message points at line 80: from abaqusConstants import * from abaqus import * def CreateSchraube(name, l, flag=None, flag2=None): import part vp = session.currentViewportName model = session.sessionState[vp]['modelName'] m = mdb.models[model] s = m.ConstrainedSketch(name='__profile__', sheetSize=1000.0) s.ConstructionLine(point1=(0.0, -500.0), point2=(0.0, 500.0)) if flag==1: dh = 15.0 z = 15.0 dz = 60.0 d = 72.0 f = 1.0 dD = f*62.0 lGwO = 110.0 if flag2==11: # here appears the beginning of the new impletation in order to variate lGwU lGwU = 0.8*d # you can see these inner if, elif, else statement 4 times, because elif flag2==12: # the outer if, elif, else statement (which works!) has 4 cases lGwU = 1.0*d elif flag==13: lGwU = 1.2*d else: pass elif flag==2: dh = 15.0 z = 15.0 dz = 60.0 d = 72.0 f = 1.0 dD = f*62.0 lGwO = 110.0 if flag2==11: lGwU = 0.8*d elif flag2==12: lGwU = 1.0*d elif flag==13: lGwU = 1.2*d else: pass elif flag==3: dh = 25.0 z = 15.0 dz = 68.0 d = 80.0 f = 1.0 dD = f*71.5 lGwO = 120.0 if flag2==11: lGwU = 0.8*d elif flag2==12: lGwU = 1.0*d elif flag==13: lGwU = 1.2*d else: pass elif flag==4: dh = 25.0 z = 15.0 dz = 68.0 d = 80.0 f = 1.0 dD = f*71.5 lGwO = 120.0 if flag2==11: lGwU = 0.8*d elif flag2==12: lGwU = 1.0*d elif flag==13: lGwU = 1.2*d else: pass else: pass xyCoords = ((dh/2, -z), (dz/2, -z), (dz/2, 0), (d/2, 0), # this is line 80, where the error message points at (d/2, lGwU), (dD/2, (d-dD)/ (2*tan(radians(12)))+lGwU), (dD/2, l-lGwO-z-(d-dD)/ (2*tan(radians(20)))), (d/2, l-lGwO-z), (d/2, l-z), (dh/2, l-z), (dh/ 2, -z)) So, a lot of code, I hope somebody will read it. My Problem ist the error message, which says: " #* UnboundLocalError: local variable 'lGwU' referenced before assignment #*File "C:\ABAQUS_Products\6.6-3\abaqus_plugins\Schraube.py", line 80, in #*CreateSchraube #* xyCoords = ((dh/2, -z), (dz/2, -z), (dz/2, 0), (d/2, 0), " So the error message is quite clear, however it is not suitable to what I've written in my script, because the local variable 'lGwU' IS assigned before referenced and, furthermore in line 80 lGwU does not appear. Another strange thing is, that the first two cases, where lGwU = 0.8*d and lGwU = 1.0*d is, do work in my abaqus script. So the error message only occurs if I choose lGwU = 1.2*d. I expect a stupid different error, since I am a Python beginner (please don't be impatient), but I am not seeing it. Sincerely, Manu From bblais at bryant.edu Wed May 23 11:41:11 2007 From: bblais at bryant.edu (Brian Blais) Date: Wed, 23 May 2007 11:41:11 -0400 Subject: Cherrypy setup questions In-Reply-To: <1179934488.347133.7010@q75g2000hsh.googlegroups.com> References: <1179934488.347133.7010@q75g2000hsh.googlegroups.com> Message-ID: <46546097.2060705@bryant.edu> fumanchu wrote: > > No, you're not missing anything; my fault. I wasn't very awake when I > wrote that, I guess. Don't include the hostname, just write: > > sn = '/~myusername/apps' > cherrypy.quickstart(Root(), sn, config) > yay! Thanks, that works perfectly. bb -- ----------------- bblais at bryant.edu http://web.bryant.edu/~bblais From carsten at uniqsys.com Wed May 16 09:49:22 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 16 May 2007 09:49:22 -0400 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464afa8d$0$10200$9b4e6d93@newsspool4.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <46478694$0$1412$426a34cc@news.free.fr> <1hy252p.1anf7sr1p4yp12N%aleax@mac.com> <464988a4$0$20289$9b4e6d93@newsspool3.arcor-online.net> <464aaee8$0$10188$9b4e6d93@newsspool4.arcor-online.net> <464afa8d$0$10200$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <1179323362.3444.30.camel@dot.uniqsys.com> On Wed, 2007-05-16 at 14:35 +0200, Ren? Fleschenberg wrote: > You have misread my statements. > > Carsten Haese schrieb: > > There is evidence against your assertions that knowing some English is a > > prerequisite for programming > > I think it is a prerequesite for "real" programming. Yes, I can imagine > that if you use Python as a teaching tool for Chinese 12 year-olds, then > it might be nice to be able to spell identifiers with Chinese > characters. However, IMO this is such a special use-case that it is > justified to require the people who need this to explicitly enable it, > by using a patched interpreter or by enabling an interpreter option for > example. There you go again with "real" programming. Nobody that I'm aware of dictates that Python must only be used for real programming. It sounds like you are acknowledging that there are use cases for allowing non-ASCII identifiers after all. Making some switch for enabling this feature is a compromise that has been suggested on this thread before, including by yours truly. I wouldn't even be opposed to making this switch be off by default, as long as the feature is there for people who need it. > > in Python and that people won't use non-ASCII > > identifiers if they could. > > I did not assert that at all, where did you get the impression that I > do? If I were convinced that noone would use it, I would have not such a > big problem with it. I fear that it *will* be used "in the wild" if the > PEP in its current form is accepted and that I personally *will* have to > deal with such code. Yes, I apologize, I completely mangled your assertion. I don't know what I was thinking when I wrote that. In reality you asserted, and I'll quote verbatim this time: "It is naive to believe that you can program in Python without understanding any English once you can use your native characters in identifiers." It is precisely this assertion that is being disproved by HYRY's students who *do* program in Python without understanding any English[*], using native characters in identifiers. But they have to launder their programs before they can run them. [*] And if you respond that they must know "some" English in the form of keywords and such, the answer is no, they need not. It is not hard for Europeans to learn to visually recognize a handful of simple Chinese characters without having to learn their pronunciation or even their actual meaning. By the same token, a Chinese person can easily learn to recognize "if", "while", "print" and so on visually as symbols, without having to learn anything beyond what those symbols do in a Python program. Regards, -- Carsten Haese http://informixdb.sourceforge.net From gigs at hi.t-com.hr Thu May 24 05:32:40 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Thu, 24 May 2007 11:32:40 +0200 Subject: function nested Message-ID: i have this function. def f(start): stack = [] def f1(start): for fname in os.listdir(startDir): path = os.path.join(startDir, fname) if os.path.isfile(path): stack.append(path) else: f1(path) return stack this is returning empty list, why? thanks From rahulnag22 at yahoo.com Sun May 6 15:01:58 2007 From: rahulnag22 at yahoo.com (rahulnag22 at yahoo.com) Date: 6 May 2007 12:01:58 -0700 Subject: tkinter - label widget text selection Message-ID: <1178478118.170827.196310@e65g2000hsc.googlegroups.com> Hi, I guess this is a very trivial question -- I am using a label widget to display text (black font in a white background color). I am trying to use my mouse to scroll over the displayed text to select it, but tkinter does not allow me to do it. Is there a method/option to do this. Thanks Rahul From bj_666 at gmx.net Thu May 10 04:37:25 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 10 May 2007 10:37:25 +0200 Subject: Minor bug in tempfile module (possibly __doc__ error) References: <1178693438.689184@smirk> <1178779520.887569@smirk> Message-ID: In <1178779520.887569 at smirk>, James T. Dennis wrote: > Marc 'BlackJack' Rintsch wrote: >> In <1178693438.689184 at smirk>, James T. Dennis wrote: > >> You can change it by simply assigning to the name: > >> In [15]: tempfile.template = 'spam' > >> In [16]: tempfile.template >> Out[16]: 'spam' > > I know you can change it. But changing it in your namespace > doesn't change the results returned by the functions called > from the module. I'm not changing it in my namespace but in the namespace of the `tempfile` module. > I don't quite understand how this name/variable in > my namespace (__main__) is able to change the value > while the functions in the module still hold the old > value. Default arguments are evaluated *once* when the ``def`` is executed and not at every function call. Ciao, Marc 'BlackJack' Rintsch From sebastien.ramage at gmail.com Thu May 10 13:55:16 2007 From: sebastien.ramage at gmail.com (=?windows-1252?q?S=E9bastien_Ramage?=) Date: 10 May 2007 10:55:16 -0700 Subject: searching algorithm In-Reply-To: References: Message-ID: <1178819716.483864.99850@e51g2000hsg.googlegroups.com> I have made a script that search anagram based on the ODS file ( call OSW in english, Official Scrabble Words) it load a file that contain 369085 words (one word per line) I create a dictionnary and store word into using the length of the word as key example : mydict[2] contain a list of word with length = 2 first I select the correct dict entry and in a second time I scan this list searching correct word my file contains 369085 and it's pretty fast Seb From jadestar at idiom.com Fri May 25 03:12:26 2007 From: jadestar at idiom.com (James T. Dennis) Date: Fri, 25 May 2007 07:12:26 -0000 Subject: append References: <1178816546.689849.255070@y5g2000hsa.googlegroups.com> <46438251$0$5908$426a34cc@news.free.fr> Message-ID: <1180077146.662129@smirk> Bruno Desthuilliers wrote: > HMS Surprise a ?crit : >> Trying not to be a whiner but I sure have trouble finding syntax in >> the reference material. I want to know about list operations such as >> append. > The only thing you have to know is that it doesn't exists. Python > strings are immutables. If you want to sequentially build a string, you > can either rebind the name to a new string : Huh? Where did strings come into this question? > s = "" > for c in "abcdef": > s += c Huh? Why not just use: s = list(s)? For a more clear example: >>> list("foo") ['f', 'o', 'o'] See? > or collect substrings in a list and join it: > s = [] > for c in "abcdef": > s.append(c) > s = "".join(s) Yes, "".join(list("foo")) is a sort of "expensive" no-op. As for the original post: dir() and help() from the interactive prompt are good friends. An ipython prompt is an even better friend to have while learning python. Consider this: In[1]:list.app[[Tab]] ... list.append In[1]:list.append[[?]][[Enter]] Type: method_descriptor Base Class: String Form: Namespace: Python builtin Docstring: L.append(object) -- append object to end In[2]: ... where I'm highlighting some keystrokes with [[]] marks. The point is that ipython offers [Tab] completion(*) and has a number other cool features. For example if you end a function/method/class/member line with a ? key and hit enter, then you get a help screen as shown in my mini-transcript above. Python simply has the best interactive introspection features around. (Also, if you use docstrings in your own code than these features will work on your code, too). For extra fun go into one of your directories which contains some of your .py files, and/or add a few such directories to your PYTHONPATH environment variable. Then start up a command like: pydoc -p 8080 ... or pick some other TCP port. Then point a web browser at localhost:8080 ... ... see? There's a mini-web service with clickable links to read the docs for all the Python modules installed on your system ... including your own code! * ([Tab]-completion is also possible in the normal python >>> interpreter using: import rlcompleter ... and then calling the relatively obscure incantation: rlcompleter.readline.parse_and_bind("tab: complete") If, like me you prefer vi-mode readline editing then you add another incantation: rlcompleter.readline.parse_and_bind("set editing-mode vi") ... or you can simply put the following in you ~/.inputrc: $if python set editing-mode vi $endif ... and, in that case, you can bind other keystrokes into macro strings like: C-o:"import sys,os" or whatever). -- Jim Dennis, Starshine: Signed, Sealed, Delivered From steve at REMOVE.THIS.cybersource.com.au Sun May 27 19:03:47 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 28 May 2007 09:03:47 +1000 Subject: Newbie question - better way to do this? References: <1180273441.455227.120170@g4g2000hsf.googlegroups.com> <1180302942.215945.58090@a26g2000pre.googlegroups.com> Message-ID: On Sun, 27 May 2007 14:55:42 -0700, John Machin wrote: > On May 28, 12:46 am, Steven D'Aprano > wrote: >> On Sun, 27 May 2007 06:44:01 -0700, Eric wrote: >> > words is a big long array of strings. What I want to do is find >> > consecutive sequences of words that have the first letter capitalized, >> > and then call doSomething on them. (And you can ignore the fact that >> > it won't find a sequence at the very end of words, that is fine for my >> > purposes). >> >> Assuming the list of words will fit into memory, and you can probably >> expect to fit anything up to millions of words comfortably into memory, >> something like this might be suitable: >> >> list_of_words = "lots of words go here".split() >> >> accumulator = [] >> for word in list_of_words: >> if word.istitle(): >> accumulator.append(word) >> else: >> doSomething(accumulator) >> accumulator = [] >> > Bzzzt. Needs the following code at the end: > if accumulator: > doSomething(accumulator) Bzzzt! Somebody didn't read the Original Poster's comment "And you can ignore the fact that it won't find a sequence at the very end of words, that is fine for my purposes". Of course, for somebody whose requirements _aren't_ broken, you would be completely right. Besides, I'm under no obligation to write all the O.P.'s code for him, just point him in the right direction. -- Steven. From warren at muse.com Thu May 31 17:00:00 2007 From: warren at muse.com (Warren Stringer) Date: Thu, 31 May 2007 14:00:00 -0700 Subject: Is PEP-8 a Code or More of a Guideline? Message-ID: <001001c7a3c6$a71d8410$240110ac@Muse> Wildemar Wildenburger wrote: > This may be a nice > idea for the Next Overwhelming Programming Escapade (Codename: NOPE) > ... > You may want to elaborate on the "new way to think about names". Maybe > you have a point which I just don't see. Is it considered pythonic to LOL? Nietzsche would love NOPE ... and so would his psychiatrist. Nope, I'm proposing: "Yo! Extend that Python" (Codename: YEP) I'm treating classes as nested dictionaries. Not *all* classes; only the ones that I want to use and code from a cell phone. I've been porting a scripting language, that was written in C++ to Python. It allows declare a structure like this: mouse position x,y button left x,y right x,y and pipe the whole tree to a recorder, like this: record << mouse// which is like doing this: record << [mouse.position.x, mouse.position.y, mouse.button.left.x, mouse.button.left.y, mouse.button.right.y, mouse.button.right.y] So, how is this related to the addinfourl example? It isn't. At least, not for rewriting old API. But for fresh APIs, add.info.url() forces you to think about names, and functionality in a fine grained way. This translates roughly to: class add(object)... class info(object)... class url(object)... or as a dict: {'add' : { 'info': 'url' { ... Then it becomes easier to think about decorators, generators, and closures in a way that is quite amorphous. (Though slow?) Tsch?s, \~/ From bj_666 at gmx.net Wed May 23 04:01:05 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 23 May 2007 10:01:05 +0200 Subject: how to use imaageop.scale References: <1179903754.084688.312200@w5g2000hsg.googlegroups.com> Message-ID: In <1179903754.084688.312200 at w5g2000hsg.googlegroups.com>, Bruce wrote: > Hi, I want to compress a jpg file. e.g. a jpg file which has RGB band > (24bit per pixel), 100 * 100 size to 50 * 50 size. I > tried to use scale function in imageop module but failed. Any > suggestions about this? Thanks! I guess you are talking about the Python Imaging Library (PIL) here? What have you tried and in which way did it fail? What about the `resize()` method on image objects? Ciao, Marc 'BlackJack' Rintsch From antroy at gmail.com Fri May 4 10:34:32 2007 From: antroy at gmail.com (Ant) Date: 4 May 2007 07:34:32 -0700 Subject: My Python annoyances In-Reply-To: References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> <1178202431.147195.249790@u30g2000hsc.googlegroups.com> Message-ID: <1178289272.280370.161770@c35g2000hsg.googlegroups.com> On May 4, 3:17 pm, Ben Collver wrote: > Chris Mellon wrote: ... > > Code like this is working directly against Python philosophy. You > > probably got told this on #python, too. There's hardly any > > circumstance where you should need to validate the exact class of an > > object, and as long as they have the same interface theres no harm > > whatsoever in tempfile changing it's return value between Python > > versions. > > I am unqualified to comment on the Python philosophy, but I would like > for my function to do some basic error checking on its arguments. I > will read up on the Python philosophy. The basic point here is that the code will do it's own error checking. If you pass in a string to your function, and it tries to call write("xxx") on it, then you will get an exception thrown: AttributeError: 'str' object has no attribute 'write If your goal is to provide feedback to a potential user that they are using the wrong arguments, then you can use something like the following (the "Easier to ask for forgiveness than for permission" idiom): >>> arg = "A String not a File" >>> try: ... arg.write("") ... except AttributeError: ... print "You need to pass in a file like object!" ... You need to pass in a file like object! From mikeminer53 at hotmail.com Wed May 23 12:43:37 2007 From: mikeminer53 at hotmail.com (mkPyVS) Date: 23 May 2007 09:43:37 -0700 Subject: Resizing listbook's listview pane In-Reply-To: <1179932659.180278.72990@w5g2000hsg.googlegroups.com> Message-ID: <1179938617.127403.28600@p77g2000hsh.googlegroups.com> Sorry, copied from wxpython submit as well.. I'm using wxpython 2.8... Primariy I want the resize to happen programatically during object creation/post creation... I can worry about app size changes later. Thanks, From tahiri.ahmed at gmail.com Wed May 2 08:19:07 2007 From: tahiri.ahmed at gmail.com (tahiriman) Date: 2 May 2007 05:19:07 -0700 Subject: Dynamic File Name Open() In-Reply-To: References: <001c01c78c7c$d14657f0$73d307d0$@rawlins@thinkbluemedia.co.uk> Message-ID: <1178108347.076617.285350@y5g2000hsa.googlegroups.com> On May 2, 7:47 am, Tim Golden wrote: > Robert Rawlins - Think Blue wrote: > > > I'm trying to open a file using open() but the name of the file is created > > dynamically as a variable, but also has part of a static path. For instance, > > the file may be called 'dave' and will always be in '/my/files/here/'. > > Well that's an absolutely normal way of doing > things, so if my toy example below doesn't make > things clear, you'd better post a code fragment > and/or some traceback. > > > import os, sys > > path = "c:/temp" > for filename in ["chas.txt", "dave.txt"]: > f = open (os.path.join (path, filename)) > print filename > print f.read () > print > f.close () > > > > TJG you have to look at the method open(string path, string mode) properties so, you can change the argument, string path, dynamicly From ashokagk at gmail.com Tue May 29 07:48:04 2007 From: ashokagk at gmail.com (Ashok) Date: 29 May 2007 04:48:04 -0700 Subject: override PyBitmapDataObject Message-ID: <1180439284.820223.159280@r19g2000prf.googlegroups.com> hi, I am new to python and am trying my experimenting with python and wxpython. I want to use wx.PyBitmapDataObject to get bitmap data form clipboard. The wx documentation says that 'to be able to provide bitmap data on demand, derive from this class and overload GetBitmap'. How do i overload GetBitmap? Thanks in adavance for any help. _____ ashok From grante at visi.com Mon May 21 13:33:10 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 21 May 2007 17:33:10 -0000 Subject: Python and GUI References: <1179761984.704369.116310@b40g2000prd.googlegroups.com> Message-ID: <1353lum18vh5h2b@corp.supernews.com> On 2007-05-21, Cameron Laird wrote: > While PyQt is plenty wonderful, Tkinter's more than adequate, > given the requirements you've described. Tkinter is easier to use for simple things. You just have to try not to think about the fact that it's pulling a complete Tcl interpreter into your app. It also seems to come only in various flavors of ugly. ;) wxPython (based on wxWidgets) is cross-platform, industrial-strength and has native look-and-feel. It is, however, more complex to use. In some places it's not very "Pythonic" and shows it's C/C++ heritage (this has improved a bit in the past couple years). There are also a couple more Pythonic wrappers on top of wxWidgets. pyGTK isn't a bad choice if Linux/Unix is what you care about. GTK for Windows was still a bit sketchy the last time I looked into it. PyQt I haven't tried, but both Linux/Unix and Windows support is reported to be solid. -- Grant Edwards grante Yow! My polyvinyl cowboy at wallet was made in Hong visi.com Kong by Montgomery Clift! From sjmachin at lexicon.net Mon May 21 18:05:41 2007 From: sjmachin at lexicon.net (John Machin) Date: Tue, 22 May 2007 08:05:41 +1000 Subject: re.compile for names In-Reply-To: <1179756122.369462.200260@r3g2000prh.googlegroups.com> References: <1179756122.369462.200260@r3g2000prh.googlegroups.com> Message-ID: <465217B5.2070801@lexicon.net> On 22/05/2007 12:02 AM, Paul McGuire wrote: > On May 21, 8:46 am, brad wrote: >> The goal of the list is to have enough strings to identify files that >> may contain the names of people. Missing a name in a file is unacceptable. >> Seems to me the OP is looking for people-names inside file-contents, not inside file-names. [snip] > You will also get better results if you constrain the location of the > match, for instance, looking for file names that *start* with > someone's name, instead of just containing them somewhere. YMevidentlyV :-) From basilisk96 at gmail.com Sat May 12 16:51:05 2007 From: basilisk96 at gmail.com (Basilisk96) Date: 12 May 2007 13:51:05 -0700 Subject: How to cleanly pause/stop a long running function? Message-ID: <1179003065.771223.25600@e65g2000hsc.googlegroups.com> Suppose I have a function that may run for a long time - perhaps from several minutes to several hours. An example would be this file processing function: import os def processFiles(startDir): for root, dirs, files in os.walk(startDir): for fname in files: if fname.lower().endswith(".zip"): # ... do interesting stuff with the file here ... Imagine that there are thousands of files to process. This could take a while. How can I implement this so that the caller can pause or interrupt this function, and resume its program flow? Doing a Ctrl+C interrupt would be a not-so-clean-way of performing such a thing, and it would quit the application altogether. I'd rather have the function return a status object of what it has accomplished thus far. I have heard about threads, queues, and asynchronous programming, but am not sure which is appropriate for this and how to apply it. Perhaps the above function should be a method of a class that inherits from the appropriate handler class? Any help will be appreciated. -Basilisk96 From bblais at bryant.edu Wed May 23 09:11:32 2007 From: bblais at bryant.edu (Brian Blais) Date: Wed, 23 May 2007 09:11:32 -0400 Subject: Cherrypy setup questions In-Reply-To: <1179891507.498030.157230@m36g2000hse.googlegroups.com> References: <1179891507.498030.157230@m36g2000hse.googlegroups.com> Message-ID: <46543D84.6070804@bryant.edu> fumanchu wrote: > On May 22, 6:38 pm, Brian Blais wrote: >> I'd like to start trying out some cherrypy apps, but I've >> been having some setup problems. I think I need some >> bone-head simple example to clear my understanding. :) >> 1) can I configure cherrypy to look at requests only >> off a base url, like: >> >> http://www.provider.com:8080/~myusername/apps > > Yes, you can. Assuming you're using the "cherrypy.quickstart" > function, supply the "base url" in the "script_name" argument; for > example: > > sn = 'http://www.provider.com:8080/~myusername/apps' > cherrypy.quickstart(Root(), sn, config) > Thanks for your reply, but for some reason it is not working as stated. I'm probably missing something. import cherrypy from cherrypy import expose class HelloWorld: @expose def hello(self,*another): if not another: return("hello") else: return("hello: %s" % str(another)) @expose def index(self): return "Hello world!" # at first I tried cherrypy.quickstart(HelloWorld()) which works, off of http://localhost:8080/ and http://localhost:8080/hello and http://localhost:8080/hello/more_stuff works fine. # so then I tried each of these (separately, of course)... baseurl='http://localhost:8080/~bblais/apps' cherrypy.quickstart(HelloWorld(),baseurl) # then baseurl='http://localhost:8080/bblais/apps' cherrypy.quickstart(HelloWorld(),baseurl) # finally, root=HelloWorld() cherrypy.tree.mount(root,'apps/') cherrypy.server.quickstart() cherrypy.engine.start() cherrypy.engine.block() In each case, there is similar behavior. The script runs fine, and the Cherrypy gives the usual startup message, but nothing is printed when I access the above urls. I know something is wrong, because cherrypy doesn't even log the events. Without the baseurl specified, I get things like: 127.0.0.1 - - [23/May/2007:08:56:24] "GET /hello HTTP/1.1" 200 5 "" "" whenever I access the site. Specifying the baseurl, nothing. Two more pieces of info. When I start, I usually get: The Application mounted at '' has an empty config. which is solved by adding a config='hello.conf', where hello.conf is: [global] server.socket_host = "localhost" server.socket_port = 8080 server.thread_pool = 10 even with that, I when I specify a baseurl (say, apps), I get: The Application mounted at 'apps' has an empty config. Is it missing something, that it can't make a default choice on? thanks for your help! Brian Blais -- ----------------- bblais at bryant.edu http://web.bryant.edu/~bblais From mikeminer53 at hotmail.com Wed May 23 12:45:24 2007 From: mikeminer53 at hotmail.com (mkPyVS) Date: 23 May 2007 09:45:24 -0700 Subject: Resizing listbook's listview pane In-Reply-To: <1179932659.180278.72990@w5g2000hsg.googlegroups.com> Message-ID: <1179938724.523541.104850@q69g2000hsb.googlegroups.com> On May 23, 9:04 am, kyoso... at gmail.com wrote: > Which Python gui toolkit are you using? Tkinter, wxPython, pyQT? Are > you wanting the resize to happen programmatically, when the user > changes the app's size, both or what? > > More details would be helpful. > > Mike Sorry, copied from wxpython submit as well.. I'm using wxpython 2.8... Primariy I want the resize to happen programatically during object creation/post creation... I can worry about app size changes later. Thanks, From steven at REMOVE.THIS.cybersource.com.au Tue May 15 05:08:03 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 15 May 2007 09:08:03 GMT Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <20070513160046.GC29172@v.igoro.us> <7x646wa9wz.fsf@ruckus.brouhaha.com> <1hy2q4c.x5ih391i7k1hyN%aleax@mac.com> Message-ID: On Sun, 13 May 2007 23:00:16 -0700, Alex Martelli wrote: > Steven D'Aprano wrote: > >> automated -- if the patch uses an unexpected "#-*- coding: blah" line, >> or > > No need -- a separate PEP (also by Martin) makes UTF-8 the default > encoding, and UTF-8 can encode any Unicode character you like. Ah, that puts a slightly different perspective on the issue. -- Steven. From grante at visi.com Fri May 18 20:33:06 2007 From: grante at visi.com (Grant Edwards) Date: Sat, 19 May 2007 00:33:06 -0000 Subject: Generate report containing pdf or ps figures? References: <132pnp6r4qg0lc2@corp.supernews.com> Message-ID: <134she2lf8sls92@corp.supernews.com> On 2007-04-23, Grant Edwards wrote: > I need to be able to generate a PDF report which consists > mostly of vector images (which I can generate as encapsulated > Postscript, PDF, or SVG). [...] > Is there a PDF generation library that can place EPS or PDF > figures on a page? I finally gave up trying to generate a PDF report. I did come up with two alternative solutions that partly work. 1) XHTML+SVG Unfortunately a lot of SVG renderers are rather broken. Opera and Firefox both seem to have rather nasty font sizing issues. 2) PyRTF+EMF Seems to work pretty well. However, some Unix apps that support RTF don't include EMF graphics support (Ted and Abiword appear to fall into that group). Still, it does work with OOo, MS Word, and with both versions of the gratis MS Word viewer. -- Grant Edwards grante Yow! NEWARK has been at REZONED!! DES MOINES has visi.com been REZONED!! From duncan.booth at invalid.invalid Thu May 10 10:14:30 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 May 2007 14:14:30 GMT Subject: newb: Python Module and Class Scope References: <1178805769.658287.178240@q75g2000hsh.googlegroups.com> Message-ID: johnny wrote: > Can a class inside a module, access a method, outside of class, but > inside of the module? > > Eg. Can instance of class a access main, if so how? What is the > scope of "def main()" interms of class A? > > myModule: > > class A: > main() > > def main(): > > > thnx. > > Yes;by using its name;global scope. Why not try it for yourself? N.B. Functions in Python do not exist until the def statement is executed, so the code like your sample will fail to find 'main' if you try to call it from inside the class body. A call from inside an instance method would be fine though (provided you didn't call it until main was defined), or a call from the class body would also be fine provided you define main before you define the class. From nicholas.petrella at gmail.com Thu May 10 13:37:40 2007 From: nicholas.petrella at gmail.com (nicholas.petrella at gmail.com) Date: 10 May 2007 10:37:40 -0700 Subject: RotatingFileHandler bugs/errors and a general logging question. In-Reply-To: <1178696252.753583.34150@q75g2000hsh.googlegroups.com> References: <1178668334.588946.256490@e51g2000hsg.googlegroups.com> <1178696252.753583.34150@q75g2000hsh.googlegroups.com> Message-ID: <1178818660.168705.90650@q75g2000hsh.googlegroups.com> On May 9, 12:37 am, Vinay Sajip wrote: > On May 9, 12:52 am, nicholas.petre... at gmail.com wrote:> The infrastructure in which I am work needs the ability to have log > > files written to from multiple instances of the same script and > > potentially from hundreds or more different machines. > > > I know that the documentation suggests using a networkloggingserver > > but I wanted to know if anyone had any other solutions to allow us to > > build off of the current pythonloggingpackages. > > Dennis is right - the logging system is threadsafe but not safe > against multiple processes (separate Python instances) writing to the > samefile. It certainly sounds like you need a scalable solution - and > having each script send the events to a network logging server seems a > good way of handling the scalability requirement. The logger name used > can include the script instance and machine name, e.g. by starting > with hostname.scriptname.scriptpid... The socket server which receives > the events can demultiplex them based on this information and write > them to a central repository in any arrangement you care to implement > (e.g. into onefileor several). > > Given that the example in the docs is a (basic) working example, is > there any particular reason why you don't want to follow the suggested > approach? > > Regards, > > Vinay Sajip Our biggest concerns with the network solution is having a single point of failure and the need for scalability. We could have potentially thousands of machines doing logging across multiple geographic sites. Our fear with the network solution is overwhelming the server or group of servers as well as having a single point of failure for the logging interface. In addition using a server or servers would require added support for the logigng server machines. Our NFS infrastructure is very well supported and can handle the load generated by these machines already (A load which would be many times more than what the logging would generate) which is why we would like to log directly to file system without going through a separate server. Also adding in a logging server introduces one more level where we could potentially have failure. We would like to keep the infrastructure for our logging as simple as possible as we rely on log files to give us critical information when troubleshooting issues. It sounds like my only option may be using a server in order to handle the logging from different hosts. That or possibly having individual log files for each host. Thanks for your input. It is much appreciated. -Nick From dotancohen at gmail.com Sat May 19 03:12:07 2007 From: dotancohen at gmail.com (Dotan Cohen) Date: Sat, 19 May 2007 10:12:07 +0300 Subject: List Moderator In-Reply-To: References: <880dece00705172218n71123b55q531ec0c5e500f208@mail.gmail.com> Message-ID: <880dece00705190012g4f3d3ef6v4e6c87a156708bb0@mail.gmail.com> On 18/05/07, Steve Holden wrote: > Dotan Cohen wrote: > > Is this list not moderated? I'm really not interested in Britney > > Spears boobs. All the spam on this list is from the same place, it > > should be very easy to filter. > > > Is it a list, is it a newsgroup? No, it's c.l.py! > > In fact you could be reading this in a number of different forms, and > there are equally many ways to inject content into the stream. It's > surprisingly difficult to filter everything out, though the list > managers at python.org seem to do a remarkably effective job. I don't believe that a python list manager would have a hard time coming up with a regex that /dev/nulled any post with the words "britney", "spears", "boobs", "tits", or the like. > I'm not particularly interested in that subject matter either, but > believe me there could be a lot more of that kind of thing than actually > makes it through! And if it doesn''t start getting filtered now, the spammers will see this list as an easy target and will attack it. Believe me. Dotan Cohen http://lyricslist.com/ http://what-is-what.com/ From james.b.looney at lmco.com Wed May 9 14:26:03 2007 From: james.b.looney at lmco.com (Looney, James B) Date: Wed, 09 May 2007 12:26:03 -0600 Subject: preferred windows text editor? In-Reply-To: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> References: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> Message-ID: I'm using Vim (http://www.vim.org/). -JB -----Original Message----- From: python-list-bounces+james.b.looney=lmco.com at python.org [mailto:python-list-bounces+james.b.looney=lmco.com at python.org] On Behalf Of T. Crane Sent: Wednesday, May 09, 2007 12:07 PM To: python-list at python.org Subject: preferred windows text editor? Right now I'm using Notepad++. What are other people using? trevis -- http://mail.python.org/mailman/listinfo/python-list From owen.nick at gmail.com Thu May 31 10:07:57 2007 From: owen.nick at gmail.com (Nick Owen) Date: 31 May 2007 07:07:57 -0700 Subject: RSA SecurID token authentication? In-Reply-To: References: Message-ID: <1180620477.462680.123690@h2g2000hsg.googlegroups.com> On May 29, 11:22 am, Chris Shenton wrote: > Anyone doing python application authentication using RSASecurID > tokens? We have a Pylons app that needs this. > > I've written code against RSA's API and found the docs terrible and > the libraries painful to use. RSA has a RADIUS server fronting their > server so I expect I could use that instead, might be easier. This is > on Solaris10 x86 which supports PAM but I've never accessed PAM from > Python, any pointers? > > I've done RADIUS before (Cistron, Ascend, FreeRADIUS) but not with > Python. Any suggestions? I see a pyrad library, last updated in March I'm guessing it's too late to choose a two-factor solution with an open API and open source python examples? :) Oh well. I recommend going with pyrad and using the Radius interface. This will allow you to use a third party radius server if you want and since all the two-factor vendors support radius, you won't have to re- write the apps if you switch strong authentication vendors. HTH, nick -- Nick Owen WiKID Systems, Inc. 404.962.8983 http://www.wikidsystems.com Commercial/Open Source Two-Factor Authentication irc.freenode.net: #wikid From john at datavoiceint.com Thu May 3 12:21:01 2007 From: john at datavoiceint.com (HMS Surprise) Date: 3 May 2007 09:21:01 -0700 Subject: cannot import name ..... Message-ID: <1178209261.189586.95540@p77g2000hsh.googlegroups.com> Greetings. What is the implication of the error message 'cannot import name .....'? It occurs when executing the line: from nBaseTest import nBaseTest The file exists and the class within it exists. Changing it to from nBaseTest import x gives me the same result so it is as though the class does not exist. Thought there may be a problem with the nBaseTest file but standalone it runs fine. Thus my earlier question. Maybe I should ask where find detailed error information. Thanks, jvh From warren at muse.com Tue May 29 11:18:43 2007 From: warren at muse.com (Warren Stringer) Date: Tue, 29 May 2007 08:18:43 -0700 Subject: Is PEP-8 a Code or More of a Guideline? In-Reply-To: References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <1180254338.292249.29520@h2g2000hsg.googlegroups.com> Message-ID: <007001c7a204$a5a45e10$240110ac@Muse> Hi Eric, You make a compelling argument for underscores. I sometimes help a visually impaired friend with setting up his computers. I'm wondering about the aural output to you second example: link.set_parse_action(emit_link_HTML) Does it sound like this: link dot set under parse under action space between parens emit under link under HTML jump out Also, does how HTML read? Is it "H T M L" or "cap H cap T cap M cap L" ? How many python programmers can reconfigure their speech-to-text and text-to-speech converter? Isn't there a Python based accessibility project? Perhaps a few lines of script to add CamelBack support, using an amplitude increase for initial caps and maybe lingering on the initial phoneme for an extra 100 milliseconds. So then, the above example would read: "camel link dot set Parse Action between parens emit Link H T M L jump out" Warren Eric S. Johansson wrote or said: > link.setParseAction(emitLinkHTML) > > is spoken > > no caps link dot set no space cap parser no space cap action between > parens emit no space cap link HTML jump out > > on the other hand, > > link.set_parse_action (emit_link_HTML) > From ptmcg at austin.rr.com Sat May 26 21:23:39 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 26 May 2007 18:23:39 -0700 Subject: ten small Python programs In-Reply-To: References: Message-ID: <1180229019.873381.52800@m36g2000hse.googlegroups.com> I ***love*** this "10 Little Programs" idea! As soon as I get a breathing space, I'm going to add a "10 Little Parsers" page to the pyparsing wiki! On May 26, 2:38 pm, Steven Bethard wrote: > > Though the code should probably follow PEP 8 guidelines, e.g. > under_scores instead of camelCase for object and method names: > > http://www.python.org/dev/peps/pep-0008/ > Really? Underscore-separated words preferred over camel case? What is the rationale for this? This style is so retro/80's/C-ish. It seems more like a Java backlash to me than anything else. If we (or Guido) don't like changing case to indicate word breaks, why are class names to be UpperCamelCase, and not Capitalized_with_underscores? If there is a casing convention nit to pick, I'd focus on UpperCamelCase for class names, lower case (either with underscores or mixed case) for attributes and method names, and UNDERSCORE_SEPARATED_ALL_CAPS for constants. If we want to just say "well, PEP-8 says such and such," I think this is an area where the thinking has possibly evolved since 2001. Also, I think the PEP would benefit from explicitly discouraging some practices, such as Hungarian notation. > > > class ShoppingCart: > > def __init__(self): self.items = [] > > def buy(self, item): self.items.append(item) > > def boughtItems(self): return self.items > > myCart = ShoppingCart() > > myCart.buy('apple') > > myCart.buy('banana') > > print myCart.boughtItems() If you want to nitpick, I'd rather go after the one-liner methods with the body on the same line as the def statement. How's this for a better non-trivial method example: MAX_ITEMS_FOR_EXPRESS_LANE = 10 def canUseExpressLane(self): return (len(self.items) <= MAX_ITEMS_FOR_EXPRESS_LANE) or call it "can_use_express_lane" if you must. I guess pyparsing with its mixedCase functions and attributes is doomed for the Dunce Corner. Too bad for BeautifulSoup, cElementTree, and wxPython that are also at variance with this canon of Python coding style. ("Modules should have short, all-lowercase names. ... Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.") -- Paul From robert.kern at gmail.com Sat May 19 15:28:57 2007 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 19 May 2007 14:28:57 -0500 Subject: docs patch: dicts and sets In-Reply-To: <1179601094.940650.276120@w5g2000hsg.googlegroups.com> References: <_5-dnU7aIN73j9LbnZ2dnUVZ_uCinZ2d@comcast.com> <1179593927.503393.127350@u30g2000hsc.googlegroups.com> <1179596822.923443.67500@k79g2000hse.googlegroups.com> <1179601094.940650.276120@w5g2000hsg.googlegroups.com> Message-ID: 7stud wrote: > On May 19, 12:36 pm, Steve Holden wrote: >> The last thing I want to read in a language's documentation is an >> ill-informed and sometimes interminable argument about a particular feature. > > Yet some readers will be able to get to the bottom of an issue they > are having by reading those comments. And most will simply be confused. -- 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 joshbloom at gmail.com Thu May 17 19:35:05 2007 From: joshbloom at gmail.com (Josh Bloom) Date: Thu, 17 May 2007 16:35:05 -0700 Subject: progress indicator in a mod_python script In-Reply-To: <1179413183.860119.264040@q23g2000hsg.googlegroups.com> References: <1179413183.860119.264040@q23g2000hsg.googlegroups.com> Message-ID: Hi Rajarshi, What you probably want to do is break this into multiple parts. When a request comes in to perform a query consider this a new job, give it an ID and set it off and running. Then return an HTML page that knows to keep checking a status URL (based on the ID) every few seconds to see if the job is done, if the job is done, return the results, if its not return keeps checking until its. Here's some info about making an HTML Page refresh itself automatically. http://en.wikipedia.org/wiki/Meta_refresh -Josh On 17 May 2007 07:46:28 -0700, Rajarshi wrote: > > Hi, I have a web application built using mod_python.Currently it > behaves like a standard CGI - gets data from a form, performs a query > on a backend database and presents a HTML page. > > However the query can sometimes take a bit of time and I'd like to > show the user some form of indeterminate progress indicator (spinning > dashes etc). My searching seems to indicate that this is based on some > form of asynchronous calls (AJAX) and I'm not sure how I can achieve > this effect in my mod_python app. > > Any pointers to achieve this would be very appreciated. > > Thanks, > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul.rudin at ntlworld.com Fri May 18 16:05:48 2007 From: paul.rudin at ntlworld.com (Paul Rudin) Date: Fri, 18 May 2007 21:05:48 +0100 Subject: emacs python debugging: pydb or pdb fringe interaction References: <87k5v61qpc.fsf@rudin.co.uk> <87veeqnf5q.fsf@merkury.smsnet.pl> <87sl9u9ceo.fsf@rudin.co.uk> <87r6pendtt.fsf@merkury.smsnet.pl> Message-ID: <87odkhaodf.fsf@rudin.co.uk> Rob Wolfe writes: > Paul Rudin writes: > >> Unfortunately this doesn't make any difference for me, with either >> emacs 22 or 21. I guess I'll just have to dig deeper into the code. > > So what happens after M-x pdb? Everything works as it should, except for the interaction with the fringe. I can't set breakpoints by clicking in the fringe, and they're not displayed in the fringe. The only thing that is displayed in the fringe is the little triangle indicating the current line. From thn at mail.utexas.edu Fri May 4 10:38:04 2007 From: thn at mail.utexas.edu (Thomas Nelson) Date: 4 May 2007 07:38:04 -0700 Subject: How do I get type methods? In-Reply-To: <1178283588.694886.204250@c35g2000hsg.googlegroups.com> References: <1178220806.664557.245780@c35g2000hsg.googlegroups.com> <1178253260.075515.43810@q75g2000hsh.googlegroups.com> <1178283588.694886.204250@c35g2000hsg.googlegroups.com> Message-ID: <1178289484.265718.198060@c35g2000hsg.googlegroups.com> On May 4, 7:59 am, yavanna... at yahoo.com wrote: > On 4 ???, 09:08, "Gabriel Genellina" wrote: > > > En Fri, 04 May 2007 01:34:20 -0300, escribio: > > > I'm not against 'dir(MyClass)'; the question is, what should I 'dir()' > > > to get methods of 'pyuno' type instance? > > Usually instances don't have its own methods, they get them from the > > class. So you actually need dir(MyClass). > > Note that dir() might not show all available methods. > > Let me retype my question: what I 'dir()' in case of 'pyuno' type > instance? > Or in case of 'dict' type instance? Or in case of any other new python > type? >>> class Foo: ... def f(self,x): ... print x+1 ... def g(self,x): ... print x-1 ... >>> dir(Foo) ['__doc__', '__module__', 'f', 'g'] Is this not what you want? These are the only methods in the Foo class. Tom From cedric.louyot at gmail.com Wed May 2 10:14:04 2007 From: cedric.louyot at gmail.com (redcic) Date: 2 May 2007 07:14:04 -0700 Subject: Writing a nice formatted csv file Message-ID: <1178115244.446071.317250@n76g2000hsh.googlegroups.com> Hi all, I use the csv module of Python to write a file. My code is of the form : cw = csv.writer(open("out.txt", "wb")) cw.writerow([1,2,3]) cw.writerow([10,20,30]) And i get an out.txt file looking like: 1,2,3 10,20,30 Whereas what I'd like to get is: 1, 2, 3, 10, 20, 30 which is more readable. Can anybody help me to do so ? Thanks, C?dric From rohitsethidce at gmail.com Mon May 7 18:36:35 2007 From: rohitsethidce at gmail.com (rohit) Date: 7 May 2007 15:36:35 -0700 Subject: randomly write to a file In-Reply-To: <1178574062.496137.11640@y5g2000hsa.googlegroups.com> References: <1178567497.042096.82940@w5g2000hsg.googlegroups.com> <1178574062.496137.11640@y5g2000hsa.googlegroups.com> Message-ID: <1178577395.500279.241390@p77g2000hsh.googlegroups.com> nick, i just wanted to ask for time constrained applications like searching won't sqlite be a expensive approach. i mean searching and editing o the files is less expensive by the time taken . so i need an approach which will allow me writing randomly to a line in file without using a database On May 8, 2:41 am, Nick Vatamaniuc wrote: > Rohit, > > Consider using an SQLite database. It comes with Python 2.5 and > higher. SQLite will do a nice job keeping track of the index. You can > easily find the line you need with a SQL query and your can write to > it as well. When you have a file and you write to one line of the > file, all of the rest of the lines will have to be shifted to > accommodate, the potentially larger new line. > > -Nick Vatamaniuc > From gagsl-py2 at yahoo.com.ar Tue May 22 04:00:50 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 22 May 2007 05:00:50 -0300 Subject: Cycle detection and object memory usage? References: Message-ID: En Mon, 21 May 2007 22:15:14 -0300, Jim Kleckner escribi?: > Gabriel Genellina wrote: >> En Sun, 20 May 2007 23:54:15 -0300, Jim Kleckner >> >> escribi?: >> >>> What is the best way to go about finding these cycles? >> >> Avoid them in the first place :) >> Use the gc module: after a call to gc.collect(), see if something >> remains in gc.garbage > > I would have sworn that there were uncollectable objects when I > tried this before. Now they don't show up. I guess that is good... (... or bad, it you actually know that you have a problem but you cant reproduce it). >>> Has anyone written a function to sweep out an object to discover how >>> much memory it and all the objects it references is using? This would >>> be great for performance tuning. >> >> A rough estimate may be the object's pickle size. But it's hard to >> measure precisely; by example, strings are immutable and you may have >> thousands of shared references to the same string, and they require >> just a few bytes >> each. > > Good idea, thanks. > I take it then that memory profiling isn't available? I don't know of any tool - maybe because I've never needed one until now. -- Gabriel Genellina From josiah.carlson at sbcglobal.net Thu May 17 15:55:09 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Thu, 17 May 2007 12:55:09 -0700 Subject: Is wsgi ready for prime time? In-Reply-To: References: Message-ID: Ron Garret wrote: >>>> wsgiref.util > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'module' object has no attribute 'util' >>>> wsgiref.headers > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'module' object has no attribute 'headers' >>>> wsgiref.handlers > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'module' object has no attribute 'handlers' wsgiref is a package. In order to access submodules/packages, you must import them. >>> import wsgiref >>> wsgiref.util Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'util' >>> import wsgiref.util >>> wsgiref.util >>> It's almost magic. - Josiah From john at datavoiceint.com Mon May 7 19:24:40 2007 From: john at datavoiceint.com (HMS Surprise) Date: 7 May 2007 16:24:40 -0700 Subject: No module named urllib In-Reply-To: <1178578923.067315.14440@q75g2000hsh.googlegroups.com> References: <1178575589.059564.226060@q75g2000hsh.googlegroups.com> <87tzuop8s2.fsf@gmail.com> <1178577562.498615.222340@e51g2000hsg.googlegroups.com> <87ps5cp816.fsf@gmail.com> <1178578923.067315.14440@q75g2000hsh.googlegroups.com> Message-ID: <1178580280.902179.248000@w5g2000hsg.googlegroups.com> Since sys.path = ['.', 'C:\\maxq\\lib\\Lib', 'C:\\maxq\\jython'] I copied urllib to c:\maxq\lib\Lib. Now I get the error - Traceback (innermost last): File "", line 5, in ? File "C:\maxq\lib\Lib\urllib.py", line 1148 _hextochr = dict(('%02x' % i, chr(i)) for i in range(256)) ^ SyntaxError: invalid syntax From tjreedy at udel.edu Fri May 4 23:53:06 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 4 May 2007 23:53:06 -0400 Subject: My Python annoyances References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> <1178202431.147195.249790@u30g2000hsc.googlegroups.com> Message-ID: "Ben Collver" wrote in message news:CuWdnZu-csr33abbnZ2dnUVZ_u2mnZ2d at scnresearch.com... | In the bug report itself, See my other response to you. | Feedback in this newsgroup names my bug report as a "hobby horse", That was not directed as you but the claim by someone else that I and other reviewers are in the 'denial' stage of the 5 Stages of Grieving. tjr From tcrane at REMOVETHISuiuc.edu Fri May 18 14:29:15 2007 From: tcrane at REMOVETHISuiuc.edu (T. Crane) Date: Fri, 18 May 2007 13:29:15 -0500 Subject: namespace question References: Message-ID: <%fm3i.726$u56.355@newssvr22.news.prodigy.net> "Robert Kern" wrote in message news:mailman.7868.1179512371.32031.python-list at python.org... > T. Crane wrote: >> Hi, >> >> If I define a class like so: >> >> class myClass: >> import numpy >> a = 1 >> b = 2 >> c = 3 >> >> def myFun(self): >> print a,b,c >> return numpy.sin(a) >> >> >> I get the error that the global names a,b,c,numpy are not defined. >> Fairly >> straightforward. But if I am going to be writing several methods that >> keep >> calling the same variables or using the same functions/classes from >> numpy, >> for example, do I have to declare and import those things in each method >> definition? Is there a better way of doing this? > > Put your imports at the module level. I'm not sure what you intended with > a, b, > c so let's also put them at the top level. If you put them at the top level, and suppose you saved it all in a file called test.py, then when you type ln [1]: from test import myClass does it still load a,b,c and numpy into the namespace? > > import numpy > a = 1 > b = 2 > c = 4 > > class myClass: > def myFun(self): > print a, b, c > return numpy.sin(a) > > > OTOH, if a, b, c were supposed to be attached to the class so they could > be > overridden in subclasses, or be default values for instances, you can > leave them > in the class definition, but access them through "self" or "myClass" > directly. Yeah, they don't need to be accessed anywhere other than within the class itself and I won't need to overwrite them, so I'll try just putting them in the top level. thanks, trevis > > > import numpy > > class myClass: > a = 1 > b = 2 > c = 4 > > def myFun(self): > print self.a, self.b, myClass.c > return numpy.sin(self.a) > > -- > 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 desertlinux at netscape.net Wed May 16 21:28:47 2007 From: desertlinux at netscape.net (Brian) Date: Wed, 16 May 2007 18:28:47 -0700 Subject: Newbie Question: Getting a list of files In-Reply-To: <1179328815.567298.109920@o5g2000hsb.googlegroups.com> References: <1179324440.729561.27920@w5g2000hsg.googlegroups.com> <1179328815.567298.109920@o5g2000hsb.googlegroups.com> Message-ID: Thank you very much for your examples! Much appreciated. Dusty --- Ant wrote: > On May 16, 3:07 pm, Gerard Flanagan wrote: > ... >> import os >> >> def iter_dirs(root, dirs=False): > ... > > Rather than rolling your own directory walker: > > The same iterator using os.walk: > > def iter_dirs(root, dirs=False): > for root, directories, files in os.walk(root): > if dirs: > for dir in directories: > yield os.path.join(root, dir) > for file in files: > yield os.path.join(root, file) > > > os.path.walk requires a different mindset: > > def visitor(yield_dirs, dirname, names): > for name in names: > pth = os.path.join(dirname, name) > if os.path.isfile(pth) or yield_dirs: > print pth > > os.path.walk(root, visitor, False) > > From jstroud at mbi.ucla.edu Tue May 15 19:48:30 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 15 May 2007 16:48:30 -0700 Subject: Name of function caller In-Reply-To: <1179266351.304587.182070@n59g2000hsh.googlegroups.com> References: <1179266351.304587.182070@n59g2000hsh.googlegroups.com> Message-ID: HMS Surprise wrote: > Is there a way that a function may access the doc string or func_name > of the caller? > > Thanks, > > jvh > Add a parameter to the function to avoid mutilating your code with implementation specific inspection: def fun(caller, *original_parameters): do_something_to_caller_without_magic(caller) do_something_with_original_parameters(*original_parameters) James From paddy3118 at googlemail.com Sun May 20 07:12:20 2007 From: paddy3118 at googlemail.com (Paddy) Date: 20 May 2007 04:12:20 -0700 Subject: python shell/Intermediate Python tools. In-Reply-To: References: <1179337107.842668.112690@k79g2000hse.googlegroups.com> <1179552984.466321.137550@u30g2000hsc.googlegroups.com> Message-ID: <1179659540.663784.228420@y80g2000hsf.googlegroups.com> On May 20, 1:56 am, cla... at lairds.us (Cameron Laird) wrote: > In article <1179552984.466321.137... at u30g2000hsc.googlegroups.com>,Paddy wrote: > >On May 16, 6:38 pm, Krypto wrote: > >> I have been using python shell to test small parts of the big program. > >> What other ways can I use the shell effectively. My mentor told me > >> that you can virtually do anything from testing your program to > >> anything in the shell. Any incite would be useful. > > >Doctest! > >http://en.wikipedia.org/wiki/Doctest > > . > . > . > will probably prove more fruitful. > > While I don't like follow-ups which consist of trivial corrections, I *very* > much want to encourage readers to explore Doctest more deeply; it deserves the > attention, even at the cost of appearing pedantic. Sometimes you have to mess with the case of letters in wiki pages which is the case here, but I did actually cut-n-paste the address from Wikipedia as I like to look at the page from time to time as, like yourself, I think doctest shows the true spirit of what is Pythonic, and created the page when I found Wikipedia did not have it. Gets me thinking along the lines of "What else should the intermediate Python programmer know about"? The other Python tool I am apt to carp on about is Kodos http://kodos.sourceforge.net/ . Kodos is a great tool for those new to reguar expressions. It allows you to test your regular expressions on snippets of text and gives great visual feedback on the results. After over a decade of writing regexps I still use Kodos occasionally, and wish I had such a tool a decade ago. - Paddy. From half.italian at gmail.com Wed May 2 03:50:45 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 2 May 2007 00:50:45 -0700 Subject: os.path.join In-Reply-To: <1178091389.258193.10200@u30g2000hsc.googlegroups.com> References: <1178072869.844914.59010@u30g2000hsc.googlegroups.com> <1178083903.677905.32710@c35g2000hsg.googlegroups.com> <1178089436.202973.148650@h2g2000hsg.googlegroups.com> <1178091389.258193.10200@u30g2000hsc.googlegroups.com> Message-ID: <1178092245.937118.166030@n59g2000hsh.googlegroups.com> On May 2, 12:36 am, Ant wrote: > On May 2, 8:03 am, half.ital... at gmail.com wrote: > > > On May 1, 11:10 pm, "Gabriel Genellina" > ... > > > I think it's a bug, but because it should raise TypeError instead. > > > The right usage is os.path.join(*pathparts) > ... > > Wow. What exactly is that * operator doing? Is it only used in > > passing args to functions? Does it just expand the list into > > individual string arguments for exactly this situation? Or does it > > have other uses? > > It's used for unpacking a collection into arguments to a function. > It's also used at the other end for receiving a variable length set of > arguments. i.e. > > >>> x = (1,3) > >>> def add(a, b): > > return a + b > > >>> add(*x) > 4 > >>> def add(*args): > > return reduce(int.__add__, args) > > >>> add(1,2,3,4,5,6) > 21 > >>> add(*x) > > 4 > > The same sort of thing holds for keyword arguments: > > >>> def print_kw(**kw): > > for k in kw: > print kw[k] > > >>> print_kw(a=1, b=2) > > 1 > 2>>> d = {'a': 1, 'b': 10, 'c': 100} > >>> print_kw(**d) > > 1 > 100 > 10 Thank you both. From kay.schluehr at gmx.net Wed May 9 01:02:58 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 8 May 2007 22:02:58 -0700 Subject: Towards faster Python implementations - theory In-Reply-To: References: <1210i.7468$2v1.2505@newssvr14.news.prodigy.net> <1178641778.266569.13290@p77g2000hsh.googlegroups.com> Message-ID: <1178686978.390755.181030@y5g2000hsa.googlegroups.com> On May 9, 1:25 pm, John Nagle wrote: > Marc 'BlackJack' Rintsch wrote: > > I don't see how this type inference for static types will work unless some > > of the dynamism of the language will get restricted. But is this really > > necessary? Isn't a JIT compiler and maybe type hinting good enough? > > Not necessarily. One of the more powerful optimizations is to optimize > reference count updates. Often, you can hoist reference count updates > out of loops, which is a big win. But to do that, you need to be sure > that the code executed by the loop won't change unexpectedly. The advantage of having a JIT is just that it can record data at runtime and respond flexible to them. It doesn't run into global static analysis problems mentioned by Paul. A "semi-dynamical" compromise would mean to use a profile of samples of runtime data and assert that they reflect typical" behaviour. Then the system needs an ability to fall back to usual bytecode interpretation. Psyco does that by analyzing the next opcode and a very clever dispatch mechanism. A more code oriented, profile driven approach would factor source into natively compilable parts and those that have to be bytecode interpreted. I wonder whether bridges to Pyrex, Boost.Python or the celerid bridge to D could be used and what the performance penalties are for all the argument/return value wrapping and unwrapping. Unfortunately ShedSkin lacks CPython integration. We talked about this here recently. Kay From jm.suresh at gmail.com Tue May 15 08:50:07 2007 From: jm.suresh at gmail.com (jm.suresh@no.spam.gmail.com) Date: 15 May 2007 05:50:07 -0700 Subject: Storing and searching nodes of a tree Message-ID: <1179233407.473173.259110@h2g2000hsg.googlegroups.com> Hi, I have a tree data structure and I name each node with the following convention: a |---aa | |--- aaa | |--- aab | |---ab | |---ac I use these names as keys in a dictionary, and store node's data. Now given a name like "abc", I want to find the key with the following rule: If the key exists return the value If the key does not exist, return the value of the leaf node whose name is in the given name. For, "abc", it is "ab" . For, "ad", it is "a". I suppose there must be a simpler solution to this problem. I implemented it like this: d = {'a':0, 'aa':12, 'ab':43, 'aaa':22, 'aab':343, 'ac':33} name = 'abc' key = max( [ x for x in d.iterkeys() if x in name] ) value = d[key] I can change the data structure from dictinory to tuple of key,value pairs or any thing, and afford to keep them in a particular order. Is there any way I can speed up this as I have to do this for around 4000 times with tree size being ~5000. - Suresh From bbxx789_05ss at yahoo.com Fri May 4 01:36:59 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 3 May 2007 22:36:59 -0700 Subject: Decorating class member functions In-Reply-To: <1178241696.641350.292210@n59g2000hsh.googlegroups.com> References: <1178241696.641350.292210@n59g2000hsh.googlegroups.com> Message-ID: <1178257019.771078.224620@e65g2000hsc.googlegroups.com> On May 3, 7:21 pm, Andy Terrel wrote: > Okay does anyone know how to decorate class member functions? > > The following code gives me an error: > > Traceback (most recent call last): > File "decorators2.py", line 33, in > s.update() > File "decorators2.py", line 13, in __call__ > retval = self.fn.__call__(*args,**kws) > TypeError: update() takes exactly 1 argument (0 given) > > ------------------ > > #! /usr/bin/env python > > class Bugger (object): > def __init__ (self, module, fn): > self.module = module > self.fn = fn > > def __call__ (self,*args, **kws): > ret_val = self.fn(*args,**kws) > return ret_val > > def instrument (module_name): > ret_val = lambda x: Bugger(module_name, x) > return ret_val > > class Stupid: > def __init__(self): > self.val = 1 > > @instrument("xpd.spam") > def update(self): > self.val += 1 > > s = Stupid() > s.update() As far as I can tell, the problem is that the decorator executes when the class is parsed, and at that time there is no self(the instance object). The decorator produces a callable Bugger object, but the callable object has no way to get self when s.update() is called. Normally when you call a class function, like s.update(), the __get__() method in the 'update' function object is called (all function objects have a __get__() method and therefore are descriptors). Then __get__() creates a method object out of the function object(update), and python automatically passes the instance object to the method object. However, the Bugger object does not have a __get__() method, so no method object is created when the Bugger object is called, and therefore self is not automatically passed to the Bugger object. The following solution adds a __get__() method to the Bugger object. Python automatically passes the instance object to the __get__() method, and the solution stores the instance in the Bugger object. Then __call__ is defined to send the instance object to update(). class Bugger (object): def __init__ (self, module, fn): self.module = module self.fn = fn def __call__ (self,*args, **kws): ret_val = self.fn(self.obj, *args,**kws) return ret_val def __get__(descr, inst, instCls=None): descr.obj = inst return descr def instrument (module_name): ret_val = lambda func: Bugger(module_name, func) return ret_val class Stupid(object): def __init__(self): self.val = 1 @instrument("xpd.spam") def update(self): self.val += 1 s = Stupid() s.update() s.update() s.update() print s.val --output:-- 4 From joncle at googlemail.com Fri May 25 05:16:33 2007 From: joncle at googlemail.com (Jon Clements) Date: 25 May 2007 02:16:33 -0700 Subject: psycopg2 & large result set Message-ID: <1180084593.130202.241550@q69g2000hsb.googlegroups.com> Hi All. I'm using psycopg2 to retrieve results from a rather large query (it returns 22m records); unsurprisingly this doesn't fit in memory all at once. What I'd like to achieve is something similar to a .NET data provider I have which allows you to set a 'FetchSize' property; it then retrieves 'n' many rows at a time, and fetches the next 'chunk' after you read past the end of the current chunk. I suppose I could use Python for .NET or IronPython but I'd rather stick with CPython 2.5 if possible. I'm not 100% sure if it's an interface or a server thing. Any ideas are most welcome. Cheers, Jon. From steve at REMOVE.THIS.cybersource.com.au Thu May 10 01:34:48 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 10 May 2007 15:34:48 +1000 Subject: change of random state when pyc created?? References: <5ae25fF2oggbqU1@mid.uni-berlin.de> Message-ID: On Wed, 09 May 2007 23:10:19 -0500, Robert Kern wrote: > Steven D'Aprano wrote: >> On Wed, 09 May 2007 21:18:25 -0500, Robert Kern wrote: >> >>> Actually, the root cause of Peter's specific example is the fact that the >>> default implementation of __hash__() and __eq__() rely on identity comparisons. >>> Two separate invocations of the same script give different objects by identity >>> and thus the "history of insertions and deletions" is different. >> >> The history is the same. The objects inserted are the same (by equality). > > No, they *were* different by equality (identity being the default implementation > equality that was not overridden in either Peter's code nor Alan's). Ah yes, you are right in the sense that Python's notion of equality for class instances is to fall back on identity by default. But in the vernacular human sense, an instance X with the same state as an instance Y is "equal", despite being at another memory address. I was using equality in the sense that two copies of the same edition of a book are the same, despite being in different places. For the record, and for the avoidance of all confusion, I'm not suggesting that Python's default behaviour is "wrong" or even "bad", merely pointing out to all those wise in hindsight that the behaviour was extremely puzzling for the reasons I've given. But you can be sure that I'll never forget this lesson :) -- Steven. From peter_7003 at yahoo.com Tue May 8 08:48:46 2007 From: peter_7003 at yahoo.com (Peter Fischer) Date: Tue, 8 May 2007 05:48:46 -0700 (PDT) Subject: Specification for win32com.client package In-Reply-To: <46406E6E.9000501@timgolden.me.uk> Message-ID: <886546.99553.qm@web63415.mail.re1.yahoo.com> Hello Tim, thank you for your quick and detailed reply. So I will try it at the python-win32 list. Many thanks for your help and if you want I will let you know when I know more. Best regards, Peter. --------------------------------- Need Mail bonding? Go to the Yahoo! Mail Q&A for great tips from Yahoo! Answers users. -------------- next part -------------- An HTML attachment was scrubbed... URL: From aldo at nullcube.com Tue May 15 21:59:27 2007 From: aldo at nullcube.com (Aldo Cortesi) Date: Wed, 16 May 2007 11:59:27 +1000 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <1hy2qg3.iqfvwnrvr9kjN%aleax@mac.com> Message-ID: <20070516015927.GA26271@nullcube.com> Thus spake Steven D'Aprano (steven at REMOVE.THIS.cybersource.com.au): > Perhaps you aren't aware that doing something "by eye" is idiomatic > English for doing it quickly, roughly, imprecisely. It is the opposite of > taking the time and effort to do the job carefully and accurately. If you > measure something "by eye", you just look at it and take a guess. Well, Steve, speaking as someone not entirely unfamiliar with idiomatic English, I can say with some confidence that that's complete and utter bollocks (idomatic usage for "nonsense", by the way). To do something "by eye" means nothing more nor less than doing it visually. Unless you can provide a citation to the contrary, please move on from this petty little point of yours, and try to make a substantial technical argument instead. > So, as I said, if you're relying on VISUAL INSPECTION (your words _now_) > you're already vulnerable. Fortunately for you, you're not relying on > visual inspection, you are actually _reading_ and _comprehending_ the > code. That might even mean, in extreme cases, you sit down with pencil > and paper and sketch out the program flow to understand what it is doing. Please, pick up a dictionary, and look up "visual" and "inspection", then re-read my message. Ponder the fact that visual inspection is in fact a necessary precursor to "reading" or "comprehending" code. Now, imagine reading a piece of code where you can never be sure that a character is what it appears to be... > >> If I've understood Martin's post, the PEP states that identifiers are > >> converted to normal form. If two identifiers look the same, they will > >> be the same. > > > > I'm sorry to have to tell you, but you understood Martin's post no > > better than you did mine. There is no general way to detect homoglyphs > > and "convert them to a normal form". Observe: > > > > import unicodedata > > print repr(unicodedata.normalize("NFC", u"\u2160")) print u"\u2160" > > print "I" > > Yes, I observe two very different glyphs, as different as the ASCII > characters I and |. What do you see? I recommend that you gain a basic understanding of the relationship between Unicode code points and the glyphs on your screen before attempting to argue this point again. The particular glyph your current font-set translates the character into is irrelevant. Indeed, the fact that there is font variation from client to client is one of the more obvious problems with your technically illiterate hope that one could homogenize characters so that everything that looks the same has the same meaning. Fiddle around with your fontsets a bit - you only have to find one combination where the two glyps look the same to prove my case... Regards, Aldo -- Aldo Cortesi aldo at nullcube.com http://www.nullcube.com Mob: 0419 492 863 From ptmcg at austin.rr.com Tue May 1 17:31:31 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 1 May 2007 14:31:31 -0700 Subject: pre-PEP: Standard Microthreading Pattern In-Reply-To: References: Message-ID: <1178055091.182156.276720@e65g2000hsc.googlegroups.com> On May 1, 3:58 pm, dus... at v.igoro.us wrote: > I've been hacking away on this PEP for a while, and there has been some > related discussion on python-dev that went into the PEP: > > http://mail.python.org/pipermail/python-dev/2007-February/070921.html > http://mail.python.org/pipermail/python-dev/2007-February/071155.html > http://mail.python.org/pipermail/python-dev/2007-February/071181.html > > I'd love to have feedback on this PEP: > - from a user's perspective (would you want to write microthreaded code?) > - from an implementer's perspective (and note that I have a reference > implementation that's just getting packaged up right now). > - from a technical perspective (efficiency, compatibility, etc.) > - regarding the two unresolved issues in the text > > And now, without further ado: > > PEP: XXX > Title: Standard Microthreading Pattern > Version: $Revision$ > Last-Modified: $Date$ > Author: Dustin J. Mitchell > Status: Draft > Type: Informational > Content-Type: text/x-rst > Created: 17-Feb-2007 > Post-History: > > Abstract > ======== > > The extended support for generators introduced in PEP 342 [2]_ > facilitated a natural way of writing generators that cooperatively > yield control to other functions, allowing multitasking within > a single OS thread. Such multitasking requires a supporting > environment (usually in the form of a scheduler), and several such > implementations are in active use. Each has slightly different > structural requirements for the task-implementing code. > > This PEP proposes a single, consistent pattern for such code. > This consistency will enable microthreaded code to run in a variety > of environments, just as threaded code can currently run atop a > variety of OS-level threading libraries. Compliant libraries, > e.g., a microthreaded urllib, could then be developed, providing > batteries-included functionality for microthreaded software. > > Definitions > =========== > > Within this PEP, "microthreading" is defined as interleaving > the execution of multiple independent codepaths by cooperatively > yielding control periodically in each codepath; a "microthread", > then, is one such codepath. This technique and variations on it > have also been referred to as "weightless threads", "tasklets", and > "greenlets". It is a specilization of the more general event-based > multitasking model. > > Microthreads are conceptually distinct from coroutines. A coroutine > can schedule a specific coroutine to be executed when it yields > control, even passing a value to that coroutine. Microthreads, > however, simply yield to facilitate multitasking, with no knowledge > or control of the next codepath to be executed. > > This PEP addresses two audiences: authors of microthreaded code > (users) and designers of microthreaded environments (implementations). > > Motivation > ========== > > Application developers usually adopt an event-based architecture in > order to exploit asynchronous IO facilities. Asynchronous IO is > ideal when the overhead of an OS-level thread for each concurrent > IO operation is too high. > > An event-based architecture is also useful when an application must > perform lightweight multitasking -- for example, an email client > must both wait for user input and monitor mailboxes for new mail. > Implementing this sort of multitasking using threads requires careful > use of synchronization primitives throughout the application to > ensure correctness. Using common event-based techniques requires > storing state on the heap and implementing callbacks for all state > transitions, which can quickly become complex. > > A microthreaded architecture brings the best of both worlds: it > allows users to store state in local varables, just as they would > in a threaded implementation, while avoiding the need for complex > synchronization primitives. An email client, for example, can > implement the complex state of an IMAP client in a natural fashion, > and reflect that state using natural Python data structures with no > need for locking. > > Several well-developed implementations of cooperative multitasking > are currently available, some of which implement microthreading. > However, each implementation approaches the subject differently, > and it is virtually impossible to share code between implementations. > > This PEP is intended to bring some measure of consistency to > microthreaded code, to facilitate development of libraries and > implementation-agnostic code repositories to support microthreaded > development. > > Rationale > ========= > > Since the introduction of generators in PEP 255 [3]_ and their > extension to support coroutines in PEP 342 [2]_, generators have been > used to implement various forms of microthreading [1]_: > > - Example 3 in PEP 342 implements a simple trampoline scheduler. > > - `Kiwi tasklets`_ (formerly GTasklets) use pre-PEP 342 generators > along with an explicit post-yield function call to retrieve any > incoming value or exception. > > - `Twisted Python`_ includes an ``inlineCallbacks`` decorator > [#inlineCallbacks]_ which allows a generator to yield ``Deferred`` > objects; callback results are then re-injected with ``send()``, > while errbacks result in a ``throw()``. > > - `Kamaelia`_ includes Axon, a library supporting microprocesses which > multitask by yielding frequently, and interact through a > well-developed IPC mechanism. > > - David Mertz's "Charming Python: Implementing "weightless threads" > with Python generators" [#Mertz]_ includes a basic microthreading > scheduler and suggests directions for improvement. > > - An ASPN recipe by Maciej Obarski [#Obarski]_ gives a simple > scheduler for task objects represnted by generators. > > Each of these implementations have specific requirements of the > microthreaded code. The requirements differ enough that code written > for one environment will generally not function properly in another. > > A common pattern for all microthreaded code will allow users to write > microthreaded code that will be portable to multiple microthreading > implementations. This will include libraries, which can then be > shared more broadly. > > The specification in this PEP specifically avoids reference > to any symbols not included in the built-in namespace, so > environment-agnostic microthreaded code need not import any > environment-specific modules. > > Implementation Specification > ============================ > > An implementation is responsible for executing a body of code written > by its users according to the microthreading pattern. > > Like a standard python thread, execution of a microthread begins with > a call to a single function, and ends when that function completes. > The function may call other functions, and so on; the entire control > flow constitutes a microthread. Completely unrelated control flows > may be occurring simultaneously in other microthreads. > > Within a microthreading implementation, all microthreads operate > within a single OS-level thread, so at most one microthread is > executing at any point. The implementation must not switch between > microthreads except at times specified by the user. > > A microthreaded function is written as a generator function, with > the points at which other microthreads may be executed indicated > by ``yield``. Normal (non-generator) functions thus cannot be > interrupted. > > While a microthreaded function is executing, its execution is > represented by a generator. The implementation is responsible for > ensuring that this generator has its ``next``, ``send``, and ``throw`` > methods called appropriately. Specifically, it must call ``next`` to > initiate processing, and ``step`` to execute each subsequent segment. > At the completion of each segment, if the return value of ``next``, > ``send``, or ``throw`` is not one of the special values described > below, then that value must be supplied to the generator via ``send`` > when it is next scheduled. > > When the generator is complete, it will raise a ``StopIteration`` > exception, which the implementation must catch and handle by either > resuming execution of the calling function (see `Nested Function > Calls`, below) or terminating the microthread. Other exceptions > must be handled as described in the `Exceptions` section, below. > > Nested Function Calls > --------------------- > > When a microthreaded function yields a generator, then it is invoking > another microthreaded function, the execution of which is represented > by the yielded generator. Execution of the current function must be > suspended until the new function has been executed to completion. > Any return value from the new function must be supplied to the > calling function via its generator's ``send`` method. > > Although the underlying implementation may vary, the effect is of > a stack of generators within each microthread, with the topmost > generator representing the state of the currently executing > microthreaded function, and the remaining generators suspended > awaiting its completion. > > Return Values > ------------- > > Microthreaded functions return values to their callers by raising > a ``StopIteration`` exception containing the return value in > ``args[0]``. Implementations must catch this exception and handle it > appropriately by supplying the return value to the next generator on > the stack via ``send``, or if there is no next generator, terminating > the microthread. > > Exceptions > ---------- > > When a generator raises an exception, that exception must > be propagated to the next generator on the stack via ``throw``. > If there is no next generator, then the implementation may display > a traceback to the user or take other appropriate action. > > Implementations may adjust tracebacks to remove implementation-related > frames, but must not alter the exception itself. > > Special Values > -------------- > > Implementations may attach special significance to other yielded > values or raised exceptions, but these values and exceptions must > be unique objects which could not be produced by code written > with no knowledge of the implementation. Specifically, no special > significance may be attached to any of the built-in Python types or > types used in the standard library. Rather, an implementation should > attach meaning to classes and objects local to the implementation's > namespace. > > Thread Manipulation > ------------------- > > Implementations are responsible for providing any appropriate > functionality for manipulating microthreads. This PEP does not > place any restrictions on such functionality. > > Pattern Specification > ===================== > > This section specifies the microthreading pattern from the perspective > of a user. In general, microthreaded code should closely resemble > ordinary threaded code, with the addition of ``yield`` keywords at > strategic locations. > > - Microthreaded functions are written as generator functions. Their > execution will not be interrupted except at statements including > the ``yield`` keyword. The value of a ``yield`` expression is > the value of its argument, unless the argument is one of the > special values discussed in this section. > > - A microthreaded function can call another microthreaded function by > yielding the generator resulting from calling the microthreaded > function. The value of the ``yield`` expression is the return > value of the called function. > > - A microthreaded function can "return" a value by raising > ``StopIteration`` with that value as an argument:: > > raise StopIteration(42) > > - An exception raised in a microthreaded function will propagate > to its callers just as in a standard function. Uncaught exceptions > will be handled in an implementation-dependent fashion. > > - Functions for thread manipulation are not specified in this PEP, > and are implementation-dependent. > > Example > ------- > > This trivial example highlights each of the aspects of the > multithreaded pattern:: > > def fibonacci(n): > latest, i = (1, 1), 2 > if n < 1: > raise ValueError # raise exception > while i < n: > latest = (latest[1], latest[0] + latest[1]) > yield # cooperative yield > raise StopIteration(latest[1]) # return value > > def fibsquared(n): > try: > fibn = (yield fibonacci(n)) ** 2 # function call > except ValueError: # catch exception > print "Sorry, cannot calculate fibsquared of", n > else: > print "fibsquared of", n, "is", fibn > > Backwards Compatibility > ======================= > > As this is an informational PEP, no backward compatibility problems > will arise from its adoption. In most cases, this PEP specifies > a superset of the functionality of existing microthreading > enviroments, so existing microthreaded code will continue to run > without modification. > > One exception to this rule is Kamaelia's Axon, which specifies > that generators which yield a false value will be terminated. > That situation is not compatible with this PEP, which directs that > such a value should be returned from the yield at the next execution > of the microthread. > > The specification of Kiwi tasklets requires that generators > implementing tasklets call ``tasklet.get_event()`` after most yields. > This is not necessary under the specification in this PEP, and the > ``get_event()`` function can simply be stubbed out to ensure backward > compatibility. > > Unresolved Issues > ================= > > Return Values > ------------- > > Currently, a ``return`` statement with a value in a generator is > a syntax error. The Python community should consider supporting > the behavior described above in the Python compiler. Specifically, > the compiler would treat:: > > return foo > > in a generator as equivalent to:: > > raise StopIteration(foo) > > This change raises no backward-compatibility issues (as the former > expression is not currently legal), but may introduce some surprising > behavior as a function could then continue executing after a return > statement:: > > try: > return 10 > except StopIteration: > print "I'm still here!" > > Non-Microthreaded Generators > ---------------------------- > > Functions which return "normal" generators may confuse a > microthreading implementation if those generators are accidentally > yielded. Consider:: > > def get_constants(dict): > return ( k for k in dict.iterkeys() if k[0] in string.uppercase ) > > def examine_module(mod): > d = mod.__dict__ > constants = yield get_constants(d) > > this example will fail, because the implementation will treat the > generator expresion in ``get_constants`` as a microthreaded function, > calling its ``send`` method until it is exhaustd, then assigning > ``None`` to ``constants`` in ``examine_module``. > > The problem only occurs when such a generator is yielded: the > snippet above will operate correctly if ``yield`` is removed from the > last line. Thus users can avoid the problem by exercising caution > in selecting the values that are yielded. > > References > ========== > > .. [1] Stackless is not included in this list because, while it does > implement a microthreaded environment, it does so without the use > of generators and (as of this writing) requires a modified Python > binary. > > .. [2] PEP 342, "Coroutines via Enhanced Generators", van Rossum, Eby > (http://www.python.org/peps/pep-0342) > > .. [3] PEP 355, "Simple Generators", Schemenauer, Peters, Hetland > (http://www.python.org/peps/pep-0342) > > .. _Kiwi tasklets: > http://www.async.com.br/projects/kiwi/api/kiwi.tasklet.html > > .. _Twisted Python:http://twistedmatrix.com/ > > .. [#inlineCallbacks] > http://twistedmatrix.com/documents/current/api/twisted.internet.defer... > > .. _Kamaelia:http://kamaelia.sourceforge.net/ > > .. [#Mertz] "Charming Python: Implementing 'weightless threads' with > Python generators," Mertz, > (http://www-128.ibm.com/developerworks/library/l-pythrd.html) > > .. [#Obarski] "simple, cooperative multitasking using generators," > Obarski, > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/466008 > > Copyright > ========= > > This document has been placed in the public domain. > > .. > Local Variables: > mode: indented-text > indent-tabs-mode: nil > sentence-end-double-space: t > fill-column: 70 > coding: utf-8 > End: Simpy also seems to be part of this landscape, albeit in the guise of a discrete event simulator. The Simpy engine manages Processes that share Resources. Processes synchronize among each other by yielding one of various values to the scheduler, which it uses to determine when to call back to the Process. Forgive me, Simpy-ers if I have butchered this description, my experience with Simpy is a few years old now. The interesting thing here is that Simpy processes do not simply yield in order to pass control on "to whoever's next" - the value returned with the yield dictates how the Process gets rescheduled at some time in the future ("future" being either realtime or simulated time - a discrete event simulator can simply advance from scheduled event to scheduled event, without having to actually wait for the intervening time to elapse). -- Paul From S.Mientki-nospam at mailbox.kun.nl Fri May 25 04:19:01 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Fri, 25 May 2007 10:19:01 +0200 Subject: Can I reference 1 instance of an object by more names ? rephrase In-Reply-To: References: <4654289a$0$2326$426a74cc@news.free.fr> <3dc25$4655ebd1$d443bb3a$31378@news.speedlinq.nl> <8c957$46568f73$d443bb3a$15533@news.speedlinq.nl> Message-ID: <8020$46569b20$d443bb3a$12216@news.speedlinq.nl> Peter Otten wrote: > Stef Mientki wrote: > >>> Again, I'm confident, again I didn't test. >> I did, ... >> ... and unfortunately it still gave errors. > > Strange. indeed .. > >> So for the moment I'll just stick to my "lots of code solution", >> and I'll try again, when I've some more understanding of these Python >> "internals". > > Anyway, here's a self-contained example: thanks very much Peter, this really works like a charm. Now I've to find out, what I did wrong with your previous suggestions. cheers, Stef Mientki From thorsten at thorstenkampe.de Sun May 20 10:25:57 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun, 20 May 2007 15:25:57 +0100 Subject: zipfile stupidly broken References: Message-ID: * Gabriel Genellina (Wed, 16 May 2007 16:38:39 -0300) > En Wed, 16 May 2007 12:18:35 -0300, Martin Maney > escribi?: > > So the author knows that there's a hard limit of 64K on the comment > > size, but feels it's more important to fail a little more quickly when > > fed something that's not a zipfile - or a perfectly legitimate zipfile > > that doesn't observe his ad-hoc 4K limitation. I don't have time to > > find a gentler way to say it because I have to find a work around for > > this arbitrary limit (1): this is stupid. > > This is not a good place for reporting bugs - use > http://sourceforge.net/bugs/?group_id=5470 Actually it is: ,--- | Giving the shortage of reviewer time, invalid bug reports on tracker | are a nuisance and a diversion from attending to valid reports and | reviewing patches. That is why I encourage people to post here for | community review. `--- http://groups.google.com/group/comp.lang.python/msg/d57b1906d3ef68a5 From michael.forbes at gmail.com Fri May 4 15:59:39 2007 From: michael.forbes at gmail.com (Michael) Date: 4 May 2007 12:59:39 -0700 Subject: Why are functions atomic? In-Reply-To: References: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> <1178044821.864741.235260@o5g2000hsb.googlegroups.com> <1178063341.779617.289690@o5g2000hsb.googlegroups.com> <1178065685.161372.81790@y80g2000hsf.googlegroups.com> <1178083318.404304.76100@q75g2000hsh.googlegroups.com> <1178260571.160570.299160@p77g2000hsh.googlegroups.com> Message-ID: <1178308779.454269.166550@e65g2000hsc.googlegroups.com> On May 4, 9:19 am, John Nagle wrote: > > ... def g(): > > ... x = x + 1 > > Too cute. Don't nest functions in Python; the scoping model > isn't really designed for it. How can you make generators then if you don't nest? > Python probably isn't the right language for N-dimensional optimization > if performance is a major concern. That's a very compute-intensive operation. > I've done it in C++, with heavy use of inlines, and had to work hard to > get the performance up. (I was one of the first to do physics engines for > games and animation, which is a rather compute-intensive problem.) > > If you're doing number-crunching in Python, it's essential to use > NumPy or some other C library for matrix operations, or it's going to > take way too long. I know. I am trying to flesh out a modular optimization proposal for SciPy. Using C++ would defeat the purpose of making it easy to extend the optimizers. I just want to make things as clean and efficient as possible when I stumbled on this python copy problem. Michael. From dborne at gmail.com Wed May 9 11:17:41 2007 From: dborne at gmail.com (Dave Borne) Date: Wed, 9 May 2007 10:17:41 -0500 Subject: How safe is a set of floats? In-Reply-To: <1178288509.067493.5140@e65g2000hsc.googlegroups.com> References: <1178288509.067493.5140@e65g2000hsc.googlegroups.com> Message-ID: <6e42ec490705090817u43733755w5cc9b9b69805f020@mail.gmail.com> On 4 May 2007 07:21:49 -0700, Thomas Nelson wrote: > I want to generate all the fractions between 1 and limit (with > limit>1) in an orderly fashion, without duplicates. Might I suggest the Stern-Brocot tree (http://en.wikipedia.org/wiki/Stern-Brocot_tree) It will eliminate the need for sets as the algorithm gurantees: "Every positive rational number can be found in this tree exactly once and in lowest terms". The order will be different than your algorithm, though. #An overly simplified fraction class for this example: class Fraction: def __init__ (self, num, den): self.num = num self.den = den def __repr__ (self): return '%(num)d/%(den)d' % self.__dict__ def all_ratios(limit): seq = [Fraction(1,1), Fraction(limit,1)] while True: newseq = seq[:1] pairs = [seq[x:x+2] for x in range(len(seq)-1)] for pair in pairs: #find the mediant value between each pair in the series newval = Fraction(pair[0].num+pair[1].num, pair[0].den+pair[1].den) yield newval newseq.append(newval) newseq.append(pair[1]) seq = newseq -Dave From __peter__ at web.de Thu May 24 05:40:28 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 24 May 2007 11:40:28 +0200 Subject: Locale case change not working References: <1179998221.372699.17600@p77g2000hsh.googlegroups.com> Message-ID: Clodoaldo wrote: > When using unicode the case change works: > >>>> print u'?'.lower() > ? > > But when using the pt_BR.utf-8 locale it doesn't: > >>>> locale.setlocale(locale.LC_ALL, 'pt_BR.utf-8') > 'pt_BR.utf-8' >>>> locale.getlocale() > ('pt_BR', 'utf') >>>> print '?'.lower() > ? > > What am I missing? I'm in Fedora Core 5 and Python 2.4.3. > > # cat /etc/sysconfig/i18n > LANG="en_US.UTF-8" > SYSFONT="latarcyrheb-sun16" > > Regards, Clodoaldo Pinto Neto str.lower() operates on bytes and therefore doesn't handle encodings with multibyte characters (like utf-8) properly: >>> u"?".encode("utf8") '\xc3\x89' >>> u"?".encode("latin1") '\xc9' >>> import locale >>> locale.setlocale(locale.LC_ALL, "de_DE.utf8") 'de_DE.utf8' >>> print unicode("\xc3\x89".lower(), "utf8") ? >>> locale.setlocale(locale.LC_ALL, "de_DE.latin1") 'de_DE.latin1' >>> print unicode("\xc9".lower(), "latin1") ? I recommend that you forget about byte strings and use unicode throughout. Peter From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri May 4 12:47:38 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 04 May 2007 18:47:38 +0200 Subject: is there a module to work with pickled objects storage in database? In-Reply-To: References: Message-ID: <463b638e$0$2127$426a74cc@news.free.fr> krishnakant Mane a ?crit : > hello all, > I am trying a very complex kind of a task in a project. > I have a knowledge management system where I need to store a lot of > objects (pickled). I have to store mostly lists and dictionaries into > a rdbms. Which totally defeats the purpose of a rdbms. From victor.lebrun at gmail.com Thu May 3 03:57:18 2007 From: victor.lebrun at gmail.com (vml) Date: 3 May 2007 00:57:18 -0700 Subject: python,win32com,scipy and vb 6 : no module named scipy In-Reply-To: References: <1178141865.741042.202250@l77g2000hsb.googlegroups.com> Message-ID: <1178179038.421643.304490@c35g2000hsg.googlegroups.com> On 3 mai, 03:30, "Terry Reedy" wrote: > scipy is a 3rd party package which I believe you get from the same place, > more or less, as numpy. the bug was between the chair and the keyboard....;) From bj_666 at gmx.net Wed May 16 09:42:40 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 16 May 2007 15:42:40 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649dd55$0$23144$9b4e6d93@newsspool1.arcor-online.net> <464a25e9$0$10188$9b4e6d93@newsspool4.arcor-online.net> <464A3354.4060205@web.de> <464ac22c$0$20297$9b4e6d93@newsspool3.arcor-online.net> <464AC4C2.7030007@web.de> Message-ID: In <464AC4C2.7030007 at web.de>, Stefan Behnel wrote: > Ren? Fleschenberg wrote: >> Marc 'BlackJack' Rintsch schrieb: >>> There are potential users of Python who don't know much english or no >>> english at all. This includes kids, old people, people from countries >>> that have "letters" that are not that easy to transliterate like european >>> languages, people who just want to learn Python for fun or to customize >>> their applications like office suites or GIS software with a Python >>> scripting option. >> >> Make it an interpreter option that can be turned on for those cases. > > No. Make "ASCII-only" an interpreter option that can be turned on for the > cases where it is really required. Make no interpreter options and use `pylint` and `pychecker` for checking if the sources follow your style guide in respect to identifiers. Ciao, Marc 'BlackJack' Rintsch From bdesth.quelquechose at free.quelquepart.fr Mon May 21 17:02:52 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 21 May 2007 23:02:52 +0200 Subject: [Fwd: Re: managed lists?] In-Reply-To: References: Message-ID: <4651fe96$0$24671$426a34cc@news.free.fr> (snip - I suppose I'm answering to Jorgen, but being another idiot myself I may be wrong... anyway:) > Thanks for the answer. I did make something myself after i could not > find anything, just because it was fun to do :-) I did saw array but > it was not for object, only for small types like int, char, Everything in Python is an object. Including integers. And there's no 'char' type in Python. > > The list I created uses a strong type check to make sure all objects > in the list are of the same type, like > > ol = objlist.ObjList(class_name = SomeClass) > > Now only classes that are an instance of SomeClass are allowed in the > array. ObjList mimics a normal list, it can index, iterate, find, > delete, append items so it was basically a drop-in replacement for my > _list = [] solution The problem with this kind of "solutions" is that it creates more problems than anything else. What you really want is a list objects that share a common interface, not a list of objects that are instances of a same class. As a simple example, let's say you need a list of file-like objects. Or to be more accurate, a list of objects that have a 'write' method that's compatible with file.write(). So StringIO instances should be allowed, but your code will reject them. You may have a perfectly valid reason to use StringIO instances instead of files in some situations, but with your (ill-named) 'ObjectList' stuff it won't be possible. For no good reason. From sjmachin at lexicon.net Thu May 3 18:50:36 2007 From: sjmachin at lexicon.net (John Machin) Date: 3 May 2007 15:50:36 -0700 Subject: getmtime in 2.5 reports GMT instead of local time In-Reply-To: References: Message-ID: <1178232636.415630.106320@l77g2000hsb.googlegroups.com> On May 4, 12:26 am, Josef Dalcolmo wrote: > Hello, > > I have tried this only on Windows XP. > > in Python 2.4 os.path.getmtime() used to return an integer representing > the local time. The docs say "seconds since the epoch". Noting that the epoch is usually defined with reference to UTC, "local time" is rather unlikely. > > in Python 2.5 os.path.getmtime() reports a float representing the GMT of the > file's modification time. > > Since I could not find any documentation to this behavioural change, I am asking > here: was this change intentional? Is it going to stay? Windows reports > the same time for the file as Python 2.4 used to. So I am tempted to > call this a bug, but wanted some feedback from the developers, > before filing a bug report. > > If you want to test this, make sure your local time differs from GMT, > then do: > > import os, time > print time.ctime(os.path.getmtime('foo.txt')) > > on a file foo.txt, once with Python 2.4 then with Python 2.5, > and you should see what I mean. No way, Jose. C:\junk>\python24\python Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os, os.path, time; fn = 'hello_u.txt'; print os.stat(fn).st_mtime, os .path.getmtime(fn) 1178228403 1178228403 >>> import os, os.path, time; fn = 'hello_u.txt'; print time.ctime(os.stat(fn).s t_mtime), time.ctime(os.path.getmtime(fn)) Fri May 04 07:40:03 2007 Fri May 04 07:40:03 2007 >>> ^Z C:\junk>\python25\python 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 os, os.path, time; fn = 'hello_u.txt'; print os.stat(fn).st_mtime, os .path.getmtime(fn) 1178228403.3 1178228403.3 >>> import os, os.path, time; fn = 'hello_u.txt'; print time.ctime(os.stat(fn).s t_mtime), time.ctime(os.path.getmtime(fn)) Fri May 04 07:40:03 2007 Fri May 04 07:40:03 2007 >>> ^Z My TZ is 10 hours (plus/minus daylight saving) away from UTC. The above ctime results are correct AFAICT to plus/minus a few minutes. The change from integer to float in 2.5 is documented under os.stat_float_times. From bernhard.voigt at gmail.com Tue May 29 05:02:46 2007 From: bernhard.voigt at gmail.com (bernhard.voigt at gmail.com) Date: 29 May 2007 02:02:46 -0700 Subject: Sci.linalg.lu permuation error In-Reply-To: <1180341898.971618.104760@q19g2000prn.googlegroups.com> References: <1180341898.971618.104760@q19g2000prn.googlegroups.com> Message-ID: <1180429366.955795.233740@g4g2000hsf.googlegroups.com> Hi Luke, you should send this to the scipy user list: scipy-user at scipy.org Bernhard On May 28, 10:44 am, Luke wrote: > I'm trying to use Scipy's LU factorization. Here is what I've got: > > from numpy import * > import scipy as Sci > import scipy.linalg > > A=array([[3., -2., 1., 0., 0.],[-1., 1., 0., 1., 0.],[4., 1., 0., 0., > 1.]]) > p,l,u=Sci.linalg.lu(A,permute_l = 0) > > now, according to the documentation: > ************************************************** > Definition: Sci.linalg.lu(a, permute_l=0, overwrite_a=0) > Docstring: > Return LU decompostion of a matrix. > > Inputs: > > a -- An M x N matrix. > permute_l -- Perform matrix multiplication p * l [disabled]. > > Outputs: > > p,l,u -- LU decomposition matrices of a [permute_l=0] > pl,u -- LU decomposition matrices of a [permute_l=1] > > Definitions: > > a = p * l * u [permute_l=0] > a = pl * u [permute_l=1] > > p - An M x M permutation matrix > l - An M x K lower triangular or trapezoidal matrix > with unit-diagonal > u - An K x N upper triangular or trapezoidal matrix > K = min(M,N) > ********************************************* > > So it would seem that from my above commands, I should have: > A == dot(p,dot(l,u)) > > but instead, this results in: > In [21]: dot(p,dot(l,u)) > Out[21]: > array([[-1., 1., 0., 1., 0.], > [ 4., 1., 0., 0., 1.], > [ 3., -2., 1., 0., 0.]]) > > Which isn't equal to A!!! > In [23]: A > Out[23]: > array([[ 3., -2., 1., 0., 0.], > [-1., 1., 0., 1., 0.], > [ 4., 1., 0., 0., 1.]]) > > However, if I do use p.T instead of p: > In [22]: dot(p.T,dot(l,u)) > Out[22]: > array([[ 3., -2., 1., 0., 0.], > [-1., 1., 0., 1., 0.], > [ 4., 1., 0., 0., 1.]]) > > I get the correct answer. > > Either the documentation is wrong, or somehow Scipy is returning the > wrong permutation matrix... anybody have any experience with this or > tell me how to submit a bug report? > > Thanks. > ~Luke From kyosohma at gmail.com Tue May 22 11:22:47 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 22 May 2007 08:22:47 -0700 Subject: xml.dom.minidom: how to preserve CRLF's inside CDATA? In-Reply-To: <1179841504.782279.86490@u36g2000prd.googlegroups.com> References: <1179841504.782279.86490@u36g2000prd.googlegroups.com> Message-ID: <1179847367.813297.191480@y2g2000prf.googlegroups.com> On May 22, 8:45 am, "sim.sim" wrote: > Hi all. > i'm faced to trouble using minidom: > > #i have a string (xml) within CDATA section, and the section includes > "\r\n": > iInStr = '\n \nEND:VCALENDAR\r\n]]>\n' > > #After i create DOM-object, i get the value of "Data" without "\r\n" > > from xml.dom import minidom > iDoc = minidom.parseString(iInStr) > iDoc.childNodes[0].childNodes[0].data # it gives u'BEGIN:VCALENDAR > \nEND:VCALENDAR\n' > > according tohttp://www.w3.org/TR/REC-xml/#sec-line-ends > > it looks normal, but another part of the documentation says that "only > the CDEnd string is recognized as markup":http://www.w3.org/TR/REC-xml/#sec-cdata-sect > > so parser must (IMHO) give the value of CDATA-section "as is" (neither > both of parts of the document do not contradicts to each other). > > How to get the value of CDATA-section with preserved all symbols > within? (perhaps use another parser - which one?) > > Many thanks for any help. I'm thinking that the endline character "\n" is relevant for *nix systems. So if you're running this on Windows, Python will translate it automatically to "\r\n". According to Lutz's book, Programming Python 3rd Ed, it's for historical reasons. It says that most text editors handle text in Unix format, with the exception of Notepad, which is why some documents are displayed as just one long line in Notepad. (see pg 150 of said book). The book goes on to talk about how to use a script that will check this endline character and fix it depending on the platform you're running under. The following link seems to do something along those lines as well. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/435882 Not exactly helpful, but maybe it'll give you some insight into the issue. Mike From theller at ctypes.org Tue May 15 14:07:03 2007 From: theller at ctypes.org (Thomas Heller) Date: Tue, 15 May 2007 20:07:03 +0200 Subject: ANN: ctypes 1.0.2 released Message-ID: <4649F6C7.3060406@ctypes.org> ctypes 1.0.2 released - May 15, 2007 ==================================== Overview ctypes is an advanced ffi (Foreign Function Interface) package for Python 2.3 and higher. ctypes allows to call functions exposed from dlls/shared libraries and has extensive facilities to create, access and manipulate simple and complicated C data types in Python - in other words: wrap libraries in pure Python. It is even possible to implement C callback functions in pure Python. ctypes runs on Windows, Windows CE, MacOS X, Linux, Solaris, FreeBSD, OpenBSD. It may also run on other systems, provided that libffi supports this platform. Changes in 1.0.2 This is exactly the same version that is distibuted with Python 2.5.1; made available as add-on package for Python 2.3 and Python 2.4. No new features, only bugfixes have been applied: The version number of the ctypes package was changed to "1.0.2". Bug #1563807: _ctypes built on AIX fails with ld ffi error. Bug #1598620: A ctypes Structure cannot contain itself. Patch #1560695: Add .note.GNU-stack to ctypes' sysv.S so that ctypes isn't considered as requiring executable stacks. Bug #1651235: When a tuple was passed to a ctypes function call, Python would crash instead of raising an error. Fix bug #1646630: ctypes.string_at(buf, 0) and ctypes.wstring_at(buf, 0) returned string up to the first NUL character. Bug #1610795: ctypes.util.find_library works now on BSD systems. ctypes callback functions only support 'fundamental' data types as result type. Raise an error when something else is used. This is a partial fix for Bug #1574584. Changes in 1.0.1 If the Python part of a ctypes callback function returns None, and this cannot be converted to the required C type, an exception is printed with PyErr_WriteUnraisable. Before this change, the C callback returned arbitrary values to the calling code. The __repr__ method of a NULL ctypes.py_object() no longer raises an exception. This release contains exactly the same code as the ctypes package included in Python 2.5. Changes in 1.0.0 Better support for comtypes. More target platforms for OpenBSD. Several small bugfixes. This is exactly the same version as included in Python 2.5b3. Download Downloads are available in the sourceforge files section Binary windows installers, which contain compiled extension modules, are also available, be sure to download the correct one for the Python version you are using. Homepage Enjoy, Thomas From michael.forbes at gmail.com Wed May 2 01:21:58 2007 From: michael.forbes at gmail.com (Michael) Date: 1 May 2007 22:21:58 -0700 Subject: Why are functions atomic? In-Reply-To: References: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> <1178044821.864741.235260@o5g2000hsb.googlegroups.com> <1178063341.779617.289690@o5g2000hsb.googlegroups.com> <1178065685.161372.81790@y80g2000hsf.googlegroups.com> Message-ID: <1178083318.404304.76100@q75g2000hsh.googlegroups.com> > Your use case appears to be that you > want to make multiple copies of the same function, and those copies > should be almost, but not quite, the same. > > The Pythonic solution is to produce the copies by a factory function... > > >>> def powerfactory(exponent): > ... def inner(x): > ... return x**exponent > ... return inner Is there a reason for using the closure here? Using function defaults seems to give better performance: >>> def powerfactory(exponent): ... def inner(x,exponent=exponent): ... return x**exponent ... return inner This is definitely one viable solution and is essentially what I had in mind, but I did not want to have to carry the generator arround with me: Instead, I wanted to use it once as a decorator and then carry only the function around. >>> @declare_options(first_option='opt1') >>> def f(x,opt1,opt2,opt3): ... return x*(opt1+opt2*opt3) >>> f.set_options(opt1=1,opt2=2,opt3=3) >>> f(1) 7 >>> from copy import copy >>> g = copy(f) >>> g.set_options(opt1=4,opt2=5,opt3=6) >>> f(1) 7 >>> g(1) 34 The decorator declare_options behaves like the generator above, but adds some methods (set_options) etc. to allow me to manipulate the options without generating a new function each time. I have functions with many options that may be called in the core of loops, and found that the most efficient solution was to provide all of the options through func_defaults. >>> def f(x,opt1,opt2,opt3): ... return x*(opt1 + opt2*opt3) The cleanest (and fastest) solution I found was to set the options in the defaults: >>> f.func_defaults = (1,2,3) Then f can be passed to the inner loops and f(x) is very quick. Other options include using lists and dict's: >>> opt = (1,2,3) >>> f(1,*opt) 7 but then I have to pass f and opt around. This also appears to be somewhat slower than the defaults method. Dictionaries have the advantage of associating the names with the values >>> opt = {'opt1':1, 'opt2':2, 'opt3':3} >>> f(1,**opt) 7 but this is much slower. Wrapping the function with a generator as you suggest also works and packages everything together, but again suffers in performance. It also complicates my code. The result of my declare_options decorator is that the result is a regular function, complete with docstring etc. but with added annotations that allow the options to be set. In addition, the performance optimal. I though this was a very clean solution until I realized that I could not make copies of the functions to allow for different option values with the usual python copy symantics (for example, a __copy__ method is ignored). I can easily get around this by adding a custom copy() method, but wondered if there was anything inherently dangerous with this approach that would justify the added complications of more complicated wrappings and the performance hit. Pickling is an obvious issue, but it seems like there is nothing wrong with the copy semantics and that the limitations are artificial and out of place. (It is also easily fixed: if the object has a __copy__ method, use it. Truely immutable objects will never have one. There may be subtle issues here, but I don't know what they are.) Thanks for all of the suggestions, Michael. From michael at jedimindworks.com Thu May 31 00:36:32 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Wed, 30 May 2007 23:36:32 -0500 Subject: ImageMagick Issue In-Reply-To: <2adc542f0705302100g3135fd0fn1e6c3decd210bd5f@mail.gmail.com> References: <2adc542f0705302100g3135fd0fn1e6c3decd210bd5f@mail.gmail.com> Message-ID: On May 30, 2007, at 11:00 PM, Sick Monkey wrote: > When I run the following command: > ozdon at SickCodeMonkey david.huggins]# identify -format %w '/someDIR/ > images/david.huggins/100_0264.JPG' > > I get the following result > 2304 > > -------------------- > However, when I try to set this value to a variable, ie > w= os.system("identify -format %w '/someDIR/images/david.huggins/ > 100_0264.JPG'") > print w > > I get > TypeError: argument 1 must be string or read-only buffer, not int The return value of os.system() is the exit status of the command it runs. You are looking for its output, instead of exit status. To get at its output, use the subprocess module http://www.python.org/ doc/current/lib/module-subprocess.html hth, Michael --- Let the wookie win. -------------- next part -------------- An HTML attachment was scrubbed... URL: From researchbase at gmail.com Fri May 4 06:18:41 2007 From: researchbase at gmail.com (krishnakant Mane) Date: Fri, 4 May 2007 15:48:41 +0530 Subject: is there a module to work with pickled objects storage in database? Message-ID: hello all, I am trying a very complex kind of a task in a project. I have a knowledge management system where I need to store a lot of objects (pickled). I have to store mostly lists and dictionaries into a rdbms. mostly I will be using mysql. I want to know if there is any module that can help me store a pickled object inside a blob field instead of a file. I know that pickle.dump() can store an object into a file but I can't find a way to transfer pickled objects into a database. I so far tried to read a dumpped file for pickled object and directly right the contents of the file to the blob field in my database. but that does not seam to give the right result. I first dump the object into the file through pickle.dump and then open the file in read mode. then I read the contents of the file and then store what ever comes out into the blob field. I know this is not right and there should be ways of storing a pickled object other than file. Please guide me on this issue. regards. Krishnakant. From mike4ty4 at yahoo.com Fri May 4 04:31:49 2007 From: mike4ty4 at yahoo.com (mike3) Date: 4 May 2007 01:31:49 -0700 Subject: Firefighters at the site of WTC7 "Move away the building is going to blow up, get back the building is going to blow up." In-Reply-To: References: <1178161820.731367.264500@y80g2000hsf.googlegroups.com> <1178163974.007362.13870@c35g2000hsg.googlegroups.com> <1178172877.755445.101340@q75g2000hsh.googlegroups.com> <1178173090.238547.62190@o5g2000hsb.googlegroups.com> <1178207619.155007.129860@o5g2000hsb.googlegroups.com> Message-ID: <1178267509.310342.146910@o5g2000hsb.googlegroups.com> On May 3, 7:22 pm, The Great Attractor wrote: > On 3 May 2007 08:53:39 -0700, malibu wrote: > > > > > > >On May 3, 12:18 am, Eric Gisse wrote: > >> On May 2, 10:14 pm, malibu wrote: > > >> > On May 2, 9:46 pm, Eric Gisse wrote: > > >> > > On May 2, 7:10 pm, Midex wrote: > > >> > > [...] > > >> > > I guess the explanation that people were looking at the building and > >> > > watching its' structure deform is too rational. > > >> > Also, that was a Larry Silverstein impostor who > >> > said they were going to 'pull it'. > > >> ...maybe if you read the context, it would make a little more rational > >> sense. Fucking nutter. > > >> > And the only reason he took out huge amounts > >> > of extra insurance on the buildings two months > >> > before this happened was because of global > >> > warming, because we all know a little bit of heat > >> > will bring down steel buildings. > > >> A little heat and major structural damage. > > >> > John > > >Gee, I'll bet all those explosions in the > >subfloors of WTC1 + WTC2 did some > >structural damage also! > > You're an idiot. > You did not refute the claim. How do you know this claim is wrong? > > > >Come to think of it. > > Slugs do not think. > You did not refute the claim. > > > >When the firefighters got there, all the glass > >on the street floors was blown out. > > You're an idiot. > You did not refute the claim. > >Shock wave from the plane hitting > >80 floors up? > > You're a goddamned retard, boy. ARe you an islamic extremist by > chance? > You did not refute the claim. > > > >Janitors and such coming up from the basement levels > >bleeding and dazed. > > You're full of shit. > You did not refute the claim. > > > >Jet fuel trickling down the elevator shafts being ignited > >by someone's roach? And exploding? > > You're an ifiot. > You did not refute the claim. > >Severing the three-foot thick steel columns? > >All 5 dozen of them? > >(That's mighty fine primo, pardner!) > > The buildings collapsed WAY WAY UP on the floors where the planes > hit, and fell from there down, taking floors out as the large top > section of the building fell. > First good argument so far... > You could be a bit more retarded, just not in this life. > > >Your brain got structural damage? > > No, but your never was right from the moment your retarded felon > criminal mother shat you out of her ass and forgot to flush. > You did not refute the claim. > >Dropped on your head as a kid? > > Got any more adolescent baby bullshit, little boy? > You did not refute the claim. > >Don't put that fire iron too close > >to the flames, honey. It'll melt > >and deform! > > You're an idiot. There was a tanker crash in Oakland a couple days > back (Sunday) that melted sections of the bridge it was on. Second good argument so far. Two good arguments and eight non-arguments, but those two good arguments happen to clinch the thing anyway... > > Got Clue? You and Rosie are retarded. From penis.Mosely8 at gmail.com Sat May 19 12:53:54 2007 From: penis.Mosely8 at gmail.com (penis.Mosely8 at gmail.com) Date: 19 May 2007 09:53:54 -0700 Subject: :// FREE TOTALLY NUDE PICS AND VIDEOS! Message-ID: <1179593634.280259.209250@l77g2000hsb.googlegroups.com> http://nudepicks.blogspot.com/ - Download the best today nude pics and vidz today!... From skip at pobox.com Wed May 2 20:39:02 2007 From: skip at pobox.com (skip at pobox.com) Date: Wed, 2 May 2007 19:39:02 -0500 Subject: curses mystical error output In-Reply-To: References: <17977.2867.158091.217653@montanaro.dyndns.org> Message-ID: <17977.12070.355553.288830@montanaro.dyndns.org> >> screen.addstr(row, 39, "|") >> >> where row is 3. Ian> You might be trying to write to a section that is currently off Ian> screen. Seems to me when I was doing some curses stuff that when I Ian> tried to write to one more row than could be fit onto my terminal Ian> that error would come up. Ian> Try doing the following code and make sure that you can enough Ian> space to draw it. >>> (height, width) = screen.getmaxyx() Thanks, I gave that a try. 40 rows and 80 columns. I should have pointed out that out before. I stuck a couple asserts on the row and column values. They didn't trip, the "addstr() returned ERR" tripped. Skip From gagsl-py2 at yahoo.com.ar Mon May 7 04:14:29 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 07 May 2007 05:14:29 -0300 Subject: default test method name in unittest framework References: <271115400705061817u3c8ee950u3c7b0ec7ddcf6576@mail.gmail.com> <271115400705070049g7f41bb3atab98d45bcea9f67@mail.gmail.com> Message-ID: En Mon, 07 May 2007 04:49:12 -0300, Vyacheslav Maslov escribi?: > Yes, i general you are right. I meant following case, please look at my > example > > Suppose i have following simple test case: > > import unittest > > class SomeTest(unittest.TestCase): > > def testAdd(self): > self.assertEqual(2+2,4) > > if __name__=="__main__": > unittest.TextTestRunner().run(SomeTest()) > > this code produce following exception: > ValueError: no such test method in : runTest > > Because default test method name is "run", but TestCase class have > constructor parameter testMethod with default value "runTest" not "run"! NO! the default test method name is not "run" but "runTest", as explained in my previous post. You can either rename the testAdd method to runTest, or change the last line to be, simply: if __name__=="__main__": unittest.main() main() will create a TestRunner, a TestLoader, a TestSuite containing all your TestCases, and run them. > As result i always should explicitly pass testMethod name when create > object > of test case class: > unittest.TextTestRunner().run(SomeTest("run")) > > Why i should do this? You should *not* do that! Your tests will not even be run that way. -- Gabriel Genellina From metaperl at gmail.com Tue May 29 11:39:02 2007 From: metaperl at gmail.com (metaperl) Date: 29 May 2007 08:39:02 -0700 Subject: Seeking author of script which generated HTML pages from pictures of them In-Reply-To: <1179392539.203491.153900@u30g2000hsc.googlegroups.com> References: <1179392539.203491.153900@u30g2000hsc.googlegroups.com> Message-ID: <1180453142.200699.13180@m36g2000hse.googlegroups.com> I found him! http://programming.reddit.com/info/k9dx/comments From anton.vredegoor at gmail.com Mon May 14 12:43:54 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Mon, 14 May 2007 18:43:54 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: Neil Hodgson wrote: > Anton Vredegoor: > >> Ouch! Now I seem to be disagreeing with the one who writes my editor. >> What will become of me now? > > It should be OK. I try to keep my anger under control and not cut > off the pixel supply at the first stirrings of dissent. Thanks! I guess I won't have to make the obligatory Sovjet Russia joke now :-) > It may be an idea to provide some more help for multilingual text > such as allowing ranges of characters to be represented as hex escapes > or character names automatically. Then someone who only normally uses > ASCII can more easily audit patches that could contain non-ASCII characters. Now that I read about IronPython already supporting some larger character set I feel like I'm somewhat caught in a side effect of an embrace and extend scheme. A. From inq1ltd at verizon.net Tue May 29 10:39:04 2007 From: inq1ltd at verizon.net (jim-on-linux) Date: Tue, 29 May 2007 10:39:04 -0400 Subject: Circular imports In-Reply-To: <20070529034901.M60755@uniqsys.com> References: <003801c7a1a3$e048d840$6701a8c0@aristotle> <20070529034901.M60755@uniqsys.com> Message-ID: <200705291039.05167.inq1ltd@verizon.net> On Tuesday 29 May 2007 00:08, Carsten Haese wrote: > On Mon, 28 May 2007 23:46:00 -0400, Ron Provost > wrote > > > [...] python is not happy about my circular > > imports [...] > > A circular import is not a problem in itself. > I'm guessing you're running into a situation > like this: > > Module A imports module B and then defines an > important class. Module B imports A (which does > nothing because A is already partially > imported) and then defines a class that depends > on the class that is defined in module A. That > causes a NameError. > > The root of the problem is that all statements > are executed in the order in which they appear, > and B is imported before A had a chance to > define the class that B depends on. > > Note that import statements don't have to be at > the top of the file. I agree, waite until python complains. You might try to remove all of the import statements then add then as they are requested by the program by a traceback error. jim-on-linux > Try moving each import > statement to the latest possible point in the > code, i.e. right before the first occurence of > whatever names you're importing from the > respective modules. That way, each module gets > to define as much as it possibly can before it > gets side-tracked by importing other modules. > > If my guess doesn't help, you're going to have > to post at least the exception/traceback you're > getting, and you're probably going to have to > post some code, too. > > Good luck, > > -- > Carsten Haese > http://informixdb.sourceforge.net From gh at gregor-horvath.com Thu May 17 04:07:04 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Thu, 17 May 2007 10:07:04 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de><1179160242.787344.48060@h2g2000hsg.googlegroups.com> <1179258692.237438.110860@p77g2000hsh.googlegroups.com> Message-ID: Hendrik van Rooyen schrieb: > I can sympathise a little bit with a customer who tries to read code. > Why that should be necessary, I cannot understand - does the stuff > not work to the extent that the customer feels he has to help you? > You do not talk as if you are incompetent, so I see no reason why > the customer should want to meddle in what you have written, unless > he is paying you to train him to program, and as Eric Brunel has > pointed out, this mixing of languages is all right in a training environment. That is highly domain and customer specific individual logic, that the costumer knows best. (For example variation logic of window and door manufacturers) He has to understand the code, so that he can verify it's correct. We are in fact developing it together. Some costumers even are coding this logic themselves. Some of them are not fluent in English especially not in the computer domain. Translating the logic into a documentation is a waste of time if the code is self documenting and easy to grasp. (As python usually is) But the code can only be self documenting if it is written in the domain specific language of the customer. Sometimes these are words that are not even used in general German. Even in German different customers are naming the same thing with different words. Talking and coding in the language of the customer is a huge benefit. Gregor From deets at nospam.web.de Wed May 9 17:14:51 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 09 May 2007 23:14:51 +0200 Subject: Behavior of mutable class variables In-Reply-To: <1178744257.369030.95310@w5g2000hsg.googlegroups.com> References: <1178744257.369030.95310@w5g2000hsg.googlegroups.com> Message-ID: <5aerugF2o7pcrU1@mid.uni-berlin.de> tkpmep at hotmail.com schrieb: > I have written a program that runs portfolio simulations with > different parameters and prints the output, but am mystified by the > behavior of a mutable class variable. A simplified version of the > program follows - would you kindly help me understand why it behaves > the way it does. > > The function main() reads some data and then repeatedly calls > simulation() with different parameter values. Each time the simulation > runs, it creates a collection of stocks, simulates their behavior and > prints the results. > > Here's what I expect to happen each time simulation( ) is called: the > class variable NStocks for the class Stock is initialized to an empty > list, and is then built up by __init__ as stocks are added to the > portfolio. Unfortunately, ths is not what actuallly happens .NStocks > is initialized to an empty list and then built up as I expect on the > first call to simulation( ), but appears to persists between calls to > simulation( ). > > Question: Why? Do I not create an entirely new list of stock objects > each time I enter simulation()? I am aware that mutable items can > behave in tricky ways, but am thoroughly mystified by the persistence > of NStocks between calls to simulation() http://www.python.org/doc/faq/general.html#why-are-default-values-shared-between-objects Diez From grante at visi.com Mon May 14 15:22:16 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 14 May 2007 19:22:16 -0000 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <134hdc9qpdjhbaa@corp.supernews.com> Message-ID: <134hdn8j41l3u16@corp.supernews.com> On 2007-05-14, Grant Edwards wrote: > On 2007-05-14, Michael Yanowitz wrote: > >> Let me guess - the next step will be to restrict the identifiers >> to be at most 6 characters long. > > Of course. If they're any longer than that then you can't fit > an entire identifier into a 26-bit CDC 6600 machine register so 36-bit > you can do a compare with a single machine instruction. -- Grant Edwards grante Yow! If our behavior is at strict, we do not need fun! visi.com From steven at REMOVE.THIS.cybersource.com.au Tue May 15 01:19:31 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 15 May 2007 05:19:31 GMT Subject: Python Power Point Slides References: <1179183962.824333.31730@q75g2000hsh.googlegroups.com> <46490372$0$334$e4fe514c@news.xs4all.nl> Message-ID: On Tue, 15 May 2007 02:48:47 +0200, Irmen de Jong wrote: > Krypto wrote: >> Hi, >> >> I want to give a short presentation in my group about benefits of >> python, why should one use python and some basic starting information >> about python, about its data type, etc. >> >> Can somebody point me to the right references on the web. I have >> searched a lot and I do get quite a few but I thought to check on >> newsgroup for a better presentation, or if you have prepared any, can >> you please share it. >> >> Thanks >> >> > Ahem, if you can't create one yourself, how could you ever give a > convincing presentation about these subjects? You'll have to tell your > own story... You know the benefits of Python etc. yourself, don't you? Doesn't mean (s)he is articulate enough to explain them in his own words without help, AND familiar enough with Powerpoint or OpenOffice to drive them effectively, AND has an artistic flair to make the slides not suck, AND has the time to do all these things. Asking for a good presentation is no worse than asking for a good code library. Maybe Krypto is like some actors or professional Masters of Ceremonies: excellent at giving the speech, lousy at writing it. -- Steven. From bdesth.quelquechose at free.quelquepart.fr Sun May 13 17:44:35 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 13 May 2007 23:44:35 +0200 Subject: __dict__ for instances? In-Reply-To: References: <46472764$0$23138$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <46477c9d$0$1408$426a74cc@news.free.fr> Ivan Voras a ?crit : > Marc Christiansen wrote: > > >>Nope, at least for PyGTK 2 :) See below. > > > Aaah, but....! > > >>[...] >> >>>This looks like it should be easy, but I can't find the solution :( >> >>Use the doc, Luke, oops, Ivan :) >>Citing the gtk.glade.XML.signal_autoconnect documentation: >> def signal_autoconnect(dict) >> dict: a mapping or an instance >> ^^^^^^^^ > > > I should have mentioned - I tried it already and it didn't work. The > specific error I get is: > > "WARNING: "on_button_clicked" not callable or a tuple" Please post the relevant code and the full traceback. From kyosohma at gmail.com Wed May 2 15:29:41 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 2 May 2007 12:29:41 -0700 Subject: Microsoft's Dynamic Languages Runtime (DLR) In-Reply-To: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> References: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> Message-ID: <1178134181.059655.133010@q75g2000hsh.googlegroups.com> On May 2, 1:22 pm, sturlamolden wrote: > On Monday Microsoft announced a new runtime for dynamic languages, > which they call "DLR". It sits on top of the conventional .NET runtime > (CLR) and provides services for dynamically typed languages like > Python or Lisp (thus the cross-posting). Apparently is is distributed > under a BSD-like open-source license. > > I am curious to know how it performs in comparison to CPython and an > efficient compiled Lisp like CMUCL. Speed is a major problem with > CPython but not with .NET or CMUCL, so it will be interesting to see > how the DLR performs in comparison. It would be great to finally see a > Python that runs on steroids, but knowing M$ bloatware my expectations > are not too high. > > Has anyone looked at the DLR yet? What are your impression? > > Jim Hugunin har written about the DLR in his blog: > > http://blogs.msdn.com/hugunin/ > > To cite one of the comments: "Fuck this microsoft bollocks! You just > stole the Lisp runtime ideas and fucked them up by stupid it salesman > lingo." (Khrishna) > > Sturla Molden I realize this is a stupid question, but why did you cite the most offensive comment to this blog post? Most of them were positive. Mike From anand.pasoria at in.bosch.com Tue May 8 06:31:39 2007 From: anand.pasoria at in.bosch.com (Anand) Date: Tue, 8 May 2007 16:01:39 +0530 Subject: File Name Format Message-ID: Greetings, How do I convert programmatically the file names from WIN32 to UNIX format? A code snippet would be of great help. We are new to python! :) Thanks. Best regards, Anand From kerny404 at gmail.com Thu May 10 08:46:12 2007 From: kerny404 at gmail.com (andrea) Date: 10 May 2007 05:46:12 -0700 Subject: Designing a graph study program In-Reply-To: References: <1178619753.077639.112510@q75g2000hsh.googlegroups.com> Message-ID: <1178801172.772583.287050@q75g2000hsh.googlegroups.com> On 9 Mag, 09:10, Alexander Schliep wrote: > andrea writes: > > Well then I wanted to draw graphs and I found that pydot is working > > really nicely. > > BUT I'd like to do this, an interactive program to see ho the > > algorithms works... > > For example in the breath search first, every time the algorithm > > colors a node, the program should redraw the graphs. Which modules > > should I use for graphics (I use macosX and I'd like something cross > > platforms). > > Check outhttp://gato.sf.net(LGPL license). It does exactly what you > want to do and there is a binary for MacOS X. Algorithms are implemented > using Gato's graph class and rudimentary visualizations you get for free > by replacing standard data structures (e.g., a vertex queue) by > animated ones (AnimatedVertexQueue). > > There is a Springer textbook forthcoming. We are also starting to collect > contributed algorithms, which we would like to make available from > our website. > > Full disclosure: I am the author of Gato > > Best, > Alexander Very very nice well done! I'd like to do something similar, just to learn something new... Could you explain me how you designed it?? How is the step mechanism done?? Any advices? From NikitaTheSpider at gmail.com Thu May 31 11:44:12 2007 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Thu, 31 May 2007 11:44:12 -0400 Subject: How to parse usenet urls? References: <1180573018.786188.220260@h2g2000hsg.googlegroups.com> <1180581992.342613.302370@k79g2000hse.googlegroups.com> Message-ID: In article <1180581992.342613.302370 at k79g2000hse.googlegroups.com>, "snewman18 at gmail.com" wrote: > > Are you aware of nntplib? > > > > http://docs.python.org/lib/module-nntplib.html > > I am, but I once I got into the article itself, I couldn't figure out > how to "call" a link inside the resulting message text: > > >>> ... 'Castro: Bush desea mi muerte, pero las ideas no se matan', > >>> 'news://newsclip.ap.org/D8PE2G6O0 at news.ap.org', ... > > How can I take the message link 'news://newsclip.ap.org/ > D8PE2G6O0 at news.ap.org' and follow it? OK, gotcha. I misunderstood your original question. Perhaps this is just a synonym for "nntp:"? THis sounds like a dangerous assumption and hopefully someone more knowledgeable will come along and shoot me down. =) But when I fire up Ethereal and paste that news: URL into my browser, Firefox launches my newsreader client and Ethereal reports that my client connects to the remote server at the NNTP port (119), sends an NNTP LIST command and Ethereal identifies the subsequent conversation as NNTP. If I were you I'd try handling news: URLs with nttplib. I bet it will work. Sorry I couldn't provide more than guesses. Good luck! -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From johnjsal at NOSPAMgmail.com Thu May 10 14:26:55 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 10 May 2007 14:26:55 -0400 Subject: Suggestions for how to approach this problem? In-Reply-To: References: <4640ca5b$0$23392$c3e8da3@news.astraweb.com> <4640d69b$0$31446$c3e8da3@news.astraweb.com> Message-ID: <46436430$0$23102$c3e8da3@news.astraweb.com> James Stroud wrote: > import re > records = [] > record = None > counter = 1 > regex = re.compile(r'^(\d+)\. (.*)') > for aline in lines: > m = regex.search(aline) > if m is not None: > recnum, aline = m.groups() > if int(recnum) == counter: > if record is not None: > records.append(record) > record = [aline.strip()] > counter += 1 > continue > record.append(aline.strip()) > > if record is not None: > records.append(record) > > records = [" ".join(r) for r in records] What do I need to do to get this to run against the text that I have? Is 'lines' meant to be a list of the lines from the original citation file? From castironpi at gmail.com Mon May 7 19:52:30 2007 From: castironpi at gmail.com (castironpi at gmail.com) Date: 7 May 2007 16:52:30 -0700 Subject: inspected console Message-ID: <1178581950.683620.251980@y80g2000hsf.googlegroups.com> Presents a console permitting inspection. Input as well as output saved in Python-readable form. Python 2.5.1 memoryconsole4.py logging to My Documents\console.log >>> class A: ... def f( self ): ... print 2 ... >>> a=A() >>> import inspect >>> inspect.getsource( a.f ) '\tdef f( self ):\n\t\tprint 2\n' This enabled by a log file, optionally set to console.log. Contents are: #Mon May 07 2007 06:33:42 PM Python win32 2.5.1 in memoryconsole4.py class A: def f( self ): print 2 a=A() import inspect inspect.getsource( a.f ) #fb: '\tdef f( self ):\n\t\tprint 2\n' Line 10 Microsoft Win32 convenience binding; line 49 a little confusing. Give it a shot. from code import InteractiveConsole import sys from os import environ from datetime import datetime from StringIO import StringIO from re import sub from os.path import join,split,abspath class LoggedStdOut(StringIO): deflog= environ['USERPROFILE']+\ '\\My Documents\\console.log' def __init__( self, log=None ): StringIO.__init__( self ) self.stdout= None self.trip,self.head= True,'' self.logname= log or LoggedStdOut.deflog self.prettyname=join(split(split(abspath( self.logname))[0])[1],split(abspath(self.logname))[1]) for x,_ in enumerate( open( self.logname,'r' ) ): continue self._lineno= x #can use linecache self._log= open( self.logname,'a' ) def catch( self,head='#fb: ' ): self.stdout= sys.stdout sys.stdout= self self.head= head self.trip= True def throw( self ): sys.stdout= self.stdout self.stdout= None def getlineno( self ): return self._lineno def logwrite( self, data ): self._log.write( data ) self._lineno+= data.count('\n') def logflush( self ): self._log.flush() def write( self, data ): datal= sub( '\n([^$])','\n%s\\1'%self.head,data ) if self.trip: self.logwrite( self.head ) self.logwrite( datal ) self.trip= data.endswith('\n') return self.stdout.write( data ) def writelines( self, data ): raise 'Branch uncoded' class LoggedInteractiveConsole(InteractiveConsole): def __init__( self,log=None,locals=None,filename=None ): self.out= LoggedStdOut( log ) if filename is None: filename= split(self.out.logname)[1] InteractiveConsole.__init__( self,locals,filename ) self.locals.update( __logname__= abspath( self.out.logname ) ) def push( self,line ): self.out.logwrite( '%s\n'%line ) self.out.logflush() self.out.catch() more= InteractiveConsole.push( self,line ) self.out.throw() return more def write( self,data ): return sys.stdout.write( data ) def interact( self,banner=None,*args ): self.out.logwrite( '\n#%s Python %s %s in %s\n'%\ ( datetime.now().strftime( '%a %b %d %Y %I:%M:%S %p' ), sys.platform,sys.version.split()[0], split(sys.argv[0])[1] ) ) if banner is None: banner=\ "Python %s %s logging to %s"%\ ( sys.version.split()[0],split(sys.argv[0])[1], self.out.prettyname ) return InteractiveConsole.interact( self,banner,*args ) import compiler import linecache class NotatedConsole(LoggedInteractiveConsole): """-Code object- intercepted in runsource, and rerun with stored source before runsource. Built-in runsource does not modify source between call and runcode.""" def runsource( self,sc,filename='',*args ): self._runsourceargs= sc,filename return LoggedInteractiveConsole.runsource( self,sc, filename,*args ) def runcode( self,*args ): sc,filename= self._runsourceargs linecache.checkcache( filename ) #custom second compile (fourth actually) t= compiler.parse( sc ) compiler.misc.set_filename( filename,t ) def set_lineno( tree, initlineno ): worklist= [ tree ] while worklist: node= worklist.pop( 0 ) if node.lineno is not None: node.lineno+= initlineno worklist.extend( node.getChildNodes() ) set_lineno( t,self.out.getlineno()-len( self.buffer )+1 ) code= compiler.pycodegen.\ InteractiveCodeGenerator( t ).getCode() LoggedInteractiveConsole.runcode( self,code ) linecache.checkcache( filename ) if __name__=='__main__': console= NotatedConsole() console.interact() From steve at holdenweb.com Wed May 30 14:47:51 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 30 May 2007 14:47:51 -0400 Subject: Appending a log file and see progress as program executes In-Reply-To: <5c5u8vF2v1pm3U2@mid.uni-berlin.de> References: <5c5u8vF2v1pm3U2@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Karim Ali schrieb: [...] > > install cygwin bash, and use > > tail out.log > I think Diez meant tail -f out.log 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From omelnyk at gmail.com Tue May 15 17:35:09 2007 From: omelnyk at gmail.com (Olexandr Melnyk) Date: Wed, 16 May 2007 00:35:09 +0300 Subject: Python Newbie Suggestions In-Reply-To: <1179264515.958714.72880@l77g2000hsb.googlegroups.com> References: <1179264515.958714.72880@l77g2000hsb.googlegroups.com> Message-ID: Byte of Python and Dive and Python as quite well-known books. -------------------------------------------------- Olexandr Melnyk, http://omelnyk.net/ 15 May 2007 14:28:36 -0700, garcigal at gmail.com : > > I'm a mechanical engineer with little experience programming. I've > used C++ and machine language for getting micro-controllers to work > and thats about it. I work allot with software developers at my job > and can read C++ code pretty good (ie. I understand whats going on). > Does anyone have any good tips or resources for someone interested in > learning PYTHON. This is purely for hobby purposes and I'd like to > expose my kids to a programing language too. If any one has any > helpful books, tips or suggestions please let me know. I have > Windows, MAC and Linux box's at my house but I'm a primarily a MAC > user. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Sun May 13 11:44:39 2007 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sun, 13 May 2007 17:44:39 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers Message-ID: <46473267$0$31532$9b622d9e@news.freenet.de> PEP 1 specifies that PEP authors need to collect feedback from the community. As the author of PEP 3131, I'd like to encourage comments to the PEP included below, either here (comp.lang.python), or to python-3000 at python.org In summary, this PEP proposes to allow non-ASCII letters as identifiers in Python. If the PEP is accepted, the following identifiers would also become valid as class, function, or variable names: L?ffelstiel, chang?, ??????, or ??? (hoping that the latter one means "counter"). I believe this PEP differs from other Py3k PEPs in that it really requires feedback from people with different cultural background to evaluate it fully - most other PEPs are culture-neutral. So, please provide feedback, e.g. perhaps by answering these questions: - should non-ASCII identifiers be supported? why? - would you use them if it was possible to do so? in what cases? Regards, Martin PEP: 3131 Title: Supporting Non-ASCII Identifiers Version: $Revision: 55059 $ Last-Modified: $Date: 2007-05-01 22:34:25 +0200 (Di, 01 Mai 2007) $ Author: Martin v. L?wis Status: Draft Type: Standards Track Content-Type: text/x-rst Created: 1-May-2007 Python-Version: 3.0 Post-History: Abstract ======== This PEP suggests to support non-ASCII letters (such as accented characters, Cyrillic, Greek, Kanji, etc.) in Python identifiers. Rationale ========= Python code is written by many people in the world who are not familiar with the English language, or even well-acquainted with the Latin writing system. Such developers often desire to define classes and functions with names in their native languages, rather than having to come up with an (often incorrect) English translation of the concept they want to name. For some languages, common transliteration systems exist (in particular, for the Latin-based writing systems). For other languages, users have larger difficulties to use Latin to write their native words. Common Objections ================= Some objections are often raised against proposals similar to this one. People claim that they will not be able to use a library if to do so they have to use characters they cannot type on their keyboards. However, it is the choice of the designer of the library to decide on various constraints for using the library: people may not be able to use the library because they cannot get physical access to the source code (because it is not published), or because licensing prohibits usage, or because the documentation is in a language they cannot understand. A developer wishing to make a library widely available needs to make a number of explicit choices (such as publication, licensing, language of documentation, and language of identifiers). It should always be the choice of the author to make these decisions - not the choice of the language designers. In particular, projects wishing to have wide usage probably might want to establish a policy that all identifiers, comments, and documentation is written in English (see the GNU coding style guide for an example of such a policy). Restricting the language to ASCII-only identifiers does not enforce comments and documentation to be English, or the identifiers actually to be English words, so an additional policy is necessary, anyway. Specification of Language Changes ================================= The syntax of identifiers in Python will be based on the Unicode standard annex UAX-31 [1]_, with elaboration and changes as defined below. Within the ASCII range (U+0001..U+007F), the valid characters for identifiers are the same as in Python 2.5. This specification only introduces additional characters from outside the ASCII range. For other characters, the classification uses the version of the Unicode Character Database as included in the ``unicodedata`` module. The identifier syntax is `` *``. ``ID_Start`` is defined as all characters having one of the general categories uppercase letters (Lu), lowercase letters (Ll), titlecase letters (Lt), modifier letters (Lm), other letters (Lo), letter numbers (Nl), plus the underscore (XXX what are "stability extensions" listed in UAX 31). ``ID_Continue`` is defined as all characters in ``ID_Start``, plus nonspacing marks (Mn), spacing combining marks (Mc), decimal number (Nd), and connector punctuations (Pc). All identifiers are converted into the normal form NFC while parsing; comparison of identifiers is based on NFC. Policy Specification ==================== As an addition to the Python Coding style, the following policy is prescribed: All identifiers in the Python standard library MUST use ASCII-only identifiers, and SHOULD use English words wherever feasible. As an option, this specification can be applied to Python 2.x. In that case, ASCII-only identifiers would continue to be represented as byte string objects in namespace dictionaries; identifiers with non-ASCII characters would be represented as Unicode strings. Implementation ============== The following changes will need to be made to the parser: 1. If a non-ASCII character is found in the UTF-8 representation of the source code, a forward scan is made to find the first ASCII non-identifier character (e.g. a space or punctuation character) 2. The entire UTF-8 string is passed to a function to normalize the string to NFC, and then verify that it follows the identifier syntax. No such callout is made for pure-ASCII identifiers, which continue to be parsed the way they are today. 3. If this specification is implemented for 2.x, reflective libraries (such as pydoc) must be verified to continue to work when Unicode strings appear in ``__dict__`` slots as keys. References ========== .. [1] http://www.unicode.org/reports/tr31/ Copyright ========= This document has been placed in the public domain. From carsten at uniqsys.com Tue May 8 11:36:45 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 08 May 2007 11:36:45 -0400 Subject: XLRD Python 2.51 Question In-Reply-To: <1178638018.606763.162650@e51g2000hsg.googlegroups.com> References: <1178638018.606763.162650@e51g2000hsg.googlegroups.com> Message-ID: <1178638605.3357.52.camel@dot.uniqsys.com> On Tue, 2007-05-08 at 08:26 -0700, kylancal at gmail.com wrote: > CompDocError: MSAT extension: accessing sector 1717046 but only 2887 > in file > > I am not sure what this means at all At least superficially that sounds like the file you're trying to open is truncated or otherwise corrupted to the point where xlrd doesn't know what to do with it. What happens if you try to open the file with Excel? If Excel manages to open the file, maybe the file is using a storage format that's newer than what xlrd is prepared to handle. In that case, try saving the file to a different file name as another format (such as Excel 97) that xlrd should be able to handle. HTH, -- Carsten Haese http://informixdb.sourceforge.net From tjreedy at udel.edu Fri May 25 14:39:39 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 25 May 2007 14:39:39 -0400 Subject: Newsgroups and mailing lists (was Re: Slightly OT: Why all thespam?) References: <3bb44c6e0705220008y10f5deb7v86ed82d3f8241761@mail.gmail.com> Message-ID: "Steve Holden" wrote in message news:f36kc1$hq3$2 at sea.gmane.org... | I *did* try to explain all this a week or two ago. Did I not make myself clear? I could ask the same. Quoting from that post: | All I am saying is that it's difficult to catch *everything* when so | much of the content comes in via Usenet. These posts never touch any | python.org infrastructure before being incorporated into the newsgroup | content on servers all over the world. I am completely aware of that. But *I* am talking about posts which I believe *do* touch python.org on the way to gmane. And please note that I asked for (but have not gotten a response to) verification of that belief before complaining . | Looking at the headers in one of the messages you were writing about it | appears they are being posted from Google groups, so maybe you could | complain to them. Good luck with that ;-). I think most everything I have looked at recently came from Google groups or Google mail. Perhaps they considered themselved immune from the usenet death penalty of being cutoff from the rest of usenet for not controlling their own spammers. Or, I suppose, perhaps their current resources are overwhelmed. In either case, being from Google should be a point toward spamishness. | The Python list managers know what they are doing, Things were fine on the gmane side until a few months ago. Then what they knew started to slip, it seems. | and they *do* keep a huge amount of spam off the list. I have previously thanked them publicly. | The occasional piece gets through For the past several months, it has been several a day, not 'the occasional piece ... from time to time'. Much was repeated (>1/day) leftist political postings from the same sources WITH SUBJECT LINES IN CAPS, MAKING THEM VERY NOTICEABLE to even the most cursory scan, whether by person or program. *If* it was indeed coming thru py.org, they I would have expected it to have been stopped (or stopped sooner). This discussion group, with its three versions, is one of the public faces of Python. A dirty, junky group is bad public relations for Python. When the current spam wave started, nobody said much for a couple of months at least. I, and perhaps others, expected the 'we know what we are doing' system to respond. These 'why spam' threads only started when it did not seem to. They constitute fair and valid public feedback. I notice today that there is no spam in 80 messages. A good sign I hope. Terry Jan Reedy From showell30 at yahoo.com Mon May 28 15:38:04 2007 From: showell30 at yahoo.com (Steve Howell) Date: Mon, 28 May 2007 12:38:04 -0700 (PDT) Subject: ten small Python programs In-Reply-To: Message-ID: <583479.11941.qm@web33502.mail.mud.yahoo.com> --- Stef Mientki wrote: > > > >> It would even be nicer, if everybody could drop > >> her/his examples > >> in a standard way, so they would be automatically > >> incorporated in > >> something like the wxPython interactive demo. > >> > > > > Can you elaborate? > > Well if you see the above demo, > I've the following in mind: > - create a new-demo in a special directory > - add some special keywords in the new-demo, in > which treenodes it should popup > - on restart of the demo, the new-demo is added to > the tree > To the extent that you just want a group of people to be able to organically organize a tree-like collection of Python examples, you could use a MoinMoin that has sensible page names and the Local Site Map featured turn on. Are you also suggesting the need for something local, so that you can actually run the programs? ____________________________________________________________________________________Luggage? GPS? Comic books? Check out fitting gifts for grads at Yahoo! Search http://search.yahoo.com/search?fr=oni_on_mail&p=graduation+gifts&cs=bz From bik.mido at tiscalinet.it Thu May 3 04:15:29 2007 From: bik.mido at tiscalinet.it (Michele Dondi) Date: Thu, 03 May 2007 10:15:29 +0200 Subject: Responding to Trolls [was Re: ignorance and intolerance in computing communties] References: <1178120019.271716.299590@e65g2000hsc.googlegroups.com> Message-ID: <3f6j33dccko0friap4a9geoigndldp2u3u@4ax.com> On Thu, 03 May 2007 14:54:21 +1000, Steven D'Aprano wrote: >Subject: Responding to Trolls [was Re: ignorance and intolerance in computing communties] Nope. No way. Michele -- {$_=pack'B8'x25,unpack'A8'x32,$a^=sub{pop^pop}->(map substr (($a||=join'',map--$|x$_,(unpack'w',unpack'u','G^ Hi, If I have a button widget w = Button(root, text = "Button", state = 'disabled') How can I get the value of option 'state' from the widget 'w'. I want something like -- print w.state >> to print out >> 'disabled' Thanks Rahul From jstroud at mbi.ucla.edu Sat May 5 02:37:11 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 04 May 2007 23:37:11 -0700 Subject: Firefighters at the site of WTC7 "Move away the building is going to blow up, get back the building is going to blow up." In-Reply-To: <1178346041.557106.129670@y80g2000hsf.googlegroups.com> References: <1178161820.731367.264500@y80g2000hsf.googlegroups.com> <1hlj33p6aq838o2urk1dv6h75b5is4i2vd@4ax.com> <3TD_h.219$mR2.195@newssvr22.news.prodigy.net> <1178329932.455122.161530@u30g2000hsc.googlegroups.com> <1178346041.557106.129670@y80g2000hsf.googlegroups.com> Message-ID: MooseFET wrote: > On May 4, 8:19 pm, James Stroud wrote: >> MooseFET wrote: >>> On May 4, 12:32 pm, James Stroud wrote: >>> [....] >>>> The Marxist contribution to western thought is that it put everything in >>>> terms of labor and thus allowed us to quantify the human component of >>>> economies. >>> No the great insight by Marx was in the selling of ducks. "Anybody >>> want to buy a duct" has done more to advance economic thinking than >>> the works of most economists. >>> Economists have a vested interest in preventing people from >>> understanding economics. They are well paid and know that they >>> wouldn't be for long if people really understood what was going on. >> You must be an economist because you provide absolutely no >> interpretation of what the hell you were saying in ghe first paragraph >> (as if you actually know what you were trying to say). Duct or duck, >> first of all. Second of all--make a point. > > Groucho Marx. > > You could have convinced me that Karl Marx was in the duck business because I wouldn't think anyone on any of these lists would be banal enough to use such a well worn joke. From python at rcn.com Mon May 28 13:29:48 2007 From: python at rcn.com (Raymond Hettinger) Date: 28 May 2007 10:29:48 -0700 Subject: itertools.groupby In-Reply-To: <1180366451.826290.142430@m36g2000hse.googlegroups.com> References: <1180295221.3163.9.camel@localhost.localdomain> <1180313441.598026.198230@d30g2000prg.googlegroups.com> <1180366451.826290.142430@m36g2000hse.googlegroups.com> Message-ID: <1180373388.112182.225700@i13g2000prf.googlegroups.com> On May 28, 8:34 am, 7stud wrote: > >- there are two more examples on the next page. those two > > examples also give sample inputs and outputs. > > I didn't see those. Ah, there's the rub. The two sections of examples and recipes are there for a reason. This isn't a beginner module. It is full of high-speed optimizations applied in a functional style. That's not for everyone, so it isn't a loss if someone sticks with writing plain, clear everyday Python instead of an itertool. Raymond From rene at korteklippe.de Wed May 16 03:12:40 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Wed, 16 May 2007 09:12:40 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <46478694$0$1412$426a34cc@news.free.fr> <1hy252p.1anf7sr1p4yp12N%aleax@mac.com> <464988a4$0$20289$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <464aaee8$0$10188$9b4e6d93@newsspool4.arcor-online.net> Steven D'Aprano schrieb: > But they aren't new risks and problems, that's the point. So far, every > single objection raised ALREADY EXISTS in some form or another. No. The problem "The traceback shows function names having characters that do not display on most systems' screens" for example does not exist today, to the best of my knowledge. And "in some form or another" basically means that the PEP would create more possibilities for things to go wrong. That things can already go wrong today does not mean that it does not matter if we create more occasions were things can go wrong even worse. > There's > all this hysteria about the problems the proposed change will cause, but > those problems already exist. When was the last time a Black Hat tried to > smuggle in bad code by changing an identifier from xyz0 to xyzO? Agreed, I don't think intended malicious use of the proposed feature would be a big problem. >> I think it is not. I think that the problem only really applies to very >> isolated use-cases. > > Like the 5.5 billion people who speak no English. No. The X people who speak "no English" and program in Python. I think X actually is very low (close to zero), because programming in Python virtually does require you to know some English, wether you can use non-ASCII characters in identifiers or not. It is naive to believe that you can program in Python without understanding any English once you can use your native characters in identifiers. That will not happen. Please understand that: You basically *must* know some English to program in Python, and the reason for that is not that you cannot use non-ASCII identifiers. I admit that there may be occasions where you have domain-specific terms that are hard to translate into English for a programmer. But is it really not feasible to use an ASCII transliteration in these cases? This does not seem to have been such a big problem so far, or else we would have seen more discussions about it, I think. >> So isolated that they do not justify a change to >> mainline Python. If someone thinks that non-ASCII identifiers are really >> needed, he could maintain a special Python branch that supports them. I >> doubt that there would be alot of demand for it. > > Maybe so. But I guarantee with a shadow of a doubt that if the change > were introduced, people would use it -- even if right now they say they > don't want it. Well, that is exactly what I would like to avoid ;-) -- Ren? From ptmcg at austin.rr.com Sat May 19 07:39:58 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 19 May 2007 04:39:58 -0700 Subject: Typed named groups in regular expression In-Reply-To: <1179552763.278347.163300@e65g2000hsc.googlegroups.com> References: <1179552763.278347.163300@e65g2000hsc.googlegroups.com> Message-ID: <1179574798.034285.65120@o5g2000hsb.googlegroups.com> On May 19, 12:32 am, Paddy wrote: > On May 16, 6:58 pm, "Hugo Ferreira" wrote: > > > Hi! > > > Is it possible to "automagically" coerce the named groups to python types? e.g.: > > > >>> type(re.match('(?P\d*)', '123').groupdict()['x']) > > > > > > But what I'm looking forward is for the type to be 'int'. > > > Cheers! > > > Hugo Ferreira > > If you do a ot of that sort of thing in many programs > then it might be worth your while to set up a framework > that does it. Something like adding an underscore > then the name of a type conversion function to all > group names, and creating a function to apply the > type convertion function to all named groups of a > match object. > - Paddy. pyparsing might just be this sort of framework, in that you can attach parse actions to elements within a grammar. At parse time, the parse action is called with the list of tokens currently matched. >>> from pyparsing import Regex >>> re = Regex( r"(\d*)" ).setResultsName("x")\ ... .setParseAction(lambda t:int(t[0])) >>> results = re.parseString("123") >>> print results.x 123 -- Paul From irmen.NOSPAM at xs4all.nl Sat May 19 10:05:21 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Sat, 19 May 2007 16:05:21 +0200 Subject: ANN: Pyro 3.7 (remote objects) Message-ID: <464f0427$0$322$e4fe514c@news.xs4all.nl> I'm happy to announce Pyro 3.7 -- Python's own powerful remote method invocation technology! You can get it via http://pyro.sourceforge.net, then go to the SF project homepage download area. This is a small improvement release since Pyro 3.6. New stuff: - bdist_rpm typo fix in setup.cfg - renamed all batch files with 'pyro-' prefix to avoid name clashes (debian package already had this) - NS broadcast retries are a bit faster now - Pyro.core.SynchronizedObjBase now correctly handles string exceptions - the NS nt service won't respond to shutdown requests anymore - wxnsc updated to recent WxPython API, deprecation warning is gone Have fun, and thanks for your interest, support, and feedback! --Irmen de Jong ---> What is Pyro? Pyro is an acronym for PYthon Remote Objects. Pyro is an advanced and powerful Distributed Object Technology system written entirely in Python, that is designed to be very easy to use. It is extremely easy to implement a distributed system with Pyro, because all network communication code is abstracted and hidden from your application. You just get a remote Python object and invoke methods on the object on the other machine. Pyro offers you a Name Server, an Event Service, mobile objects, remote exceptions, dynamic proxies, remote attribute access, automatic reconnection, a very good and detailed manual, and many examples to get you started right away. From mcl.office at googlemail.com Sat May 5 04:50:46 2007 From: mcl.office at googlemail.com (mosscliffe) Date: 5 May 2007 01:50:46 -0700 Subject: Newbie and Page Re-Loading In-Reply-To: <1178313011.279170.292200@u30g2000hsc.googlegroups.com> References: <1178275290.158007.248180@h2g2000hsg.googlegroups.com> <463b6678$0$10433$426a34cc@news.free.fr> <1178302555.479739.227920@o5g2000hsb.googlegroups.com> <1178313011.279170.292200@u30g2000hsc.googlegroups.com> Message-ID: <1178355046.841131.43700@n76g2000hsh.googlegroups.com> Miki, Thank you very much for your helpful reply. A simple example is the best way of getting started, I have found. I have no excuses now - to not get it working. I recently tried Visual Studio with Visual Basic. Nice for five minutes, but then all the helping bits got in the way, so then you try to do it all yourself and the logic behind 'viewstate' just seemed to do different things at different times and my silver surfing brain, just wants to do things, rather than learn all sorts of exceptions, which I will not remember tomorrow, never mind the next week or month. I will try the local server, after I get forms working. A question for the future. I am creating several spreadsheets on google which contain data, I need to search and display on my web page. The data is quite large so I need to filter it as opposed to just looking at the spreadsheet. Am I right in thinking there is something called an 'atom' feed, which will supply me the data from google as a 'cursor' (think it is an SQL term) and I can read the rows as records in python ? Thanks again Richard On May 4, 10:10 pm, Miki wrote: > Hello Richard, > > > I do not want to run a framework yet. I would like to understand > > python at script level, before adding more aspects to learn, like > > frameworks. > > The way CGI works is that your script is called every time the > corresponding HTML is loaded. You can access all the parameters sent > to the script using cgi.FieldStorage. > > > I think I get your idea about hidden fields and how to alter them. > > Note that hidden fields are passed in plain text format from/to the > server, don't send anything sensitive in them. > > > My single page script should work something like this > > > DisplayHTMLHeaderandBodyHeader > > Check if this is a Re-Load (HiddenField would not exist first time I > > am assuming) > > It could be None: cgi.FieldStorage().getvalue("hidden_attribute") == > None > > > Display SearchSection with previous SearchRequest > > If SearchRequest is True: Get and Display Results > > Display TrailerHTMLandTrailerBody > > > ......... Wait for NewSearch or NextPage > > In CGI you don't wait, the script exists and called again when use > hits a button/refresh ... > > > Does the above make sense or is there a better way ? > > There are many other ways (AJAX, Web frameworks, FastCGI ...). However > I'd recommend you start with plain CGI which is *simple*. > Here is a small example: > #!/usr/local/bin/python > > import cgitb; cgitb.enable() # Show errors in HTML output > from cgi import FieldStorage > > FUNNY = [ "mickey", "donald", "daisy", "minnie", "goofy" ] > > def main(): > print "Content-Type: text/html" > print > > form = FieldStorage() > query = form.getvalue("query", "") > > print ''' >

    Disney Search

    > >
    > > > ''' % query > > if query: > for someone in FUNNY: > if query in someone: > print "
    %s" % someone > > print "
    " > > if __name__ == "__main__": > main() > > > How do I get the directory of my modules into the Python Path > > import sys > sys.path.append("/path/to/my/modules") > > Note that your script directory is automatically added to the path. > > > Is there a lightweight Https Server I could run locally (WINXP), which > > would run .py scripts, without lots of installation modifications ? > > http://lighttpd.net. > Make sure "mod_cgi" is uncommented, set your document root and set > right python interpreter in cgi.assign > > HTH, > -- > Miki http://pythonwise.blogspot.com From bbxx789_05ss at yahoo.com Sun May 27 12:06:37 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 27 May 2007 09:06:37 -0700 Subject: PHP5 programmer learning Python In-Reply-To: <1180280496.946434.26760@q69g2000hsb.googlegroups.com> References: <1180280496.946434.26760@q69g2000hsb.googlegroups.com> Message-ID: <1180281997.755970.194030@k79g2000hse.googlegroups.com> On May 27, 9:41 am, romiro wrote: > Hi all, > > I'm a PHP5 developer looking to "broaden my horizons" so to speak by > learning a new language. I emphasize the 5 in PHP since I have fully > engrossed myself in the full OOP of version 5 with my own ground-up > projects as well as some work with PRADO (http://pradosoft.com) > > I've dabbled with a number of languages in the past, Python being no > exception, but always ended up coming back to PHP due to being > comfortable with it. Python has stuck to me as a language I _really_ > think I should know more about. I've recently tried C#, a very short > lived re-attempt at C++ and Java, and Ruby. None of those seemed > "fun" except for Ruby, although from what I've seen the syntax between > Ruby and Python are very similar to each other compared to the other > languages. > > Anyway, my first question was if anyone knows of a tutorial that > focuses on PHP -> Python learning, in such that there might be a block > of PHP code alongside an example of how to do the same thing in > Python. One example of something I've already mapped a comparison to > thanks to standard tutorials is a PHP numeric indexed array being > similar to a list and a PHP associative array being similar to a > dictionary. Of course finding such of a tutorial isn't a deal breaker > by any means, but I figured that having it available would be a boon > for me to actually make some headway in my Python learning adventure. > > If there's anything else that could be said about the migration > between the two languages, I'm all ears. I also don't really need to > hear about how "disgusting" php is as a language...I am aware of the > contained chaos that is PHP4, which is why I develop strictly in 5 > using its OOP to the extent my feeble brain allows, a wariness toward > the insecure pitfalls the language has begat in the past, and an > attempt to produce as clean of a syntax as the language can allow. > > Thanks in advance for any help. Read "Learning Python(2nd ed)" and do all the exercises. If you have questions, post them. From sjmachin at lexicon.net Sun May 6 08:16:39 2007 From: sjmachin at lexicon.net (John Machin) Date: 6 May 2007 05:16:39 -0700 Subject: change of random state when pyc created?? In-Reply-To: <1178451709.085624.226940@u30g2000hsc.googlegroups.com> References: <1178408359.113807.181570@l77g2000hsb.googlegroups.com> <1178451709.085624.226940@u30g2000hsc.googlegroups.com> Message-ID: <1178453799.048907.192110@l77g2000hsb.googlegroups.com> On May 6, 9:41 pm, Dustan wrote: > On May 6, 1:00 am, Steven D'Aprano > > > > wrote: > > On Sun, 06 May 2007 00:20:04 +0000, Alan Isaac wrote: > > >> Should you not expect to get the same result each time? Is that not > > >> the point of setting a constant seed each time you run the script? > > > > Yes. That is the problem. > > > If I delete module2.pyc, > > > I do not get the same result. > > > I think you have missed what John Machin is pointing out. According to > > your original description, you get different results even if you DON'T > > delete module2.pyc. > > > According to your original post, you get the _same_ behaviour the first > > time you run the script, regardless of the pyc file being deleted or not. > > > You wrote: > > > [quote] > > module1 sets a seed like this:: > > > if __name__ == "__main__": > > random.seed(314) > > main() > > > I execute module1.py from the (Windows) shell. > > I get a result, let's call it result1. > > I execute it again. I get another result, say result2. > > Running it again and again, I get result2. > > [end quote] > > > So, with module2.pyc file existing, you get result1 the first time you > > execute module1.py, and then you get result2 every time from then onwards. > > Umm... no. > > module2.pyc is created by the first run. > Yes, I've realised that too. Some news: (1) Alan has sent Dustan and me a second smaller version of the two files. I'll forward them on to Steven -- they're now called test.py and test1.py, but I'll continue to call them module[12].py (2) The problem is definitely reproducible -- whether or not module2.pyc has been deleted or retained from the previous run is affecting the results. [Windows XP SP2; Python 2.5.1] (3) module2.py appears to me not to be guilty of causing any changes in state; it contains only rather inocuous functions and classes. (4) I have put print random.getstate() before and after the call to main() in the executed script (module1.py). Diffing the stdout of a no-pyc run and a with-pyc run shows differences in Alan's output but NO DIFFERENCES in either the "before" or the "after" random.getstate() output. Looks like the problem is nothing to do with the random module. (5) I have backported the files to Python 2.4 by replacing the use of defaultdict in module2.py with explicit "if key in the_dict" code -- now the problem is reproducible with Python 2.4.3 as well as with 2.5.1. (6) I've changed the 'from module2 import foo, bar, zot; foo()" to use the "import module2; module2.foo()" style -- no effect; still has the problem. Cheers, John From irmen.NOSPAM at xs4all.nl Wed May 30 03:07:36 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Wed, 30 May 2007 09:07:36 +0200 Subject: Periodic tasks. In-Reply-To: <1180420430.610215.96330@a26g2000pre.googlegroups.com> References: <1180420430.610215.96330@a26g2000pre.googlegroups.com> Message-ID: <465d22b8$0$325$e4fe514c@news.xs4all.nl> Ramashish Baranwal wrote: > Hi, > > I am trying to execute some tasks periodically, those familiar with > unix can think of it as equivalent to cron jobs. I have tried looking > around, but couldn't find a way. Would appreciate any pointers or > clues.. > > Thanks, > -Ram > Have a look at Kronos, a simple task scheduler I wrote a while ago, based on sched. It's part of Turbogears as well: http://trac.turbogears.org/browser/trunk/turbogears/scheduler.py --Irmen From kay.schluehr at gmx.net Mon May 28 11:48:30 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 28 May 2007 08:48:30 -0700 Subject: speeding things up with C++ In-Reply-To: <1180171179.687276.77930@z28g2000prd.googlegroups.com> References: <1180171179.687276.77930@z28g2000prd.googlegroups.com> Message-ID: <1180367310.156165.177650@m36g2000hse.googlegroups.com> On May 26, 11:19 am, bullockbefriending bard wrote: > I've done all the requisite profiling and thought fairly deeply about > the efficiency of my python code, but am still going to have to speed > up the innermost guts of what I am doing. > > Essentially, I need to pass a list of 6-tuples containing only > integers to my new sadly necessary super-fast compiled language > function which i am not looking forward to writing: > > input: [(1,2,3,4,5,6), (7,8,9,10,11,12),...] > > and after much thrashing of processor resources, return data which > looks like this to the Python calling environment: > > output: [( (1, 2), (1,), (12,), (13), (1, 7, 11), (9,) ), ( another > nested tuple like preceding one ), .... ] > > Each member of the returned list is a tuple containing 6 tuples, and > each of those 6 tuples has at least one integer member. It would also > be acceptable for the return values to be entirely nested lists > instead of having the two innermost sequence types as tuples. > > I probably want to be using something like C++ because i'm going to > need to use STL vectors and sets for what i'm doing in the algorithm > i'm trying to speed up. IIRC Boost tuple is a bit painful for more > than 10 elements + isn't really essential that I use a a non-mutable > data type in what will be a small encapsulated bit of a much larger > system. > > Anyway, I can probably very quickly figure out some hacked way to get > the data into my function given that in the worst case I could take > advantage of the knowledge that each input tuple always has 6 > elements, and simply pass in a big array of ints. Yes, I know this is > a bit retarded, but I'm talking worst case assuming on very tight > schedule and no time to delve deeply into SWIG or whatever. Similarly > it wouldn't be too difficult to return the result as the mother all of > all strings which i could then parse fairly easily. > > However, I hope someone reading this will be able to tell me that I'm > being a total pessimist and that in fact it isn't very difficult to do > what I want to do using SWIG. I'm not asking for a complete solution, > more like some general pointers from someone who has actually done > something similar before. > > As an added bonus, I wouldn't if this is 'easily' doable using Ocaml > as the guts instead of C++, I'd be happy to know about it. A just too obvious recommendation is to drop C++ and use D together with the Pyd/celerid bridge. Yeah, it sounds a little esoteric but D is really the Python among the statically typed imperative languages. http://www.digitalmars.com/d/ http://pyd.dsource.org/index.html From paddy3118 at googlemail.com Sun May 13 03:32:52 2007 From: paddy3118 at googlemail.com (Paddy) Date: 13 May 2007 00:32:52 -0700 Subject: Off Topic: Is the use of supererogatory supererogatory? In-Reply-To: <1hy0cy8.eg6p1p135hbo3N%aleax@mac.com> References: <1178986686.510137.195490@p77g2000hsh.googlegroups.com> <1178991933.421386.58500@u30g2000hsc.googlegroups.com> <1178992910.318929.77790@e51g2000hsg.googlegroups.com> <1178995630.925969.207740@w5g2000hsg.googlegroups.com> <1hy0cy8.eg6p1p135hbo3N%aleax@mac.com> Message-ID: <1179041572.791862.293010@h2g2000hsg.googlegroups.com> On May 13, 12:13 am, a... at mac.com (Alex Martelli) wrote: > As somebody else alredy pointed out, the lambda is supererogatory (to > say the least). What a wonderful new word! I did not know what supererogatory meant, and hoped it had nothing to do with Eros :-) Answers.com gave me a meaning synonymous with superfluous, which I think is what was meant here, but Chambers gave a wonderful definition where they say it is from the RC Church practice of doing more devotions than are necessary so they can be 'banked' for distribution to others (I suspect, that in the past it may have been for a fee or a favour). Supererogatory, my word of the day. - Paddy P.S; http://www.chambersharrap.co.uk/chambers/features/chref/chref.py/main?query=supererogatory+&title=21st From mad.vijay at gmail.com Wed May 23 05:05:06 2007 From: mad.vijay at gmail.com (SamG) Date: 23 May 2007 02:05:06 -0700 Subject: OSError[Error 5] In-Reply-To: <1179866393.429055.18680@r3g2000prh.googlegroups.com> References: <1179831143.709611.61580@b40g2000prd.googlegroups.com> <1179866393.429055.18680@r3g2000prh.googlegroups.com> Message-ID: <1179911106.161009.193050@h2g2000hsg.googlegroups.com> On May 23, 1:39 am, Miki wrote: > Hello SamG, > > > I do this on PowerPC.. > > > >>> import os > > >>> os.listdir('/usr/bin') > > > And endup getting this ... > > > OSError: [Error 5] Input/output error:/usr/bin > > What happens when you run "ls /usr/bin" in the terminal? > > HTH, > -- > Miki http://pythonwise.blogspot.com I get a perfect listing of /usr/bin folder. From phil at riverbankcomputing.co.uk Tue May 29 07:18:47 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Tue, 29 May 2007 12:18:47 +0100 Subject: PyQt: Is signal / slot really working across threads? In-Reply-To: References: Message-ID: <200705291218.47239.phil@riverbankcomputing.co.uk> On Tuesday 29 May 2007 11:58 am, Alexander Eisenhuth wrote: > Hello pyqt users, > > i tried to use signal / slot across threads. With the following example I > want to emit a signal when the thread loop is entered. The connected slot > is never called. Why? > > Any help is very welcome ... > > Alexander > > import time > import sys > import PyQt4 > from PyQt4.QtCore import (QObject, QThread) > SIGNAL = PyQt4.QtCore.SIGNAL > > class CancelableQtThread_(QThread): > > def __init__(self): > QThread.__init__(self) > self.sigStarted = SIGNAL("sigStarted()") > > def run(self): > print "Enter thread" > self.emit(self.sigStarted) > time.sleep(0.1) > print "Leave thread" > > class TestSigSlot(QObject): > > def __init__(self): > QObject.__init__(self) > self._thread = CancelableQtThread_() > self.connect(self._thread, self._thread.sigStarted, self.Called) > self._thread.start() > > time.sleep(1.0) > > def Called(self): > print "Called !" > > if __name__ == "__main__": > obj = TestSigSlot() Signals across threads are implemented using the event loop. You don't have an event loop running in your main thread - you don't even have a QCoreApplication instance. Phil From newsuser at stacom-software.de Thu May 31 09:01:29 2007 From: newsuser at stacom-software.de (Alexander Eisenhuth) Date: Thu, 31 May 2007 15:01:29 +0200 Subject: PEP 8 style enforcing program In-Reply-To: <1180613790.317480.314600@p47g2000hsd.googlegroups.com> References: <1180613790.317480.314600@p47g2000hsd.googlegroups.com> Message-ID: montyphyton at gmail.com schrieb: > Some recent posts about Python programming style got me thinking. > Since we have the PEP 8 which gives some guidelines about the style to > be used, do we have any program that can check for violations of these > guidelines within the source code? I understand that there are a lot > of code beautifiers out there, but i haven't seen one specially > tailored for Python... Is there even a desire in Python community for > a program like this (by Python community I mean the people in this > group:) ) ? I think it would be a nice little project for practice and > I'd like to do it, but if there is already something like this then I > can probably spend my time on something more productive. So, I'd like > to hear your opinion on this... > There is one thing that I don't understand about PEP 8 - why is using > spaces considered more desirable than using tabs for indentation? > Pylint is one of them (http://www.logilab.org/857) With spaces you get always the same len of the line, where tabs can use 2,4,8 spaces, dependingt on the settings of the IDE Alexander From __peter__ at web.de Wed May 30 03:24:30 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 30 May 2007 09:24:30 +0200 Subject: print bypasses calling write method for objects inheriting from file? References: <1180508789.556984.204520@o11g2000prd.googlegroups.com> Message-ID: MisterPete wrote: > I created an object that inherits from file and was a bit surprised to > find that print seems to bypass the write method for objects > inheriting from file. An optimization I suppose. Does this surprise > anyone else at all or am I missing something? No, your analysis is correct, though I'd consider optimization an euphemism for bug here. Noone was annoyed enough to write a patch, it seems. Peter From wgwigw at gmail.com Tue May 29 20:30:52 2007 From: wgwigw at gmail.com (momobear) Date: 29 May 2007 17:30:52 -0700 Subject: Speex bindings for python 2.5 In-Reply-To: <1180467121.238065.111720@r19g2000prf.googlegroups.com> References: <1180466922.114571.46410@d30g2000prg.googlegroups.com> <1180467121.238065.111720@r19g2000prf.googlegroups.com> Message-ID: <1180485052.149837.105080@a26g2000pre.googlegroups.com> > I forgot to give the url :http://www.freenet.org.nz/python/pySpeex/ I Couldn't Open the website. From http Tue May 22 23:17:10 2007 From: http (Paul Rubin) Date: 22 May 2007 20:17:10 -0700 Subject: howto check does module 'asdf' exist? (is available for import) References: <1179753436.736228.321400@x35g2000prf.googlegroups.com> <1179818823.916836.226090@r3g2000prh.googlegroups.com> <7xsl9ox2ld.fsf@ruckus.brouhaha.com> Message-ID: <7xtzu4jkjt.fsf@ruckus.brouhaha.com> kaens writes: > I think that's there because you just wanted to check if it was > available for import, implying that you didn't actually want to import > it right then. Whether it's available for import and whether you've already imported it are two separate questions. Maybe you said "import fghj as asdf" and now you want to find out if there's another module actually named asdf. It would be cleaner if there's a method with no side effects. From jstroud at mbi.ucla.edu Thu May 10 17:58:07 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 10 May 2007 14:58:07 -0700 Subject: searching algorithm In-Reply-To: <7dydnfjNWbo9H97bnZ2dnUVZ_oupnZ2d@comcast.com> References: <7dydnfjNWbo9H97bnZ2dnUVZ_oupnZ2d@comcast.com> Message-ID: Gordon Airporte wrote: > >> For the above (abrideged) dictionary, you would generate (use a >> fixed-width "programmers" font so the tree looks good): >> >> a >> | >> b >> | >> s >> / \ >> i o >> / / \ >> n l r >> / / \ \ >> t u v b->(absorbirati, crpisti) >> / | | >> (pelin)<-h t e->(odrije?iti, osloboditi) >> | | >> (pelin)<-e e->(apsolutan, apsolutni kod) >> >> As the user enter letters, you just march down the tree, printing >> all the words held in leaf nodes held in the current node. >> > > Call me dense, but how does one do this in Python - which doesn't have > pointers? Dictionaries with dictionaries within dictionaries... (with > each letter as the key and the its children as values) is going to be > extremely space inefficient, right? How would this be significantly more space inefficient than "pointers"? The implementation of the dict would, in fact, itself be pointers, where each key (same memory requirement if using pointers) is mapped to a pointer to a dict node or a pointer to a leaf, same as with a more "low level" construction. A printout of the graph as a dict might look a little ugly, though. I could be wrong, however. James From kyosohma at gmail.com Wed May 30 10:05:13 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 30 May 2007 07:05:13 -0700 Subject: Python 2.5 and WXPython demo's In-Reply-To: <974af$465d6e19$83aef404$30110@news1.tudelft.nl> References: <1180523448.993195.59180@q69g2000hsb.googlegroups.com> <974af$465d6e19$83aef404$30110@news1.tudelft.nl> Message-ID: <1180533913.658410.308510@p47g2000hsd.googlegroups.com> On May 30, 7:29 am, stef wrote: > Wildemar Wildenburger wrote: > > Andrew P wrote: > >> Hello, > > >> I am new (very) to Python and have just down loaded the latest version > >> of Python (2.5) and WXPython (2.8). > > >> For some reason I cannot get the WXPython demo to run at all. I run > >> windows XP and it can't find a program to run the demo. Any advice? > >> (apologies if this has been posted before). > > > There *should* be a link in your startmenu in the wxPython group. I'm > > quite positive, but not 100% sure. I think it has the snake-icon. But > > if it's really not there (as you suggested), simply go the the folder > > you installed the demo to and run demo.py. > > > Maybe there's a blunder in the installer for the 2.8 demo? Anyone? > > Can't answer that, but on one from two (almost identical) PC's, > I had trouble too, the other went fluently. > On both PC's, > there was an older wxPython (2.6 I believe), > (which from what I've read should be no problem at all), > which wasn't overruled, by some specific file (wx.pth) to point to the > newest. > The effect is that the demo tries to run, can't find aiw?? or something > like that and crashes > (on fast PC's you actually just see a dos box flashing). > Editing the wx.pth file solved the problem. > > cheers, > Stef Mientki I haven't had any problems in with the demo...but then again, I uninstalled the previous version before putting on the new demo. I did have some minor problems choosing which version I wanted to run with my scripts, but that has nothing to do with the demo. Mike From steve at holdenweb.com Mon May 7 07:29:51 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 07 May 2007 07:29:51 -0400 Subject: Basic question about sockets and security In-Reply-To: References: Message-ID: Dave Dean wrote: [socket security inquiry] One further point: everything I wrote for server sockets applies to client sockets too if there's a possibility they are interacting with a server that's been maliciously coded, or compromised in some way by an attacker. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon May 14 16:19:43 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 14 May 2007 22:19:43 +0200 Subject: Simulating simple electric circuits References: <5a9838F2nlbanU1@mid.individual.net> <5ae44aF2ku9rtU1@mid.individual.net> <5ak3u9F2odts2U1@mid.individual.net> <1178974027.175679.51130@k79g2000hse.googlegroups.com> Message-ID: <5aruivF2osbvdU1@mid.individual.net> Arnaud Delobelle wrote: > I'm interested! I was tempted to have a go at it after your > initial post, it sounded like a nice little project :) Here you go, see below (quite long). It works from Python 2.5 and above and should be straightly executable from command line. (It'll work with lower Python versions if you backtranslate the few "A if (condition) else B" parts.) We have: - class CurrentController which does the main work - classes Source and Ground for convenience when creating circuits - class Relay for the realisation of logic Please have a look at the example at the end. It's taken from my actual project. A relay "ZT" is brought up if an outside key is pressed. This forces the normally-"up" latching relay "ZTS" down. This in turn causes relay "FTS" to go "up" (which causes many other complicated stuff). I'm open for questions and/or suggestions. :) The names used and docstrings may sound a bit strange since I hastily translated the source from german (we have some very special terms regarding relay technology). I suspect that this is a dead end though, because in more complex designs the creation of circuits becomes cumbersome. Also, for the system I want to model, the circuits are OOH very complex and OTOH I don't have access to all circuit diagrams. :( So I think I'll try next to transfer my problem to digital two-level logic. I'll go with Dave Baum's suggestion with the event queue and post again here soon with report of my achievements ... Regards, Bj?rn ---snip--- #!/usr/bin/env python class CurrentController(object): def __init__(self): self.currentSources = {} # Contents: {ID1: source1, ID2: source2, ...} self.circuits = {} # Contents: {ID1: [all circuits starting at source 1], ID2: [...], ...} def newID(self): ID = 0 while ID in self.currentSources: ID += 1 return ID def newSource(self, func = None): id = self.newID() s = Source(id, func) self.currentSources[id] = s return s def newGround(self): e = Ground() return e def newRelay(self, name, **argv): r = Relay(name, **argv) return r def changed(self, relay): """ Relay relay changed. Re-try all circuits containing it. """ print "CurrentController: changed:", relay.name, "up" if relay.up else "down" for ID, circuits in self.circuits.items(): for circuit in circuits: if circuit.contains(relay): circuit.test() def showCircuits(self, activeOnly = False): """ Show all circuits. If activeOnly is True, show only active ones. """ print "| Circuits: " for ID, circuits in self.circuits.items(): print "| ID: %i" % ID for circuit in circuits: if (not activeOnly) or circuit.active: print circuit def start(self): """ All circuits are defined -- try them out and start monitoring changes. """ for ID, source in self.currentSources.items(): source.start() for ID, circuits in self.circuits.items(): for circuit in circuits: circuit.test() def toGround(self, telegram): """ Save telegram as valid circuit and monitor it. Called from the outside if a telegram reaches "ground" (i. e., circuit closed). """ try: self.circuits[telegram.ID].append(telegram) except KeyError: self.circuits[telegram.ID] = [telegram] class CurrentTelegram(object): """ Class for recording and managing a circuit. """ usedIDs = [] def __init__(self, id): self.relays = [] # Contents: [(group name, relay object, coil function), ...] self.switches = [] # Format: [(group name, relay object, switch function), ...] self.ID = id # ID of the source of this telegram self.circuitID = self.newID() # unique telegram ID # default priority is 1. Should always be > 0. # It's used for weighing of multiple currents, see Relay class. self.prio = 1 self.active = False def newID(self): ID = 0 while ID in self.usedIDs: ID += 1 self.usedIDs.append(ID) return ID def __str__(self): relays = [""] # for an extra newline at the beginning of the string to return for group, r, f in self.relays: type = repr(f) temp = "||| Group %s, Relay %s %s" % (group, r.name, type) relays.append(temp) relays = "\n".join(relays) switches = [""] for group, r, f in self.switches: type = repr(f) temp = "||| Group %s, Relay %s %s" % (group, r.name, type) switches.append(temp) switches = "\n".join(switches) return """|| CurrentTelegram || Source %i || Relays: %s || Switches: %s || %sactive ||""" % (self.ID, relays, switches, "" if self.active else "not ") def __repr__(self): return self.__str__() def copy(self): """ Generate and return a copy of this telegram (for current "forks") """ other = CurrentTelegram(self.ID) other.relays = self.relays[:] other.switches = self.switches[:] other.prio = self.prio other.active = self.active # self.active should at this point normally be always False # circuits aren't added after CurrentController.start is # called return other def addSwitch(self, byWho, relay, f): """ Add a switch to the circuit. Parameters: - byWho: Name of caller (for information only) - relay: Relay object - f: A callable. If it returns True or equivalent, switch is "closed", else "open". """ self.switches.append((byWho, relay, f)) def addRelay(self, byWho, relay, f): """ Add a relay to the circuit. Parameters: - byWho: Name of caller (for information only) - relay: Relay object - f: A callable ("coil function"). It's called as f(True) if the circuit gets active, and f(False) if it becomes inactive. """ self.relays.append((byWho, relay, f)) def contains(self, relay): return self.containsRelay(relay) or self.containsSwitch(relay) def containsRelay(self, r): for _, relay, __ in self.relays: if relay is r: return True else: return False def containsSwitch(self, r): for _, relay, __ in self.switches: if relay is r: return True else: return False def mayBecomeActive(self): """ Determine if circuit is "closed" (i. e. all switches are closed so current can flow). """ for name, relay, f in self.switches: if not f(): break else: return True return False def becomeActive(self): """ Make circuit active: Give "current" to all relays in this circuit. """ if self.active: return self.active = True for name, relay, f in self.relays: # Also give circuitID for relay to know who activated it f(True, self.circuitID) def stop(self): """ Make circuit inactive: Relay falls """ if not self.active: return self.active = False for name, relay, f in self.relays: # Also give circuitID for relay to know who deactivated it f(False, self.circuitID) def test(self): if self.mayBecomeActive(): self.becomeActive() else: self.stop() # TODO: Eliminate circle currents currentController = CurrentController() class Source(object): def __init__(self, ID, neighbour = None): self.connections = [] self.ID = ID if neighbour: self.verbindungen.append(neighbour) def start(self): """ Create CurrentTelegrams and send them to all connected. """ for c in self.connections: t = CurrentTelegram(self.ID) c(t) class Ground(object): c = currentController def input(self, t): self.c.toGround(t) class Relay(object): c = currentController """ Continuous current relay/latching relay TODO: Delay! """ def __init__(self, name, latching = False, initiallyUp = False, minStrength = 1): self.up = False if not initiallyUp else True self.name = name self.latching = True if latching else False # In here, pairs "Circuit-ID: strength" of currents through # raising coil are saved self.currents = {} # This helps decide when Relay goes to "up": # If the sum of all "flowing" strengths in # self.currents is >= minStrength. # # Example: minStrength = 2. # => The relay will go to "up" if at least # - one current of strength "2" # - two currents of strength "1" each # - ... # are active. self.minStrength = minStrength def strengthBigEnough(self): """ Test the magnitude of the sum of all currents through the "raise" coil. If it's big enough, return True, else False. """ total = 0 for _,strength in self.currents.items(): total += strength return True if total >= self.minStrength else False def normalSw(self): """ Normal switch -- is closed if relay is "up", else open. """ return True if self.up else False def reverseSw(self): """ Reverse switch -- opens if relay is "up", else it's closed. """ return True if not self.up else False def normalCoil(self, status, circuitID, strength = 1): """ Send a "current" through the normal coil. Relay goes "up" if status is True or equivalent. Else, if no currents remain and relay is no latching relay, it goes to "down". """ if status: assert circuitID not in self.currents self.currents[circuitID] = strength if self.strengthBigEnough(): self.goUp() else: del self.currents[circuitID] if not self.strengthBigEnough(): if not self.latching: self.goDown() def forceDownCoil(self, status, circuitID): """ Relay goes down, no matter what. """ if status: self.goDown() # CurrentController will be notified of change here # and will retry all circuits through normal coil, # so it's okay to ignore self.currents here def goUp(self): if not self.up: self.up = True self.c.changed(self) def goDown(self): if self.up: self.up = False self.c.changed(self) def __str__(self): return "Relay %s: %s%s (Currents: %r)" % (self.name, "up" if self.up else "down", " (latching relay)" if self.latching else "", self.currents) def __repr__(self): return self.__str__() # following not in main method for usability of "python -i" # create some relays ZT = currentController.newRelay("ZT") FTS = currentController.newRelay("FTS", latching = True) ZTS = currentController.newRelay("ZTS", latching = True, initiallyUp = True) # create one source and one ground s = currentController.newSource() g = currentController.newGround() name = "tester" def circuit1(t): t.addSwitch(name, ZT, ZT.normalSw) u = t.copy() # fork! u.addRelay(name, ZTS, ZTS.forceDownCoil) g.input(u) t.addSwitch(name, ZTS, ZTS.reverseSw) t.addRelay(name, FTS, FTS.normalCoil) g.input(t) s.connections.append(circuit1) # example circuit: # # V (+) # |____________________________ # | | # _|_ ZT sw (closes when up) |_ ZTS sw (opens when up) # | | # | ^ | # O | ZTS ("force down" coil) O FTS (normal coil) # | ("up" at beginning) | # | | # --- GND --- GND # def main(): currentController.start() print "Putting ZT up with my finger ..." ZT.goUp() currentController.showCircuits() if __name__ == "__main__": main() ---snap--- -- BOFH excuse #401: Sales staff sold a product we don't offer. From Eric_Dexter at msn.com Sat May 26 20:08:27 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 26 May 2007 17:08:27 -0700 Subject: python -- prolog bridge error Message-ID: <1180224507.324418.52170@q69g2000hsb.googlegroups.com> I am getting an error with pyswip on xp that says the .dll isn't installed as a shared library. Is there a manual way to install the .dll as such??? prolog seems to work fine it is just the bridge that gives an error From afaNOSPAM at neuf.fr Sun May 6 15:58:16 2007 From: afaNOSPAM at neuf.fr (Amaury Forgeot d'Arc) Date: Sun, 06 May 2007 21:58:16 +0200 Subject: howto make Python list from numpy.array? In-Reply-To: References: <1178480447.245977.293010@n59g2000hsh.googlegroups.com> Message-ID: Hello, John Nagle a ?crit : > dmitrey wrote: >> howto make Python list from numpy.array? >> Thx, D. >> > > lst = map(None, arr) // for 1D arrays. Which can be expressed more simply as: lst = list(arr) -- Amaury From thorsten at thorstenkampe.de Wed May 16 14:50:16 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Wed, 16 May 2007 19:50:16 +0100 Subject: python shell References: <1179337107.842668.112690@k79g2000hse.googlegroups.com> Message-ID: * Krypto (16 May 2007 10:38:27 -0700) > I have been using python shell to test small parts of the big program. > What other ways can I use the shell effectively. My mentor told me > that you can virtually do anything from testing your program to > anything in the shell. Any incite would be useful. use IPython From michael.buonomo at gmail.com Thu May 24 14:33:26 2007 From: michael.buonomo at gmail.com (michael.buonomo at gmail.com) Date: 24 May 2007 11:33:26 -0700 Subject: Python script not mapping our site correctly? Message-ID: <1180031606.747537.306030@r3g2000prh.googlegroups.com> We have been using the Google recommended python script for about a year. We recently realized that the script was not crawling our sites url's, but just our folders which reside on the server. The python script seems to be designed for 'non database' sites, not a site which is using .asp, and has dynamic pages. We are an ecommerce site. What are other ecommerce sites using to create an xml file? Are they using the python script? Thank you for your help. Michael From tjreedy at udel.edu Thu May 3 16:29:03 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 3 May 2007 16:29:03 -0400 Subject: My Python annoyances References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> Message-ID: "John Nagle" wrote in message news:Eep_h.6829$2v1.1832 at newssvr14.news.prodigy.net... | Ben Collver wrote: || > from the person who closed it. I get the unspoken message: bug reports | > are not welcome. | | That's the problem with bug reporting systems which let developers | close bugs arbitrarily. I think you should have looked at the actual tracker item, the evidence, before responding, instead of relying on a misleading claim. The item was closed as invalid three week after an explantion was given with no response from the OP. The link is in my response. | Defect reporting systems should have a status for "developer in denial". The willingness of bystanders like you to trash volunteers with random hobby horses is one reason there are fewer volunteers than needed. | Bug handling in loosely managed projects tends to follow the | same path as the "stages of grief": denial, anger, bargaining, | depression, and acceptance. Blah, blah. Not as profound as you seem to think. | Getting through the process requires a year or so. Ben got a respond in 3 days. Terry Jan Reedy From victor.lebrun at gmail.com Fri May 4 03:44:40 2007 From: victor.lebrun at gmail.com (vml) Date: 4 May 2007 00:44:40 -0700 Subject: passing an array of variant in vb to a python COM object = win32com bug ? In-Reply-To: References: <1178178883.246149.279780@c35g2000hsg.googlegroups.com> <1178196117.469260.12770@e65g2000hsc.googlegroups.com> Message-ID: <1178264680.211881.166510@l77g2000hsb.googlegroups.com> On 4 mai, 06:56, "Gabriel Genellina" wrote: > En Thu, 03 May 2007 09:41:57 -0300,vml escribi?: > > > On 3 mai, 14:20, "Gabriel Genellina" wrote: > >> En Thu, 03 May 2007 04:54:43 -0300,vml > >> escribi?: > > >> > I have a python com object which contains a method to inverse an array > >> > in vb 6 the definition of the class is : > > > I just tried to replace the *val by SqVal(self,val) and call the > > method in vb but it crashes down : > > > "when refilling safe array the sequence must have the same number of > > dimension as the existing array" > > That can't happen with your Python code below, so it must be on the > caller. Maybe you wrote something like: xx=something.SqVal(yy) and xx,yy > are declared of different sizes. > It is true that I call the python routine like that in vb : toto = obj.SqVal(ty) If I am understanding well I need to pass an array of 2x2 and I should retireve an array of variant of 2x2 .... I tried to do that : vb6 : Dim obj As Object Dim toto(1, 1, 2) As Variant Set obj = CreateObject("Python.Fop") Dim ty(1, 1, 2) As Variant ty(0, 0, 0) = 1 ty(0, 1, 0) = 2 ty(0, 0, 1) = 3 ty(0, 0, 2) = 7 ty(0, 1, 1) = 4 ty(0, 1, 2) = 45 ty(1, 0, 0) = 1 ty(1, 1, 0) = 2 ty(1, 0, 1) = 3 ty(1, 0, 2) = 7 ty(1, 1, 1) = 4 ty(1, 1, 2) = 45 toto = obj.SqVal(ty) but it is saying that the compiler can not assign the array toto at the line toto=obj.SqVal().... hum strange ..... any ideas ? Thank you for your help ! > > def SqVal(self,val): > > ## ... > > return val > > > By the way Do you have any idea to debug the com server script ? ( I > > would like to know if a can access the value in the function while > > calling it from vb 6) > > Write a log file as suggested, or use OutputDebugString with the DebugView > program fromwww.sysinternals.com > > -- > Gabriel Genellina From john at datavoiceint.com Tue May 1 17:23:03 2007 From: john at datavoiceint.com (HMS Surprise) Date: 1 May 2007 14:23:03 -0700 Subject: Using python with MySQL In-Reply-To: <1178049722.530888.269840@c35g2000hsg.googlegroups.com> References: <1178048415.272711.261930@n59g2000hsh.googlegroups.com> <1178049722.530888.269840@c35g2000hsg.googlegroups.com> Message-ID: <1178054583.088226.144750@l77g2000hsb.googlegroups.com> > hi, > download this module:http://sourceforge.net/projects/mysql-python > and look at the tutorial here:http://www.kitebird.com/articles/pydbapi.html Done, thank you too. jh From sjmachin at lexicon.net Wed May 9 18:12:44 2007 From: sjmachin at lexicon.net (John Machin) Date: 9 May 2007 15:12:44 -0700 Subject: Comparing dates problem In-Reply-To: <1178746479.776908.319930@p77g2000hsh.googlegroups.com> References: <1178746479.776908.319930@p77g2000hsh.googlegroups.com> Message-ID: <1178748764.663230.186570@y80g2000hsf.googlegroups.com> On May 10, 7:34 am, kyoso... at gmail.com wrote: > Hi, > > I am writing a reminder program for our Zimbra email client. One of > the requirements I was given was to automatically increment or > decrement the display to show something like the following: > > 5 minutes until appointment > > or > > 10 minutes past your appointment > > Either way, as each minute goes by, I need to increment it or > decrement it. I am having trouble finding a coherent way to take the > same date and compare just the number of minutes between them to find > the difference. Like if I have an appointment at 9:30 a.m. and the app > is loaded at 8 a.m., I need to know the number of minutes or hours and > minutes until the appointment. > > I have looked at the dateutils module and it has many comparison > methods, but they seem to only return the number of days or seconds. > Ermmm ... what's wrong with minutes = seconds / 60.0 hours = minutes / 60.0 ? From arunmail at gmail.com Tue May 15 22:04:02 2007 From: arunmail at gmail.com (lazy) Date: 15 May 2007 19:04:02 -0700 Subject: url question - extracting (2 types of) domains Message-ID: <1179281042.229172.246760@k79g2000hse.googlegroups.com> Hi, Im trying to extract the domain name from an url. lets say I call it full_domain and significant_domain(which is the homepage domain) Eg: url=http://en.wikipedia.org/wiki/IPod , full_domain=en.wikipedia.org ,significant_domain=wikipedia.org Using urlsplit (of urlparse module), I will be able to get the full_domain, but Im wondering how to get significant_domain. I will not be able to use like counting the number of dots. etc Some domains maybe like foo.bar.co.in (where significant_domain= bar.co.in) I have around 40M url list. Its ok, if I fallout in few(< 1%) cases. Although I agree that measuring this error rate itself is not clear, maybe just based on ituition. Anybody have clues about existing url parsers in python to do this. Searching online couldnt help me much other than the urlparse/urllib module. Worst case is to try to build a table of domain categories(like .com, .co.il etc and look for it in the suffix rather than counting dots and just extract the part till the preceding dot), but Im afraid if I do this, I might miss some domain category. From facundo at taniquetil.com.ar Thu May 31 08:23:44 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Thu, 31 May 2007 12:23:44 +0000 (UTC) Subject: ImageMagick Issue References: <2adc542f0705302100g3135fd0fn1e6c3decd210bd5f@mail.gmail.com> Message-ID: Sick Monkey wrote: > When I run the following command: > ozdon at SickCodeMonkey david.huggins]# identify -format %w > '/someDIR/images/david.huggins/100_0264.JPG' >From Python interpreter: >>> cmd = "identify -format %w test.jpg" >>> p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) >>> t = p.stdout.read() >>> p.stdout.close() >>> t '50\n' >>> >From command line: facundo at expiron:~$ identify -format %w test.jpg 50 facundo at expiron:~$ Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From istvan.albert at gmail.com Thu May 17 13:43:19 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: 17 May 2007 10:43:19 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464C5382.6080403@v.loewis.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <464C5382.6080403@v.loewis.de> Message-ID: <1179423799.254286.294930@w5g2000hsg.googlegroups.com> On May 17, 9:07 am, "Martin v. L?wis" wrote: > up. I interviewed about 20 programmers (none of them Python users), and > most took the position "I might not use it myself, but it surely > can't hurt having it, and there surely are people who would use it". Typically when you ask people about esoteric features that seemingly don't affect them but might be useful to someone, the majority will say yes. Its simply common courtesy, its is not like they have to do anything. At the same time it takes some mental effort to analyze and understand all the implications of a feature, and without taking that effort "something" will always beat "nothing". After the first time that your programmer friends need fix a trivial bug in a piece of code that does not display correctly in the terminal I can assure you that their mellow acceptance will turn to something entirely different. i. From tbrkic at yahoo.com Mon May 28 12:42:13 2007 From: tbrkic at yahoo.com (glomde) Date: 28 May 2007 09:42:13 -0700 Subject: Good idea to use a class as function with __new__? In-Reply-To: References: <1180354650.472117.144430@p77g2000hsh.googlegroups.com> Message-ID: <1180370533.702501.63430@o5g2000hsb.googlegroups.com> Gabriel Genellina wrote: > def __call__(self, *args, **kwds): > return self.__TemplateMethod(*args, **kwds) > > x = Template()(prefix="foo") > or perhaps: > x = Template(prefix="foo")() > > I think the extra () improves readability - it's clear that x comes from a > function call, it's not a Template instance as one would expect from your > original code. > And depending on the application, you could keep the instances and call > them with different arguments - with the original code you always create a > new instance just to discard it immediately. > > -- Thanks for the reply. I was considering __call__ but in my case it is really something that will be discarded immediately. And right now it is is implemented as function where I have arguments to send in which customize functions something like: def Template(self, func1=Customize1, func2= Customize2, *args, **kwds): func1(*args, **kwds) func2(*args, **kwds) So I just wanted to organize it a little bit nicer and be able to subclass instead of sending in function pointers. But that had the same interface. But you are right the extra () does make it clearer, so I probably go for that. Cheers, /T > Gabriel Genellina From wgwigw at gmail.com Sun May 27 08:07:36 2007 From: wgwigw at gmail.com (momobear) Date: 27 May 2007 05:07:36 -0700 Subject: a bug in python windows service? In-Reply-To: References: <1180231245.444827.171390@g37g2000prf.googlegroups.com> Message-ID: <1180267656.857094.260980@d30g2000prg.googlegroups.com> > Instead of extending join(), write a specific method to signal the > quitEvent or just let the caller signal it. And I don't see in this > example why do you need two different events (one on the thread, another > on the service controller), a single event would suffice. I don't think a single event is enought, since I think the event python created and windows event are not same kind of event. From sreckotoroman at gmail.com Sat May 26 18:35:41 2007 From: sreckotoroman at gmail.com (Che Guevara) Date: 26 May 2007 15:35:41 -0700 Subject: speeding things up with C++ In-Reply-To: <1180171179.687276.77930@z28g2000prd.googlegroups.com> References: <1180171179.687276.77930@z28g2000prd.googlegroups.com> Message-ID: <1180218941.924926.164270@q75g2000hsh.googlegroups.com> On May 26, 11:19 am, bullockbefriending bard wrote: > However, I hope someone reading this will be able to tell me that I'm > being a total pessimist and that in fact it isn't very difficult to do > what I want to do using SWIG. I'm not asking for a complete solution, > more like some general pointers from someone who has actually done > something similar before. I do stuff like that with ctypes ( http://docs.python.org/lib/module-ctypes.html )! I'm sure you can figure out some way to pass/return data to/from your C ++ lib. The easiest way - use strings or arrays, but if you dig deeper into ctyles documentation, I'm sure you will find a better solution! Good luck, -- misreckoning From jstroud at mbi.ucla.edu Mon May 7 23:09:39 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 07 May 2007 20:09:39 -0700 Subject: How to make Python poll a PYTHON METHOD In-Reply-To: <1178590029.225298.195430@y80g2000hsf.googlegroups.com> References: <1178590029.225298.195430@y80g2000hsf.googlegroups.com> Message-ID: johnny wrote: > Is there a way to call a function on a specified interval(seconds, > milliseconds) every time, like polling user defined method? > > Thanks. > A very literal interpretation of your question yields the following very simple answer: import time while True: time.sleep(some_number_of_seconds) user_defined_method() A more sophisticated approach would use threading, for example: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/464959 James From sjmachin at lexicon.net Wed May 2 17:13:45 2007 From: sjmachin at lexicon.net (John Machin) Date: 2 May 2007 14:13:45 -0700 Subject: pack/unpack zero terminated string In-Reply-To: References: <1178114191.580368.59520@c35g2000hsg.googlegroups.com> Message-ID: <1178140425.827144.57150@q75g2000hsh.googlegroups.com> On May 3, 12:01 am, Laurent Pointal wrote: > tmp123 a ?crit : > > > Hello, > > > Thanks for your time. > > > After review the "struct" documentation, it seems there are no option > > to pack/unpack zero terminated strings. > > > By example, if the packed data contains: byte + zero terminated string > > + zero terminated string + byte, it seems no possible to unpack it > > using "struct". > > > Please, has someone any hint or pointer to another librarian to be > > used? > > May look at xstruct too > > http://www.sis.nl/python/xstruct/xstruct.shtml Hi, Laurent, It's a reasonable presumption that the OP needs to unpack *variable- length* zero-terminated strings, otherwise why is he asking? This would need a new format type e.g. "z". xstruct doesn't appear to offer variable-length strings, and is frozen in time (October 1999) -- inspection of the source shows that it is a copy of Python 1.5.2 structmodule.c with added stuff. The OP might like to try a bit of DIY in Python, along the following lines: C:\junk>type unpackz.py def getz(strg, start=0): zpos = strg.index('\0', start) return strg[start:zpos], zpos + 1 def getB(strg, start=0): return ord(strg[start]), start + 1 def unpack_BzzB(strg): pos = 0 r0, pos = getB(strg, pos) r1, pos = getz(strg, pos) r2, pos = getz(strg, pos) r3, pos = getB(strg, pos) assert pos == len(strg) return r0, r1, r2, r3 x = chr(42) + 'foo\0' + 'mumble\0' + '\xff' print unpack_BzzB(x) print unpack_BzzB('\0' * 4) C:\junk>unpackz.py (42, 'foo', 'mumble', 255) (0, '', '', 0) HTH, John From andre.roberge at gmail.com Sun May 13 14:16:25 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 13 May 2007 11:16:25 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46473267$0$31532$9b622d9e@news.freenet.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <1179080185.225291.126420@w5g2000hsg.googlegroups.com> On May 13, 12:44 pm, "Martin v. L?wis" wrote: > PEP 1 specifies that PEP authors need to collect feedback from the > community. As the author of PEP 3131, I'd like to encourage comments > to the PEP included below, either here (comp.lang.python), or to > python-3... at python.org > It should be noted that the Python community may use other forums, in other languages. They would likely be a lot more enthusiastic about this PEP than the usual crowd here (comp.lang.python). Andr? From bdesth.quelquechose at free.quelquepart.fr Sat May 12 11:00:36 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 12 May 2007 17:00:36 +0200 Subject: Dynamic subclassing ? In-Reply-To: <1178976888.443891.116090@y80g2000hsf.googlegroups.com> References: <1178976888.443891.116090@y80g2000hsf.googlegroups.com> Message-ID: <4645cc78$0$20196$426a74cc@news.free.fr> manatlan a ?crit : > I've got an instance of a class, ex : > > b=gtk.Button() > > I'd like to add methods and attributes to my instance "b". > I know it's possible by hacking "b" with setattr() methods. You don't even need setattr() here, you can set the attributes directly. > But i'd > like to do it with inheritance, a kind of "dynamic subclassing", > without subclassing the class, only this instance "b" ! > > In fact, i've got my instance "b", and another class "MoreMethods" > > class MoreMethods: > def sayHello(self): > print "hello" > > How could i write ... > > "b = b + MoreMethods" > > so "b" will continue to be a gtk.Button, + methods/attributs of > MoreMethods (it's what i call "dynamic inheritance") ...so, things > like this should work : > > - b.set_label("k") > - b.sayHello() > > I can't find the trick, but i'm pretty sure it's possible in an easy > way. You don't necessarily need subclassing here. What you want is a typical use case of the Decorator pattern: class MoreMethods(object): def __init__(self, button): self._button = button def sayHello(self): print "hello" def __getattr__(self, name): return getattr(self._button, name) def __setattr__(self, name, value): if name in dir(self._button): setattr(self._button, name, value) else: object.__setattr__(self, name, value) b = MoreMethods(gtk.Button()) b.set_label("k") b.say_hello() From kyosohma at gmail.com Tue May 22 11:56:15 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 22 May 2007 08:56:15 -0700 Subject: NOOOOB In-Reply-To: <1179836189.980255.38810@a26g2000pre.googlegroups.com> References: <1179829763.464614.123920@a26g2000pre.googlegroups.com> <1179836189.980255.38810@a26g2000pre.googlegroups.com> Message-ID: <1179839381.066896.119990@y2g2000prf.googlegroups.com> On May 22, 7:16 am, marc wyburn wrote: > On May 22, 11:29 am, jolly wrote: > > > Hey guys, > > > I want to begin python. Does anyone know where a good starting point > > is? > > > Thanks, > > Jem > > i went through the tutorials on the main site and then followed up > with mark Hammonds book for windows stuff. I got a few other books as > well to reference but I've found it easy enough to find info for > almost everything on the net. If you need reference books that delve deep into the language while being somewhat understandable, I would recommend "Programming Python" by Lutz or "Core Python Programming" by Chun. "Beginning Python" by Hetland covers just about everything you'd need to know and it includes some fairly complex examples in the back...plus it's about half the size of the other two books. Other than that, I'd with the other guys on this. The web has lots of good examples, puzzles and for most of the standard library, decent docs, although not always with good or thorough examples. Enjoy! Mike From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed May 23 07:28:27 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 23 May 2007 13:28:27 +0200 Subject: Basic Class/Instance Question In-Reply-To: <1179918439.085344.171330@u30g2000hsc.googlegroups.com> References: <1179918439.085344.171330@u30g2000hsc.googlegroups.com> Message-ID: <46542543$0$6795$426a74cc@news.free.fr> Siah a ?crit : > Ready to go insane here. Class A, taking on a default value for a > variable. Instantiating two separate objects of A() gives me a shared > val list object. Just see the example bellow: > > > class A(object): > def __init__(self, val=[]): > self.val=val > > obj1 = A() > obj2 = A() > > print obj1 is obj2 # False - as expected > print obj1.val is obj2.val # True! - Why... oh god WHY > > > ----------- > Using python 2.4. Is this a bug with this version of python? How can I > trust the rest of the universe is still in place? Could she still like > me? Many questions I have. Lets start with the python problem for now. This is a FAQ. Default arguments are only evaled once - when the def statement is evaled (which is usually at import time). The solution is simple: don't use mutable objects as default arguments: class A(object): def __init__(self, val=None): if val is None: val = [] self.val=val FWIW, do you really believe such a 'bug' would have stayed unnoticed ?-) Else, the rest of the universe seems to be in place, and I don't know if she'll still like you if she learn you didn't read the FAQ before posting !-) HTH From kyosohma at gmail.com Tue May 29 14:09:14 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 29 May 2007 11:09:14 -0700 Subject: wxpython demo error on debian etch In-Reply-To: <1180459989.799593.243960@u30g2000hsc.googlegroups.com> References: <1180445918.523446.133300@g4g2000hsf.googlegroups.com> <1180446704.521350.72450@k79g2000hse.googlegroups.com> <1180459989.799593.243960@u30g2000hsc.googlegroups.com> Message-ID: <1180462154.551455.83010@k79g2000hse.googlegroups.com> On May 29, 12:33 pm, BartlebyScrivener wrote: > On May 29, 8:51 am, kyoso... at gmail.com wrote: > > > The wxPython > > website details how to get the latest version of wxPython (2.8.4) > > I'm fairly new to Linux, so I probably shouldn't mess with my stable > Etch. > > I'll make do with this version of wxPython or go back to puzzling over > Tkinter. > > Thanks, > > rick The newer versions of wxPython won't make your Debian crash or anything. We run Debian at work and I've upgraded the Python to 2.4 and the wxPython to its newest version. This has not affected the server's stability in any way. This link explains the process the Debian team takes to implement new versions of packages (like wxPython): http://en.wikipedia.org/wiki/Debian Basically, they test it for months before finally putting it in to the "stable" category. However, since they have to do this for lots of packages, one by one the packages get marked stable. So you could have something like wxPython marked stable in March and 6 months later, the rest of the packages are done so they're marked stable. And then after additional testing, they release the new version. Hopefully that wasn't too confusing. Mike From larry.bates at websafe.com Tue May 22 13:11:38 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 22 May 2007 12:11:38 -0500 Subject: pipe tutorial In-Reply-To: References: <6LOdndzGvuaCZ8_bnZ2dnUVZ_oDinZ2d@comcast.com> Message-ID: Gabriel Genellina wrote: > En Tue, 22 May 2007 11:11:45 -0300, Larry Bates > escribi?: > >> Gigs_ wrote: >>> does anyone know some good tutorial on pipes in python? >> >> Pipes is specific only to Windows (you can use sockets >> on Windows/Linux/mac). The only specific treatment of >> pipes I've seen is in Python Programming for Win32 by >> Mark Hammond/Andy Robinson. > > There are pipes in Unix too, named and anonymous, and I think they > predate its introduction in Windows (first on NT4 I believe). "Pipes" > used to redirect standard input/output are certainly much older. > To the OP: what do you want to do, exactly? > > --Gabriel Genellina > You are right. I didn't think about piping of commands since that wouldn't really be a Python question. I thought user wanted pipes for interprocess communication that is prevalent in Windows. I guess the OP can chime in and we can answer the question better. -Larry From john at datavoiceint.com Tue May 15 15:04:24 2007 From: john at datavoiceint.com (HMS Surprise) Date: 15 May 2007 12:04:24 -0700 Subject: Splitting a string In-Reply-To: <1179253692.110024.96330@w5g2000hsg.googlegroups.com> References: <1179253692.110024.96330@w5g2000hsg.googlegroups.com> Message-ID: <1179255864.876759.120540@h2g2000hsg.googlegroups.com> I found my problem, the backslash isn't really there. It is just the way it was displayed in the shell after being split from a larger string. Printing it yields D132259','','status=no,location=no,width=630,height=550,left=200,top=100')" target="_blank" class="dvLink" title="Send an Email to selected employee"> As as opposed to what I got by just typing the variable name in the shell. jh From aisaac at american.edu Wed May 9 22:50:49 2007 From: aisaac at american.edu (Alan Isaac) Date: Thu, 10 May 2007 02:50:49 GMT Subject: change of random state when pyc created?? References: <5ae25fF2oggbqU1@mid.uni-berlin.de> Message-ID: "Carsten Haese" wrote in message news:mailman.7498.1178763619.32031.python-list at python.org... > Knowing that maps don't have reproducible ordering is one thing. > Realizing that that's the cause of the problem that's arbitrarily and > wrongly attributed to the 'random' module, in a piece of code that's not > posted to the public, and presumably not trimmed down to the shortest > possible example of the problem, is quite another. There is no reason to be unfriendly about this. I posted an observation about my code behavior and my best understanding of it. I asked for an explanation and did not assert a bug, although when someone doubted that the presence or absence of the .pyc file mattered for the results I said that *if* it should not matter *then* there was a bug. I offered the code to all that asked for it. I did not post it **because** I had not adequately isolated the problem. (But indeed, I was not isolating the problem due to misconceptions.) > I'll venture the guess that most Python programmers with a modicum of > experience will, when asked point blank if it's safe to rely on a > dictionary to be iterated in a particular order, answer no. Again, that misses the point. This is clearly documented. I would have said the same thing: no, that's not safe. But the question is whether the same people will be surprised when *unchanged* code rerun with an *unchanged* implementation produces *changed* results. I do not see how a reader of this thread cannot conclude that yes, even some sophisticated users (who received my code) will be surprised. The docs should not be useful only to the most sophisticated users. > It does, at least for dicts: "Keys and values are listed in an arbitrary > order." If this wording is not present for sets, something to this > effect should be added. Even Robert did not claim that *that* phrase was adequate. I note that you cut off "which is non-random"! Alan Isaac From spamtrap at dot-app.org Fri May 11 16:16:22 2007 From: spamtrap at dot-app.org (Sherm Pendley) Date: Fri, 11 May 2007 16:16:22 -0400 Subject: test References: Message-ID: Joe Eagar writes: > sorry just a test. Sorry, you failed. You missed alt.test by a mile. sherm-- -- Web Hosting by West Virginians, for West Virginians: http://wv-www.net Cocoa programming in Perl: http://camelbones.sourceforge.net From aleax at mac.com Fri May 4 10:50:21 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 4 May 2007 07:50:21 -0700 Subject: How safe is a set of floats? References: <1178288509.067493.5140@e65g2000hsc.googlegroups.com> Message-ID: <1hxkw5d.1ipc1zfocmqm9N%aleax@mac.com> Thomas Nelson wrote: > I want to generate all the fractions between 1 and limit (with > limit>1) in an orderly fashion, without duplicates. > > def all_ratios(limit): > s = set() > hi = 1.0 > lo = 1.0 > while True: > if hi/lo not in s: > s.add(hi/lo) > yield (hi,lo) > hi += 1 > if hi/lo > limit: > lo += 1 > hi = lo > > I use a set to keep from giving duplicates; but is this safe? In C > they always tell you not to trust floating point equality comparisons, > since they may not work as you expect. My code seems fine for the > limited amount I've tested, but I'm curious: is there a gaurantee > about sets of floats? Or a warning? sets of floats work exactly like sets of anything else and thus in particular they DO intrinsically rely on == comparisons, i.e., exact equality checks (just like dicts whose keys are floats, etc). In your code, some "fractions" that actually differ from others you're previously seen will in fact be skipped because they don't differ _by enough_ -- i.e. they do compare == to within the limited precision of floating-point computations. But if you do want to be yielding floats, and never want to yield the (num, denom) tuples for two items that *as float* compare ==, there's nothing you can do about that issue. My main suggestion to you actually would be to compute hi/lo ONCE per iteration rather than 3 times -- I detest repetition in principle and here it may be costing you a few nanoseconds' speed:-) [[If you don't truly care about whether the fractions you yield do compare as == "as floats", you might e.g. use gmpy.mpq rather than division to perform your checks]] Alex From aleax at mac.com Wed May 9 00:16:24 2007 From: aleax at mac.com (Alex Martelli) Date: Tue, 8 May 2007 21:16:24 -0700 Subject: Towards faster Python implementations - theory References: <1210i.7468$2v1.2505@newssvr14.news.prodigy.net> <4640dedf$0$19020$426a34cc@news.free.fr> Message-ID: <1hxtccr.8311641cqosu7N%aleax@mac.com> Bruno Desthuilliers wrote: > John Nagle a ?crit : > > Some faster Python implementations are under development. > > JPython has been around for a while, > > s/JP/J/ These days, yes, but it WAS originally called JPython (it was renamed to Jython later). So, "has been around a while" is an appropriate context for using the good old name. > And FWIW, I'm not sure Jython is really faster than CPython... Definitely not, last I measured. Not IronPython either, overall (though it's much better than Jython and does get to beat CPython on some specific benchmarks). Alex From beliavsky at aol.com Thu May 10 12:56:31 2007 From: beliavsky at aol.com (Beliavsky) Date: 10 May 2007 09:56:31 -0700 Subject: Single precision floating point calcs? In-Reply-To: <1343v0emvdjr545@corp.supernews.com> References: <1343v0emvdjr545@corp.supernews.com> Message-ID: <1178816191.210383.309700@q75g2000hsh.googlegroups.com> Off-topic, but maybe as practical as "[making] your own Python build from altered source." --- Fortran 95 (and earlier versions) has single and double precision floats. One could write a Fortran code with variables declared REAL, and compilers will by default treat the REALs as single precision, but most compilers have an option to promote single precision variables to double. In Fortran 90+ one can specify the KIND of a REAL, so if variables as REAL (kind=rp) :: x,y,z throughout the code with rp being a global parameter, and one can switch from single to double by changing rp from 4 to 8. G95 is a good, free compiler. F95 has most but not all of the array operations of NumPy. From nogradi at gmail.com Wed May 16 18:51:42 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Thu, 17 May 2007 00:51:42 +0200 Subject: cPickle.dumps differs from Pickle.dumps; looks like a bug. In-Reply-To: <4866bea60705161539q19378836j108750b3e287132e@mail.gmail.com> References: <1179335622.006820.22460@q23g2000hsg.googlegroups.com> <1179352356.025319.43310@w5g2000hsg.googlegroups.com> <5f56302b0705161524u5902320cy11e0f67a798e8089@mail.gmail.com> <4866bea60705161539q19378836j108750b3e287132e@mail.gmail.com> Message-ID: <5f56302b0705161551m250605daq364874c544bb8dd4@mail.gmail.com> > > > > I've found the following strange behavior of cPickle. Do you think > > > > it's a bug, or is it by design? > > > > > > > > Best regards, > > > > Victor. > > > > > > > > from pickle import dumps > > > > from cPickle import dumps as cdumps > > > > > > > > print dumps('1001799')==dumps(str(1001799)) > > > > print cdumps('1001799')==cdumps(str(1001799)) > > > > > > > > outputs > > > > > > > > True > > > > False > > > > > > > > vicbook:~ victor$ 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.>>> > > > quit() > > > > > > > > vicbook:~ victor$ uname -a > > > > Darwin vicbook 8.9.1 Darwin Kernel Version 8.9.1: Thu Feb 22 20:55:00 > > > > PST 2007; root:xnu-792.18.15~1/RELEASE_I386 i386 i386 > > > > > > If you unpickle though will the results be the same? I suspect they > > > will be. That should matter most of all (unless you plan to compare > > > objects' identity based on their pickled version.) > > > > The OP was not comparing identity but equality. So it looks like a > > real bug, I think the following should be True for any function f: > > > > if a == b: f(a) == f(b) > > > > or not? > > > > Obviously not, in the general case. random.random(x) is the most > obvious example, but there's any number functions which don't return > the same value for equal inputs. Take file() or open() - since you get > a new file object with new state, it obviously will not be equal even > if it's the same file path. Right, sorry about that, posted too quickly :) I was thinking for a while about a deterministic > For certain inputs, cPickle doesn't print the memo information that is > used to support recursive and shared data structures. I'm not sure how > it tells the difference, perhaps it has something to do with > refcounts. In any case, it's an optimization of the pickle output, not > a bug. Caching? >>> from cPickle import dumps >>> dumps('0') == dumps(str(0)) True >>> dumps('1') == dumps(str(1)) True >>> dumps('2') == dumps(str(2)) True ........ ........ >>> dumps('9') == dumps(str(9)) True >>> dumps('10') == dumps(str(10)) False >>> dumps('11') == dumps(str(11)) False Daniel From john at datavoiceint.com Tue May 1 15:40:20 2007 From: john at datavoiceint.com (HMS Surprise) Date: 1 May 2007 12:40:20 -0700 Subject: Using python with MySQL Message-ID: <1178048415.272711.261930@n59g2000hsh.googlegroups.com> Greetings, I need to peform some simple queries via MySQL. Searching the list I see that folks are accessing it with python. I am very new to python and pretty new to MySQL too. Would appreciate it if you could point me to some documentation for accessing MySQL via python. Something of the "Python and MySQL for Dummies" caliber would be about my speed, but of course I will be thankful for anything offered. Thanks, jvh From laurstorage at yahoo.com Mon May 28 04:20:30 2007 From: laurstorage at yahoo.com (Laurentiu) Date: Mon, 28 May 2007 09:20:30 +0100 (BST) Subject: Video tutorials In-Reply-To: Message-ID: <20070528082030.27800.qmail@web36714.mail.mud.yahoo.com> Hello! i was searching the net for some video tutorials (free and payed). i found some interesting stuff at www.showmedo.com but i want something more complex. can someone give me some address for video tutorials or companies how made this tutorials, free or payed. i search at Lynda.com and vtc but i didn't find any python references. thanks for all answers. Laurentiu ___________________________________________________________ Yahoo! Mail is the world's favourite email. Don't settle for less, sign up for your free account today http://uk.rd.yahoo.com/evt=44106/*http://uk.docs.yahoo.com/mail/winter07.html From aleax at mac.com Tue May 8 01:18:39 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 7 May 2007 22:18:39 -0700 Subject: how do you implement a reactor without a select? References: <1178543812.260333.39280@w5g2000hsg.googlegroups.com> <1hxqfgq.4sjxga1dz7vv3N%aleax@mac.com> <1178552069.229745.124040@l77g2000hsb.googlegroups.com> <1hxrdhf.179bobg6tzv9cN%aleax@mac.com> <1178596109.282088.175300@u30g2000hsc.googlegroups.com> Message-ID: <1hxrk27.be77j7p8fqvN%aleax@mac.com> Michele Simionato wrote: > On May 8, 4:53 am, a... at mac.com (Alex Martelli) wrote: > > What do you expect from "timers on Linux" that you could not get with a > > simple "sleep for the next N milliseconds"? A timer (on Linux or > > elsewhere) can jog your process N milliseconds from now, e.g. with a > > SIGALRM or SIGPROF, and you can set one with the setitimer syscall > > (presumably accessible via ctypes, worst case -- I've never used it from > > Python, yet), but how would that help you (compared to plain sleep, > > select, poll, or whatever else best fits your need)? > > I hoped there was a library such thay I could register a Python > callable (say > a thunk) and having it called by the linux timer at time t without > blocking > my process. But if a Linux timer will just send to my process an > alarm, I would need to code myself a mechanism waiting for the alarm > and doing the function call. In that case as you say, I would be > better off with a select+timeout or a even with a queue+timeout, which > already do most of the job. Python or not, I don't know of a way to "register a callback" from the OS without using threads. Considering that your callback WOULD be executing on a different thread no matter what (your "only" thread being blocked on some blocking syscall, or executing other code -- having other code in your process suddenly start executing at that point is pre-emptive threading, by whatever name you choose to call it), it's not clear to me why the "avoiding threads" issue should matter to you. Alex From howe.steven at gmail.com Thu May 17 17:56:35 2007 From: howe.steven at gmail.com (Steven Howe) Date: Thu, 17 May 2007 14:56:35 -0700 Subject: remove all elements in a list with a particular value In-Reply-To: <1179435415.258096.167900@y80g2000hsf.googlegroups.com> References: <1179328873.105705.95580@l77g2000hsb.googlegroups.com> <1179435415.258096.167900@y80g2000hsf.googlegroups.com> Message-ID: <464CCF93.6060102@gmail.com> MRAB wrote: > On May 16, 4:21 pm, Lisa wrote: > > I am reading in data from a text file. I want to enter each value on > the line into a list and retain the order of the elements. The number > of elements and spacing between them varies, but a typical line looks > like: > > ' SRCPARAM 1 6.35e-07 15.00 340.00 1.10 3.0 ' > Using builtin functions: ax = ' SRCPARAM 1 6.35e-07 15.00 340.00 1.10 3.0 ' >>> ax.replace(' ','') # replace all double spaces with nothing ' SRCPARAM 1 6.35e-07 15.00340.00 1.103.0 ' >>> ax.replace(' ','').strip() # strip leading/trailing white spaces 'SRCPARAM 1 6.35e-07 15.00340.00 1.103.0' >>> ax.replace(' ','').strip().split(' ') # split string into a list, using remaining white space as key ['SRCPARAM', '1', '6.35e-07', '15.00340.00', '1.103.0'] def getElements( str ): return str.replace( ' ', '' ).strip().split(' ') sph -- HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -------------- next part -------------- An HTML attachment was scrubbed... URL: From eugene.vandenbulke at gmail.com Fri May 4 03:06:01 2007 From: eugene.vandenbulke at gmail.com (EuGeNe Van den Bulke) Date: Fri, 04 May 2007 09:06:01 +0200 Subject: base64 and unicode Message-ID: Hi, I am trying to convert the file hebrew.b64 attached into hebrew.lang (text file usable by Inline Search for localization purposes. >>> import base64 >>> base64.decode(file("hebrew.b64","r"),file("hebrew.lang","w")) It runs but the result is not correct: some of the lines in hebrew.lang are correct but not all of them (hebrew.expected.lang is the correct file). I guess it is a unicode problem but can't seem to find out how to fix it. ---- hebrew.b64 = file to convert ---- //4jACAARQBuAGcAbABpAHMAaAAgAHYAIAAxAC4ANAANAAoAMQA6AOIF0QXoBdkF6gUNAAoA DQAKADEAMAAxADoA0QXZBdgF1QXZBSAA3AXQBSAA4AXeBeYF0AUNAAoAMQAwADIAOgDUBdIF 2QXiBSAA3AXhBdUF4wUgANQF0wXjBSwAIADeBd4F6QXZBdoFIADeBegF0AXpBSAA1AXTBeMF DQAKADEAMAAzADoA0gXoBeEF1AUgANcF0wXpBdQFIADpBdwFIABJAG4AbABpAG4AZQAgAFMA ZQBhAHIAYwBoACAA4AXeBeYF0AXUBS4AIADcBdcF5QUgAOIF3AUgACIA2wXfBSIAIADbBdMF 2QUgANwF4gXRBdUF6AUgANwF0wXjBSAA1AXUBdUF6AXTBdQFLgANAAoAMQAwADQAOgDZBekF IADcBdoFIADQBeoFIADUBdIF6AXhBdQFIADUBdAF1wXoBdUF4AXUBSAA6QXcBSAASQBuAGwA aQBuAGUAIABTAGUAYQByAGMAaAAuAA0ACgAxADAANQA6AN4F5gXQBSAAOgANAAoAMQAwADYA OgDUBeoF0AXdBSAA6AXZBekF2QXVBeoFDQAKADEAMQAxADoA3gXmBdAFIADQBeoFIADUBdEF 0AUNAAoAMQAxADIAOgDeBeYF0AUgANAF6gUgANQF5wXVBdMF3QUNAAoAMQAxADMAOgDUBdMF 0gXpBSAA1AXbBdwFDQAKAA0ACgAjACAATQBlAG4AdQANAAoAMwAyADcANgA4ADoA0AXVBdMF 1QXqBQ0ACgAzADIANwA2ADkAOgDRBdMF1QXnBSAA0AXdBSAA5wXZBdkF3QUgAOIF0wXbBdUF 3wUNAAoAMwAyADcANwAwADoA1AXqBdAF3QUgANAF2QXpBdkF6gUuAC4ALgANAAoADQAKACMA IABPAHAAdABpAG8AbgAgAGQAaQBhAGwAbwBnAA0ACgAxADAANwA6ANQF6gXQBd0FIADQBdkF 6QXZBeoFIADQBeoFIABJAG4AbABpAG4AZQAgAFMAZQBhAHIAYwBoAA0ACgAxADAAOAA6AOkF 5AXUBQ0ACgAxADAAOQA6ANEF1wXoBSAA0AXqBSAA1AXpBeQF1AUgANQF3gXVBeIF0wXkBeoF IADiBdwF2QXaBSAAOgANAAoAMQAxADAAOgDpBdkF4AXVBdkF2QXdBSAA0QXpBeQF1AUgANkF 1QXkBdkF4gXVBSAA0QXUBeQF4gXcBdQFIADUBdEF0AXUBSAA6QXcBSAASQBuAHQAZQByAG4A ZQB0ACAARQB4AHAAbABvAHIAZQByAA0ACgA= ---- hebrew.expected.lang = expected output ---- # English v 1.4 1:????? 101:????? ?? ???? 102:???? ???? ???, ????? ???? ??? 103:???? ???? ?? Inline Search ?????. ??? ?? "??" ??? ????? ??? ??????. 104:?? ?? ?? ????? ??????? ?? Inline Search. 105:??? : 106:???? ?????? 111:??? ?? ??? 112:??? ?? ????? 113:???? ??? # Menu 32768:????? 32769:???? ?? ???? ????? 32770:???? ?????... # Option dialog 107:???? ????? ?? Inline Search 108:??? 109:??? ?? ???? ??????? ???? : 110:??????? ???? ?????? ?????? ???? ?? Internet Explorer Could someone enlighten me on how to go from hebrew.b64 to hebrew.expected.lang? Thanks a lot, EuGeNe -- http://www.3kwa.com From mccredie at gmail.com Tue May 29 23:33:53 2007 From: mccredie at gmail.com (Matimus) Date: 29 May 2007 20:33:53 -0700 Subject: Rats! vararg assignments don't work In-Reply-To: References: Message-ID: <1180496033.608791.35840@g37g2000prf.googlegroups.com> Your attemtp: [code] first, rest = arglist[0], arglist[1:] [/code] Is the most obvious and probably the most accepted way to do what you are looking for. As for adding the fucntionality you first suggested, it isn't likely to be implemented. The first step would be to write a PEP though. Remember, in Python "there is only one way to do it". So, unless you can come up with a valid use case where that syntax allows you to do something that wasn't possible before, I wouldn't count on getting much support. From Steffen.Oschatz at googlemail.com Thu May 10 06:52:45 2007 From: Steffen.Oschatz at googlemail.com (Steffen Oschatz) Date: 10 May 2007 03:52:45 -0700 Subject: matplotlib problem In-Reply-To: <1178785874.916502.84960@y80g2000hsf.googlegroups.com> References: <1178785874.916502.84960@y80g2000hsf.googlegroups.com> Message-ID: <1178794365.511188.25580@h2g2000hsg.googlegroups.com> On 10 Mai, 10:31, redcic wrote: > I've got a question regarding matplotlib. I use the command: > pylab.plot(...) > to create a graph. > Then, the execution of the code stops after the line: > pylab.show() > which is off course the last line of my code. > > My problem is that I have to close the figure window before in order > to finish the execution of my code. > I'd like to be able to launch my program other times with different > parameters without having to close the figure windows before each > launch. > Just so you know, I'm using TkAgg backend and the SciTE editor. > > Following the answer I was given in the thread:http://groups.google.com/group/comp.lang.python/browse_thread/thread/... > I set "interactive : True" in matplotlibrc. > I also tried the other things I had been advised to do but I still > have the same problem. > > Any other idea ? > > Thanks, > > C?dric Use ipython (http://ipython.scipy.org/moin/) : IPython accepts the special option -pylab (Sec. 5.2). This configures it to support matplotlib, honoring the settings in the .matplotlibrc file. IPython will detect the user's choice of matplotlib GUI backend, and automatically select the proper threading model to prevent blocking. It also sets matplotlib in interactive mode and modifies %run slightly, so that any matplotlib-based script can be executed using %run and the final show() command does not block the interactive shell. Steffen From theller at ctypes.org Thu May 31 08:52:15 2007 From: theller at ctypes.org (Thomas Heller) Date: Thu, 31 May 2007 14:52:15 +0200 Subject: with ctypes, how to parse a multi-string In-Reply-To: <1180563125.783144.34260@m36g2000hse.googlegroups.com> References: <1180563125.783144.34260@m36g2000hse.googlegroups.com> Message-ID: Eric schrieb: > Hi, > > I am currently dealing with ctypes, interfacing with winscard libbrary > (for smart card access). > > Several APIs (e.g. SCardListReaderGroupsW ) take a pointer to an > unicode string as a parameter , which points at function return to a > "sequence" of unicode strings, NULL terminated. The last string is > double NULL terminated. (of course buffer length is also returned as > another parameter). > > e.g. it could return something like > 'group1\x00group2\x00group3\x00\x00' > > What should I use as argtypes to my function prototype in order to > gain access to the full list? using c_wchar_p works, but it resolves > the string until it reaches the first \x00, resulting in having access > to the first entry of the list only. A c_wchar_p instance represent a (one!) zero-terminated string, as you already know. A POINTER(c_wchar) instance is more flexible, you should use that instead. It can be indexed/sliced with arbitrary indexes. Here is a simple script to get you started: """ from ctypes import * # Normally, the function call will fill the buffer: buf = create_unicode_buffer("first\0second\0third\0") # The pointer you will pass to the function call ptr = cast(buf, POINTER(c_wchar)) # function call omitted # Print the raw result print ptr[:len(buf)] # Print a list of strings print ptr[:len(buf)].split("\0") """ Thomas From jzgoda at o2.usun.pl Fri May 18 03:31:10 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 18 May 2007 09:31:10 +0200 Subject: (Modular-)Application Framework / Rich-Client-Platform in Python In-Reply-To: References: Message-ID: Wildemar Wildenburger napisa?(a): > To make it short: Is there something like this already? > > There seem to loads of python frameworks for Web-Apps, but I have a hard > time finding one for desktop-apps. > I imagine it wouldn't be too hard (if still time consuming) whipping up > something simple myself, but I thought, I'd ask here before diving into it. There are few GUI frameworks building on various toolkits. I used to use Kiwi for PyGTK, it's mature and stable, although the approach is not the same as, for example, Delphi. -- Jarek Zgoda "We read Knuth so you don't have to." From avera at coes.org.pe Tue May 15 10:42:37 2007 From: avera at coes.org.pe (Alberto Vera) Date: Tue, 15 May 2007 09:42:37 -0500 Subject: f2py problem Message-ID: <4649C6DD.8080200@coes.org.pe> Hello. After I installed f2py using Python, NumPy and Numarray software, I can't use f2py I saw this error: Traceback (most recent call last): File "", line 1, in NameError: name 'f2py' is not defined >>> Could you tell me what is the problem? Regards. From bbxx789_05ss at yahoo.com Thu May 24 13:38:54 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 24 May 2007 10:38:54 -0700 Subject: How can I time a method of a class in python using Timeit In-Reply-To: <1180027843.322955.57280@q75g2000hsh.googlegroups.com> References: <1180020970.039576.319230@m36g2000hse.googlegroups.com> <1180027843.322955.57280@q75g2000hsh.googlegroups.com> Message-ID: <1180028334.650900.283930@m36g2000hse.googlegroups.com> On May 24, 11:30 am, 7stud wrote: > On May 24, 9:36 am, "silverburgh.me... at gmail.com" > > > > wrote: > > Hi, > > > I am using timeit to time a global function like this > > > t = timeit.Timer("timeTest()","from __main__ import timeTest") > > result = t.timeit(); > > > But how can i use timeit to time a function in a class? > > class FetchUrlThread(threading.Thread): > > def aFunction(self): > > # do something .... > > > def run(self): > > # how can I time how long does aFunction() take here? > > aFunction(); > > > Thank you. > > How about this: > > class Dog(object): > def run(self): > result = 10 * 20 + 3 > > import timeit > > t = timeit.Timer("d.run()", "from __main__ import Dog; d = Dog()") > print t.timeit() Actually, you could do this: class Dog(object): def aFunction(self): result = 20 + 2 def run(self): #do stuff aFunction() #do other stuff import timeit t = timeit.Timer("d.aFunction()", "from __main__ import Dog; d = Dog()") print t.timeit() It doesn't matter if you call aFunction() directly if all you want to do is time aFunction(). From rampeters at gmail.com Thu May 10 10:14:44 2007 From: rampeters at gmail.com (johnny) Date: 10 May 2007 07:14:44 -0700 Subject: How to make Python poll a PYTHON METHOD In-Reply-To: <1178594341.680457.192440@q75g2000hsh.googlegroups.com> References: <1178590029.225298.195430@y80g2000hsf.googlegroups.com> <1178592128.327658.212000@p77g2000hsh.googlegroups.com> <1178594341.680457.192440@q75g2000hsh.googlegroups.com> Message-ID: <1178806483.999546.74050@u30g2000hsc.googlegroups.com> Is it possible to call threads inside another thread (nested threads)? The example above creates a thread to call a function "eat" every time based on a specified interval. Now for example, if I make the called function "eat" to spawn threads to do the work in a queue and when all jobs are done, spawned threads join. When the next interval is up this process repeat itself. Thanks. On May 7, 11:19 pm, Nick Vatamaniuc wrote: > On May 7, 10:42 pm, Nick Vatamaniuc wrote: > > > > > On May 7, 10:07 pm, johnny wrote: > > > > Is there a way to call a function on a specified interval(seconds, > > > milliseconds) every time, like polling user defined method? > > > > Thanks. > > > Sure, > > > >>> def baz(): > > > ...: print "Baz!" > > ...: > > > >>> from threading import Timer > > >>> timer=Timer(5.0,baz) > > >>> timer.start() > > >>> Baz! > > > Cheers, > > -Nick Vatamaniuc > > By the way, here is another way to do it. This way it will repeat, the > other one executed once. Of course, if it executed once, you can make > it do it again, but there is some trickery involved. Here is a way to > do it using threads. > > Hope it helps, > -Nick Vatamaniuc > > from threading import Thread > from time import sleep > > class Repeater(Thread): > def __init__(self,interval,fun,*args,**kw): > Thread.__init__(self) > self.interval=interval > self.fun=fun > self.args=args > self.kw=kw > self.keep_going=True > > def run(self): > while(self.keep_going): > sleep(self.interval) > self.fun(*self.args,**self.kw) > > def stop_repeating(self): > self.keep_going=False > > def eat(*a): > print "eating: " , ','.join([stuff for stuff in a]) > > r=Repeater(1.0, eat, 'eggs','spam','kelp') > r.start() > sleep(6.0) > r.stop_repeating() From knipknap at gmail.com Tue May 22 09:11:59 2007 From: knipknap at gmail.com (Samuel) Date: 22 May 2007 06:11:59 -0700 Subject: Simple omniORBpy example throws exception with error 0x41540002 In-Reply-To: <5bg40hF2moliaU1@mid.uni-berlin.de> References: <1179833680.255391.198490@x18g2000prd.googlegroups.com> <5bg40hF2moliaU1@mid.uni-berlin.de> Message-ID: <1179839519.216407.124960@z24g2000prd.googlegroups.com> On May 22, 1:54 pm, "Diez B. Roggisch" wrote: > It indeed does open a connection - because it wants to register with a > NameServer. Ah, I see now how this works. I happen to run Ubuntu here, so I tried the following: - sudo apt-get install orbit-name-server-2 - orbit-name-server-2 & - Add to /etc/omniORB4.cfg: InitRef = NameService=IOR:010000002b000000... (where everything starting from "IOR:" is the output given by orbit- name-server-2. However, this does not seem to change the behavior. Any hints? Thanks, -Samuel From bbxx789_05ss at yahoo.com Thu May 17 21:40:48 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 17 May 2007 18:40:48 -0700 Subject: omissions in python docs? In-Reply-To: <1179451395.440662.127760@y80g2000hsf.googlegroups.com> References: <1179419983.750044.65030@n59g2000hsh.googlegroups.com> <1179451395.440662.127760@y80g2000hsf.googlegroups.com> Message-ID: <1179452448.886371.169000@q75g2000hsh.googlegroups.com> On May 17, 7:23 pm, 7stud wrote: > On May 17, 5:24 pm, "Gabriel Genellina" > wrote: > > > At least for 2) you're late. It's already documented on 2.5.1:http://sourceforge.net/tracker/index.php?func=detail&aid=1630844&grou... > > Darn. I could have been somebody! > > >Nit-pickingly yours, > >John > > No so. I checked the downloaded docs on my computer and the supposedly > up to date docs here: > > http://docs.python.org/lib/module-fnmatch.html > > before posting. I rechecked them after reading Gabriel Genellina's > post, and I couldn't find translate() in the fnmatch module. > > There's still time! By the way, have the python doc keepers ever visited the php docs? In my opinion, they are the best docs of any language I've encountered because users can add posts to any page in the docs to correct them or post code showing how to get around various idiosyncrasies when using the functions. From rene at korteklippe.de Tue May 15 09:34:26 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 15 May 2007 15:34:26 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <464996b9$0$10193$9b4e6d93@newsspool4.arcor-online.net> <4649a72d$0$10186$9b4e6d93@newsspool4.arcor-online.net> <4649aca1$0$23148$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <4649b6e0$0$23143$9b4e6d93@newsspool1.arcor-online.net> Thorsten Kampe schrieb: > No, if you claim that something by itself is good and has to be > encouraged then you are obliged to prove or give arguments for that. That would be well outside the scope of this newsgroup, and if you cannot see the reaons for this yourself, I am afraid that I won't be able to convince you anyway. > Exactly. So whether this PEP encourages or discourages code sharing > (and I don't think it does either) has nothing to do with the value of > this PEP. That completely depends on how you look at code-sharing. My impression always was that the Python community in general does regard code-sharing as A Good Thing. It is not as if we were talking about forcing people to share code. Just about creating/keeping an environment that makes this easily possible and encourages it. That *is* something I regard as good and which therefore, for me, forms an argument against this PEP -- wether you share that opinion or not. -- Ren? From stefan.behnel-n05pAM at web.de Tue May 15 18:25:24 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 16 May 2007 00:25:24 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464a25e9$0$10188$9b4e6d93@newsspool4.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649dd55$0$23144$9b4e6d93@newsspool1.arcor-online.net> <464a25e9$0$10188$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <464A3354.4060205@web.de> Ren? Fleschenberg wrote: > Javier Bezos schrieb: >>> But having, for example, things like open() from the stdlib in your code >>> and then ?ffnen() as a name for functions/methods written by yourself is >>> just plain silly. It makes the code inconsistent and ugly without >>> significantly improving the readability for someone who speaks German >>> but not English. >> Agreed. I always use English names (more or >> less :-)), but this is not the PEP is about. > > We all know what the PEP is about (we can read). The point is: If we do > not *need* non-English/ASCII identifiers, we do not need the PEP. If the > PEP does not solve an actual *problem* and still introduces some > potential for *new* problems, it should be rejected. So far, the > "problem" seems to just not exist. The burden of proof is on those who > support the PEP. The main problem here seems to be proving the need of something to people who do not need it themselves. So, if a simple "but I need it because a, b, c" is not enough, what good is any further prove? Stefan From sjdevnull at yahoo.com Tue May 29 17:18:01 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 29 May 2007 14:18:01 -0700 Subject: Is PEP-8 a Code or More of a Guideline? In-Reply-To: References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <007001c7a204$a5a45e10$240110ac@Muse> Message-ID: <1180473481.265262.75690@o5g2000hsb.googlegroups.com> On May 29, 3:22 pm, "Eric S. Johansson" wrote: > Warren Stringer wrote: > > Hi Eric, > > > You make a compelling argument for underscores. I sometimes help a visually > > impaired friend with setting up his computers. > > > I'm wondering about the aural output to you second example: > > > link.set_parse_action(emit_link_HTML) > > > Does it sound like this: > > unfortunately, I do not have text to speech set up on this machine as I'm saving > the storage for more MP3s. :-) > > > link dot set under parse under action space between parens emit under link > > under HTML jump out > > it would probably say underscore instead of under and left ( and right ) (too > much work is make it spell out the symbol). > > > > > Also, does how HTML read? Is it "H T M L" or "cap H cap T cap M cap L" ? > > probably HTML. Remember case is not apparent in an aural interface. I don't do text-to-speech at all, but I do often have someone ask "what's the method for blah?" and case is important there. In such cases, I'd say "lowercase emit underscore link underscore all caps H T M L". For emitLinkHTML it'd be "lowercase emit capital-L link all-caps H T M L". For emitLinkHtml it'd be "lowercase emit capital-L link capital-H H T M L". FWIW, even though I think proper-case-with-seperators is greatly preferrable to camelCase, I certainly don't think that speaking the names is a really major point. From montyphyton at gmail.com Wed May 30 05:02:38 2007 From: montyphyton at gmail.com (montyphyton at gmail.com) Date: 30 May 2007 02:02:38 -0700 Subject: writing to a file Message-ID: <1180515758.671628.43200@k79g2000hse.googlegroups.com> as i understand there are two ways to write data to a file: using f.write("foo") and print >>f, "foo". what i want to know is which one is faster (if there is any difference in speed) since i'm working with very large files. of course, if there is any other way to write data to a file, i'd love to hear about it From bbxx789_05ss at yahoo.com Thu May 24 13:41:16 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 24 May 2007 10:41:16 -0700 Subject: How can I time a method of a class in python using Timeit In-Reply-To: <1180028334.650900.283930@m36g2000hse.googlegroups.com> References: <1180020970.039576.319230@m36g2000hse.googlegroups.com> <1180027843.322955.57280@q75g2000hsh.googlegroups.com> <1180028334.650900.283930@m36g2000hse.googlegroups.com> Message-ID: <1180028476.396282.316330@q69g2000hsb.googlegroups.com> Actually, you can do this: class Dog(object): def aFunction(self): result = 20 + 2 def run(self): #do stuff aFunction() #do other stuff import timeit t = timeit.Timer("d.aFunction()", "from __main__ import Dog; d = Dog()") print t.timeit() Since you only want to time aFunction(), you can call it directly. From tjreedy at udel.edu Tue May 22 20:11:29 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 22 May 2007 20:11:29 -0400 Subject: Can I reference 1 instance of an object by more names ? References: Message-ID: "Stef Mientki" wrote in message news:f0b3e$46537f87$d443bb3a$20034 at news.speedlinq.nl... | port_D = IO_port('D') | | Now I want to assign a more logical name to that port, | (In JAL: "var byte My_New_Name IS port_D") | | Is that possible ? | | I think the answer is "no", | because the object itself is not mutable. | Am I right ? no | But I read: "An object can have any number of names, or no name at all." | So am I wrong ? yes Believe the docs. Use the interactive interpreter to try things for yourself: port_nice_name = port_awkward_name ! Terry Jan Reedy From rkmr.em at gmail.com Tue May 22 19:18:06 2007 From: rkmr.em at gmail.com (rkmr.em at gmail.com) Date: Tue, 22 May 2007 16:18:06 -0700 Subject: querying dictionary / list of dictionary like SQL Message-ID: Hi Is there a module /add on in python that will let me query a dictionary [ or a list of dictionary] exactly like an SQL query? For ex: a=[{'id':1, 'name':'mark'}, {'id':2,'name': 'richard'}] select * from a where id =1 should give me the a[0] or something similar to this. thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From jjl at pobox.com Mon May 28 08:40:34 2007 From: jjl at pobox.com (John J. Lee) Date: Mon, 28 May 2007 12:40:34 GMT Subject: Is PEP-8 a Code or More of a Guideline? References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <1180254338.292249.29520@h2g2000hsg.googlegroups.com> Message-ID: <87ps4lazor.fsf@pobox.com> Paul McGuire writes: [...] > http://mail.python.org/pipermail/python-dev/2005-December/058750.html > > At first, Guido seemed ambivalent, and commented on the > contentiousness of the issue, but it seems that the "non-English > speakers can more easily find word breaks marked with underscores" > justification tipped the scale in favor of > lower_case_with_underscores. [...] That rationale seems undermined by the frequent use of runtogether names in the standard library. These can be confusing even to native speakers. And every time you come up with a new name, or try to remember an old one, you have to decide or remember whether it's likethis or like_this. Even as a native English speaker, some of these are tricky -- e.g. urllib has a private class named "addinfourl". "What's this 'fourl' we're adding in?" (In fact, the method adds attributes named "info" and "url". Even though I've read that name hundreds of times, my brain always insists on reading it "add in fourl".) This is the worst of both worlds: inconsistent and hard to understand. John From dformosa at usyd.edu.au Fri May 4 08:37:36 2007 From: dformosa at usyd.edu.au (David Formosa (aka ? the Platypus)) Date: Fri, 04 May 2007 12:37:36 GMT Subject: Why stay with lisp when there are python and perl? References: <1178155239.007219.205020@y5g2000hsa.googlegroups.com> <1178219732.127815.3260@y80g2000hsf.googlegroups.com> <463a9668$0$8719$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: Nameless wrote: > Why should I keep on learning lisp when there are python and perl? The more programing languages you know the better programer you will be. Lisp can teach you a number of key things that are required to be a good programmer in any of the P* lanuages. From walterbyrd at iname.com Sat May 19 12:19:09 2007 From: walterbyrd at iname.com (walterbyrd) Date: 19 May 2007 09:19:09 -0700 Subject: Python compared to other language In-Reply-To: <1hycp1k.1g93oj9ezbinxN%aleax@mac.com> References: <1179540061.598417.13870@y80g2000hsf.googlegroups.com> <1hybvdz.1qnlesglcv0vcN%aleax@mac.com> <1179556574.341550.229190@q23g2000hsg.googlegroups.com> <1hycp1k.1g93oj9ezbinxN%aleax@mac.com> Message-ID: <1179591549.342767.269090@o5g2000hsb.googlegroups.com> On May 19, 9:36 am, a... at mac.com (Alex Martelli) wrote: > > From these numbers it would seem that Ruby (and PHP) aren't really more > web-specific than Perl (and Python). > Excellent find, nice work. However, if it is found that there are "X" many PHP programs running payroll applications, does that mean that those PHP programs are *not* web applications? I don't think that it does. I was surprised to see Ruby in the same catagory as Perl and Python, when it came to Scientific apps. I always thought of Ruby as being used for database oriented web-based stuff. Just goes to show what I don't know. I can tell you this much for sure: when it comes to UNIX system scripting, Perl is the leader, with Python as a solid second. Unless, maybe, you count bash & bourne, which I don't because those are not multi-purpose languages. From showell30 at yahoo.com Sun May 27 02:51:29 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sat, 26 May 2007 23:51:29 -0700 (PDT) Subject: ten small Python programs In-Reply-To: Message-ID: <205986.61567.qm@web33513.mail.mud.yahoo.com> --- Steven D'Aprano wrote: > On Sat, 26 May 2007 18:48:45 -0700, Steve Howell > wrote: > > > It also has a ComplexNumber class, but I don't > want to > > scare away mathphobes. > > > Is it as short as this one-liner? > > ComplexNumber = complex > Along the idea of not reinventing a class from the standard library in the list of ten small Python programs (which has since grown), I went with the classic BankAccount example for the first program to introduce the "class" statement. You can see the code here: http://wiki.python.org/moin/SimplePrograms ____________________________________________________________________________________Be a better Globetrotter. Get better travel answers from someone who knows. Yahoo! Answers - Check it out. http://answers.yahoo.com/dir/?link=list&sid=396545469 From michele.simionato at gmail.com Mon May 7 11:34:29 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 7 May 2007 08:34:29 -0700 Subject: how do you implement a reactor without a select? In-Reply-To: <1hxqfgq.4sjxga1dz7vv3N%aleax@mac.com> References: <1178543812.260333.39280@w5g2000hsg.googlegroups.com> <1hxqfgq.4sjxga1dz7vv3N%aleax@mac.com> Message-ID: <1178552069.229745.124040@l77g2000hsb.googlegroups.com> On May 7, 4:39 pm, a... at mac.com (Alex Martelli) wrote: > Michele Simionato wrote: > > I wonder if real mainloops are done in this way and how bad/good is > > this implementation compared to a serious one. Any suggestion/hint/ > > advice is well appreciated. Thanks, > > Module sched in Python's standard library may suggest one clearly-better > approach: when you know in advance when future events are scheduled for, > sleep accordingly (rather than polling every millisecond). sched's > sources are simple enough to study, and its architecture clean and > strong enough that it's easy to extend to other cases, e.g. where > previously-unscheduled events may be delivered from other threads, > without necessarily hacking the sources. > > Specifically, sched implements the Dependency Injection DP: rather than > just calling time.time and time.sleep, it accepts those two callables > upon initialization. This makes it easy, among many other > customizations, to pass instead of time.sleep a user-coded callable > (typically a bound method) that "sleeps" by a wait-with-timeout on a > Queue (so that other threads, by putting an event on the Queue in > question, immediately wake up the scheduler, etc, etc). > > Alex I know about sched (it was the first thing I looked at): the problem is that sched adopt a blocking approach and it basically requires threads, whereas I wanted to avoid them. Diez B. Roggisch's reply is closer to my expectations: >> Most probably the OS will have specialized APIs (or some >> wrapper lib has) that allow for reactor registration for events of different >> kinds including timers. But what kind of specialized API do I have at my disposition for timers on Linux? It looks like this is the question I should have asked the first time ;) Michele Simionato From gagsl-py2 at yahoo.com.ar Wed May 16 03:20:05 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 16 May 2007 04:20:05 -0300 Subject: Python Dijkstra Shortest Path References: <4e8efcf50705152039g2234cc2cl236b0cde644549c0@mail.gmail.com> Message-ID: En Wed, 16 May 2007 00:39:20 -0300, Hugo Ferreira escribi?: > While trying to optimize this: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/119466 > > ... and still have a fast edge lookup, I've done the following tweaks: I've replaced that strange deeply nested list with an old-fashioned tuple and got about a 10% improvement (over a small graph, 60 nodes). But you really should try the effect with larger objects. def findPath(self, start, end): q = [(0, start, ())] # Heap of (cost, path_head, path_rest). visited = set() # Visited vertices. # Eliminate the dots pattern push, pop, add = heapq.heappush, heapq.heappop, visited.add G, E = self.G, self.E while True: (cost, v1, path) = pop(q) if v1 not in visited: add(v1) path += (v1,) if v1 == end: return path for (v2, e) in G[v1].iteritems(): if v2 not in visited: push(q, (cost + E[e], v2, path)) -- Gabriel Genellina From adonis at REMOVETHISearthlink.net Wed May 2 17:01:37 2007 From: adonis at REMOVETHISearthlink.net (Adonis Vargas) Date: Wed, 02 May 2007 21:01:37 GMT Subject: bitwise shift? In-Reply-To: <4638e2bf$0$16368$88260bb3@free.teranews.com> References: <462FEE8B.2030701@lexicon.net> <4638d8c5$0$16290$88260bb3@free.teranews.com> <4638e2bf$0$16368$88260bb3@free.teranews.com> Message-ID: Tobiah wrote: > Wow, thunderbird displayed this to me as a true exponent, even > though it is an ascii message. anyone else get this? > > Yeah I can confirm Thunderbird 1.5.10 on Linux. Adonis From mmara at fibertel.com.ar Fri May 11 00:32:33 2007 From: mmara at fibertel.com.ar (Mariano Mara) Date: Fri, 11 May 2007 01:32:33 -0300 Subject: how to use cx_Oracle callfunc In-Reply-To: <1178857111.377900.178290@p77g2000hsh.googlegroups.com> References: <1178848279.652462.291690@e51g2000hsg.googlegroups.com> <1178857111.377900.178290@p77g2000hsh.googlegroups.com> Message-ID: <4643F1E1.5060604@fibertel.com.ar> Godzilla escribi?: > On May 11, 11:51 am, Godzilla wrote: > >> Hi all, >> >> I need to know how to use the method callfunc in cx_Oracle. I am >> trying to get a primary key after an insert via a function call, but I >> do not know how to pass the return value from the function via the >> callfunc method. Can anyone help? >> >> I also tried the execute(), and callproc(), but to no avail. My >> function is as below: >> >> create or replace function addRow(desc table1.col1%type) return number >> is id number; >> begin >> insert into table1 (description) values (desc) returning table1ID >> into id; >> return(id); >> exception >> when others then return(-1) >> end; >> >> The code in the callfunc: >> >> cur.callfunc("addRow", returnType, param) >> >> Question is: >> - What is returnType and how to I declare that before passing into the >> function? >> - How do I define the parameters? >> >> I tried the setinputsizes and setoutputsize, but I keep getting errors >> saying the parameter is incorrectly defined. Please help. Thank. >> > > Hello, > > found a solution in another thread... see > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/ab13d3364aafdd28/4ca1fde2069ff3da?lnk=st&q=cx_oracle+how+to+setinputsizes&rnum=9&hl=en#4ca1fde2069ff3da > > for more info. > > Thanks. > > Did you mean A. Tuininga's suggestion dated Sep 13 2002? cx_Oracle improved since then. Maybe I fail to understand the problem but the following code looks like valid anwer for what you asked: create table test1 (id1 number, id2 varchar2(600)); create sequence testseq; create or replace function functest(texto in test1.id2%type) return number is output number; begin insert into test1 (id1, id2) values (testseq.nextval, texto) returning id1 into output; commit work; return output; end functest; / >>> import cx_Oracle as ora >>> con = ora.connect('myuser', 'qwerty', 'orcl') >>> cur = con.cursor() >>> val = 0 >>> cur.callfunc("functest", val, ['this is a test']) '1' >>> cur.callfunc("functest", val, ['this is a test']) '2' >>> cur.callfunc("functest", val, ['this is a test']) '3' >>> cur.callfunc("functest", val, ['this is a test']) '4' >>> cur.callfunc("functest", val, ['this is a test']) '5' >>> cur.callfunc("functest", val, ['this is a test']) '6' Cheers -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Fri May 18 22:28:19 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 18 May 2007 22:28:19 -0400 Subject: Python compared to other language In-Reply-To: <1179540061.598417.13870@y80g2000hsf.googlegroups.com> References: <1179540061.598417.13870@y80g2000hsf.googlegroups.com> Message-ID: walterbyrd wrote: > On May 18, 2:17 pm, Larry Bates wrote: > >> Python is Portable - C is probably the only more portable language > > Small quibble: IMO, although C runs on many platforms, I don't think C > code is typically portable between platorms. Unless you are doing > something very simple. If you write something with Visual Studio to do > something fairly advanced on Windows, I don't think the same, > unmodified, code will usually run on UNIX, or MS-DOS. Maybe if you use > pure ANSI C, but I don't think many people do that. > Surely the fact that Python is available on so many platforms implies that C is a fairly portable language. I realise that you have to take platform specifics into account much more than you do in Python, but I do feel you are being somewhat unfair to C. > I'm just learning Python. FWIW: my opinions about 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From ramashish.lists at gmail.com Wed May 23 03:32:42 2007 From: ramashish.lists at gmail.com (Ramashish Baranwal) Date: 23 May 2007 00:32:42 -0700 Subject: Module listing in order. Message-ID: <1179905562.541601.264400@m36g2000hse.googlegroups.com> Hi, I want to get a module's contents (classes, functions and variables) in the order in which they are declared. Using dir(module) therefore doesn't work for me as it returns a list in alphabetical order. As an example- # mymodule.py class B: pass class A: pass class D: pass # test.py import mymodule # This returns['A', 'B', 'D', '__builtins__', '__doc__', '__file__', '__name__'] contents = dir(mymodule) I want a way to get the contents in the order of their declaration, i.e. [B, A, D]. Does anyone know a way to get it? Thanks, Ram From broek at cc.umanitoba.ca Wed May 23 12:06:37 2007 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Wed, 23 May 2007 12:06:37 -0400 Subject: Properties/Decorators [WAS: Can I reference 1 instance of an object by more names ? rephrase] In-Reply-To: <465436E0.7040907@freakmail.de> References: <4654289a$0$2326$426a74cc@news.free.fr> <465436E0.7040907@freakmail.de> Message-ID: <4654668D.1070707@cc.umanitoba.ca> Wildemar Wildenburger said unto the world upon 05/23/2007 08:43 AM: > Bruno Desthuilliers wrote: >> here's an example using a property: >> >> class cpu_ports(object): >> def __init__(self, value=0): >> self._d = value >> @apply >> def value(): >> def fset(self, value): >> print 'vv' >> self._d = value >> def fget(self): >> return self._d >> return property(**locals()) >> > Wow! I've never seen properties written that way. Kind of takes all the > mess out of what it usually is. Nice. BUT! I don't quite get the > @apply-decorator here. The rest I get and so I gather what it is sort of > kind of supposed to do. I have only found the depricated apply() > function in the docs (which I also don't quite get just by scanning it). > Is it that? If yes: How does it work? If not: What's going on there? > > humbly ;) > W Hi all, I had the same sort of question as Wildemar and I set about investigating as any good pythonista would by typing help(apply) at the interactive prompt. That produced a help text that started: Help on built-in function apply in module __builtin__: But: >>> [x for x in dir('__builtin__') if 'apply' in x] [] ? If apply is in the __builtin__ module, why doesn't dir('__builtin__') know about it? Best to all, Brian vdB From thn at mail.utexas.edu Mon May 14 12:49:56 2007 From: thn at mail.utexas.edu (Thomas Nelson) Date: 14 May 2007 09:49:56 -0700 Subject: Sorting troubles In-Reply-To: <1179158708.433792.127150@h2g2000hsg.googlegroups.com> References: <1179158708.433792.127150@h2g2000hsg.googlegroups.com> Message-ID: <1179161396.220858.86150@q75g2000hsh.googlegroups.com> On May 14, 11:05 am, seyens... at yahoo.com wrote: > I have the following implementations of quicksort and insertion sort: > > def qSort(List): > if List == []: return [] > return qSort([x for x in List[1:] if x< List[0]]) + List[0:1] + \ > qSort([x for x in List[1:] if x>=List[0]]) > > def insertSort(List): > for i in range(1,len(List)): > value=List[i] > j=i > while List[j-1]>value and j>0: > List[j]=List[j-1] > j-=1 > List[j]=value > > Now, the quickSort does not modify the original list, mostly because > it works on products and concatenations, rather than alterations. > The insertion sort, however, does modify the list. Now, to give > results, they should be called in such a way( A is an unsorted list) > A=qSort(A) > # the insertion sort does not require this, > insertSort(A) > > I would like to know how can I modify the qSort function such that it > affects the list directly inside > I have tried doing it like this > > def qSort(List): > if List == []: return [] > List = qSort([x for x in List[1:] if x< List[0]]) + List[0:1] + \ > qSort([x for x in List[1:] if x>=List[0]]) > return List > > while processing, the list changes, but those changes remain inside > the function, so that once it's over, if nothis catches the return, > the original List remains unchanged. > > If not a solution, I would like to at least know why it does what it > does. I so understand that List(above) is only a reference to the > actual data(a list), but I'm not passing a copy of the data to the > function, but the actual reference(hence, insertSort does > modifications). But then how can I change, inside the function, the > object List is referencing to? If I can't modify the original list, > maybe I can make the variable List point to another list? But changes > inside the function are local. Sorry if this is a bit confusing. The thing is that [x for x in List[1:]...] is a brand new list created by iterating over the old one. How about: qSortHelp(List): newlist = qSort(List) for i, val in enumerate(newlist): List[i] = val You have to iterate over one more time, but this sorts the list in place. HTH, Tom From thorsten at thorstenkampe.de Tue May 15 08:09:15 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 15 May 2007 13:09:15 +0100 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <464996b9$0$10193$9b4e6d93@newsspool4.arcor-online.net> Message-ID: * Ren? Fleschenberg (Tue, 15 May 2007 13:17:13 +0200) > Steven D'Aprano schrieb: > >> A Python > >> project that uses Urdu identifiers throughout is just as useless > >> to me, from a code-exchange point of view, as one written in Perl. > > > > That's because you can't read it, not because it uses Unicode. It could > > be written entirely in ASCII, and still be unreadable and impossible to > > understand. > > That is a reason to actively encourage people to write their code in > English whereever possible, not one to allow non-ASCII identifiers, > which might even do the opposite. There is no reason to encourage or discourage people in which language to write their code. Code that's meant to be shared makes just a tiny percentage of all the code written right this moment. This "ready to be shared" code is neither better nor worse than "closed" german or chinese-only code. From john at datavoiceint.com Wed May 16 17:18:11 2007 From: john at datavoiceint.com (HMS Surprise) Date: 16 May 2007 14:18:11 -0700 Subject: try Message-ID: <1179350291.106871.25640@e65g2000hsc.googlegroups.com> I read in the ref man that try-except-finally did not work in earlier versions, I am using jython 2.2. Does this imply that try-except without finally does not work either? I get a syntax error on the else below. Some of the functions embedded in the try section try to convert strings to ints, etc and may fail on bad data, thus try seemed like a good start for a workaround. Thanks, jh #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def restoreDevice(self, deviceId, closeTime = time()): self.logon() try: lst = self.getLastUpdatedDevice(deviceId) lastUpdated = lst[0] incidentId = lst[1] print 'L', lastUpdated, 'I', incidentId self.restore(incidentId, lastUpdated) except: else: print "couldn't find incident" From martin at v.loewis.de Thu May 17 05:38:20 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 17 May 2007 11:38:20 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179153757.844925.14230@p77g2000hsh.googlegroups.com> <4648DF39.70901@v.loewis.de> <1179302916.340760.177420@h2g2000hsg.googlegroups.com> Message-ID: <464C228C.80302@v.loewis.de> > PEP 3131 uses a similar definition to C# except that PEP 3131 > disallows formatting characters (category Cf). See section 9.4.2 of > http://www.ecma-international.org/publications/standards/Ecma-334.htm UAX#31 discusses formatting characters in 2.2, and recognizes that there might be good reasons to allow (and ignore) them; however, it recommends against doing so except in special cases. So I decided to disallow them. Regards, Martin From steve at holdenweb.com Thu May 17 17:38:11 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 17 May 2007 17:38:11 -0400 Subject: omissions in python docs? In-Reply-To: <464C9038.6000109@v.loewis.de> References: <1179419983.750044.65030@n59g2000hsh.googlegroups.com> <464C9038.6000109@v.loewis.de> Message-ID: Martin v. L?wis wrote: > 7stud schrieb: >> I have a hard time believing I am the first one to notice those >> omissions. Are the docs just old and poorly maintained? Or, is there >> some reason those methods were omitted? > > You are likely the first one to notice, and then talk about that. > > It often happened in the past that patches were admitted which don't > simultaneously update the documentation, hence they diverge. These > days, patches are regularly rejected for not providing proper > documentation changes. > > As you now found a difference, please write a patch and submit it > to sf.net/projects/python. > Please note that the documentation patch doesn't need to be in the Latex source format used to produce the docs - editors will add any necessary markup. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From DustanGroups at gmail.com Fri May 18 19:42:14 2007 From: DustanGroups at gmail.com (Dustan) Date: 18 May 2007 16:42:14 -0700 Subject: converting strings to most their efficient types '1' --> 1, 'A' ---> 'A', '1.2'---> 1.2 In-Reply-To: <1179529661.555196.13070@k79g2000hse.googlegroups.com> References: <1179529661.555196.13070@k79g2000hse.googlegroups.com> Message-ID: <1179531734.602200.56410@n59g2000hsh.googlegroups.com> On May 18, 6:07 pm, py_genetic wrote: > Hello, > > I'm importing large text files of data using csv. I would like to add > some more auto sensing abilities. I'm considing sampling the data > file and doing some fuzzy logic scoring on the attributes (colls in a > data base/ csv file, eg. height weight income etc.) to determine the > most efficient 'type' to convert the attribute coll into for further > processing and efficient storage... > > Example row from sampled file data: [ ['8','2.33', 'A', 'BB', 'hello > there' '100,000,000,000'], [next row...] ....] > > Aside from a missing attribute designator, we can assume that the same > type of data continues through a coll. For example, a string, int8, > int16, float etc. > > 1. What is the most efficient way in python to test weather a string > can be converted into a given numeric type, or left alone if its > really a string like 'A' or 'hello'? Speed is key? Any thoughts? given the string s: try: integerValue = int(s) except ValueError, e: try: floatValue = float(s) except ValueError: pass else: s = floatValue else: s = integerValue I believe it will automatically identify base 8 and base 16 integers (but not base 8/16 floats). > 2. Is there anything out there already which deals with this issue? > > Thanks, > Conor From miki.tebeka at gmail.com Tue May 22 16:35:36 2007 From: miki.tebeka at gmail.com (Miki) Date: 22 May 2007 13:35:36 -0700 Subject: how to use python to checking password on servlet In-Reply-To: <1179846014.641052.118540@36g2000prm.googlegroups.com> References: <1179846014.641052.118540@36g2000prm.googlegroups.com> Message-ID: <1179866135.949197.119850@a26g2000pre.googlegroups.com> Hello sandeep, > my application design on java servlet i want to check password in > python & return result again servlet to forward to next page. > how to set session in python .get session It depends on the web platform you use, can you elaborate more? (To make the browser send a GET method, just specify it using the form METHOD="GET" attribute). HTH. -- Miki http://pythonwise.blogspot.com From nogradi at gmail.com Sun May 20 16:02:57 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Sun, 20 May 2007 22:02:57 +0200 Subject: model browser In-Reply-To: <5f56302b0705201155j706cc8e0ydc62a436e4c86299@mail.gmail.com> References: <5f56302b0705201155j706cc8e0ydc62a436e4c86299@mail.gmail.com> Message-ID: <5f56302b0705201302n3b061ca1g95500935e73c9561@mail.gmail.com> And before you ask, yes, I did read http://mail.python.org/pipermail/python-list/2007-May/440337.html but there was nothing beyond django/tg :) From aahz at pythoncraft.com Sat May 5 15:31:50 2007 From: aahz at pythoncraft.com (Aahz) Date: 5 May 2007 12:31:50 -0700 Subject: What happened to webmaster@python.org? References: Message-ID: In article , Carsten Haese wrote: > >I just tried sending an email to webmaster at python.org to request a >website change, and the email bounced back with this excerpt from the >delivery failure report: Oops! I've informed the appropriate people. For now, either hang on to your request or send it directly to me. Thanks for letting us know! -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Look, it's your affair if you want to play with five people, but don't go calling it doubles." --John Cleese anticipates Usenet From sinoodle at yahoo.com Fri May 11 19:51:06 2007 From: sinoodle at yahoo.com (sinoodle at yahoo.com) Date: 11 May 2007 16:51:06 -0700 Subject: Questions about bsddb In-Reply-To: References: <1178713407.968873.260950@n59g2000hsh.googlegroups.com> <1178720648.233560.319570@p77g2000hsh.googlegroups.com> <1178740902.495700.60310@p77g2000hsh.googlegroups.com> Message-ID: <1178927466.762408.321770@w5g2000hsg.googlegroups.com> Thanks for the suggestion, I do remember reading that, but I don't think that helped much. I found experimenting around with the different settings, that the cache size is where the problem was. I've got it set to 1.5 GB and it's pretty happy at the moment, and the reduction in build time is a fraction of what it used to be. Thanks again for all the suggestions. Regards, JM From gagsl-py2 at yahoo.com.ar Sat May 19 19:23:56 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 19 May 2007 20:23:56 -0300 Subject: regex matching question References: <1179595319.239229.262160@l77g2000hsb.googlegroups.com> <1179614439.044253.141170@u30g2000hsc.googlegroups.com> Message-ID: En Sat, 19 May 2007 19:40:39 -0300, bullockbefriending bard escribi?: > from my cursory skimming of friedl, i get the feeling that the all > pairs different constraint would give rise to some kind of fairly > baroque expression, perhaps likely to bring to mind the following > quotation from samuel johnson: > > "Sir, a woman's preaching is like a dog's walking on his hind legs. > It is not done well; but you are surprised to find it done at all." Try this, it's not as hard, just using match and split (with the regular expression propossed by MR): import re regex = re.compile(r'(\d+,\d+/){5}\d+,\d+') def checkline(line): if not regex.match(line): raise ValueError("Invalid format: "+line) for pair in line.split("/"): a, b = pair.split(",") if a==b: raise ValueError("Duplicate number: "+line) Here "all pairs different" means "for each pair, both numbers must be different", but they may appear in another pair. That is, won't flag "1,2/3,4/3,5/2,6/8,3/1,2" as invalid, but this wasn't clear from your original post. -- Gabriel Genellina From george.sakkis at gmail.com Wed May 23 17:01:42 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 23 May 2007 14:01:42 -0700 Subject: Parallel/distributed generator In-Reply-To: <5bjee5F2qu0euU1@mid.uni-berlin.de> Message-ID: <1179954101.940331.45260@u30g2000hsc.googlegroups.com> On May 23, 2:11 pm, "Diez B. Roggisch" wrote: > George Sakkis wrote: > > I'm looking for any existing packages or ideas on how to implement the > > equivalent of a generator (in the Python sense, i.e. > >http://www.python.org/dev/peps/pep-0255/) in a parallel/distributed > > way. As a use case, imagine a function that generates a range of > > primes. I'd like to be able to do something along the following lines: > > > def iterprimes(start=1, end=None): > > # ... > > yield prime > > > # rpc-related initialization > > ... > > rpc_proxy = some_rpc_lib(iterprimes, start=1e6, end=1e12) > > for prime in proxy: > > print prime > > > Is there any module out there that does anything close to this ? > > Have you tried using pyro to just return a generator? After all, it's just > an object with a next()-method, that raises a certain exception. I can't > see why pyro shouldn't be able to handle that. Just tried it: cPickle.PicklingError: Can't pickle : attribute lookup __builtin__.generator failed George From jzgoda at o2.usun.pl Mon May 14 09:01:20 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Mon, 14 May 2007 15:01:20 +0200 Subject: GUI tutorial In-Reply-To: <1179104242.701176.160180@e65g2000hsc.googlegroups.com> References: <1179104242.701176.160180@e65g2000hsc.googlegroups.com> Message-ID: BartlebyScrivener napisa?(a): >> Can someone point me in the direction of a good tutorial on programming >> python with a GUI? > > Alan Gauld added a gui programming tutorial to his main course. > > http://www.freenetpages.co.uk/hp/alan.gauld/ > > It's a frame page so I can't link directly, but select "GUI > Programming" under Advanced Topics on the left. wxPython section of this tutorial seems bit outdated (the code resembles what was required in time of wxPython 2.4). Anyway, the explanation of event-driven approach is essential. -- Jarek Zgoda "We read Knuth so you don't have to." From C.delete_this.Sanders at BoM.GOv.AU Fri May 18 08:06:27 2007 From: C.delete_this.Sanders at BoM.GOv.AU (Charles Sanders) Date: Fri, 18 May 2007 22:06:27 +1000 Subject: Regexes: How to handle escaped characters In-Reply-To: <877ir6r3dh.fsf@wilson.homeunix.com> References: <87tzubqniq.fsf@wilson.homeunix.com> <87irarqkz7.fsf@wilson.homeunix.com> <1179435962.962404.191600@y80g2000hsf.googlegroups.com> <877ir6r3dh.fsf@wilson.homeunix.com> Message-ID: <464d96c4$0$52290$c30e37c6@lon-reader.news.telstra.net> Torsten Bronger wrote: > Hall?chen! [...] >>> >>> Example string: u"Hollo", escaped positions: [4]. Thus, the >>> second "o" is escaped and must not be found be the regexp >>> searches. >>> >>> Instead of re.search, I call the function guarded_search(pattern, >>> text, offset) which takes care of escaped caracters. Thus, while >>> > > Tsch?, > Torsten. I'm still pretty much a beginner, and I am not sure of the exact requirements, but the following seems to work for at least simple cases when overlapping matches are not considered. def guarded_search( pattern, text, exclude ): return [ m for m in re.finditer(pattern,text) if not [ e for e in exclude if m.start() <= e < m.end() ] ] txt = "axbycz" exc = [ 3 ] # "y" pat = "[xyz]" mtch = guarded_search(pat,txt,exc) print "Guarded search text='%s' excluding %s" % ( txt,exc ) for m in mtch: print m.group(), 'at', m.start() txt = "Hollo" exc = [ 4 ] # Final "o" pat = "o$" mtch = guarded_search(pat,txt,exc) print "Guarded search text='%s' excluding %s %s matches" % (txt,exc,len(mtch)) for m in mtch: print m.group(), 'at', m.start() Guarded search text='axbycz' excluding [3] 2 matches x at 1 z at 5 Guarded search text='Hollo' excluding [4] 0 matches Simply finds all the (non-overlapping) matches and rejects any that include one of the excluded columns (the "y" in the first case and the final "o" in the second). Charles From jzgoda at o2.usun.pl Mon May 14 09:03:14 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Mon, 14 May 2007 15:03:14 +0200 Subject: GUI tutorial In-Reply-To: References: Message-ID: John K Masters napisa?(a): > Can someone point me in the direction of a good tutorial on programming > python with a GUI? I'm just starting out with python and have written a > few scripts successfully but would like to add a graphical front end to > them to make it easier for my work colleagues, most of whom have never > used a command line, to use. Each of GUI frameworks/libraries has its own tutorial and some even more than one... The choice is directly related to what library you would use. -- Jarek Zgoda "We read Knuth so you don't have to." From christopher.m.russell at gmail.com Tue May 1 13:59:14 2007 From: christopher.m.russell at gmail.com (Chris Russell) Date: 1 May 2007 10:59:14 -0700 Subject: Lisp-like macros in Python? In-Reply-To: <1178035825.193334.184250@o5g2000hsb.googlegroups.com> References: <1178035825.193334.184250@o5g2000hsb.googlegroups.com> Message-ID: <1178042354.689281.182070@h2g2000hsg.googlegroups.com> On May 1, 5:10 pm, sturlamolden wrote: > Hello > > The Lisp crowd always brags about their magical macros. I was > wondering if it is possible to emulate some of the functionality in > Python using a function decorator that evals Python code in the stack > frame of the caller. The macro would then return a Python expression > as a string. Granted, I know more Python than Lisp, so it may not work > exactly as you expect. The 'magical macros' of lisp are executed at compile time, allowing arbitrary code transformations without the loss of run time efficiency. If you want to hack this together in python you should write a preprocessor that allows python code *to be run in future* inter spaced with python code *to be executed immediately* and replaces the executed code with it's output. The immediately executed code should be able to make use of any existing code or definitions that are marked as to be compiled in the future. This is should be quite do-able in python(I think I haven't really looked at it) because it has a REPL and everything that implies, but you'd have to implement lispy macros as some kind of def_with_macros which immediately produces a string which is equivalent to the macro expanded function definition and then evaluates it. Good luck in doing anything useful with these macros in a language with non-uniform syntax however. From aleax at mac.com Thu May 31 00:22:39 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 30 May 2007 21:22:39 -0700 Subject: Create a new class on the fly References: <1180568447.449581.250500@g37g2000prf.googlegroups.com> Message-ID: <1hyy30j.f4k5tc17kc7ohN%aleax@mac.com> py_genetic wrote: > Is this possible or is there a better way. I need to create a new > class during runtime to be used inside a function. The class > definition and body are dependant on unknows vars at time of exec, > thus my reasoning here. > > class PosRecords(tables.IsDescription): > > > class A(object): > self.__init__(self, args): This makes 0 sense; maybe you should learn elementary Python syntax well _before_ trying advanced stuff, no? > ........ > def mkClass(self, args): > eval( "class B(object): ...") #definition on B is dependant > on dynamic values in string > ......do stuff with class Just use a class statement, and setattr on the resulting class object to set stuff dynamically on it. eval won't do what you want (it takes expressions, not statements), and exec is an even worse way to go about it. E.g.: class A(object): def mkClass(self, name, *k): class bah(object): pass bah.__name__ = name for n in k: setattr(bah, n, k[n]) return bah Alex From jowr.pi at gmail.com Thu May 3 02:18:10 2007 From: jowr.pi at gmail.com (Eric Gisse) Date: 2 May 2007 23:18:10 -0700 Subject: Firefighters at the site of WTC7 "Move away the building is going to blow up, get back the building is going to blow up." In-Reply-To: <1178172877.755445.101340@q75g2000hsh.googlegroups.com> References: <1178161820.731367.264500@y80g2000hsf.googlegroups.com> <1178163974.007362.13870@c35g2000hsg.googlegroups.com> <1178172877.755445.101340@q75g2000hsh.googlegroups.com> Message-ID: <1178173090.238547.62190@o5g2000hsb.googlegroups.com> On May 2, 10:14 pm, malibu wrote: > On May 2, 9:46 pm, Eric Gisse wrote: > > > On May 2, 7:10 pm, Midex wrote: > > > [...] > > > I guess the explanation that people were looking at the building and > > watching its' structure deform is too rational. > > Also, that was a Larry Silverstein impostor who > said they were going to 'pull it'. ...maybe if you read the context, it would make a little more rational sense. Fucking nutter. > And the only reason he took out huge amounts > of extra insurance on the buildings two months > before this happened was because of global > warming, because we all know a little bit of heat > will bring down steel buildings. A little heat and major structural damage. > > John From nick at craig-wood.com Sun May 6 14:30:04 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Sun, 06 May 2007 13:30:04 -0500 Subject: Python Binding References: Message-ID: Georg Grabler wrote: > There's a C library which i'd like to have python bindings for. I havn't > known anything before about how to write python bindings for a C library. > > I succeeded now by using distutils to write the first bindings for functions > and similar. > > Now, it seems as something is blocking my brain. For the library, i > need "custom" types, so types defined in this library (structures), > including pointers and similar. > > I've been thinking about what i will need to represent this lists in python. > I thought about creating an external python object, providing "information" > i get from the list in C structures which can be converted. > > Basically, it are list of packages, which have several attributes (next, > prev, etc). But i don't know how to supply a proper list from the binding / > object written in C. > > Any suggestions or hints about this? Sounds like a job for ctypes which is bundled with py 2.5. http://docs.python.org/lib/module-ctypes.html It is great for access C libraries (assuming you have a shared library (.so or .dll). You'll end up writing python code rather than C code which you'll enjoy! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From bj_666 at gmx.net Sat May 5 02:19:18 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 05 May 2007 08:19:18 +0200 Subject: Python regular expressions just ain't PCRE References: <1178323901.381993.47170@e65g2000hsc.googlegroups.com> Message-ID: In <1178323901.381993.47170 at e65g2000hsc.googlegroups.com>, Wiseman wrote: > Note: I know there are LALR parser generators/parsers for Python, but > the very reason why re exists is to provide a much simpler, more > productive way to parse or validate simple languages and process text. > (The pyparse/yappy/yapps/ generator here> argument could have been used to skip regular > expression support in the language, or to deprecate re. Would you want > that? And following the same rule, why would we have Python when > there's C?) I don't follow your reasoning here. `re` is useful for matching tokens for a higher level parser and C is useful for writing parts that need hardware access or "raw speed" where pure Python is too slow. Regular expressions can become very unreadable compared to Python source code or EBNF grammars but modeling the tokens in EBNF or Python objects isn't as compact and readable as simple regular expressions. So both `re` and higher level parsers are useful together and don't supersede each other. The same holds for C and Python. IMHO. Ciao, Marc 'BlackJack' Rintsch From ggrabler at gmail.com Sat May 12 05:22:11 2007 From: ggrabler at gmail.com (Georg Grabler) Date: Sat, 12 May 2007 09:22:11 +0000 Subject: Python Binding References: <1178618848.423760.53420@p77g2000hsh.googlegroups.com> <4640ACB5.6020507@web.de> Message-ID: You are completely right wihtin this. It's some time i didn't reply, but i've taken a look on pyrex and swig now which did cost me some time, and they really make it easier. SWIG provides more possibilities and bindings for other languages too, though - i must say i've been faster with pyrex, for some reason it fits me better. I'd like to use swig, but for some reason i've troubles defining a completely new type, so a type which is not a wrapper type, but a type provided to python. Kind regards, Georg Stefan Behnel wrote: > STiAT wrote: >> Why do you all suggest other things than the way suggested by python? > > Because going to Paris is not the only way to get french bread? > > Why would you want to write all that ugly glue code by hand that Pyrex > generates for free? Module descriptors? Class descriptors? Method > descriptors? Reference counting? That's what Pyrex saves you from. > Honestly. > > From what I read in your mail, that's exactly the kind of thing you're > having trouble with. Wouldn't you prefer concentrating on your real code > instead? > > >> I havn't got a real problem writing the code in C, actually, it looked >> as if it would give me several possibilities i wouldn't have with >> pyrex (like binding more library functions to one provided python >> function and so on). > > No idea what you mean in your parentheses, but I don't think there are > many "possibilities" you "wouldn't have with Pyrex". > > We used Pyrex to write lxml, a wrapper around the huge API of libxml2 and > libxslt. It's some 11000 lines of Pyrex code by now, but the generated C > code is some 67000 lines in total. Even if it's somewhat verbose and > generic in places, I wouldn't have wanted to write that by hand. > > Stefan From rahulnag22 at yahoo.com Wed May 30 12:48:22 2007 From: rahulnag22 at yahoo.com (rahulnag22 at yahoo.com) Date: 30 May 2007 09:48:22 -0700 Subject: Tkinter Listbox - Different Text colors in one listbox In-Reply-To: <1180526692.171952.310950@w5g2000hsg.googlegroups.com> References: <1180458123.139727.182500@d30g2000prg.googlegroups.com> <1180526692.171952.310950@w5g2000hsg.googlegroups.com> Message-ID: <1180543702.421694.147650@x35g2000prf.googlegroups.com> On May 30, 6:04 am, rfg... at gmail.com wrote: > On May 29, 2:02 pm, rahulna... at yahoo.com wrote: > > > Hi, > > Is it possible to havedifferentitems in alistboxindifferentcolors? Or is it justonecolor for all items in alistbox? > > Thanks > > Rahul > > from Tkinter import * > > root = Tk() > l = Listbox(root) > l.pack() > for x in range(10): > l.insert(END, x) > l.itemconfig(2, bg='red', fg='white') > l.itemconfig(4, bg='green', fg='white') > l.itemconfig(5, bg='cyan', fg='white') > root.mainloop() > > You can _only_ configurate 'background', 'foreground', > 'selectbackground', 'selectforegroud', not font :( > > HTH Thanks for the feedback all. I tried the itemconfig method and it works great. Thanks From gregcorradini at gmail.com Tue May 8 13:14:58 2007 From: gregcorradini at gmail.com (Greg Corradini) Date: Tue, 8 May 2007 10:14:58 -0700 (PDT) Subject: 1.#QNAN Solution Message-ID: <10379999.post@talk.nabble.com> Hello all, I'm running descriptive stats on mileages from a database (float numbers, about a million records). My sum returns 1.#QNAN, which I understand from searching this forum is an error. While I'm looking for help in solving this problem, I'm more interested in a general explanation about the cause of this problem. Any ideas? Thanks Greg Corradini -- View this message in context: http://www.nabble.com/1.-QNAN-Solution-tf3710941.html#a10379999 Sent from the Python - python-list mailing list archive at Nabble.com. From walterbyrd at iname.com Thu May 17 10:36:54 2007 From: walterbyrd at iname.com (walterbyrd) Date: 17 May 2007 07:36:54 -0700 Subject: In a text file: how do I tell the EOF, from a blank line? In-Reply-To: <134nlhtgg55qg9d@corp.supernews.com> References: <1179368197.929029.134400@p77g2000hsh.googlegroups.com> <134nlhtgg55qg9d@corp.supernews.com> Message-ID: <1179412609.648556.293340@h2g2000hsg.googlegroups.com> On May 16, 10:12 pm, Grant Edwards wrote: > On 2007-05-17, walterbyrd wrote: > > This has already been explained to you by at least 5 different > people -- complete with examples. Sorry about dual posting. I am using google groups. Usually, after I submit a message, I can find that message after a few minutes. This time, I could not find the messages that I posted after waiting for hours. I figured something must have gone wrong, so I re-posted. From gagsl-py2 at yahoo.com.ar Mon May 21 07:29:08 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 21 May 2007 08:29:08 -0300 Subject: Translating some Java to Python References: <1179692679.422164.27700@r3g2000prh.googlegroups.com> <1179738814.282655.192700@r3g2000prh.googlegroups.com> <465176ce$0$323$e4fe514c@news.xs4all.nl> Message-ID: En Mon, 21 May 2007 07:39:09 -0300, Unknown escribi?: > "Ant" schreef in bericht > news:1179738814.282655.192700 at r3g2000prh.googlegroups.com... > >> Herman has shown you *how* to do static methods in Python, but >> typically they are not used. Since Python has first class functions, >> and they can be defined at the module level, there is no need to use >> static methods. > > As an experienced developer I'm rather new to Python, so please forgive > me any non-Pythonic babbling. >> From a language point you're probably right, but from a design point I'd > like to have methods that are clearly associated with a class as methods > of that class, even if they don't use any class or instance related data. In that case you might want to revise the design, perhaps you carry some preconceptions about how things should be, that are not directly applicable here. (I'm not saying this is related to your specific problem because I don't know exactly what you want, but in general, a lot of design patterns *implementations* are not directly applicable to Python). Modules are objects too - they're a good example of singletons. If you want to create a class containing only static methods: use a module instead. If you want to create a class having a single instance (a singleton), most of the time you can use a module instead. Functions don't *have* to be methods in a class, and the resulting design may still be a good design from an OO point of view. -- Gabriel Genellina From exarkun at divmod.com Thu May 10 08:53:11 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 10 May 2007 08:53:11 -0400 Subject: Thread-safe dictionary In-Reply-To: <1178801124.236604.153070@u30g2000hsc.googlegroups.com> Message-ID: <20070510125311.19381.68228471.divmod.quotient.31667@ohm> On 10 May 2007 05:45:24 -0700, tuom.larsen at gmail.com wrote: >Hi, > >please consider the following code: > > >from __future__ import with_statement > >class safe_dict(dict): > def __init__(self, *args, **kw): > self.lock = threading.Lock() > dict.__init__(self, *args, **kw) > def __getitem__(self, key): > with self.lock: > return dict.__getitem__(self, key) > def __setitem__(self, key, value): > with self.lock: > dict.__setitem__(self, key, value) > def __delitem__(self, key): > with self.lock: > dict.__delitem__(self, key) > > >- would I need to override another methods e.g. update() or items() in >order to remain thread-safe or is this enough? >- in __getitem__, does it release the lock after returning the item? >- wouldn't it be better to use threading.RLock, mutex, ... instead? > The builtin dict type is already thread safe. Jean-Paul From romain.feuillette at st.com Thu May 10 04:31:50 2007 From: romain.feuillette at st.com (Romain FEUILLETTE) Date: Thu, 10 May 2007 10:31:50 +0200 Subject: Newbie Prob : IDLE can't import Tkinter Message-ID: <4642D876.7090000@st.com> Hello, I'have just install Python 2.5.1 on Linux and the IDLE doesn't seem to works because it didn't find Tcl/Tk Is there someone to explain how to modify the file "setup.py" to tell the install that Tcl/Tk are at the paht : "/usr/bin/tclsh" and "usr/bin/wish/" ? I have attached to log file of my terminal. Thanks a lot in advance. Romain -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: idle_error.log URL: From laurent.pointal at limsi.fr Thu May 10 04:55:15 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Thu, 10 May 2007 10:55:15 +0200 Subject: preferred windows text editor? In-Reply-To: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> References: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> Message-ID: T. Crane a ?crit : > Right now I'm using Notepad++. What are other people using? > > trevis Notepad++ :-) And still use ConTEXT from time to time when I have big (MB) xml files to look at. From torriem at chem.byu.edu Sun May 13 15:49:11 2007 From: torriem at chem.byu.edu (Michael Torrie) Date: Sun, 13 May 2007 13:49:11 -0600 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46476081.7080609@web.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476081.7080609@web.de> Message-ID: <1179085751.17533.18.camel@enterprise> On Sun, 2007-05-13 at 21:01 +0200, Stefan Behnel wrote: > For example, I could write > > def zieheDreiAbVon(wert): > return zieheAb(wert, 3) > > and most people on earth would not have a clue what this is good for. However, > someone who is fluent enough in German could guess from the names what this does. > > I do not think non-ASCII characters make this 'problem' any worse. So I must > ask people to restrict their comments to the actual problem that this PEP is > trying to solve. I think non-ASCII characters makes the problem far far worse. While I may not understand what the function is by it's name in your example, allowing non-ASCII characters makes it works by forcing all would-be code readers have to have all kinds of necessary fonts just to view the source code. Things like reporting exceptions too. At least in your example I know the exception occurred in zieheDreiAbVon. But if that identifier is some UTF-8 string, how do I go about finding it in my text editor, or even reporting the message to the developers? I don't happen to have that particular keymap installed in my linux system, so I can't even type the letters! So given that people can already transliterate their language for use as identifiers, I think avoiding non-ASCII character sets is a good idea. ASCII is simply the lowest denominator and is support by *all* configurations and locales on all developers' systems. > > Stefan From mikeminer53 at hotmail.com Wed May 23 12:53:37 2007 From: mikeminer53 at hotmail.com (mkPyVS) Date: 23 May 2007 09:53:37 -0700 Subject: Resizing listbook's listview pane In-Reply-To: <1179932659.180278.72990@w5g2000hsg.googlegroups.com> Message-ID: <1179939217.550237.300830@o5g2000hsb.googlegroups.com> On May 23, 9:04 am, kyoso... at gmail.com wrote: > Which Python gui toolkit are you using? Tkinter, wxPython, pyQT? Are > you wanting the resize to happen programmatically, when the user > changes the app's size, both or what? > > More details would be helpful. > > Mike Sorry, copied from wxpython submit as well.. I'm using wxpython 2.8... Primariy I want the resize to happen programatically during object creation/post creation... I can worry about app size changes later. Thanks, From newsgroups at debain.org Mon May 21 15:53:30 2007 From: newsgroups at debain.org (Samuel) Date: Mon, 21 May 2007 19:53:30 +0000 (UTC) Subject: Components for a client/server architecture References: <5bd99qF2s85heU1@mid.uni-berlin.de> Message-ID: On Mon, 21 May 2007 12:06:50 +0200, Diez B. Roggisch wrote: > I'm not sure which configuration you want to change how often. But I'm > not convinced that the python threading limitations really do make a > difference here. Do you really benefit from multi-core capabilities in > this scenario? The threading issues are not bound to multi cpu systems. The problem is that some of Python's blocking functions require holding the global lock. "Not all built-in functions that may block waiting for I/O allow other threads to run." "It is not possible to interrupt the acquire() method on a lock" http://docs.python.org/lib/module-thread.html I also found that IronPython does not have a global lock, so far it seems well suited for solving the problems I am trying to avoid. I am still looking for a good comparison between IronPython, Python, and Jython. > Sounds like CORBA to me. CORBA has a very mature and good implementation > for Python called OmniORB, and interoperability with other orbs (the > ones available for e.g. Java) is very good - as CORBA as standard is > mature. I have worked with Bonobo (an implementation of CORBA) before, though not on the network - it is fairly complex. But I did not think of using it for this purpose, it might actually make sense. I'll have to look into the transport protocol more. > And from what I know about SOAP it's certainly not better > suited (besides the fact that it sucks big time anyway) SOAP seems well suited for web services. But it comes with quite some overhead, I tend to say that it's not a perfect fit for our purpose. Thank you for your comment! -Samuel From thorsten at thorstenkampe.de Sun May 20 13:31:46 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun, 20 May 2007 18:31:46 +0100 Subject: zipfile [module and file format, both] stupidly broken References: <1179675378.137903.83170@y80g2000hsf.googlegroups.com> Message-ID: * Paul Boddie (20 May 2007 08:36:18 -0700) > Thorsten Kampe wrote: > > Don't be silly. Where would you look for the URL to report bugs? On > > the website of the project, of course. It's not that easy to find on > > python.org (although not as hard as Martin says): > > > > Core Development > Links for Developers > Bug Manager or > > This is the "in crowd" route. Hehe > > About > Help > Got a Python problem or question? > Python Bug Tracker > > And this is the "it's not my fault, it's yours" route. Hehe, it's /never/ my fault, actually ;) > > Both ways are kind of misleading (or non-intuitive) as you do not want > > to engage in Core Development to report a bug. Lots of good projects > > have a prominent link on their website (start page) how to report > > bugs. Python hasn't. > > Indeed. The big problem with python.org in its current form is the > navigation, as I have complained about already. Yeah, probably. But for me there is no doubt that the website's new appearance looks much better, cleaner, more professional and visually pleasing than the previous one. Thorsten From half.italian at gmail.com Fri May 11 03:22:35 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 11 May 2007 00:22:35 -0700 Subject: module error for elementtree In-Reply-To: <1178867119.666923.204000@h2g2000hsg.googlegroups.com> References: <1178867119.666923.204000@h2g2000hsg.googlegroups.com> Message-ID: <1178868155.638154.112200@h2g2000hsg.googlegroups.com> On May 11, 12:05 am, saif.shak... at gmail.com wrote: > #!/usr/bin/env python > > from elementtree import ElementTree as Element > tree = et.parse("testxml.xml") > > for t in tree.getiterator("SERVICEPARAMETER"): > if t.get("Semantics") == "localId": > t.set("Semantics", "dataPackageID") > > tree.write("output.xml") > > Hi, > For the above code to work elementtree is > imported in first line ,but when running it says : > ImportError: No module named elementtree.ElementTree > Does thie module exists as default or a patch is needed? > Thanks http://groups.google.com/group/comp.lang.python/browse_frm/thread/e095cc79d1efb99/a4523a6e9b7061af?rnum=1#a4523a6e9b7061af Read carefully. From sidewinder.asu at gmail.com Thu May 24 13:54:20 2007 From: sidewinder.asu at gmail.com (Christopher Anderson) Date: Thu, 24 May 2007 10:54:20 -0700 Subject: Windows Debugging w/o MS In-Reply-To: <1179933005.903709.258250@q75g2000hsh.googlegroups.com> References: <1179933005.903709.258250@q75g2000hsh.googlegroups.com> Message-ID: <5a12a1120705241054j70535724v2d6d925a25029421@mail.gmail.com> > Debug builds are incompatible with release builds. You'll need to > build every binary extension in debug mode (assuming the original > authors don't provide debug builds). Right, and this is what I would like to avoid having to do. Thanks, Chris PS. Sorry for the duplicate olsongt From jstroud at mbi.ucla.edu Tue May 8 20:51:47 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 08 May 2007 17:51:47 -0700 Subject: tkinter get widget option value In-Reply-To: <1178649638.119603.265380@y5g2000hsa.googlegroups.com> References: <1178649638.119603.265380@y5g2000hsa.googlegroups.com> Message-ID: rahulnag22 at yahoo.com wrote: > Hi, > If I have a button widget > > w = Button(root, text = "Button", state = 'disabled') > > How can I get the value of option 'state' from the widget 'w'. > I want something like -- > > print w.state >> to print out >> 'disabled' > > Thanks > Rahul > print w["state"] James From gh at gregor-horvath.com Sat May 19 00:20:33 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Sat, 19 May 2007 06:20:33 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179523111.401781.125660@k79g2000hse.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <464C5382.6080403@v.loewis.de> <1179423799.254286.294930@w5g2000hsg.googlegroups.com> <1179503525.018943.95740@u30g2000hsc.googlegroups.com> <1179508599.868680.177960@e65g2000hsc.googlegroups.com> <1179523111.401781.125660@k79g2000hse.googlegroups.com> Message-ID: sjdevnull at yahoo.com schrieb: > opposed. But dismissing the fact that Outlook and other quite common > tools may have severe problems with code seems naive (or disingenuous, > but I don't think that's the case here). Of course there is broken software out there. There are even editors that mix tabs and spaces ;-) Python did not introduce braces to solve this problem but encouraged to use appropriate tools. It seems to work for 99% of us. Same here. It is the 21st century. Tools that destroy Unicode byte streams are seriously broken. Face it. You can not halt progress because of some broken software. Fix or drop it instead. I do not think that this will be a big problem because only a very small fraction of specialized local code will use Unicode identifiers anyway. Unicode strings and comments are allowed today and I didn't heard of a single issue of destroyed strings because of bad editors, although I guess that Unicode strings in code are way more common than Unicode identifiers would ever be. Gregor From miki.tebeka at gmail.com Fri May 4 16:37:04 2007 From: miki.tebeka at gmail.com (Miki) Date: 4 May 2007 13:37:04 -0700 Subject: how to find a lable quickly? In-Reply-To: References: Message-ID: <1178311024.265842.242870@o5g2000hsb.googlegroups.com> Hello Frank, > I am a new user on Python and I really love it. The more you know, the deeper the love :) > I have a big text file with each line like: > > label 3 > teststart 5 > endtest 100 > newrun 2345 > > I opened the file by uu=open('test.txt','r') and then read the data as > xx=uu.readlines() This reads the whole file to memory, which might be a problem. > In xx, it contains the list of each line. I want to find a spcefic labels > and read the data. Currently, I > do this by > for ss in xx: > zz=ss.split( ) > if zz[0] = endtest: > index=zz[1] > > Since the file is big and I need find more lables, this code runs slowly. > Are there anyway to speed up the process? I thought to convert the data xx > from list to a dictionay, so I can get the index quickly based on the > label. Can I do that effeciently? IMO a better way is either to not load the whole file to memory: # Untested labels = {}.fromkeys(["endtest", "other_label"]) for line in open("test.txt"): label, value = line.split() if label in labels: labels[label] = value.strip() Another option is to use an external fast program (such as egrep): from os import popen labels = {} for line in popen("egrep 'endtest|other_label' test.txt"): label, value = line.strip().split() labels[label] = value HTH, -- Miki http://pythonwise.blogspot.com/ From bdesth.quelquechose at free.quelquepart.fr Wed May 2 19:38:52 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 03 May 2007 01:38:52 +0200 Subject: Can I use Python instead of Joomla? In-Reply-To: <1178138925.498663.252920@o5g2000hsb.googlegroups.com> References: <1178138925.498663.252920@o5g2000hsb.googlegroups.com> Message-ID: <4639173e$0$2415$426a74cc@news.free.fr> walterbyrd a ?crit : > If I wanted to build a website with forums, news feeds, galleries, > event calander, document managment, etc. I do so in Joomla easily. > > But, I would perfer to use django/python, if that would be at all > practical. > > I suppose I could put python scripts into django, if those scripts > exist. > You're mixing apples, fishes, and cars here. Joomla is a content management system, Django a framework and Python a language. From john at datavoiceint.com Tue May 8 22:06:14 2007 From: john at datavoiceint.com (HMS Surprise) Date: 8 May 2007 19:06:14 -0700 Subject: String parsing In-Reply-To: References: <1178672992.522463.228620@l77g2000hsb.googlegroups.com> Message-ID: <1178676374.081202.74850@e51g2000hsg.googlegroups.com> Thanks for posting. Could you reccommend an HTML parser that can be used with python or jython? john From tkpmep at hotmail.com Wed May 9 18:49:49 2007 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: 9 May 2007 15:49:49 -0700 Subject: Behavior of mutable class variables In-Reply-To: <1178748332.766271.86950@e51g2000hsg.googlegroups.com> References: <1178744257.369030.95310@w5g2000hsg.googlegroups.com> <1178745918.395377.282470@u30g2000hsc.googlegroups.com> <1178748332.766271.86950@e51g2000hsg.googlegroups.com> Message-ID: <1178750989.107897.260360@y80g2000hsf.googlegroups.com> Thanks for the insights. I solved the problem as follows: I created a new class method called cleanUp, which resets NStocks to an empty list and N1 to 0. Works like a charm - it's the first time I've used a class method, and I immediately see its utility. Thanks again class Stock(object): NStocks = [] #Class variables N1 = 0 @classmethod def cleanUp(cls): Stocks.NStocks = [] Stocks.N1 = 0 def simulation(N, par1, par2, idList, returnHistoryDir): Stock.cleanUp() results = ...... print results. From baptiste13 at altern.org Mon May 7 17:26:09 2007 From: baptiste13 at altern.org (Baptiste Carvello) Date: Mon, 07 May 2007 23:26:09 +0200 Subject: matplotlib: howto redraw figure automatically, without stop in show()/draw()? In-Reply-To: <463f1b6f$0$11094$3b214f66@aconews.univie.ac.at> References: <1178532299.418643.267790@e51g2000hsg.googlegroups.com> <463f1b6f$0$11094$3b214f66@aconews.univie.ac.at> Message-ID: WEINHANDL Herbert a ?crit : > dmitrey wrote: >> Hi all, >> here is a question already mentioned below, and I'm also interested in >> that one very much. >> unfortunatly, I can't write anything to matplotlib mailing lists >> because I constantly get server internal error (500) >> Does anyone knows the answer? > > maybe this is what you want ? > > http://matplotlib.sourceforge.net/faq.html#DYNAMIC > > happy pythoning > > herbert Or maybe simply this ? http://matplotlib.sourceforge.net/interactive.html Baptiste From b24warbaby at gmail.com Mon May 14 13:51:44 2007 From: b24warbaby at gmail.com (wb) Date: 14 May 2007 10:51:44 -0700 Subject: Jessica Simpson Sports new "Boob Job"!!!@ In-Reply-To: <1179126576.229946.109600@k79g2000hse.googlegroups.com> References: <1179126576.229946.109600@k79g2000hse.googlegroups.com> Message-ID: <1179165104.582094.200400@l77g2000hsb.googlegroups.com> On May 14, 2:09 am, ready.or.speci... at gmail.com wrote: If her boobs getting any bigger she won't be able to stand up. From gagsl-py2 at yahoo.com.ar Thu May 3 23:44:43 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 04 May 2007 00:44:43 -0300 Subject: file Error References: <1178195977.521889.167910@p77g2000hsh.googlegroups.com> <1178198152.382431.306950@c35g2000hsg.googlegroups.com> Message-ID: En Thu, 03 May 2007 10:15:52 -0300, escribi?: > Thanks for the reply........How do i accept the filename is a > parameter and avoid the error.Can you elaborate. To get the arguments passed to the script, use sys.argv[] Most introductory texts should cover it, like the Python tutorial: http://docs.python.org/tut/node4.html -- Gabriel Genellina From tkpmep at hotmail.com Mon May 21 13:40:07 2007 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: 21 May 2007 10:40:07 -0700 Subject: pyExcelerator bug? In-Reply-To: <4650C482.4090606@lexicon.net> References: <1179355368.793891.233240@u30g2000hsc.googlegroups.com> <1179694886.941462.308560@b40g2000prd.googlegroups.com> <4650C482.4090606@lexicon.net> Message-ID: <1179769206.923238.73190@b40g2000prd.googlegroups.com> John, I'd be delighted to try xlwt (does it work under Python 2.4 and 2.5?) I followed the link to ...svn/xlwt/trunk and found a collection of files, but no Windows installer. How do I install xlwt? Thanks in advance Thomas Philips From gdonald at gmail.com Tue May 1 15:58:27 2007 From: gdonald at gmail.com (Greg Donald) Date: Tue, 1 May 2007 14:58:27 -0500 Subject: Using python with MySQL In-Reply-To: <1178048415.272711.261930@n59g2000hsh.googlegroups.com> References: <1178048415.272711.261930@n59g2000hsh.googlegroups.com> Message-ID: <15e66e4e0705011258m36ad5450s7f3bd1ef64abe1f1@mail.gmail.com> On 1 May 2007 12:40:20 -0700, HMS Surprise wrote: > I need to peform some simple queries via MySQL. Searching the list I > see that folks are accessing it with python. I am very new to python > and pretty new to MySQL too. Would appreciate it if you could point me > to some documentation for accessing MySQL via python. Something of the > "Python and MySQL for Dummies" caliber would be about my speed, but of > course I will be thankful for anything offered. http://mysql-python.sourceforge.net/ -- Greg Donald http://destiney.com/ From aleax at mac.com Mon May 7 00:34:03 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 6 May 2007 21:34:03 -0700 Subject: My newbie annoyances so far References: <1177688082.758043.133920@r30g2000prh.googlegroups.com> <_9pYh.1787$uJ6.894@newssvr17.news.prodigy.net> <1178400807.051103.95690@q75g2000hsh.googlegroups.com> <1hxp15f.1bvtgo11ydx3cvN%aleax@mac.com> <1hxpfyw.oaolu9kesvabN%aleax@mac.com> Message-ID: <1hxpnk5.7ipnxkxk39cbN%aleax@mac.com> Neil Hodgson wrote: > Alex Martelli: > > > Can you run a generic benchmark "inside the current implementation of > > Flash" to check out its Javascript performance? I can't, so, ... > > I can't either (without going to a lot of effort) so here is a page > comparing SpiderMonkey and Tamarin from someone with an adobe.com address: > > http://www.playercore.com/pub/Tamarin/Avmplus_vs._javascript.htm > > The median improvement for Tamarin over SpiderMonkey is better than > 2:1 and for Tamarin with type declarations better than 4:1. There are > some tests with much more noticeable results but overall we're not > looking at C or Lisp compiler levels of performance even with type > declarations. Thanks! Trusting those reports, it looks like CPython may well NOT be particularly (or, at all...?) slower than Javascript with Tamarin -- making the assertion that CPython is "unreasonably slower" than some Javascript implementation definitely unfounded, if so. Alex From notbob at nothome.com Fri May 11 18:03:26 2007 From: notbob at nothome.com (notbob) Date: Fri, 11 May 2007 17:03:26 -0500 Subject: OMG BRITNEYS AT IT AGAIN AGAIN!!!!!! References: <1178920641.280005.221690@p77g2000hsh.googlegroups.com> Message-ID: <24edndmfSP6zddnbnZ2dnUVZ_oSdnZ2d@comcast.com> On 2007-05-11, wise.of.clean789 at gmail.com wrote: > http://britneyboobs.blogspot.com/2007/05/britney-spears-slips-up-again-exposes.html > - Exclusive pics of Britney Spears...... Britneyboobs ....what?... you take pride in being one? nb From stephen04 at tiscali.co.uk Thu May 17 21:21:05 2007 From: stephen04 at tiscali.co.uk (Stephen Lewitowski) Date: Fri, 18 May 2007 02:21:05 +0100 Subject: Python Newbie Suggestions In-Reply-To: <1179282318.821090.82840@h2g2000hsg.googlegroups.com> References: <1179264515.958714.72880@l77g2000hsb.googlegroups.com> <464a50d7$1_4@mk-nntp-2.news.uk.tiscali.com> <1179282318.821090.82840@h2g2000hsg.googlegroups.com> Message-ID: <464cff85$1_4@mk-nntp-2.news.uk.tiscali.com> Michael Tobis wrote: > I think > > http://www.diveintopython.org/ > > would be very suitable for you. > > mt > > > > I disagree here. The site was last updated in 2004; its out of date. For a newbie any material referenced should be current and include what is available in Python 2.5. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon May 14 07:33:16 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 14 May 2007 13:33:16 +0200 Subject: How to do basic CRUD apps with Python In-Reply-To: <1179098458.333666.307750@e65g2000hsc.googlegroups.com> References: <1179098458.333666.307750@e65g2000hsc.googlegroups.com> Message-ID: <464848fa$0$465$426a74cc@news.free.fr> walterbyrd a ?crit : > With PHP, libraries, apps, etc. to do basic CRUD are everywhere. Ajax > and non-Ajax solutions abound. > > With Python, finding such library, or apps. seems to be much more > difficult to find. > > I thought django might be a good way, but I can not seem to get an > answer on that board. > > I would like to put together a CRUD grid with editable/deletable/ > addable fields, click on the headers to sort. Something that would > sort-of looks like an online spreadsheet. It would be nice if the > fields could be edited in-line, but it's not entirely necessary. > > Are there any Python libraries to do that sort of thing? Can it be > done with django or cherrypy? You may want to have a look at turbogears's widgets. From maric at aristote.info Tue May 29 11:34:27 2007 From: maric at aristote.info (Maric Michaud) Date: Tue, 29 May 2007 17:34:27 +0200 Subject: [B,IX] = sort(A,...) - Order for sort()-function In-Reply-To: <8cc339d80705290734r3c0e3828vd53e1b80de89527@mail.gmail.com> References: <8cc339d80705290734r3c0e3828vd53e1b80de89527@mail.gmail.com> Message-ID: <465C4803.2040007@aristote.info> Orlando D?hring a ?crit : > ... > A = [ 3 7 5 > 0 4 2 ]; > > # in Python: A = [[3,7,5],[0,4,2]] > > [B,IX] = sort(A,2) > > # sort by rows > > B = > 3 5 7 > 0 2 4 > > IX = > 1 3 2 > 1 3 2 > > # first line: 3 was formerly in the first position, 5 formerly in > position 3, 7 formerly in position 2 > # second line: similiarly > > Like this : In [122]: l=[[3,2,1], [4,6,5,0]] In [123]: from operator import itemgetter In [124]: [ list(sorted(enumerate(e), key=itemgetter(1))) for e in l ] Out[124]: [[(2, 1), (1, 2), (0, 3)], [(3, 0), (0, 4), (2, 5), (1, 6)]] except the old position is the first element of each tuple, you may have the same order with this one : In [126]: [ list((pos, elt) for pos, elt in sorted(enumerate(e), key=itemgetter(1))) for e in l ] Out[126]: [[(1, 2), (2, 1), (3, 0)], [(0, 3), (4, 0), (5, 2), (6, 1)]] From sjmachin at lexicon.net Sat May 5 19:39:19 2007 From: sjmachin at lexicon.net (John Machin) Date: 5 May 2007 16:39:19 -0700 Subject: change of random state when pyc created?? In-Reply-To: References: Message-ID: <1178408359.113807.181570@l77g2000hsb.googlegroups.com> On May 5, 1:48 pm, "Alan Isaac" wrote: > This may seem very strange, but it is true. > If I delete a .pyc file, my program executes with a different state! > > In a single directory I have > module1 and module2. > > module1 imports random and MyClass from module2. That's rather ambiguous. Do you mean (a) module1 imports random and (MyClass from module2) or (b) module1 imports (random and MyClass) from module2 > module2 does not import random. This statement would *appear* to rule out option (b) but appearances can be deceptive :-) It's a bit of a worry that you call the first file "module1" and not "the_script". Does module2 import module1, directly or indirectly? > > module1 sets a seed like this:: > > if __name__ == "__main__": > random.seed(314) > main() > > I execute module1.py from the (Windows) shell. > I get a result, let's call it result1. > I execute it again. I get another result, say result2. > Running it again and again, I get result2. Stop right there. Never mind what happens when you delete module2.pyc. Should you not expect to get the same result each time? Is that not the point of setting a constant seed each time you run the script? ====>>> Problem 1. > > Now I delete module2.pyc. > I execute module1.py from the shell. > I get result1. > I execute it again; I get result2. > From then on I get result2, > unless I delete module.pyc again, > in which case I once again get result1. > > Can someone explain this to me? > > Thank you, > Alan Isaac Compiling module2 is causing code to be executed that probably shouldn't be executed. ===>>> Problem 2. With all due respect to your powers of description :-) no, it can't be explained properly, without seeing the contents of the source files. I strongly suggest that if you continue to experience Problem1 and/or Problem 2, you cut your two files down to the bare minima and post them here. Meanwhile, my deja-vu detector is kicking in ... uh-huh (1), from 25 April: === %%%%% test2.py %%%%%%%%%%%%% from random import seed seed(314) class Trivial: pass === Is module2 (still) doing that? Is module1 importing itself (directly or indirectly)? uh-huh (2), the long thread about relative imports allegedly being broken ... It appears to me that you need to divorce the two concepts "module" and "script" in your mind. Modules when executed should produce only exportables: classes, functions, NAMED_CONSTANTS, etc. It is OK to do things like process the easier-to-create _ds = """\ foo 1 bar 42 zot 666""" into the easier-to-use USEFUL_DICT = {'foo': 1, 'bar': 42, zot: 666} but not to change global state. Scripts which use functions etc from a module or package should be independent of the module/package such that they don't need anything more complicated than simple importing of the module/package. The notion of inspecting the script's path to derive the module/package path and then stuffing that into sys.paths is mind boggling. Are module1/script1 and module2 parts of a package? Here's a suggestion for how you should structure scripts: def main(): # All productive code is inside a function to take advantage # of access to locals being faster than access to globals import mymodule mymodule.do_something() if __name__ == "__main__": main() else: raise Exception("Attempt to import script containing nothing importable") and your modules should *start* with: if __name__ == "__main__": raise Exception("Attempt to execute hopefully-pure module as a script") HTH, John From don.stockbauer at gmail.com Wed May 2 23:20:56 2007 From: don.stockbauer at gmail.com (Don Stockbauer) Date: 2 May 2007 20:20:56 -0700 Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? In-Reply-To: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> Message-ID: <1178162456.929395.139390@q75g2000hsh.googlegroups.com> Ask yourself WHY havn't I seen this footage before? **************************** "Don, why havent you seen this footage before?" he asked himself, self- referentially in the best tradition of Douglas R. Hofstadter. 'Er, because I haven't seen it before?" Don responded in a tautological fashion. (uproarius laughter ensues) From cbtube03 at gmail.com Sat May 12 14:43:50 2007 From: cbtube03 at gmail.com (cbtube03 at gmail.com) Date: 12 May 2007 11:43:50 -0700 Subject: package rating system for the Cheese Shop Message-ID: <1178995430.511788.161150@e51g2000hsg.googlegroups.com> Is there a package rating system for the Cheese Shop, like how Perl has cpanratings (http://cpanratings.perl.org/)? Do you think it would be useful? I see that we already have Cheesecake (http://pycheesecake.org/) for rating a package's kwalitee (like Perl's CPANTS). But browsing the Cheese Shop, I don't see a way to view or sort by Cheesecake rating... How can I see the kwalitee ratings of the packages at the Cheese Shop? From rene at korteklippe.de Wed May 16 06:00:37 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Wed, 16 May 2007 12:00:37 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <46478694$0$1412$426a34cc@news.free.fr> <1hy252p.1anf7sr1p4yp12N%aleax@mac.com> <464988a4$0$20289$9b4e6d93@newsspool3.arcor-online.net> <464aaee8$0$10188$9b4e6d93@newsspool4.arcor-online.net> <464ab811$0$10185$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <464ad643$0$23136$9b4e6d93@newsspool1.arcor-online.net> Gregor Horvath schrieb: >> *That* logic can be used to justify the introduction of *any* feature. >> > > No. That logic can only be used to justify the introduction of a feature > that brings freedom. That is any feature that you are not forced to use. So let's get gotos and the like. Every programming language dictates some things. This is not a bad thing. -- Ren? From john at datavoiceint.com Tue May 22 14:40:16 2007 From: john at datavoiceint.com (HMS Surprise) Date: 22 May 2007 11:40:16 -0700 Subject: Inheritance Message-ID: <1179859216.425460.252130@w5g2000hsg.googlegroups.com> I am trying to understand the 'if' statement and the exec statement in the code below. I would like to add several common routines to this class and then inherit it into a class in another file. This other class would need to access these common functions as well as inherit the PyHttpTestCase class. In particular what is the purpose of the surrounding plus signs? May I assume the if statement overrides an imported assignment statement. Thanks, jh ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ from PyHttpTestCase import PyHttpTestCase from com.bitmechanic.maxq import Config global validatorPkg if __name__ == 'main': validatorPkg = Config.getValidatorPkgName() # Determine the validator for this testcase. exec 'from '+validatorPkg+' import Validator' # definition of test class class baseClass(PyHttpTestCase): def logon() print 'logon()' def runTest(self): print 'runTest()' def myFn(self): print 'myFn()' # Code to load and run the test if __name__ == 'main': test = baseClass("bClass") test.runTest() From normanlorrain at telusplanet.net Wed May 16 23:30:46 2007 From: normanlorrain at telusplanet.net (Norman Lorrain) Date: Thu, 17 May 2007 03:30:46 GMT Subject: how do I count spaces at the beginning of a string? References: <1179367338.906430.97420@k79g2000hse.googlegroups.com> Message-ID: <2007051621305616807-normanlorrain@telusplanetnet> On 2007-05-16 20:02:18 -0600, walterbyrd said: > The strings start with whitespace, and have a '*' or an alphanumeric > character. I need to know how many whitespace characters exist at the > beginning of the string. a = ' three spaces' print len(a) -len(a.lstrip()) From timr at probo.com Thu May 24 02:59:32 2007 From: timr at probo.com (Tim Roberts) Date: Thu, 24 May 2007 06:59:32 GMT Subject: 0 == False but [] != False? References: <1179982400.412340.178710@g4g2000hsf.googlegroups.com> Message-ID: <1rda53hphn117k5scvcqrc7c2e37utfhgu@4ax.com> Rajarshi wrote: >This is a slightly naive question, but I know that 0 can be used to >represent False. So > >>>> 0 == False >True > >But, I know I can use [] to represent False as in > >>>> if not []: print 'empty' >... >empty > >But then doing the following gives a surprising (to me!) result > >>>> [] == False >False > >Could anybody point out why this is the case? False is just a constant. 0, (), '', [], and False are all constants that happen to evaluate to a false value in a Boolean context, but they are not all the same. As a general rule, I've found code like "if x == False" to be a bad idea in ANY language. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From tuom.larsen at gmail.com Sat May 12 21:00:21 2007 From: tuom.larsen at gmail.com (tuom.larsen at gmail.com) Date: 12 May 2007 18:00:21 -0700 Subject: Thread-safe dictionary In-Reply-To: <46458b72$0$7654$9b622d9e@news.freenet.de> References: <1178821512.229872.98120@n59g2000hsh.googlegroups.com> <46458b72$0$7654$9b622d9e@news.freenet.de> Message-ID: <1179018021.322981.267300@w5g2000hsg.googlegroups.com> On May 12, 11:40 am, "Martin v. L?wis" wrote: > > - in __getitem__, does it release the lock after returning the item? > > Yes, it does. > > > - wouldn't it be better to use threading.RLock, mutex, ... instead? > > Better in what sense? Performance-wise? Semantically? Performance-wise, > the best thing would be to do > > safe_dict = dict > > because the builtin dict is already thread-safe unless user-defined > __hash__ or __eq__ methods get invoked (in which case the dictionary > still works correctly - it's only that it may get modified while > __hash__ or __eq__ is running). > > Semantically, it would be better to use a threading.RLock, if you > expect that __hash__ or __eq__ may access the dictionary recursively. > > Regards, > Martin Thank you! From steve at holdenweb.com Fri May 25 12:41:28 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 25 May 2007 12:41:28 -0400 Subject: webbrowser module bug? In-Reply-To: References: <1180106384.198363.14120@p47g2000hsd.googlegroups.com> Message-ID: <465711B8.7070505@holdenweb.com> Ron Adam wrote: > kyosohma at gmail.com wrote: >> On May 24, 5:03 pm, Ron Adam wrote: >>> Is anyone else having problems with the webbrowser module? >>> >>> Python 2.5.1c1 (release25-maint, Apr 12 2007, 21:00:25) >>> [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 >>> Type "help", "copyright", "credits" or "license" for more information. >>> >>> import webbrowser >>> >>> webbrowser.open('http://www.python.org') >>> True >>> >>> >>> >>> It opens firefox as expected, but the url is ... >>> >>> file:///home/ron/%22http://www.python.org%22 >>> >>> Which of course doesn't do what is expected. >>> >>> Any ideas? >>> >>> Ron >> I don't know. This works for me with Python 2.4 on Windows XP SP2. The >> docs don't say much (http://docs.python.org/lib/module- >> webbrowser.html). Maybe it would be beneficial to read the module's >> code? Or use the "register" command manually? > > It works for me on python 2.4 also, but not on later versions. > > Looks like I'll need to try to test the url at the point where it calls the > browser from webbrowser.py. > > Can someone else test this on python 2.5? > On my Windows laptop it works on 2.4.1 and 2.5.1 native, but not on 2.5.1 for Cygwin. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From __peter__ at web.de Thu May 24 06:03:30 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 24 May 2007 12:03:30 +0200 Subject: Checking parameters prior to object initialisation References: Message-ID: Brett_McS wrote: > In C++ (gack!) I got used to creating a helper function with each class to > check the class object initialisation parameters prior to creating the > object. > > In Python, this would be > ----------------------------------------------- > import example > > if example.ParametersOK(a, b, c, d): > newObj = example.Example(a, b, c, d) > else: > print "Error in parameters" > ----------------------------------------------- > > I presume this would still be considered good practise in Python, or is > there some other, preferred, method? Use exceptions to signal wrong parameters and move the parametersOk() test into the initializer class Example: def __init__(self, a, b, c, d): if a < 0: raise ValueError("Negative length not allowed") #... Write a factory if - creating the Example instance carries too much overhead and wrong parameters are likely, or - the checks are costly and you often get parameters known to be OK. def make_example(a, b, c, d): if a < 0: raise ValueError("Negative length not allowed") #... return Example(a, b, c, d) Example object creation then becomes try: newObj = example.Example(1,2,3,4) # or make_example(...) except ValueError, e: print e # you will get a specific message here If the checks still have to occur in multiple places in your code you are of course free to factor them out in a separate function. Peter From sjdevnull at yahoo.com Sun May 27 14:18:31 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 27 May 2007 11:18:31 -0700 Subject: Is PEP-8 a Code or More of a Guideline? In-Reply-To: References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> Message-ID: <1180289911.951691.78640@k79g2000hse.googlegroups.com> Stefan Sonnenberg-Carstens wrote: > Paul McGuire schrieb: > > I'm starting a new thread for this topic, so as not to hijack the one > > started by Steve Howell's excellent post titled "ten small Python > > programs". > > > > In that thread, there was a suggestion that these examples should > > conform to PEP-8's style recommendations, including use of > > lower_case_with_underscores style for function names. I raised some > > questions about this suggestion, since I liked the names the way they > > were, but as a result, part of the discussion has drifted into a > > separate track about PEP-8, and naming styles. > > > > I was under the impression that lower_case_with_underscores was a > > dated recommendation, and that recent practice is more inclusive of > > mixedCase style identifiers. On the contrary, Steven Bethard > > straightened me out, saying that PEP-8 used to accept either style, > > but has been amended to accept only lower_case_with_underscores. > > > > My latest thought on the topic relates back to the Martin v. Lo:wis > > thread-that-would-not-die requesting feedback about PEP 3131, on > > adding support for non-ASCII identifiers in Py3K. I posted an out-of- > > curiosity comment asking about how underscore separators mix with > > Unicode identifiers, including the mechanics of actually typing an > > underscore on a non-US keyboard. At this point, I realized that I was > > taking things too far off-topic, so I decided to start a new thread. > > > > Steve, sorry for taking your thread down a rathole. I hope we can > > move any further PEP-8-related discussion (if the point merits any) to > > this thread. > > > > -- Paul > > > > > I prefer mixedCaseStyle, and I think that should be "standard", as this > style is commonly > used in all "major" languages , for example Java,C++,C#. > It shortens the identifiers but leaves the meaning intact. Actually, proper_case is standard in C++ (see, e.g., the naming section of http://www.research.att.com/~bs/bs_faq2.html ) . And C is still more common than Java, and Perl and Lisp are about as common as C#--all use proper case (though Lisp uses - instead of _). Historically, it's only Java and the Windows world (including non- standard Windows-style C++) that use forcedCase significantly (C# draws from both). The underscore version is not "lower case"; it is "proper case"--case is used as in normal English. Compare plot_line_slope() vs. plot_line_Besenheim(); with the underscore method, you preserve all the natural meaning of case. Especially when you have, say, acronyms in variable names, forcedCase can be somewhat confusing even for native English speakers; the style forces you to use a specific case for naming convention reasons, losing the natural meaning of the case. From martin at v.loewis.de Thu May 17 18:04:10 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 18 May 2007 00:04:10 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <464C5382.6080403@v.loewis.de> <1179423799.254286.294930@w5g2000hsg.googlegroups.com> Message-ID: <464CD15A.9070409@v.loewis.de> >> At the same time it takes some mental effort to analyze and understand >> all the implications of a feature, and without taking that effort >> "something" will always beat "nothing". >> > Indeed. For example, getattr() and friends now have to accept Unicode > arguments, and presumably to canonicalize correctly to avoid errors, and > treat equivalent Unicode and ASCII names as the same (question: if two > strings compare equal, do they refer to the same name in a namespace?). Actually, that is not an issue: In Python 3, there is no data type for "ASCII string" anymore, so all __name__ attributes and __dict__ keys are Unicode strings - regardless of whether this PEP gets accepted or not (which it just did). Regards, Martin From steven.bethard at gmail.com Wed May 23 03:17:09 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 23 May 2007 01:17:09 -0600 Subject: xml.parsers.expat loading xml into a dict and whitespace In-Reply-To: References: <163f0ce20705222316x7d6247a7hea019e7fd2aa2ee2@mail.gmail.com> Message-ID: kaens wrote: > Now the code looks like this: > [snip ElementTree code] > > freaking easy. Compare with making a generic xml parser class, and > inheriting from it for doing different things with different xml > files. This does exactly the right thing. I'm sure it's not perfect > for all cases, and I'm sure there will be times when I want something > closer to expat, but this is PERFECT for what I need to do right now. > > That settles it, I'm addicted to python now. I swear I had a little > bit of a nerdgasm. This is orders of magnitude smaller than what I had > before, way easier to read and way easier to maintain. > > Thanks again for the point in the right direction, Steve. You're welcome. In return, you've helped me to augment my vocabulary with an important new word "nerdgasm". ;-) STeVe From simon at brunningonline.net Thu May 17 08:30:30 2007 From: simon at brunningonline.net (Simon Brunning) Date: Thu, 17 May 2007 18:00:30 +0530 Subject: problem with import in python 2.2.3 In-Reply-To: References: Message-ID: <8c7f10c60705170530k3c206bd3s533549f75111b4b3@mail.gmail.com> On 5/17/07, Anthony Irwin wrote: > Does anyone know why the datetime module is not being found in python > 2.2.3 and how I can make the script work in the older version of python? The datetime modules was added in Python 2.3 - that's why you aren't finding it. This might help - http://tinyurl.com/37677u - but I've not tried it myself. -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues From fonnesbeck at gmail.com Tue May 29 18:30:27 2007 From: fonnesbeck at gmail.com (Chris Fonnesbeck) Date: Tue, 29 May 2007 18:30:27 -0400 Subject: updates in sqlite3 do not work Message-ID: <723eb6930705291530w190a7818i71f49d976217f38@mail.gmail.com> I have a script set up to perform UPDATE commands on an sqlite database using the sqlite3 module. Everything appears to run fine (there are no error messages), except that none of the UPDATE commands appear to have actually updated the table. If I run each command on its own in a sqlite session, the UPDATE command works fine, so it is not a SQL syntax issue. UPDATE simply seems not to work. Any idea what the problem might be? Thanks, Chris -------------- next part -------------- An HTML attachment was scrubbed... URL: From info at thegrantinstitute.com Wed May 30 01:18:02 2007 From: info at thegrantinstitute.com (Anthony Jones) Date: 29 May 2007 22:18:02 -0700 Subject: Professional Grant Proposal Writing Workshop (July 2007: University of Montana, Missoula) Message-ID: <20070529221801.E1BE2866672050BC@thegrantinstitute.com> An HTML attachment was scrubbed... URL: From metastart at gmail.com Thu May 24 06:50:53 2007 From: metastart at gmail.com (Alok, MetaStart) Date: 24 May 2007 03:50:53 -0700 Subject: Hiring Lead Python Programmer for Mozilla-Based Project Message-ID: <1180003853.208148.124630@k79g2000hse.googlegroups.com> We're a US-based start-up building new software with the Mozilla Platform and are at present seeking a lead programmer/architect for our project. At present, we're planning to build a team in India, so we'd need the lead to be on-site for 6 to 12 months. We may, however, end up developing in the US or elsewhere. We're also building websites (ideally in Python) which will work in conjunction with the client application. Our projects are quite challenging and exciting. They're motivated by the general transition to a net-based lifestyle--we need better tools to help organize and improve the functionality of critical web services. They thus have the potential to reach a lot of people, and involve a breadth of fun but difficult technical challenges. We're building a small team of extremely capable developers. We're seeking independently motivated, dedicated and generally brilliant programmers--the sort of programmers who coded a C compiler for fun in college. We offer a competitive salary, intense, challenging and rewarding work, and the potential for spectacular bonuses. If you're seeking a new challenge and would like to build exciting new products, please send us your CV or resume and a letter of interest in technology/programming. Thanks, Alok, MetaStart metastart at gmail.com From gagsl-py2 at yahoo.com.ar Wed May 2 21:02:32 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 02 May 2007 22:02:32 -0300 Subject: gpp (conditional compilation) References: <1178127460.046945.254100@y80g2000hsf.googlegroups.com> Message-ID: En Wed, 02 May 2007 14:37:40 -0300, maxwell at ldc.upenn.edu escribi?: > I'm trying to use the gpp utility (Gnu points to > http://en.nothingisreal.com/wiki/GPP) > to do conditional compilation in Python, and I'm running into a > problem: the same '#' character introduces Python comments and is used > by default to introduce #ifdef etc. lines. > > Here's an example of what I'm trying to do: > > #ifdef DEBUG > stderr.write("variable is...") #details of msg omitted > #endif In addition to all previous comments, I just want to menction the existence of Tools/Scripts/ifdef.py, included in every Python install; it can process #if #ifdef #else etc. -- Gabriel Genellina From steve at REMOVEME.cybersource.com.au Tue May 1 23:23:30 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 02 May 2007 13:23:30 +1000 Subject: Dict Copy & Compare References: Message-ID: On Tue, 01 May 2007 08:14:53 -0500, Hamilton, William wrote: >> -----Original Message----- >> From: Steven D'Aprano >> Sent: Monday, April 30, 2007 10:14 PM >> To: python-list at python.org >> Subject: RE: Dict Copy & Compare >> >> On Mon, 30 Apr 2007 12:50:58 -0500, Hamilton, William wrote: >> >> >> On quick question, how can I order a dict by the 'values' >> >> (not keys) before looping? Is that possible? >> >> >> > >> > The easiest way I can think of is to create a new dict that's >> > reversed. >> > >> > reverseDict = {} >> > for key in dict1: >> > if dict1[key] not in reverseDict: >> > reverseDict[dict1[key]]=[key] >> > else: >> > reverseDict[dict1[key]].append(key) >> > >> > This gives you a dictionary that has the old dict's values as keys, >> > and the old dict's keys as lists of values. You can then sort the >> > keys of this dict and do what you want with it. Of course, the >> > values in dict1 have to be valid dictionary keys for this to work. >> > If they aren't, you may be able to get away with converting them to >> > strings. >> >> >> Oh man, maybe you need to re-think what you consider "easier". >> >> for value in dict1.itervalues() >> do_something_with(value) > > This iterates through a list of values, with no information about the > keys at all. Not particularly applicable to the OP's needs. The OP asked for the values. You're just assuming he wants the values and keys. Even if he does, my solution is the first step to having a better understanding of what built-in methods Python dictionaries have, instead of rolling his own sub-optimal solutions. >> If you need the keys as well: >> >> for key, value in dict1.iteritems() >> do_something_with(key, value) > > This iterates through values and keys, in no particular order. Still > not useful. And apart from being much faster, more readable and concise, and not breaking if the values are lists or sets, how is my solution different from your solution? Hint: what order is your "reverse dictionary" in? >> If you need to process the values (say, sort them) first: >> >> pairs = list(dict1.iteritems()) # or dict1.items() >> pairs.sort() >> for key, value in pairs: >> do_something_with(key, value) >> >> I'll leave sorting by value instead of key as an exercise. > > Hrmm. Maybe you missed the part where the OP was asking how to sort a > dict's contents by value? I'm pretty sure I quoted it. Maybe you missed the part where I say "I'll leave sorting by value instead of by key as an exercise". I'm pretty sure you quoted it. I don't have to solve every last detail of the OP's problem for him, I just need to point him in the right direction. The right direction is to extract the key/items pairs and sort them whatever way he wants them. The wrong solution is to stuff them into an unsorted dictionary, *then* extract the keys and sort them whatever way he wants them. > My bit of code would be better if I had used iteritems() (I hadn't come > across that function yet). But, it's a solution, No it isn't. It doesn't solve the question asked, and it spends far too much effort (both programmer and CPU) to not solve it. > and more useful than > vague statements about what someone else needs to rethink and various > bits of code that don't solve the problem presented. They are not vague statements. Apart from the place-holder names (do_something_with and dict1) you could copy and paste my examples into an interactive session and have them work correctly. Your "solution" doesn't even answer the OP's question, but merely builds an intermediate data structure, leaving the actual solution up to him. A vague statement would be your comment "Of course, the values in dict1 have to be valid dictionary keys for this to work. If they aren't, you may be able to get away with converting them to strings." Now that's vague. -- Steven D'Aprano From paul at boddie.org.uk Fri May 4 06:37:35 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 4 May 2007 03:37:35 -0700 Subject: is there a module to work with pickled objects storage in database? In-Reply-To: References: Message-ID: <1178275055.800438.74120@q75g2000hsh.googlegroups.com> On 4 Mai, 12:18, "krishnakant Mane" wrote: > > I first dump the object into the file through pickle.dump and then > open the file in read mode. > then I read the contents of the file and then store what ever comes > out into the blob field. > I know this is not right and there should be ways of storing a pickled > object other than file. Try pickle.dumps to produce a string containing the pickled object. Obviously, you then need to supply the string to the database using the normal DB-API mechanisms. That said, although I haven't done much work with BLOBs in the DB-API, it would surprise me if it were not possible with some database modules to pass a file-like object as a parameter to the cursor's execute method, although I don't recall there being any classes whose objects act like files and produce pickled objects on demand. Paul From thorsten at thorstenkampe.de Tue May 15 05:25:50 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 15 May 2007 10:25:50 +0100 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> <4648294F.2000704@web.de> <46487a6c$0$2400$426a74cc@news.free.fr> Message-ID: * Eric Brunel (Tue, 15 May 2007 10:52:21 +0200) > On Tue, 15 May 2007 09:38:38 +0200, Duncan Booth > wrote: > > Recently there has been quite a bit of publicity about the One Laptop Per > > Child project. The XO laptop is just beginning rollout to children and > > provides two main programming environments: Squeak and Python. It is an > > exciting thought that that soon there will be millions of children in > > countries such as Nigeria, Brazil, Uruguay or Nepal[*] who have the > > potential to learn to program, but tragic if the Python community is too > > arrogant to consider it acceptable to use anything but English and ASCII. > > You could say the same about Python standard library and keywords then. You're mixing apples and peaches: identifiers (variable names) are part of the user interface for the programmer and free to his diposition. Thorsten From efrat_regev at yahoo.com Tue May 1 15:33:20 2007 From: efrat_regev at yahoo.com (Efrat Regev) Date: Tue, 01 May 2007 22:33:20 +0300 Subject: Grabbing the output of a long-winded shell call (in GNU/Linux) In-Reply-To: <1178047885.767785.35320@h2g2000hsg.googlegroups.com> References: <46378364$1@news.bezeqint.net> <1178047885.767785.35320@h2g2000hsg.googlegroups.com> Message-ID: <46379600.3060502@yahoo.com> draghuram at gmail.com wrote: > On May 1, 2:23 pm, Efrat Regev wrote: > >> So my question is if there's a way to "grab" the output as it's being >> generated. It doesn't matter if the solution is blocking (as opposed to >> callback based), since threads can handle this. I just don't know how to >> "grab" the output. I appreciate your time in reading (and answering >> this), as I've been googling several hours for this. > > There may be more pythonic solution than what I suggest here but this > is what I have done when I needed similar functionality. Basically run > your command in the background and redirect its stdout/err to a temp > file. You may run the command either in the background or in a > separate thread. You can then run the command "tail --retry -- > pid= -n+0 -F " and grab the output. The tail command > exits once the real command is done. > > Raghu. > > > > Many Thanks! I'll try this From reinaldoc at gmail.com Wed May 2 21:48:41 2007 From: reinaldoc at gmail.com (Reinaldo Carvalho) Date: Wed, 2 May 2007 22:48:41 -0300 Subject: how update a qListView in backgroud Message-ID: <4a5881460705021848l7119ffd6m304c0307a4b21b87@mail.gmail.com> Hi, I programming with qt module and i have a qWidgetTab with a qListView inside, and i need update the qListView every 5 seconds, how do this on transparent mode to user. I do a function to update, but i dont know call then. I will start this update when user select this tab, and stop whe user leave this tab. I need a thread ot something else? -- Reinaldo Carvalho From notro at tronnes.org Wed May 9 13:46:38 2007 From: notro at tronnes.org (Noralf Trřnnes) Date: Wed, 9 May 2007 19:46:38 +0200 Subject: ctypes: Problems using Windows-DLL from VB example code References: <4641fd20$1@news.broadpark.no> Message-ID: <4642091d$1@news.broadpark.no> > Have you tried to pass the structure by reference? > > dso_lib.port_init(byref(init_data)) > > Thomas > That gives me another exeption: print dso_lib.port_init(byref(init_data)) ValueError: Procedure called with not enough arguments (4 bytes missing) or wrong calling convention Noralf. From stefan.sonnenberg at pythonmeister.com Mon May 7 10:35:07 2007 From: stefan.sonnenberg at pythonmeister.com (Stefan Sonnenberg-Carstens) Date: Mon, 7 May 2007 16:35:07 +0200 (CEST) Subject: problem with quoted strings while inserting into varchar field of database. In-Reply-To: <1178548015.856661.308070@u30g2000hsc.googlegroups.com> References: <1178475772.423687.118800@e65g2000hsc.googlegroups.com> <1178526655.933789.294700@h2g2000hsg.googlegroups.com> <1178530363.516882.228380@l77g2000hsb.googlegroups.com> <1178548015.856661.308070@u30g2000hsc.googlegroups.com> Message-ID: <1068189.28014.BlRUCl8VTQA=.1178548507.squirrel@webmailer.hosteurope.de> On Mo, 7.05.2007, 16:26, Daniele Varrazzo wrote: >> >> >> > cur.execute("INSERT INTO datatable (data) VALUES (%s);", >> >> >> > (pickled_data,)) > >> %s is not a placeholder IMHO. > >> What happens when using %s is, that the string given will be inserted >> where >> %s is; that is something python does as with every print or such. > > It is indeed. The behavior you describe would be true if i had used > the "%" operator. Read better what i have written: There is no "%" > operator. > > cur.execute() receives 2 parameters: a SQL string with placeholders > and a tuple with values: it's not me mangling values into the SQL > string. This is the driver responsibility and it has the chance > because it receives SQL and values as two distinct parameters. The > driver can ask the SQL string to contain placeholders either in qmark > "?" or in format "%s" style, but there is no functional difference. > Notice that the placeholder is always "%s" and not "%d" or "%f" for > integers or float: there is always an escaping phase converting each > python object into a properly encoded string and then the placeholders > are replaced with the value. This happens into the execute() > machinery. > >> By using the qmark style, it is up the the implementation of the >> cursor.execute method to decide what to do. python itself, and it's >> string >> implementation, don't know anything to do with the qmark. >> So, IMHO it *makes* a difference: >> with %s the execute function sees a string and nothing more as the >> parameters are consumed away by the % substitution. >> with ?, the execute implementation must do it's best, it gets a string >> and >> a list/tuple with values. > > Again, this would be true for "cur.execute(sql % data)": what i wrote > is "cur.execute(sql, data)". > > -- Daniele > > -- > http://mail.python.org/mailman/listinfo/python-list > > Ashes on my head. From john at datavoiceint.com Fri May 11 14:21:59 2007 From: john at datavoiceint.com (HMS Surprise) Date: 11 May 2007 11:21:59 -0700 Subject: File writing success Message-ID: <1178907719.896993.299910@h2g2000hsg.googlegroups.com> If file writing has no return value (http://docs.python.org/lib/bltin- file-objects.html), how do you know if the write was successful? Should one assume that if the open was successful then write are also? Thanks, jvh From bj_666 at gmx.net Thu May 3 10:45:54 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 03 May 2007 16:45:54 +0200 Subject: How to replace the last (and only last) character in a string? References: <1178202464.201578.211150@c35g2000hsg.googlegroups.com> Message-ID: In <1178202464.201578.211150 at c35g2000hsg.googlegroups.com>, Johny wrote: > Let's suppose > s='12345 4343 454' > How can I replace the last '4' character? > I tried > string.replace(s,s[len(s)-1],'r') > where 'r' should replace the last '4'. > But it doesn't work. > Can anyone explain why? Because you can't change strings. Any function or method that "changes" a string returns a new and modified copy. So does the `string.replace()` function. And you don't bind the result to a name, so it is "lost". This is shorter than using `replace()`: In [9]: s = '12345 4343 454' In [10]: s = s[:-1] + 'r' In [11]: s Out[11]: '12345 4343 45r' BTW most things in the `string` module are deprecate because they are available as methods on string objects. Ciao, Marc 'BlackJack' Rintsch From arnodel at googlemail.com Sat May 12 08:47:07 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 12 May 2007 05:47:07 -0700 Subject: Simulating simple electric circuits In-Reply-To: <5ak3u9F2odts2U1@mid.individual.net> References: <5a9838F2nlbanU1@mid.individual.net> <5ae44aF2ku9rtU1@mid.individual.net> <5ak3u9F2odts2U1@mid.individual.net> Message-ID: <1178974027.175679.51130@k79g2000hse.googlegroups.com> On May 11, 10:02 pm, Bjoern Schliessmann wrote: [...] > P.S.: If anyone happens to be interested in details, just ask, I'll > post some code. I'm interested! I was tempted to have a go at it after your initial post, it sounded like a nice little project :) -- Arnaud From michael at jedimindworks.com Thu May 31 22:37:56 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Thu, 31 May 2007 21:37:56 -0500 Subject: ImageMagick Issue In-Reply-To: <2adc542f0705311808g61b1ababob62ad7c7f58b2bbb@mail.gmail.com> References: <2adc542f0705302100g3135fd0fn1e6c3decd210bd5f@mail.gmail.com> <2adc542f0705311808g61b1ababob62ad7c7f58b2bbb@mail.gmail.com> Message-ID: <42289AC2-73B7-461D-BEB9-DC81D1BDA434@jedimindworks.com> On May 31, 2007, at 8:08 PM, Sick Monkey wrote: > I ran into another slight problem. And I attempted to fix it, but > have not been able to do so yet. If a filename does not contain a > space, then this method works like a charm. But if there is a > space then the code throws a nasty error. > > import os > import subprocess > from os import * > imagefile = "/somedir/images/david.huggins/Photo 1.jpg" > cmdw = "identify -format %w '"+imagefile+"'" > cmdh = "identify -format %h '"+imagefile+"'" > pw = subprocess.Popen(cmdw.split(), stdout=subprocess.PIPE, > stderr=subprocess.STDOUT) > ph = subprocess.Popen(cmdh.split(), stdout=subprocess.PIPE, > stderr=subprocess.STDOUT) > w = pw.stdout.read().strip() > h = ph.stdout.read ().strip() > > ------------ > identify: Unable to open file ('/somedir/images/david.huggins/ > Photo) [No such file or directory]. > identify: Unable to open file (1.jpg') [No such file or directory]. > identify: Missing an image file name [No such file or directory]. > identify: Unable to open file ('/somedir/images/david.huggins/ > Photo) [No such file or directory]. > identify: Unable to open file (1.jpg') [No such file or directory]. > identify: Missing an image file name [No such file or directory]. > Traceback (most recent call last): Try inserting a backslash before the space: imagefile = imagefile.replace(' ', '\ ') hth, Michael --- The Rules of Optimization are simple. Rule 1: Don't do it. Rule 2 (for experts only): Don't do it yet. -Michael A. Jackson -------------- next part -------------- An HTML attachment was scrubbed... URL: From marcello.lussana at nekhem.com Tue May 22 11:13:09 2007 From: marcello.lussana at nekhem.com (marcello lussana) Date: Tue, 22 May 2007 17:13:09 +0200 Subject: SOAPpy - send xml data Message-ID: <20070522151309.GA969@avalon.nekhem.com> Hi, I'm trying to send some xml data to a WSDL server. Here's my code: xmldata = " Test di messaggio 1 + 3202181465 17.5.2007 12:59:53 """ SOAPpy.WSDL.Config.namespaceStyle = '2001' server = SOAPpy.WSDL.Proxy('https://www.oesystem.net/services/oeservice.asmx?WSDL') print server.insertMessages(xmlRequest=xmldata) parsing the output I've got two problems, about the tag, that is the tag that contains my xml data: - soappy escape xmlRequest tag, in my output I've got _xFFFF_xmlRequest as xml is _xFFFF_ - I didn't find a way to specify the type of the data that I send to my WSDL server => <_xFFFF_xmlRequest xsi3:type="xsd3:string"> In other words, I'd like to include my xmldata into a simple and I don't know how to do it with SOAPpy library. thank you From inkey56 at yahoo.co.uk Wed May 30 07:10:49 2007 From: inkey56 at yahoo.co.uk (Andrew P) Date: 30 May 2007 04:10:49 -0700 Subject: Python 2.5 and WXPython demo's Message-ID: <1180523448.993195.59180@q69g2000hsb.googlegroups.com> Hello, I am new (very) to Python and have just down loaded the latest version of Python (2.5) and WXPython (2.8). For some reason I cannot get the WXPython demo to run at all. I run windows XP and it can't find a program to run the demo. Any advice? (apologies if this has been posted before). From johannaostertag at gmail.com Thu May 31 04:02:54 2007 From: johannaostertag at gmail.com (johannaostertag at gmail.com) Date: 31 May 2007 01:02:54 -0700 Subject: Researcher/Lecturer Position at MODUL University Vienna Message-ID: <1180598574.761695.182060@o5g2000hsb.googlegroups.com> I would like to draw your attention to the following open position at the Department of New Media Technology of MODUL University Vienna (under accreditation): * Geospatial, Semantic and Web 2.0 Technologies http://www.ecoresearch.net/download/nmt-tech.pdf MODUL University Vienna is a recently founded private university on top of Kahlenberg, a scenic hill overlooking Vienna. The university combines a strong academic foundation with state-of-the-art curricula and a commitment to innovation and sustainability as key drivers of success in a dynamic and knowledge-based society. Appointees are expected to make significant contributions to the university's teaching and research activities. I would be very grateful if you could forward this information to potential candidates who might be interested in this offer. ------------------------------------------------- Prof. Arno Scharl Know-Center & Graz University of Technology Inffeldgasse 21a, A-8010 Graz (t) +43-316-8739257 (e) scharl at tugraz.at ------------------------------------------------- Sent by: Johanna Ostertag Institute for Tourism and Leisure Studies Vienna Unversity of Economics and Business Administration From mccredie at gmail.com Wed May 16 11:14:45 2007 From: mccredie at gmail.com (Matimus) Date: 16 May 2007 08:14:45 -0700 Subject: Trying to choose between python and java In-Reply-To: References: Message-ID: <1179328485.144103.152840@q75g2000hsh.googlegroups.com> > I tend to use the shebang #!/usr/bin/env python in my scripts so far > but I imagine that having that would not work on say windows. Or is > there some kind of file extension association for people running > windows instead of the shebang? The shebang is ignored in Windows (as far as I know). There is are .py, .pyc, .pyo and .pyw associations added to the registry when you install Python on a Windows machine. They can be executed like any other program. > I saw on the python site a slide from 1999 that said that python was > slower then java but faster to develop with is python still slower > then java? I don't have any numbers, but yes it probably is a bit slower for some tasks. Especially for hardcore number crunching. Of course, you can always rewrite the slow bits in C and get a speedup. Also, there are optimizers that are supposed to work pretty well. In the end though, Python is fast enough for most tasks. For very heavy computation I wouldn't use Java either. The interpreter does seem to start much quicker than the JVM. Also, I'm sure it has been mentioned, but you might checkout Jython, which is essentially python written in Java. Matt From aleax at mac.com Tue May 1 00:28:19 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 30 Apr 2007 21:28:19 -0700 Subject: sqlite for mac? References: <1177993261.572563.70370@n76g2000hsh.googlegroups.com> Message-ID: <1hxejkv.1liairs1gt8pl3N%aleax@mac.com> 7stud wrote: > Does sqlite come in a mac version? Sure, and it's part of the Python 2.5 for the Mac that you can download from python.org. Alex From rtw at freenet.co.uk Fri May 11 17:25:39 2007 From: rtw at freenet.co.uk (Rob Williscroft) Date: Fri, 11 May 2007 16:25:39 -0500 Subject: Interesting list Validity (True/False) References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> Message-ID: wrote in news:1178911704.529457.292280 at e51g2000hsg.googlegroups.com in comp.lang.python: > >>> [] == [] > True > >>> ['-o'] == [] > False > >>> ['-o'] == False > False > >>> To test wether something is true use if. To test wether something is false use if not. The python values "True" and "False" are for when you need to *store* a boolean value (for later testing). I you want to to see if an arbitry expression would test as true or false at the interactive prompt use bool(): >>> bool([]) False >>> bool(['-o']) True >>> There is *never* any need to write things like: expression == True or: expression == False Once you stop doing this things will become much simpler. Rob. -- http://www.victim-prime.dsl.pipex.com/ From cedric.louyot at gmail.com Fri May 4 08:53:16 2007 From: cedric.louyot at gmail.com (redcic) Date: 4 May 2007 05:53:16 -0700 Subject: Plot with scipy Message-ID: <1178283196.755609.241790@n59g2000hsh.googlegroups.com> Hi all, I've just downloaded scipy v 0.5.2 and I would like to be able to draw plots. I've tried: import scipy.gplt import scipy.plt import scipy.xplt and none of them work. Are these modules still included in scipy ? If not, where can I find them ? Thanks for your answers, C?dric From khemkaamit at gmail.com Thu May 24 06:00:43 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Thu, 24 May 2007 15:30:43 +0530 Subject: function nested In-Reply-To: References: Message-ID: <1360b7230705240300t2db6b78dh6edb672efc6cf2b0@mail.gmail.com> On 5/24/07, Gigs_ wrote: > def f(start): > stack = [] > def f1(start): > for fname in os.listdir(start): > path = os.path.join(start, fname) > if os.path.isfile(path): > stack.append(path) > else: > f1(path) > f1(start) > return stack > > > i feel s stupid right now > forgot to call f1 > > any comments how to make this better? os.walk is just the way for you ! Cheers, ---- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. From S.Mientki-nospam at mailbox.kun.nl Wed May 30 14:14:40 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Wed, 30 May 2007 20:14:40 +0200 Subject: is there a standard way to "install" egg-files under windows ? Message-ID: <4c205$465dbe2b$d443bb3a$17537@news.speedlinq.nl> hello, after 4 months playing around with Python, and I still have troubles with egg files. Sometimes it works, sometimes it doesn't. If I google on "python egg", I get lost of links, which contains huge pages of information, and I'm totally scared off. I've used several methods, the last one, success with 1 egg file, no success with another egg-file: - download ez_setup.py and put it in a sub-directory of the Python path - open an Python IDE - open the ez_setup.py in the IDE - dump the egg files in the same directory as ez_setup.py - set in the IDE, the commandline parameters to the egg-filename (no path) - run ez_setup.py in the IDE Can someone tell how to install an egg file in just 1 line ? Or even better, can there be an icon on the desktop, where I just can drop the egg-file ? thanks, Stef Mientki From gagsl-py2 at yahoo.com.ar Tue May 22 11:18:13 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 22 May 2007 12:18:13 -0300 Subject: doctest environment question References: <1179762737.153434.143030@b40g2000prd.googlegroups.com> <1179775483.685881.236940@x18g2000prd.googlegroups.com> <1179818466.394663.222390@k79g2000hse.googlegroups.com> <1179832577.759863.164860@z24g2000prd.googlegroups.com> Message-ID: En Tue, 22 May 2007 08:57:29 -0300, tag escribi?: > On 22 May, 10:11, "Gabriel Genellina" wrote: >> The version given by Peter Otten may do what you want, but I'd consider >> if >> you really need an announce_function in the first place, given all the >> other ways you already have to do the same thing. >> Implicitely rebinding globals does not look good. > > Thanks for the advice Gabriel. The use case I have is that I'd like to > be able to decorate classes and even modules in this way: > > import announce > import spam > announce.announce_module(spam) > > ... code which calls into spam module > > Here, "announce.announce_module" has a look in "spam", finds all the > functions and instancemethods, and decorates them (rebinds them) by > announcing calls to these functions and instancemethods. > > It's something I've found useful, though clearly the behaviour of > "spam" has been drastically changed. I'd appreciate advice on better > ways to achieve this kind of thing, or why it doesn't look good. Ah, then you *have* a reference to the containing module. announce_module might be something like this: def announce_module(module): for fname in find_all_functions_by_name_in_module(module): function = getattr(module, fname) setattr(module, fname, announce_function(function)) And no need to guess anything. It works even if the original function name is not the same as the name used in the module (this may happen when you assign a function with another name). Remember "Explicit is better than implicit" and "In the face of ambiguity, refuse the temptation to guess." -- Gabriel Genellina From vel.accel at gmail.com Wed May 23 05:48:15 2007 From: vel.accel at gmail.com (D.Hering) Date: 23 May 2007 02:48:15 -0700 Subject: Shared Memory Space - Accross Apps & Network In-Reply-To: Message-ID: <1179913695.863674.325520@u30g2000hsc.googlegroups.com> On May 23, 4:04 am, Tim Golden wrote: > Robert Rawlins - Think Blue wrote: > > > I've got an application that runs on an embedded system, the application > > uses a whole bunch or dicts and other data types to store state and other > > important information. > > I'm looking to build a small network of these embedded systems, and I'd love > > to have them all share the same set or data. Is it possible to share the > > applications variables across multiple applications, so certain lists are > > like a 'pool' written to by the different systems? I'm sure I could cobble > > something together by writing the lists to shared files instead of keeping > > them in RAM, but that feels a little inefficient. I'd like to try and > > configure some form of master/slave relationship between my applications if > > possible. > > I was really surprised you hadn't received a whole > slew of answers for this (even if they were: search > the newsgroup for the last time this was asked!) But > then I noticed that the post hadn't appeared on Google > Groups, at least. I read things via the mailing list; > is it possible your post hasn't made it across to > Usenet either? > > Just to get the ball rolling, I'd suggest two things: > > Pyro -http://pyro.sf.net > > This is actively maintained and has been going for a while. > We use it here (on a fairly small scale) and I know that > others use it elsewhere for bigger things. It's based on > a threaded socket server so whenever someone starts to say: > "I know; I'll roll my own threaded socket server", I'm > inclined to say: "Don't reinvent the wheel; try Pyro". > > PyLinda -http://www-users.cs.york.ac.uk/~aw/pylinda/ > > This implements the tuplespace paradigm. It's great > fun to use, but as far as I know this implementation > was a PhD project and lacks the robustness and wide > use of other things. That said, it works perfectly > well within its remit and might be a good match for > what you're trying to do. > > No doubt other people can chime in with suggestions > > TJG Possibly, IPython's new interactive parallel environment is what you are looking for: http://ipython.scipy.org/moin/Parallel_Computing From wise.of.clean791 at gmail.com Fri May 11 05:49:35 2007 From: wise.of.clean791 at gmail.com (wise.of.clean791 at gmail.com) Date: 11 May 2007 02:49:35 -0700 Subject: Jessica Reveals all "Again" Message-ID: <1178876975.091697.263370@y5g2000hsa.googlegroups.com> http://jessicasboobs.blogspot.com/ - Download snazzy jessica images (I bet you will find her naked) From thin.myrna at spamhaters.com Fri May 18 10:43:29 2007 From: thin.myrna at spamhaters.com (Thin Myrna) Date: Fri, 18 May 2007 16:43:29 +0200 Subject: Python for Smartcards on Windows XP (Python 2.4) Message-ID: <464dbb93$0$3813$5402220f@news.sunrise.ch> Dear all I headed for for a Smartcard lib for Python and found PyCSC. The zipped sources do not build [1] and the installer (exe file) wants to see a Python 2.5 installation. Does anyone know of an installer for Python 2.4? Kind regards Thin Myrna [1] "python setup.py install" yields F:\Software.Python\PyCSC\PyCSC-0.3>python setup.py install running install running bdist_egg running egg_info writing .\PyCSC.egg-info\PKG-INFO writing top-level names to .\PyCSC.egg-info\top_level.txt installing library code to build\bdist.win32\egg running install_lib running build_py running build_ext error: The .NET Framework SDK needs to be installed before building extensions for Python. This is strange, becaus ethere shouldn't be any dep's on .NET. Instead it should use MSVC6 to compile/link into pycsc.pyd. From mike.klaas at gmail.com Wed May 9 19:08:36 2007 From: mike.klaas at gmail.com (Klaas) Date: 9 May 2007 16:08:36 -0700 Subject: Towards faster Python implementations - theory In-Reply-To: References: <1210i.7468$2v1.2505@newssvr14.news.prodigy.net> <1178705421.711371.182770@e65g2000hsc.googlegroups.com> Message-ID: <1178752116.216271.297120@y80g2000hsf.googlegroups.com> On May 9, 10:02 am, John Nagle wrote: > One option might be a class "simpleobject", from which other classes > can inherit. ("object" would become a subclass of "simpleobject"). > "simpleobject" classes would have the following restrictions: > > - New fields and functions cannot be introduced from outside > the class. Every field and function name must explicitly appear > at least once in the class definition. Subclassing is still > allowed. > - Unless the class itself uses "getattr" or "setattr" on itself, > no external code can do so. This lets the compiler eliminate the > object's dictionary unless the class itself needs it. > > This lets the compiler see all the field names and assign them fixed slots > in a fixed sized object representation. Basically, this means simple objects > have a C/C++ like internal representation, with the performance that comes > with that representation. Hey look, it already exists: >>> class A(object): ... __slots__ = 'a b c d'.split() >>> a = A() >>> a.e = 2 Traceback (most recent call last): File "", line 1, in AttributeError: 'A' object has no attribute 'e' >>> hasattr(a, '__dict__') False -Mike From half.italian at gmail.com Wed May 2 02:17:30 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 1 May 2007 23:17:30 -0700 Subject: ScrolledText? In-Reply-To: <1178057529.486757.154860@y5g2000hsa.googlegroups.com> References: <1178057529.486757.154860@y5g2000hsa.googlegroups.com> Message-ID: <1178086650.307817.285720@p77g2000hsh.googlegroups.com> On May 1, 3:12 pm, nik wrote: > I've been trying to get the scrollbar and text box always going to the > last line and have been completely unsuccessful. > > I've tried, ScrolledText, text.see, and text.yview_pickplace without > success > > for instance this was the last setup: > > self.text = ScrolledText(master, relief=RIDGE) > self.text.grid(column=1, row=2, columnspan=10,\ > rowspan=5, pady=10, sticky=NSEW) > > with this text entry: > > self.text.insert(END, ins) > self.text.yview_pickplace("end") > > Can anybody please tell me what I might be doing wrong, or an example > that works, so that I can see what's going wrong. > > Thanks, > Nik try... self.text.yview_moveto(1) ~Sean From tcrane at REMOVETHISuiuc.edu Wed May 9 14:06:52 2007 From: tcrane at REMOVETHISuiuc.edu (T. Crane) Date: Wed, 9 May 2007 13:06:52 -0500 Subject: preferred windows text editor? Message-ID: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> Right now I'm using Notepad++. What are other people using? trevis From nagle at animats.com Tue May 8 11:53:33 2007 From: nagle at animats.com (John Nagle) Date: Tue, 08 May 2007 15:53:33 GMT Subject: Towards faster Python implementations - theory Message-ID: <1210i.7468$2v1.2505@newssvr14.news.prodigy.net> Some faster Python implementations are under development. JPython has been around for a while, and PyPy and ShedSkin continue to move forward. It's worth thinking about what slows down Python implementations. It isn't the dynamism, really. As others have pointed out in the Python literature, most of the time, the more elaborate dynamic features aren't being used for any given variable or object. If code has something like "x = 1.0", the odds are that "x" is going to stay a floating point number, and not suddenly turn into a list or an object reference. The type inference of Shed Skin builds on that assumption, adding some restrictions about changing of variable types. The Shed Skin effort indicates that explicit typing, via 'decorators' or otherwise, isn't really necessary. What's necessary is the avoidance of "surprises" in the language. In this context, a "surprise" is the use of a dynamic feature in a way that can't be seen at compile time. A typical "surprise" would be the use of "setattr" on an object from outside the compilation unit that defines the object. Within a module, "setattr" on an object in that module is no problem; the compiler can see it and generate the extra machinery needed to make an object dynamically alterable at run time. But if an object doesn't need that extra machinery and associated dictionary, it's a big win to discard the excess baggage and use a simpler fixed-size representation, comparable to a C struct, for the object. On the typing front, the neatest way to express typing is via initialization. With the Shed Skin restrictions, if all variables are initialized before use (preferably in __init__), there's no need to maintain an "undefined" flag for a variable. And, of course, if the type of a varaible is simple and can't change, it doesn't have to be "boxed", (enclosed in an object) which is a big win. The point here is that we don't need language changes or declarations to make Python much faster. All we need are a few restrictions that insure that, when you're doing something unusual, the compiler can tell. John Nagle From anton.vredegoor at gmail.com Sun May 13 14:21:06 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Sun, 13 May 2007 20:21:06 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46473267$0$31532$9b622d9e@news.freenet.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote: > In summary, this PEP proposes to allow non-ASCII letters as > identifiers in Python. If the PEP is accepted, the following > identifiers would also become valid as class, function, or > variable names: L?ffelstiel, chang?, ??????, or ??? > (hoping that the latter one means "counter"). I am against this PEP for the following reasons: It will split up the Python user community into different language or interest groups without having any benefit as to making the language more expressive in an algorithmic way. Some time ago there was a discussion about introducing macros into the language. Among the reasons why macros were excluded was precisely because anyone could start writing their own kind of dialect of Python code, resulting in less people being able to read what other programmers wrote. And that last thing: 'Being able to easily read what other people wrote' (sometimes that 'other people' is yourself half a year later, but that isn't relevant in this specific case) is one of the main virtues in the Python programming community. Correct me if I'm wrong please. At that time I was considering to give up some user conformity because the very powerful syntax extensions would make Python rival Lisp. It's worth sacrificing something if one gets some other thing in return. However since then we have gained metaclasses, iterators and generators and even a C-like 'if' construct. Personally I'd also like to have a 'repeat-until'. These things are enough to keep us busy for a long time and in some respects this new syntax is even more powerful/dangerous than macros. But most importantly these extra burdens on the ease with which one is to read code are offset by gaining more expressiveness in the *coding* of scripts. While I have little doubt that in the end some stubborn mathematician or Frenchman will succeed in writing a preprocessor that would enable him to indoctrinate his students into his specific version of reality, I see little reason to actively endorse such foolishness. The last argument I'd like to make is about the very possibly reality that in a few years the Internet will be dominated by the Chinese language instead of by the English language. As a Dutchman I have no special interest in English being the language of the Internet but -given the status quo- I can see the advantages of everyone speaking the *same* language. If it be Chinese, Chinese I will start to learn, however inept I might be at it at first. That doesn't mean however that one should actively open up to a kind of contest as to which language will become the main language! On the contrary one should hold out as long as possible to the united group one has instead of dispersing into all kinds of experimental directions. Do we harm the Chinese in this way one might ask by making it harder for them to gain access to the net? Do we harm ourselves by not opening up in time to the new status quo? Yes, in a way these are valid points, but one should not forget that more advanced countries also have a responsibility to lead the way by providing an example, one should not think too lightly about that. Anyway, I feel that it will not be possible to hold off these developments in the long run, but great beneficial effects can still be attained by keeping the language as simple and expressive as possible and to adjust to new realities as soon as one of them becomes undeniably apparent (which is something entirely different than enthusiastically inviting them in and let them fight it out against each other in your own house) all the time taking responsibility to lead the way as long as one has any consensus left. A. From nospam at noemailhere.nowhere Tue May 15 01:30:22 2007 From: nospam at noemailhere.nowhere (Anthony Irwin) Date: Tue, 15 May 2007 15:30:22 +1000 Subject: Trying to choose between python and java Message-ID: Hi All, I am currently trying to decide between using python or java and have a few quick questions about python that you may be able to help with. #1 Does python have something like javas .jar packages. A jar file contains all the program files and you can execute the program with java -jar program.jar I am sort of hoping python has something like this because I feel it makes it easier to distribute between platforms e.g. linux, mac windows etc. #2 What database do people recommend for using with python that is easy to distribute across linux, mac, windows. #3 Is there any equivalent to jfreechart and jfreereport (http://www.jfree.org for details) in python. #4 If I write a program a test it with python-wxgtk2.6 under linux are the program windows likely to look right under windows and mac? #5 someone said that they used to use python but stopped because the language changed or made stuff depreciated (I can fully remember which) and old code stopped working. Is code written today likely to still work in 5+ years or do they depreciate stuff and you have to update? Anyway hopefully someone can help me out with these last few questions I have. Also does anyone else have any useful comments about python vs java without starting a flame war. -- Kind Regards, Anthony Irwin http://www.irwinresources.com http://www.makehomebusiness.com email: anthony at above domains, - www. From kyosohma at gmail.com Fri May 18 09:22:26 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 18 May 2007 06:22:26 -0700 Subject: List Moderator In-Reply-To: References: <880dece00705172218n71123b55q531ec0c5e500f208@mail.gmail.com> Message-ID: <1179494546.468892.49460@l77g2000hsb.googlegroups.com> On May 18, 12:36 am, Steve Holden wrote: > Dotan Cohen wrote: > > Is this list not moderated? I'm really not interested in Britney > > Spears boobs. All the spam on this list is from the same place, it > > should be very easy to filter. > > Is it a list, is it a newsgroup? No, it's c.l.py! > > In fact you could be reading this in a number of different forms, and > there are equally many ways to inject content into the stream. It's > surprisingly difficult to filter everything out, though the list > managers at python.org seem to do a remarkably effective job. > > I'm not particularly interested in that subject matter either, but > believe me there could be a lot more of that kind of thing than actually > makes it through! > > 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 your way to fame!! > holdenweb.blogspot.com squidoo.com/pythonology > tagged items: del.icio.us/steve.holden/python > All these services currently offer free registration! > -------------- Thank You for Reading ---------------- You're probably right, but this week has been pretty bad. Every few posts there's another porn or boob related link. Sheesh! Mike From gagsl-py2 at yahoo.com.ar Tue May 8 21:21:00 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 08 May 2007 22:21:00 -0300 Subject: Win32: shortpathname to longpathname References: <1178669090.118174.142670@y80g2000hsf.googlegroups.com> Message-ID: En Tue, 08 May 2007 21:04:50 -0300, Jim Tittsler escribi?: > I wrap my cross platform application up with py2exe on Windows, and > have the installer associate a particular file type with it. When a > user double clicks on a document to launch my application, Windows > appears to pass me the "short" Windows pathname. How can I convert to > the long version of the pathname? (Ideally using the standard library > rather than win32all AKA pywin32.) You want GetLongPathName: http://msdn2.microsoft.com/en-us/library/aa364980.aspx It's not directly available on the standard library; you can either use win32api.GetLongPathName or call it using ctypes. -- Gabriel Genellina From maric at aristote.info Tue May 29 10:27:45 2007 From: maric at aristote.info (Maric Michaud) Date: Tue, 29 May 2007 16:27:45 +0200 Subject: Is PEP-8 a Code or More of a Guideline? In-Reply-To: <316098.9123.qm@web33510.mail.mud.yahoo.com> References: <316098.9123.qm@web33510.mail.mud.yahoo.com> Message-ID: <465C3861.8010508@aristote.info> Steve Howell a ?crit : > --- Carsten Haese wrote: > >> On Sun, 2007-05-27 at 07:30 +0000, OKB (not >> okblacke) wrote: >>> Underscores are harder to type than any >> alphanumeric character. >> >> This is a discussion about underscores versus >> capital letters denoting >> the word boundaries in identifiers. How is an >> underscore harder to type >> than a capital letter? >> > > longer reach with the pinkie on American keyboards > > Slowly type the following two keywords, you'll see > what I mean: > > hop_count > hopCount > > Also note the number of characters. > While this point was certainly discussed by those who wrote the PEP 8, I see hardly how it can be a valid argument. I used two keyboard maps in my life for development, fr_FR and fr_CH, in fr_CH both '.' and the pair '[', ']' are really more easy to type, and I think they appear at least as often as '_'. All in all, I never felt more productive with any keyboard, but, of course, I'm not a typist. Is typist ok ? It's the google's translation for "dactylo". From fdu.xiaojf at gmail.com Tue May 22 03:19:05 2007 From: fdu.xiaojf at gmail.com (fdu.xiaojf at gmail.com) Date: Tue, 22 May 2007 15:19:05 +0800 Subject: questions about programming styles In-Reply-To: <4651AB2E.20509@freakmail.de> References: <46501710.6090904@gmail.com> <46515E7D.5010103@gmail.com> <4651AB2E.20509@freakmail.de> Message-ID: <46529969.5000407@gmail.com> Wildemar Wildenburger wrote: > fdu.xiaojf at gmail.com wrote: > >> Thanks a lot for all kind replies! >> >> I think I need a systematic learning of design patterns. I have found >> some tutorials >> about design pattern about python, but can somebody point me which is >> the best to start with ? >> >> > When you say "Design Patterns", what do you mean? Do you mean it in the > computer-science-vocabulary-sense, as in [Singleton, Observer, Template, > ...]? If you're a novice or hobby programmer, let me tell you this: > Don't. Or at least: Don't, yet. Design patterns are meant to solve > problems that you run into relatively often, but don't let that trick > you: You have to get some intuition about them, or they'll make > virtually no sense to you. They're not guide as to how to write > programs. They help you overcome these "little obstacles" that you > commonly run into. But if you really must know: Wikipedia is a good > start (duh! ;)). > > > If you mean the term in a looser sense, like how to approach > programming, when to use what idiom, etc ...: Don't read too much, just > write code, see if it works and if it doesn't, be creative. If it still > doesn't work, ask. Like you did. Don't bother with theory all too long; > you will understand programming concepts much more easily when you're > "in it". And for the light stuff, like the Idea behind OO (classes, > methods, etc.), Wikipedia is always good enough. > > :) > W > Thanks. I think what I actually want to learn is design pattern in a looser sense, not in the computer-science-vocabulary-sense. I'm a graduate student in science, and python is my favourite programming language in daily work. I can solve most of the problems with python, but my programming efficienct is really low. Somethimes I have to stop to think about when to use what idiom, such as when to use functions and when to use methods. I want to learn how to write better programs more effectively and more efficiently. I will try to have a look at the wikipedia. Thanks again for your kind suggestion :) Regards, xiaojf From vatamane at gmail.com Mon May 7 22:42:08 2007 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 7 May 2007 19:42:08 -0700 Subject: How to make Python poll a PYTHON METHOD In-Reply-To: <1178590029.225298.195430@y80g2000hsf.googlegroups.com> References: <1178590029.225298.195430@y80g2000hsf.googlegroups.com> Message-ID: <1178592128.327658.212000@p77g2000hsh.googlegroups.com> On May 7, 10:07 pm, johnny wrote: > Is there a way to call a function on a specified interval(seconds, > milliseconds) every time, like polling user defined method? > > Thanks. Sure, >>> def baz(): ...: print "Baz!" ...: >>> from threading import Timer >>> timer=Timer(5.0,baz) >>> timer.start() >>> Baz! >>> Cheers, -Nick Vatamaniuc From max at alcyone.com Wed May 30 01:57:42 2007 From: max at alcyone.com (Erik Max Francis) Date: Tue, 29 May 2007 22:57:42 -0700 Subject: "is" and == In-Reply-To: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> Message-ID: BlueJ774 wrote: > Can someone please explain to me the difference between the "is" > keyword and the == boolean operator. I can't figure it out on my own > and I can't find any documentation on it. > > I can't understand why this works: > > if text is None: > > and why this always returns false: > > if message is 'PING': > > even when message = 'PING'. > > What's the deal with that? `x is y` means the same thing as: id(x) == id(y) You use the `is` operator for when you're testing for _object identity_, not value. `None` is a special object sentinel that is not only a value but a special _object_, and so if you're testing whether or not an object is `None`, you do so with the `is` operator. If you're testing whether an object is equal to the string "PING" then you do not want to do so by identity, but rather value, so you use the `==` operator, not `is`. -- 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 You could have another fate / You could be in another place -- Anggun From jgodoy at gmail.com Thu May 3 22:38:19 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Thu, 03 May 2007 23:38:19 -0300 Subject: Decorating class member functions References: <1178241696.641350.292210@n59g2000hsh.googlegroups.com> <1178244237.702552.201410@l77g2000hsb.googlegroups.com> <1178245732.628599.251020@l77g2000hsb.googlegroups.com> Message-ID: <87wszpxqhw.fsf@gmail.com> Andy Terrel writes: > I just need to keep the state around. I make a call to some function > that is pretty expensive so I want to save it as a member during the > __init__ of the decorator. > > Yeah I'm afraid it can't be done either, that's why I asked the group. Have you looked at memoize decorators? They seem to do what you want. There are examples at the Python website (some link in there, I'm sorry...). This will give you lots of resources, including full recipes and comments from the Python cookbook: http://www.google.com.br/search?q=python+decorator+memoize -- Jorge Godoy From noagbodjivictor at gmail.com Thu May 3 20:01:06 2007 From: noagbodjivictor at gmail.com (noagbodjivictor at gmail.com) Date: 3 May 2007 17:01:06 -0700 Subject: How do I output a list like the interpreter do? In-Reply-To: <1178236804.658955.204140@h2g2000hsg.googlegroups.com> References: <1178236804.658955.204140@h2g2000hsg.googlegroups.com> Message-ID: <1178236866.035271.81460@c35g2000hsg.googlegroups.com> On May 3, 8:00 pm, noagbodjivic... at gmail.com wrote: > >>> s = ['a','b'] > >>> s > ['a', 'b'] > > This is what I want so that I can put it in a module then import that > module to work with my variable. Sorry for that typo in the title... From rene at korteklippe.de Tue May 15 08:04:07 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 15 May 2007 14:04:07 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> <4648294F.2000704@web.de> <46487a6c$0$2400$426a74cc@news.free.fr> Message-ID: <4649a1b6$0$23131$9b4e6d93@newsspool1.arcor-online.net> Thorsten Kampe schrieb: > Because keywords are not meant meant to extended or manipulated or > something similar by the programmers. Keywords are well known and only > a limited set of words. That's why you can't use keywords as > identifiers. This is true for keywords, but not for the stdlib. Are you suggesting that the stdlib should be "internationalized"? > There really is no difference to allow strings or comments in non- > english languages and non-ASCII characters. Comments in a non-English language are a bad idea. And of course there is a difference between strings (data) and identifiers (program logic). -- Ren? From bob at snee.com Tue May 22 19:03:02 2007 From: bob at snee.com (bob at snee.com) Date: 22 May 2007 16:03:02 -0700 Subject: trying to gzip uncompress a StringIO In-Reply-To: <46536E01.2080702@lexicon.net> Message-ID: <1179874982.451092.150540@k79g2000hse.googlegroups.com> Perfect, thanks! Now I have a working WMF file and everything. Bob From no_spam at tilanus.com Mon May 21 03:51:59 2007 From: no_spam at tilanus.com (Winfried Tilanus) Date: Mon, 21 May 2007 09:51:59 +0200 Subject: mod_python performs several magnitudes slower than PHP? In-Reply-To: <1179625827.647353.50840@p77g2000hsh.googlegroups.com> References: <1179616996.948606.319670@q75g2000hsh.googlegroups.com> <4dM3i.3287$y_7.725@newssvr27.news.prodigy.net> <1179625827.647353.50840@p77g2000hsh.googlegroups.com> Message-ID: <46514F9F.2060004@tilanus.com> On 05/20/2007 Graham Dumpleton wrote: Hi, > A more suitable example for comparison would have been: And are there any benchmarks with this new version available? Just curious... best wishes, Winfried From __peter__ at web.de Fri May 4 02:34:22 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 04 May 2007 08:34:22 +0200 Subject: Getting some element from sets.Set References: <1178258913.095438.173020@h2g2000hsg.googlegroups.com> Message-ID: jm.suresh at no.spam.gmail.com wrote: > It is not possible to index set objects. That is OK. > But, what if I want to find some element from the Set. > > from sets import Set > s = Set( range(12 ) > > if I do pop, that particular element gets removed. > I do not want to remove the element, but get some element > from the Set. > > s.some_element() # Is not available > > Is there a way to do this. I am doing it like this: > > for x in s: break > > Now x is /some_element/ from s. A set is probably not the appropriate container then. What is your use case? Peter From richardjones at optushome.com.au Tue May 29 17:52:06 2007 From: richardjones at optushome.com.au (Richard Jones) Date: Wed, 30 May 2007 07:52:06 +1000 Subject: Open Source Developers' Conference 2007 - Brisbane - Call for Papers Message-ID: <200705300752.06873.richardjones@optushome.com.au> Call for Papers --------------- Open Source Developers' Conference 2007 - Brisbane, Australia "Success in Development & Business" OSDC is a grass-roots conference providing Open Source developers with an opportunity to meet, share, learn, and of course show-off. OSDC focuses on Open Source developers building solutions directly for customers and other end users, anything goes as long as the code or the development platform is Open Source. Last year's conference attracted over 180 people, 60 talks, and 6 tutorials. Entry for delegates is kept easy by maintaining a low registration fee (approx $300), which always includes the conference dinner. This year OSDC will be held in Brisbane from the 26th to the 29th of November, with an extra dedicated stream for presentations on Open Source business development, case studies, software process, and project management. The theme for this year's conference is "Success in Development & Business". If you are an Open Source maintainer, developer or user we would encourage you to submit a talk proposal on the open-source tools, solutions, technologies, or languages you are working with. Previous years have included numerous talks on topics such as: - FOSS Software Development Tools, Software Process and Project Management - Languages/Platforms: C/C++, Java, C#/Mono/OSS.Net - Scripting: Perl, PHP, Python, Ruby - Databases - Education - Web Technologies - Emerging Technologies and Innovation For more details and to submit your proposal(s), see http://osdc.com.au/papers/cfp.html If you have any questions or require assistance with your submission, please don't hesitate to ask! We recognise the increasing importance of Open Source in providing a medium for collaboration between individuals, researchers, business and government. In recognition of this, we offer optional peer-review for those members of our community who desire it. We are still finalising our review board, in addition to which those requesting peer-review will be asked to contribute reviews for up to three papers. OSDC 2007 Brisbane - Key Program Dates -------------------------------------- 30 Jun - Proposals deadline 31 Jul - Proposal acceptance 31 Aug - Submission deadline 15 Sep - Peer-review response (optional) 30 Sep - Final version for proceedings 26 Nov - OSDC 2007 Tutorials 27-29 Nov - OSDC 2007 Main Conference! For all information, contacts and updates, see the OSDC conference web site at http://osdc.com.au/ Sponsorship ----------- We gratefully acknowledge the following companies for their early commitment in sponsoring OSDC 2007: - Apress (http://apress.com/) - Common Ground (http://commongroundgroup.com/) - Google (http://google.com.au/) - OpenGear (http://opengear.com.au/) Interested in sponsoring also? See http://www.osdc.com.au/sponsors/opportunities.html From john at datavoiceint.com Tue May 8 09:19:01 2007 From: john at datavoiceint.com (HMS Surprise) Date: 8 May 2007 06:19:01 -0700 Subject: No module named urllib In-Reply-To: References: <1178575589.059564.226060@q75g2000hsh.googlegroups.com> <87tzuop8s2.fsf@gmail.com> <1178577562.498615.222340@e51g2000hsg.googlegroups.com> <87ps5cp816.fsf@gmail.com> <1178578923.067315.14440@q75g2000hsh.googlegroups.com> <1178580280.902179.248000@w5g2000hsg.googlegroups.com> Message-ID: <1178630341.147781.39380@y5g2000hsa.googlegroups.com> On May 7, 6:54 pm, Carsten Haese wrote: > On Mon, 2007-05-07 at 16:24 -0700, HMS Surprise wrote: > > Since sys.path = ['.', 'C:\\maxq\\lib\\Lib', 'C:\\maxq\\jython'] I > > copied urllib to c:\maxq\lib\Lib. > > > Now I get the error - > > > Traceback (innermost last): > > File "", line 5, in ? > > File "C:\maxq\lib\Lib\urllib.py", line 1148 > > _hextochr = dict(('%02x' % i, chr(i)) for i in range(256)) > > ^ > > SyntaxError: invalid syntax > > The urllib.py you're using is not compatible with the Python you're > using. The snippet above uses Python 2.4+ syntax, and Jython's syntax is > at 2.1 (stable) or 2.2 (beta). > > -- > Carsten Haesehttp://informixdb.sourceforge.net Thanks for posting. How does one ensure (or even detect) that their libraries are compatible? I loaded this library as part of Python 2.5. Thanks, jh From martin at v.loewis.de Thu May 17 09:01:27 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 17 May 2007 15:01:27 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <464C5227.7060804@v.loewis.de> > In the code I was looking at identifiers were allowed to use non-ASCII > characters. For whatever reason, the programmers choose not use non-ASCII > indentifiers even though they had no problem using non-ASCII characters > in commonets. One possible reason is that the tools processing the program would not know correctly what encoding the source file is in, and would fail when they guessed the encoding incorrectly. For comments, that is not a problem, as an incorrect encoding guess has no impact on the meaning of the program (if the compiler is able to read over the comment in the first place). Another possible reason is that the programmers were unsure whether non-ASCII identifiers are allowed. Regards, Martin From bbxx789_05ss at yahoo.com Thu May 24 14:27:56 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 24 May 2007 11:27:56 -0700 Subject: Different methods with same name but different signature? In-Reply-To: References: <713634.7367.qm@web37902.mail.mud.yahoo.com> Message-ID: <1180031276.132085.157770@p47g2000hsd.googlegroups.com> In python, every(?) variable name and its value is stored in a dict somewhere, and when you try to access the name, it is looked up in the dict. So if you write: def f(x): print x def f(x, y): print x,y when those lines are first parsed as your file loads, somewhere this happens: somedict = {} somedict["f"] = fx somedict["f"] = fxy which has the same effect as: d = {} d["a"] = 10 d["a"] = "hello" print d["a"] --output:-- "hello" So the second value for "f" overwrites the first value. Then when you call f(...), the name "f" is looked up in the dict, and the corresponding value is returned. In this case, that would be a reference to the second function f(x,y). From bscrivener42 at gmail.com Sat May 12 12:55:11 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: 12 May 2007 09:55:11 -0700 Subject: need help with python In-Reply-To: <1178934447.719778.197150@h2g2000hsg.googlegroups.com> References: <1178934447.719778.197150@h2g2000hsg.googlegroups.com> Message-ID: <1178988911.443161.287350@k79g2000hse.googlegroups.com> I'm not sure how you installed Python, or how you are using it, but I made something last year to help Windows XP users who are brand new to Python and can't get things to run, etc. You might try either jumping into somewhere midway, or if you keep having trouble, uninstall whatever you installed and start over using this: http://www.richarddooling.com/index.php/2006/03/14/python-on-xp-7-minutes-to-hello-world/ If that link breaks, use this: http://tinyurl.com/w7wgp Good luck. rd From mahall at ncsa.uiuc.edu Wed May 30 14:33:42 2007 From: mahall at ncsa.uiuc.edu (Matteo) Date: 30 May 2007 11:33:42 -0700 Subject: Appending a log file and see progress as program executes In-Reply-To: <1180549778.237118.291090@p47g2000hsd.googlegroups.com> References: <1180549778.237118.291090@p47g2000hsd.googlegroups.com> Message-ID: <1180550022.751881.61110@q75g2000hsh.googlegroups.com> On May 30, 1:29 pm, Matteo wrote: > - Write an autoflush class: > class AutoFlush: > def __init__(self, stream): > self.stream = stream > def write(self, text): > self.stream.write(text) > self.stream.flush() > > ... > flog=open('out.log','a') > flog=AutoFlush(flog) > > print >>flog,"I'm a message!" Oops! According to another thread, this won't work for files (but will work for stdio/stderr) Check the thread entitled "print bypasses calling write method for objects inheriting from file?" From nagle at animats.com Sun May 13 23:03:24 2007 From: nagle at animats.com (John Nagle) Date: Sun, 13 May 2007 20:03:24 -0700 Subject: BeautifulSoup vs. real-world HTML comments - possible fix In-Reply-To: References: <1175711322.448629.20300@y80g2000hsf.googlegroups.com> <1175717833.872281.6300@l77g2000hsb.googlegroups.com> <1175724136.054215.249970@p77g2000hsh.googlegroups.com> Message-ID: Robert Kern wrote: > Carl Banks wrote: > >>On Apr 4, 4:55 pm, Robert Kern wrote: >> >>>Carl Banks wrote: >>> >>>>On Apr 4, 2:43 pm, Robert Kern wrote: >>>> >>>>>Carl Banks wrote: >>>>> >>>>>>On Apr 4, 2:08 pm, John Nagle wrote: >>>>>> >>>>>>>BeautifulSoup can't parse this page usefully at all. >>>>>>>It treats the entire page as a text chunk. It's actually >>>>>>>HTMLParser that parses comments, so this is really an HTMLParser >>>>>>>level problem. >>I think the authors of BeautifulSoup have the right to decide what >>their own mission is. > > > Yes, and he's stated it pretty clearly: > > """You didn't write that awful page. You're just trying to get some data out of > it. Right now, you don't really care what HTML is supposed to look like. > > Neither does this parser.""" That's a good summary of the issue. It's a real problem, because BeautifulSoup's default behavior in the presence of a bad comment is to silently suck up all remaining text, ignoring HTML markup. The problem actually is in BeautifulSoup, in parse_declaration: def parse_declaration(self, i): """Treat a bogus SGML declaration as raw data. Treat a CDATA declaration as a CData object.""" j = None if self.rawdata[i:i+9] == '', i) if k == -1: k = len(self.rawdata) data = self.rawdata[i+9:k] j = k+3 self._toStringSubclass(data, CData) else: try: j = SGMLParser.parse_declaration(self, i) except SGMLParseError: toHandle = self.rawdata[i:] self.handle_data(toHandle) j = i + len(toHandle) return j Note what happens when a bad declaration is found. SGMLParser.parse_declaration raises SGMLParseError, and the exception handler just sucks up the rest of the input (note that "rawdata[i:]"), treats it as unparsed data, and advances the position to the end of input. That's too brutal. One bad declaration and the whole parse is messed up. Something needs to be done at the BeautifulSoup level to get the parser back on track. Maybe suck up input until the next ">", treat that as data, then continue parsing from that point. That will do the right thing most of the time, although bad declarations containing a ">" will still be misparsed. How about this patch? except SGMLParseError: # bad decl, must recover k = self.rawdata.find('>', i) # find next ">" if k == -1 : # if no find k = len(self.rawdata) # use entire string toHandle = self.rawdata[i:k] # take up to ">" as data self.handle_data(toHandle) # treat as data j = i + len(toHandle) # pick up parsing after ">" This is untested, but this or something close to it should make BeautifulSoup much more robust. It might make sense to catch some SGMLParseError at some other places, too, advance past the next ">", and restart parsing. John Nagle From wildemar at freakmail.de Fri May 18 11:15:29 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Fri, 18 May 2007 17:15:29 +0200 Subject: (Modular-)Application Framework / Rich-Client-Platform in Python In-Reply-To: <1179485905.764950.124000@p77g2000hsh.googlegroups.com> References: <1179485905.764950.124000@p77g2000hsh.googlegroups.com> Message-ID: <464DC311.5000401@freakmail.de> stefaan wrote: >> To make it short: Is there something like this already? > > To make it short again: http://code.enthought.com/ets/ > > Nice, seems very interesting. Bit of a bitch to set up, as it appears from scanning the site, but that might be it. Thanks :) Now for the everlasting circle of evaluating, feature-wanting, to-write-myself-deciding, failing, for-the-next-big-idea-waiting, asking, evaluationg, ... ;) > I also know some people are trying to create something called pyxides, > but > also there I am not sure about the status: http://pyxides.stani.be/ > Seems interesting as well, if only for the fact that Edward Ream (author of LEO) seems to be involved there in some way. But then, I can't quite make out what it is really about. The link just brings me to the google-group. Seems to be some kind of text-editor effort. I'll keep an eye on that, but so far, enthought is the front runner. Thx to everyone :) W From wildemar at freakmail.de Mon May 21 10:36:26 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Mon, 21 May 2007 16:36:26 +0200 Subject: NEWBIE: Extending a For Statement. In-Reply-To: <1179751973.199316.248370@x35g2000prf.googlegroups.com> References: <1179749446.179064.222990@z28g2000prd.googlegroups.com> <1179751973.199316.248370@x35g2000prf.googlegroups.com> Message-ID: <4651AE6A.1080606@freakmail.de> Dustan wrote: >>>> (key, mydict[key] for key in mydict if key in xrange(60, 69) or key == 3] >>>> > File "", line 1 > (key, mydict[key] for key in mydict if key in xrange(60, 69) or > key == 3] > ^ > SyntaxError: invalid syntax > > Perhaps you meant that second one to be: > (key, mydict[key] for key in mydict if key in xrange(60, 69) or key == > 3) > Clearly not! Its called *list*-comprehension, not tuple-comprehension. ;) This works: [(key, mydict[key]) for key in mydict if key in xrange(60, 69) or key ==3] (Note the parenthesis around (key, mydict[key]), they are MENDATORY.) regards W From robert.kern at gmail.com Wed May 9 15:45:18 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 09 May 2007 14:45:18 -0500 Subject: change of random state when pyc created?? In-Reply-To: References: <5ae25fF2oggbqU1@mid.uni-berlin.de> Message-ID: Alan G Isaac wrote: > Diez B. Roggisch wrote: >> Not really, but that depends on what you know about the concept of sets and >> maps as collections of course. >> >> The contract for sets and dicts doesn't imply any order whatsoever. Which is >> essentially the reason why >> >> set(xrange(10))[0] >> >> doesn't exist, and quite a few times cries for an ordered dictionary as part >> of the standard libraries was made. > > It seems to me that you are missing the point, > but maybe I am missing your point. > > The question of whether a set or dict guarantees > some order seems quite different from the question > of whether rerunning an **unchanged program** yields the > **unchanged results**. The latter question is the question > of replicability. > > Again I point out that some sophisticated users > (among which I am not numbering myself) did not > see into the source of this "anomaly". This > suggests that an explicit warning is warranted. http://docs.python.org/lib/typesmapping.html """ Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary's history of insertions and deletions. """ The sets documentation is a bit less explicit, though. http://docs.python.org/lib/types-set.html """ Like other collections, sets support x in set, len(set), and for x in set. Being an unordered collection, sets do not record element position or order of insertion. """ -- 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 gagsl-py2 at yahoo.com.ar Tue May 15 01:30:26 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 15 May 2007 02:30:26 -0300 Subject: Interesting list Validity (True/False) References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> <1178914190.166662.285410@p77g2000hsh.googlegroups.com> <1178915791.584216.293130@l77g2000hsb.googlegroups.com> <1178918808.091358.233740@o5g2000hsb.googlegroups.com> <1179017740.656323.209590@e51g2000hsg.googlegroups.com> <1179020634.130689.171960@o5g2000hsb.googlegroups.com> <1179031812.090768.248750@l77g2000hsb.googlegroups.com> <1179168081.603409.39970@e51g2000hsg.googlegroups.com> <1179203827.881205.287910@l77g2000hsb.googlegroups.com> Message-ID: En Tue, 15 May 2007 01:37:07 -0300, mensanator at aol.com escribi?: >> > >> > Sec 2.2.3: >> > Objects of different types, *--->except<---* different numeric types >> > and different string types, never compare equal; >> > >> >> The exceptions you mean are not exceptions to "'X==Y' means 'X equals >> Y'". > > I never said they were. I said they were exceptions to > "Obbjects of different types never compare equal". This is an unfortunate wording, and perhaps should read: "For most builtin types, objects of different types never compare equal; such objects are ordered consistently but arbitrarily (so that sorting a heterogeneous sequence yields a consistent result). The exceptions being different numeric types and different string types, that have a special treatment; see section 5.9 in the Reference Manual for details." And said section 5.9 should be updated too: "The objects need not have the same type. If both are numbers or strings, they are converted to a common type. Otherwise, objects of different builtin types always compare unequal, and are ordered consistently but arbitrarily. You can control comparison behavior of objects of non-builtin types by defining a __cmp__ method or rich comparison methods like __gt__, described in section 3.4." I hope this helps a bit. Your performance issues don't have to do with the *definition* of equal or not equal, only with how someone decided to write the mpz class. -- Gabriel Genellina From ardent at gmail.com Sun May 27 21:39:32 2007 From: ardent at gmail.com (Joe Ardent) Date: 27 May 2007 18:39:32 -0700 Subject: os.path.walk not pruning descent tree (and I'm not happy with that behavior?) Message-ID: <1180316372.126765.213530@r19g2000prf.googlegroups.com> Good day, everybody! From what I can tell from the archives, this is everyone's favorite method from the standard lib, and everyone loves answering questions about it. Right? :) Anyway, my question regards the way that the visit callback modifies the names list. Basically, my simple example is: ############################## def listUndottedDirs( d ): dots = re.compile( '\.' ) def visit( arg, dirname, names ): for f in names: if dots.match( f ): i = names.index( f ) del names[i] else: print "%s: %s" % ( dirname, f ) os.path.walk( d, visit, None ) ############################### Basically, I don't want to visit any hidden subdirs (this is a unix system), nor am I interested in dot-files. If I call the function like, "listUndottedDirs( '/usr/home/ardent' )", however, EVEN THOUGH IT IS REMOVING DOTTED DIRS AND FILES FROM names, it will recurse into the dotted directories; eg, if I have ".kde3/" in that directory, it will begin listing the contents of /usr/home/ardent/.kde3/ . Here's what the documentation says about this method: "The visit function may modify names to influence the set of directories visited below dirname, e.g. to avoid visiting certain parts of the tree. (The object referred to by names must be modified in place, using del or slice assignment.)" So... What am I missing? Any help would be greatly appreciated. -- Joe Ardent From sjmachin at lexicon.net Mon May 7 09:06:24 2007 From: sjmachin at lexicon.net (John Machin) Date: 7 May 2007 06:06:24 -0700 Subject: assisging multiple values to a element in dictionary In-Reply-To: References: <1178535831.870912.44220@p77g2000hsh.googlegroups.com> Message-ID: <1178543184.846426.309770@y5g2000hsa.googlegroups.com> On May 7, 10:59 pm, Carsten Haese wrote: > On Mon, 2007-05-07 at 04:03 -0700, saif.shak... at gmail.com wrote: > > Hi, > > I have a dictionary which is something like this: > > id_lookup={ > > 16:'subfunction', > > 26:'dataId', > > 34:'parameterId', > > 39:'subfunction', > > 44:'dataPackageId', > > 45:'parameterId', > > 54:'subfunction', > > 59:'dataId', > > 165:'subfunction', > > 169:'subfunction', > > 170:'dataPackageId', > > 174:'controlParameterId' > > } > > How do i assign multiple values to the key here.Like i want the > > key 170 to take either the name 'dataPackageID' or the name > > 'LocalId'.I use this in my code,and hence if either comes it should > > work . > > That sounds to me like you're translating names to numbers. If that is > true, you're much better off turning your dictionary around, making the > name the key and the corresponding number the value. That way you'll > have two keys pointing to the same value, which is perfectly legal, > whereas having one key pointing to two values is not really possible. > You could have one key pointing to a list or tuple of two values, but > it's not obvious whether that would solve your problem. > > Hope this helps, Unlikely. "Turning it around" produces one key ('subfunction') with *FIVE* different values. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed May 16 04:43:08 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 16 May 2007 10:43:08 +0200 Subject: Trying to choose between python and java In-Reply-To: <1179263947.704564.77650@n59g2000hsh.googlegroups.com> References: <1179250163.596672.321480@o5g2000hsb.googlegroups.com> <464a190c$0$19570$426a34cc@news.free.fr> <1179263947.704564.77650@n59g2000hsh.googlegroups.com> Message-ID: <464ac405$0$2136$426a74cc@news.free.fr> sjdevnull at yahoo.com a ?crit : > On May 15, 5:16 pm, Bruno Desthuilliers > wrote: >> Beliavsky a ?crit : >> >> >> >>> On May 15, 1:30 am, Anthony Irwin wrote: >>> >>>> #5 someone said that they used to use python but stopped because the >>>> language changed or made stuff depreciated (I can fully remember >>>> which) and old code stopped working. Is code written today likely to >>>> still work in 5+ years or do they depreciate stuff and you have to update? >>> Because Python 3 will change the syntax of print to disallow >>> print "Hello, world." >>> a substantial fraction of Python programs in existence, including all >>> of my programs, will be broken. Draw your own conclusions. >> The fact that Py3K will be a "big cleanup" release is not new - it has >> been clear for some years now that this would be the first release that >> would break compatibility. > > Eliminating core libraries breaks compatibility. Getting rid of regex > was very traumatic, and I still find myself occasionally patching up > code because of that change. To be fair, regex was deprecated for > many versions before it was dropped (and warned loudly of the coming > change), and Java's been notably worse at maintaining backward > compatibility. But saying it's the first release that breaks > compatibility isn't true unless you have a very limited definition of > compatibility. Looks like you're right on this - there have been at least one "compatibility-break" release before. As far as I'm concerned, I have been totally unaffected by this change, which is probably why I don't even remember it. >> Still GvR and the team seem to be making >> their best to not avoid as much breakage as possible, clearly document >> what will break, and if possible provide tools to ease migration. > > Absolutely. > From max at alcyone.com Thu May 31 19:53:05 2007 From: max at alcyone.com (Erik Max Francis) Date: Thu, 31 May 2007 16:53:05 -0700 Subject: c[:]() In-Reply-To: References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> <135tobve86qj808@corp.supernews.com> <135tru124pie2b3@corp.supernews.com> <135tv1bjqgbmsc9@corp.supernews.com> Message-ID: Warren Stringer wrote: > I'm still a bit new at this, was wondering why c[:]() doesn't work, and > implicitly wondering why it *shouldn't* work. It does work. It means "make a sliced copy of `c`, and then call it with no arguments." Functionally that is _no different_ from `c()`, which means "take `c` and call it with no arguments," because presuming `c` is a list, `c[:]` makes a shallow copy. So if you think `c()` and `c[:]()` should do something different in this case, you are profoundly confused about Python's semantics of what objects are, what it means to shallow copy a list, and what it means to make a function call. That you keep including the slice suggests that there's something about its meaning that's not yet clicking. If you really want syntax where a function call on a container calls all of its elements, then that is trivially easy to do by creating such an object and overriding its `__call__` method. If you're not willing to do that, but still insisting that `c[:]()` makes sense, then perhaps it would be more advisable to learn more about Python rather than try to suggest profound changes to the language and its conventions. -- 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 The quality, not the longevity, of one's life is what is important. -- Dr. Martin Luther King, Jr. From eopadoan at altavix.com Mon May 21 15:08:33 2007 From: eopadoan at altavix.com (Eduardo "EdCrypt" O. Padoan) Date: Mon, 21 May 2007 16:08:33 -0300 Subject: NEWBIE: Extending a For Statement. In-Reply-To: <4651AE6A.1080606@freakmail.de> References: <1179749446.179064.222990@z28g2000prd.googlegroups.com> <1179751973.199316.248370@x35g2000prf.googlegroups.com> <4651AE6A.1080606@freakmail.de> Message-ID: > > Perhaps you meant that second one to be: > > (key, mydict[key] for key in mydict if key in xrange(60, 69) or key == > > 3) > > > Clearly not! Its called *list*-comprehension, not tuple-comprehension. ;) With () instead of [], it is a generator expression. http://docs.python.org/ref/genexpr.html From XX.XmcX at XX.XmclaveauX.com Tue May 8 03:34:17 2007 From: XX.XmcX at XX.XmclaveauX.com (MC) Date: Tue, 08 May 2007 09:34:17 +0200 Subject: Windows, subprocess.Popen & encodage References: <46401c16$0$5072$ba4acef3@news.orange.fr> <464023a6$0$4795$9b622d9e@news.freenet.de> Message-ID: Thank you. -- @-salutations Michel Claveau From a.schmolck at gmail.com Fri May 25 17:33:22 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: Fri, 25 May 2007 22:33:22 +0100 Subject: matplotlib, usetex References: Message-ID: Bill Jackson writes: > > The problem does not exist when text.usetex is False. Ideas? I have no idea whether this will resolve your problem, but you could try updating to 0.90 (BTW what happens if you do axis([0,128,0,128])). cheers, 'as From steve at holdenweb.com Fri May 18 01:36:40 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 18 May 2007 01:36:40 -0400 Subject: List Moderator In-Reply-To: <880dece00705172218n71123b55q531ec0c5e500f208@mail.gmail.com> References: <880dece00705172218n71123b55q531ec0c5e500f208@mail.gmail.com> Message-ID: Dotan Cohen wrote: > Is this list not moderated? I'm really not interested in Britney > Spears boobs. All the spam on this list is from the same place, it > should be very easy to filter. > Is it a list, is it a newsgroup? No, it's c.l.py! In fact you could be reading this in a number of different forms, and there are equally many ways to inject content into the stream. It's surprisingly difficult to filter everything out, though the list managers at python.org seem to do a remarkably effective job. I'm not particularly interested in that subject matter either, but believe me there could be a lot more of that kind of thing than actually makes it through! 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From arkanes at gmail.com Wed May 2 12:52:23 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 2 May 2007 11:52:23 -0500 Subject: Is it possible to determine what a function needs for parameters - In-Reply-To: <1178124116.362731.248260@c35g2000hsg.googlegroups.com> References: <1178115727.932794.100390@h2g2000hsg.googlegroups.com> <1178118792.289104.212670@l77g2000hsb.googlegroups.com> <1178124116.362731.248260@c35g2000hsg.googlegroups.com> Message-ID: <4866bea60705020952j6c02dfberad9106f26b7f07f2@mail.gmail.com> On 2 May 2007 09:41:56 -0700, rh0dium wrote: > On May 2, 8:25 am, Gary Herron wrote: > > rh0dium wrote: > > >> This is far more work than you need. Push an (args, kwargs) tuple into > > >> your arguments queue and call self.function(*args, **kwargs). > > > > > No see I tried that and that won't work. > > > > Won't work? How does it fail?> I'm assuming what you are referring to is this (effectively) > > > > > Q.put(((),{a:"foo", b:"bar})) > > > > > input = Q.get() > > > self.function( *input[0], **input[1]) > > > > > This will obviously fail if several conditions aren't met - hence the > > > kludge. Am I missing something here? > > > > Obviously? Conditions? What conditions? > > > > We do things like this constantly, and in fact, it *does* work. > > > > Please tell us how it fails, or what is unsatisfactory about it. > > > > Gary Herron > > Good - It looks like I am the one who is clueless.. > > If I do this: > > def funcA(input): > pass > > Then I run the code > for x in range(lod):myQ.put(random.random()) > myQ.put(None) > a=WorkerB(requestQ=myQ, function=funcA).start() > > This will fail because there isn't an input[1] > Thats because you put the wrong value into the arguments queue. For this use case, we define the arguments queue as being a source of 2-tuples, with an argument list and a kwargs dict. So you have to do: for x in range(lod): myQ.put((random.random(), {})) (don't be afraid of indentation and newlines - I started to modify your source to provide a working example and got frustrated reformatting it so I could read it) Since you've now defined the external interface for your system (pass it a queue of argument, kwargs tuples and a callable) it's the responsibility of the caller to correctly satisfy that interface. From markg85 at gmail.com Wed May 16 14:51:53 2007 From: markg85 at gmail.com (Mark) Date: Wed, 16 May 2007 20:51:53 +0200 Subject: Python + Cairo widget examples.. where can i get them? Message-ID: <6e24a8e80705161151v2238de0v54b2a267dec47c9a@mail.gmail.com> Hey, a while ago i found a widget somewhere that was written in python with the cairo extension. that widget wasn't just a window.. it was a window without decorations and a red round thing in it. now i was trying to find that thing again and i`ve searched over a million blogs (oke not that much but alot) and i can`t find it.. so can someone point me to a python sample with a decorationless window/widget? all other python samples are also welcome. Thanx in favor. -------------- next part -------------- An HTML attachment was scrubbed... URL: From vasudevram at gmail.com Thu May 24 12:39:35 2007 From: vasudevram at gmail.com (vasudevram) Date: 24 May 2007 09:39:35 -0700 Subject: How can I time a method of a class in python using Timeit In-Reply-To: <1180020970.039576.319230@m36g2000hse.googlegroups.com> Message-ID: <1180024775.607715.138490@a26g2000pre.googlegroups.com> On May 24, 8:36 pm, "silverburgh.me... at gmail.com" wrote: > Hi, > > I am using timeit to time a global function like this > > t = timeit.Timer("timeTest()","from __main__ import timeTest") > result = t.timeit(); > > But how can i use timeit to time a function in a class? > class FetchUrlThread(threading.Thread): > def aFunction(self): > # do something .... > > def run(self): > # how can I time how long does aFunction() take here? > aFunction(); > > Thank you. Try this: def run(self): import time t1 = time.clock() aFunction(); t2 = time.clock() print "aFunction took %d seconds" % int(t2 - t1 + 1) (Code is not tested as I'm not at my PC right now). The int() is to round it off to an integer, and the +1 is to give a more accurate result - may not work in all cases, experiment, and check for a ceil/floor type function in Python. Vasudev Ram Dancing Bison Enterprises www.dancingbison.com From howe.steven at gmail.com Thu May 3 17:46:52 2007 From: howe.steven at gmail.com (Steven Howe) Date: Thu, 03 May 2007 14:46:52 -0700 Subject: How to replace the last (and only last) character in a string? In-Reply-To: <6e42ec490705031330v3c9fa0b7xf145b333befb2568@mail.gmail.com> References: <1178202464.201578.211150@c35g2000hsg.googlegroups.com> <6e42ec490705031330v3c9fa0b7xf145b333befb2568@mail.gmail.com> Message-ID: <463A584C.8000900@gmail.com> Dave Borne wrote: >> Let's suppose >> s='12345 4343 454' >> How can I replace the last '4' character? >> > > If the last '4' will not always be the last character in the string, > you could do: > 'X'.join(s.rsplit('4',1)) > from string import rfind def replaceLast_X_with_Y( s, x, y ): lastX = s.rfind(x) return s[:lastX]+ y + s[lastX+1:] s = '12345 4343 454' replaceLast_X_with_Y( s, '4', '9' ) '12345 4343 459' sph -- HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -------------- next part -------------- An HTML attachment was scrubbed... URL: From kay.schluehr at gmx.net Mon May 28 11:42:29 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 28 May 2007 08:42:29 -0700 Subject: ten small Python programs In-Reply-To: References: Message-ID: <1180366949.530888.31040@q75g2000hsh.googlegroups.com> Just for the amusement of the audience. The following is a reusable testscript: >>> def add_money(amounts): ... pennies = sum([round(int(amount * 100)) for amount in amounts]) ... return float(pennies / 100.0) ... >>> add_money([0.13, 0.02]) == 0.15 0.14999999999999999 >>> add_money([0.13, 0.02]) == 0.15 True >>> assert add_money([0.13, 0.02]) == 0.15 >>> assert add_money([100.01, 99.99]) == 200 >>> assert add_money([0, -13.00, 13.00]) == 0 It's just a matter of perspective... http://fiber-space.de/EasyExtend/doc/consoletest/consoletest.html From esther at bitranch.com Sat May 5 15:15:49 2007 From: esther at bitranch.com (estherschindler) Date: 5 May 2007 12:15:49 -0700 Subject: OT somewhat: Do you telecommute? What do you wish the boss understood about it? In-Reply-To: References: <1177951550.535520.144460@h2g2000hsg.googlegroups.com> Message-ID: <1178392549.938617.140750@u30g2000hsc.googlegroups.com> Oh! what a lovely response -- and I agree with almost all of it. I just handed in the article, and hadn't seen your message, but you'll be glad to know that I ended up with a whole sidebar about the costs that a telecommuter may bear. That didn't include the travel and hotel outlay, though it might have, since I just spent $400 on plane tickets to Boston for next month, and I won't be reimbursed for them until after the trip. (The devil's advocate piece of that, however, is that I don't pay for gas to commute to-and-from the office, either, which never is reimbursed. One side effect of telecommuting is that I have to put fuel in the car only once a month.) Anyway, my sidebar focused on the more direct questions of "what does the company cover?" Many of them don't have right or wrong answers, but there ought to be a policy in place before either the telecommuter or the accounting department have a fit. (If a telecommuter wears out her office chair, who pays for it? The usual answer is "the telecommuter" but is that really fair? If I had a cube in the office, they'd get me a chair. Maybe a junky one, but there would be a facilities budget to cover it.) I think you can tell that I liked what you wrote. I'll be sure to let you know when the article is published. Esther From claird at lairds.us Tue May 1 20:32:27 2007 From: claird at lairds.us (Cameron Laird) Date: Wed, 2 May 2007 00:32:27 +0000 Subject: Read and Write the same file References: <1178060601.700099.263240@y5g2000hsa.googlegroups.com> Message-ID: In article , Ian Clark wrote: . . . >the file, overwriting the oringinal copy. Now, this only really works >if you're dealing with small files. . . . On modern hosts (and I persist in using WinNT on a 133 MHz machine) "small" here can easily mean, "up to 20 megabytes". From carlistixx at gmail.com Thu May 31 21:45:56 2007 From: carlistixx at gmail.com (carlistixx) Date: Fri, 1 Jun 2007 11:45:56 +1000 Subject: Roundup, smtplib, TLS and MS Exchange Message-ID: <40170aa80705311845q460975adl4ec842343d1bc318@mail.gmail.com> Hi, I'm using the roundup issue tracker (http://roundup.sourceforge.net) which uses smtplib to send mail. It all worked until we moved to a hosted Exchange MTA. The hosting provider requires the use of TLS. Now roundup can't send mail. My version of python is: Python 2.3.4 (#1, Feb 6 2006, 10:38:46) [GCC 3.4.5 20051201 (Red Hat 3.4.5-2)] on linux2 Roundup version: $ roundup-server --version 1.1.2 (python 2.3.4) I've reproduced the SMTP conversation below. I'm not sure if it's a problem with Roundup, smtplib, or Exchange. Any assistance appreciated. [foobar at moe tracker]$ roundup-server -p 8081 roundup=/home/foobar/roundup/tracker Roundup server started on :8081 send: 'STARTTLS\r\n' reply: '503 5.5.2 Send hello first\r\n' reply: retcode (503); Msg: 5.5.2 Send hello first send: 'ehlo moe.foobar.local\r\n' reply: '250-smtpx15.msoutlookonline.net Hello [202.173.131.223]\r\n' reply: '250-SIZE 31457280\r\n' reply: '250-PIPELINING\r\n' reply: '250-ENHANCEDSTATUSCODES\r\n' reply: '250-STARTTLS\r\n' reply: '250-AUTH LOGIN\r\n' reply: '250-8BITMIME\r\n' reply: '250-BINARYMIME\r\n' reply: '250 CHUNKING\r\n' reply: retcode (250); Msg: smtpx15.msoutlookonline.net Hello [202.173.131.223] SIZE 31457280 PIPELINING ENHANCEDSTATUSCODES STARTTLS AUTH LOGIN 8BITMIME BINARYMIME CHUNKING send: 'AUTH LOGIN ************==\r\n' reply: '334 ************\r\n' reply: retcode (334); Msg: ************ send: '************\r\n' reply: '235 2.7.0 Authentication successful\r\n' reply: retcode (235); Msg: 2.7.0 Authentication successful send: 'mail FROM: size=1090\r\n' reply: '451 5.7.3 Must issue a STARTTLS command first\r\n' reply: retcode (451); Msg: 5.7.3 Must issue a STARTTLS command first send: 'rset\r\n' send: 'STARTTLS\r\n' reply: '503 5.5.2 Send hello first\r\n' reply: retcode (503); Msg: 5.5.2 Send hello first send: 'ehlo moe.foobar.local\r\n' reply: '250-smtpx15.msoutlookonline.net Hello [202.173.131.223]\r\n' reply: '250-SIZE 31457280\r\n' reply: '250-PIPELINING\r\n' reply: '250-ENHANCEDSTATUSCODES\r\n' reply: '250-STARTTLS\r\n' reply: '250-AUTH LOGIN\r\n' reply: '250-8BITMIME\r\n' reply: '250-BINARYMIME\r\n' reply: '250 CHUNKING\r\n' reply: retcode (250); Msg: smtpx15.msoutlookonline.net Hello [202.173.131.223] SIZE 31457280 PIPELINING ENHANCEDSTATUSCODES STARTTLS AUTH LOGIN 8BITMIME BINARYMIME CHUNKING send: 'AUTH LOGIN ******************************==\r\n' reply: '334 ************\r\n' reply: retcode (334); Msg: ************ send: '************\r\n' reply: '235 2.7.0 Authentication successful\r\n' reply: retcode (235); Msg: 2.7.0 Authentication successful send: 'mail FROM: size=1711\r\n' reply: '451 5.7.3 Must issue a STARTTLS command first\r\n' reply: retcode (451); Msg: 5.7.3 Must issue a STARTTLS command first send: 'rset\r\n' 192.168.100.68 - - [31/May/2007 16:14:01] "POST /roundup/issue1638 HTTP/1.1" 400 - EXCEPTION AT Thu May 31 16:14:01 2007 Traceback (most recent call last): File "/usr/lib/python2.3/site-packages/roundup/scripts/roundup_server.py", line 106, in run_cgi self.inner_run_cgi() File "/usr/lib/python2.3/site-packages/roundup/scripts/roundup_server.py", line 266, in inner_run_cgi tracker.Client(tracker, self, env).main() File "/usr/lib/python2.3/site-packages/roundup/cgi/client.py", line 196, in main self.inner_main() File "/usr/lib/python2.3/site-packages/roundup/cgi/client.py", line 314, in inner_main self.mailer.exception_message() File "/usr/lib/python2.3/site-packages/roundup/mailer.py", line 153, in exception_message self.standard_message(to, subject, content) File "/usr/lib/python2.3/site-packages/roundup/mailer.py", line 93, in standard_message self.smtp_send(to, message) File "/usr/lib/python2.3/site-packages/roundup/mailer.py", line 180, in smtp_send raise MessageSendError("Error: couldn't send email: %s"%msg) MessageSendError: Error: couldn't send email: Connection unexpectedly closed From herman_slagman at placid-dash-sky-dot-org Mon May 21 08:26:19 2007 From: herman_slagman at placid-dash-sky-dot-org (Herman Slagman) Date: Mon, 21 May 2007 14:26:19 +0200 Subject: Translating some Java to Python In-Reply-To: References: <1179692679.422164.27700@r3g2000prh.googlegroups.com><1179738814.282655.192700@r3g2000prh.googlegroups.com><465176ce$0$323$e4fe514c@news.xs4all.nl> Message-ID: <46518fec$0$339$e4fe514c@news.xs4all.nl> "Gabriel Genellina" schreef in bericht news:mailman.7960.1179746966.32031.python-list at python.org... > En Mon, 21 May 2007 07:39:09 -0300, Unknown > escribi?: > >> "Ant" schreef in bericht >> news:1179738814.282655.192700 at r3g2000prh.googlegroups.com... >> >>> Herman has shown you *how* to do static methods in Python, but >>> typically they are not used. Since Python has first class functions, >>> and they can be defined at the module level, there is no need to use >>> static methods. >> >> As an experienced developer I'm rather new to Python, so please forgive >> me any non-Pythonic babbling. >>> From a language point you're probably right, but from a design point I'd >> like to have methods that are clearly associated with a class as methods >> of that class, even if they don't use any class or instance related data. > > In that case you might want to revise the design, perhaps you carry some > preconceptions about how things should be, that are not directly > applicable here. (I'm not saying this is related to your specific problem > because I don't know exactly what you want, but in general, a lot of > design patterns *implementations* are not directly applicable to Python). I don't really have problems with Python (yet), merely responding to the OPs question. One example that comes to mind is a class that is a proxy for a database class, say Person. The Person.Load(id) method doesn't use any instance or class data, it instantiates a Person and populates it from the database. It is clearly a part of the class's interface so for that I use a @staticmethod. > Modules are objects too - they're a good example of singletons. If you > want to create a class containing only static methods: use a module > instead. If you want to create a class having a single instance (a > singleton), most of the time you can use a module instead. > Functions don't *have* to be methods in a class, and the resulting design > may still be a good design from an OO point of view. *That* Pythonic I'm already ;-) For a utility 'class' I'm using a module, no need for a class there. Using a module for a Singleton is good tip though. Herman From steven.bethard at gmail.com Fri May 25 14:14:55 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 25 May 2007 12:14:55 -0600 Subject: optparse: list out entered values In-Reply-To: <1180091234.397739.262450@x35g2000prf.googlegroups.com> References: <1180087678.416600.316860@z28g2000prd.googlegroups.com> <1180091234.397739.262450@x35g2000prf.googlegroups.com> Message-ID: Nirnimesh wrote: > On May 25, 3:07 am, Nirnimesh wrote: >> I'm using optparse.OptionParser for parsing command line arguments. >> >> parser = optparse.OptionParser() >> parser.add_option("-x", "--xample", help="example", >> default="nothing", >> dest="ex") >> options = parser.parse_args()[0] >> >> python example.py -x value >> >> I'm in search of a method to list out all the entered options along >> with the values. something which gives me: >> ex => value >> help => example >> version => blah blah.. >> I expected such a method to be there already. [snip] > I dug around with the optparse module and got this: > > for key, val in parser.values.__dict__.iteritems(): > print key, val I would tend to write this as:: for key, val in vars(options).iteritems(): print key, val STeVe From __peter__ at web.de Sun May 13 13:46:29 2007 From: __peter__ at web.de (Peter Otten) Date: Sun, 13 May 2007 19:46:29 +0200 Subject: Using "subprocess" without lists. . .? References: Message-ID: Michael Williams wrote: > I've recently seen the "subprocess" module and am rather confused by > it's requirements. Is it not possible to execute an entire string > without having to break them up into a list of arguments? For > instance, I'd much rather do the following: > > > subprocess.call("ls -al | grep -i test") Try subprocess.call("ls -al | grep -i test", shell=True) > > > . . .than to have to: > > > list = ["ls", "-a", "-l" ] . . . . . . and so on and so forth. > subprocess.call(list. . .) which avoids a lot of problems with shell quoting. Peter From chris.ogara at dot.state.fl.us Thu May 10 19:40:28 2007 From: chris.ogara at dot.state.fl.us (rover) Date: 10 May 2007 16:40:28 -0700 Subject: Avenue Language to Python Conversion Message-ID: <1178840428.691497.22150@w5g2000hsg.googlegroups.com> Does anyone know of a bridge or wrapper I can use to convert old avenue GIS scripts into Python Scripts? From harald.karner at a1.net Thu May 3 05:58:46 2007 From: harald.karner at a1.net (Harald Karner) Date: Thu, 03 May 2007 11:58:46 +0200 Subject: 32 OS on 64-bit machine In-Reply-To: <1178183424.548438.303170@y80g2000hsf.googlegroups.com> References: <1178183424.548438.303170@y80g2000hsf.googlegroups.com> Message-ID: <1178186326.789203@nntpcache01.si.eunet.at> SamG wrote: > If anyone has a x86_64 machine and is running a 32bit OS on top of > that.... could you tell me what output would you get for the following > program > > #====================== > import platform > print platform.processor() > print platform.architecture() > #====================== > > Thanks in advance > : )~ > Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\>python Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import platform >>> print platform.processor () >>> print platform.architecture () ('32bit', 'WindowsPE') >>> From johnmasters at oxtedonline.net Sat May 26 15:15:16 2007 From: johnmasters at oxtedonline.net (John K Masters) Date: Sat, 26 May 2007 20:15:16 +0100 Subject: ten small Python programs In-Reply-To: <162044.45569.qm@web33507.mail.mud.yahoo.com> References: <162044.45569.qm@web33507.mail.mud.yahoo.com> Message-ID: <20070526191516.GA29741@spookie1.spookiegate> On 11:43 Sat 26 May , Steve Howell wrote: > I've always thought that the best way to introduce new > programmers to Python is to show them small code > examples. > > When you go to the tutorial, though, you have to wade > through quite a bit of English before seeing any > Python examples. > > Below is my attempt at generating ten fairly simple, > representative Python programs that expose new users > to most basic concepts, as well as the overall syntax. > > It was an interesting exercise. I constrained myself > to ten lines or less, and it was pretty easy to > incorporate loops, conditionals, print, open(), lists, > tuples, dictionaries, and imported modules. > > It was harder to show classes, and my ShoppingCart > class is nothing more than an encapsulation of a list, > which has dubious value (although it's the start of > something more useful). > > Anyway, here goes: > Many thanks for that. This is exactly what is missing in most introductory books. Simple, relevant and concise examples. Regards, John -- War is God's way of teaching Americans geography Ambrose Bierce (1842 - 1914) From usenet at solar-empire.de Sun May 13 10:57:40 2007 From: usenet at solar-empire.de (Marc Christiansen) Date: 13 May 2007 14:57:40 GMT Subject: __dict__ for instances? References: Message-ID: <46472764$0$23138$9b4e6d93@newsspool1.arcor-online.net> Ivan Voras scribis: > While using PyGTK, I want to try and define signal handlers > automagically, without explicitly writing the long dictionary (i.e. I > want to use signal_autoconnect()). > > To do this, I need something that will inspect the current "self" and > return a dictionary that looks like: > > { > "method_name" : self.method_name > } Nope, at least for PyGTK 2 :) See below. [...] > This looks like it should be easy, but I can't find the solution :( Use the doc, Luke, oops, Ivan :) Citing the gtk.glade.XML.signal_autoconnect documentation: def signal_autoconnect(dict) dict: a mapping or an instance ^^^^^^^^ The signal_autoconnect() method is a variation of the gtk.glade.XML.signal_connect method. It uses Python's introspective features to look at the keys (if dict is a mapping) or attributes (if ^^^^^^^^^^^^^^ dict is an instance) and tries to match them with the signal handler ^^^^^^^^^^^^^^^^^^^ names given in the interface description. The callbacks referenced by each matched key or attribute are connected to their matching signals. The argument is called dict due to compatibility reasons since originally only the mapping interface was supported. The instance variant was introduced in PyGTK 2.0. So simply using signal_autoconnect(self) should work. Adia?, Marc From rhamph at gmail.com Fri May 4 13:19:32 2007 From: rhamph at gmail.com (Rhamphoryncus) Date: 4 May 2007 10:19:32 -0700 Subject: Decorating class member functions In-Reply-To: References: <1178241696.641350.292210@n59g2000hsh.googlegroups.com> Message-ID: <1178299172.646205.128870@e65g2000hsc.googlegroups.com> On May 3, 10:34 pm, Peter Otten <__pete... at web.de> wrote: > The problem is not that you are decorating a method but that you are trying > to use a callable class instance as a method. For that to work the class > has to implement the descriptor protocol, see > > http://users.rcn.com/python/download/Descriptor.htm > > class Bugger (object): > def __init__ (self, module, fn, instance=None): > self.module = module > self.fn = fn > self.instance = instance > > def __call__ (self, *args, **kws): > print "calling %s.%s()" % (self.module, self.fn.__name__) > if self.instance is not None: > args = (self.instance,) + args > ret_val = self.fn(*args, **kws) > return ret_val > > def __get__(self, instance, class_): > if instance is None: > return self > return Bugger(self.module, self.fn, instance) > > def instrument (module_name): > ret_val = lambda x: Bugger(module_name, x) > return ret_val > > class Stupid(object): > @instrument("xpd.spam") > def update(self): > print "update()" > > s = Stupid() > s.update() > Stupid.update(s) I've been bitten by the "class instances as decorators won't get bound" bug many times. I had no idea there was a direct solution. Thanks! -- Adam Olsen, aka Rhamphoryncus From see.signature at no.spam Fri May 18 03:15:11 2007 From: see.signature at no.spam (Eric Brunel) Date: Fri, 18 May 2007 09:15:11 +0200 Subject: tkinter button state = DISABLED References: <1179163831.016938.79840@w5g2000hsg.googlegroups.com> <1179175592.011635.103980@e51g2000hsg.googlegroups.com> <03f601c7979e$83559740$03000080@hendrik> Message-ID: On Thu, 17 May 2007 09:30:57 +0200, Hendrik van Rooyen wrote: > "Gabriel Genellina" wrote: >> En Wed, 16 May 2007 03:22:17 -0300, Hendrik van Rooyen >>> I have never seen this working in Tkinter, unless the button was >>> pressed >>> on the >>> widget >>> in question - and worse, once you have clicked down on a ButtonRelease >>> binding >>> you can move the mouse pointer anywhere you like, even out of the >>> application >>> and when you release it, the bound function is called... >>> >>> Its either a bug or a feature, I don't know. >> >> Uhmm... I'm not sure I understand you completely. I only said that the >> "command" is fired only when the mouse button is pressed on the widget, >> AND released inside the same widget. If both events don't happen in the >> same widget, "command" won't fire. Maybe you are saying the same >> thing... >> anyway I'm not a Tk expert. > > No command is ok and you have described it right - its ButtonRelease that > seems broken to me Apparently, this behaviour is the intended one, at least for buttons; see: http://www.tcl.tk/man/tcl8.4/TkCmd/bind.htm#M11 As for the question "why?", maybe you should ask it on the c.l.tcl newsgroup? -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From artdent at freeshell.org Wed May 9 15:09:19 2007 From: artdent at freeshell.org (Jacob Lee) Date: Wed, 9 May 2007 19:09:19 +0000 (UTC) Subject: ANN: parley 0.2 Message-ID: Release Announcement: PARLEY version 0.2 PARLEY is an API for writing Python programs that implement the Actor model of distributed systems, in which lightweight concurrent processes communicate through asynchronous message-passing. Actor systems typically are easier to write and debug than traditional concurrent programs that use locks and shared memory. PARLEY can run using either traditional native threads or user-space threads (i.e. the "tasklets" implemented by Stackless Python). A program written using PARLEY can choose between the two by changing a single line of code. Code samples, documentation, and source code can be found at the PARLEY home page: http://osl.cs.uiuc.edu/parley/ PARLEY is licensed under the LGPL. -- Jacob Lee From mtobis at gmail.com Tue May 8 20:31:31 2007 From: mtobis at gmail.com (Michael Tobis) Date: 8 May 2007 17:31:31 -0700 Subject: interesting exercise In-Reply-To: <1178661851.606885.104330@p77g2000hsh.googlegroups.com> References: <1178595952.641173.76540@y80g2000hsf.googlegroups.com> <1178601624.812907.23550@u30g2000hsc.googlegroups.com> <1178661305.063868.130730@e65g2000hsc.googlegroups.com> <1178661851.606885.104330@p77g2000hsh.googlegroups.com> Message-ID: <1178670691.209680.119330@o5g2000hsb.googlegroups.com> Thanks castironpi and alex, for this: def p(a,b): if not b: return [''] return [i+j for i in a for j in p(a,b-1)] That is a thing of beauty! As usual you guys didn't disappoint. (Validity check of alphabet removed; you didn't check for duplicate characters.) Here is the bloated mess I came up with. I did see that it had to be recursive, and was proud of myself for getting it pretty much on the first try, but the thing still reeks of my sorry old fortran-addled mentality. def validAlphabet(alphabet): if not isinstance(alphabet,str): return False if len(alphabet) > 256: return False for index in range(len(alphabet)-1): if not alphabet[index] < alphabet[index+1]: return False return True def nextword(word,alphabet): if len(word) == 1: index = alphabet.find(word) if index < 0: raise ValueError("bad token found %s" % word) if index == len(alphabet) -1: return None else: return alphabet[index+1] else: a = nextword(word[1:],alphabet) if a: return word[0] + a else: b = nextword(word[0],alphabet) if b: return b + (len(word) - 1) * alphabet[0] else: return None def allwords(length,alphabet="01"): if not validAlphabet(alphabet): raise ValueError("bad token list %s" % alphabet) word = length * alphabet[0] result = [word] while word < length * alphabet[-1]: word = nextword(word,alphabet)) result.append(word) return result ###### if __name__ == "__main__": for item in allwords(5,"abc"): print item From eric.brunel at pragmadev.com Thu May 10 03:29:33 2007 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Thu, 10 May 2007 09:29:33 +0200 Subject: tkinter - Screen Resolution References: <1178728652.490682.239650@u30g2000hsc.googlegroups.com> Message-ID: On Wed, 09 May 2007 18:37:32 +0200, wrote: > Hi, > I have developed a GUI using tkinter (grid geometory manager). > The structure is a top frame containing multiple subframes. Each > subframe has a combination of widgets like(Entry, label, > button,listboxes). The subframes are placed with a padx and pady > offset with regards to the other subframes. And the widgets within > these subframes have their own padx and pady offsets. The GUI runs > fine on my linux box, but on a different linux box things get wierd. > I see things like- > 1) The frame width increasing > 2) The widget padx translating to much bigger offsets with reference > to the subframe edges > 3) Widget widths like that for Entry become bigger > > I Know its to do with the screen resolution settings and user settings > on different machines. Can anyone point me in the right > direction(before I start looking into it)as how to account for > different screen resolutions so as to have as uniform a GUI look as > possible across different user machines. [snip] For some reason, tk uses different default units for coordinates and font sizes: a coordinate specified as just a number is considered to be in pixels (a.k.a screen points); a font size specified as just a number is considered to be in points, i.e 1/72 inch. So these units are the same only if your screen resolution is exactly 72 dpi, which is usually not the case. If this is actually your problem, the way to correct it is quite simple: the tk command "tk scaling 1" tells tk that a point and a pixel are the same thing. To issue it, you may have to use explicitely the tcl interpreter used by Tkinter by doing: aWidget.tk.call('tk', 'scaling', 1) where aWidget is any Tkinter widget. This is what I had to do with Python 2.1; it may be easier with later Python/Tkinter versions. HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From nogradi at gmail.com Wed May 23 03:36:28 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Wed, 23 May 2007 09:36:28 +0200 Subject: Slightly OT: Why all the spam? In-Reply-To: <3bb44c6e0705220008y10f5deb7v86ed82d3f8241761@mail.gmail.com> References: <3bb44c6e0705220008y10f5deb7v86ed82d3f8241761@mail.gmail.com> Message-ID: <5f56302b0705230036o7fcdc318w28bab12109bcf99e@mail.gmail.com> > Actually, it would be nice to know if anybody has any good filters > worked up that will work in Gmail for reading python-list. I use this filter in gmail applied to the body of the message, if there is a match, it skips inbox and gets deleted: britney OR boobs OR tits OR sex OR pamela OR pics OR 911 OR boob OR britneys OR pamelas OR fbi OR cia OR bush OR cheney OR wolfowitz OR wtc OR pussy OR boobies OR tities OR chicks Works pretty well, although not perfect. From ptmcg at austin.rr.com Sun May 27 12:09:24 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 27 May 2007 09:09:24 -0700 Subject: Is PEP-8 a Code or More of a Guideline? In-Reply-To: <87myzqpstb.fsf@benfinney.id.au> References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <87myzqpstb.fsf@benfinney.id.au> Message-ID: <1180282164.427316.51710@p47g2000hsd.googlegroups.com> On May 27, 3:35 am, Ben Finney wrote: > Paul McGuire writes: > > At this point, I realized that I was taking things too far > > off-topic, so I decided to start a new thread. > > So, uh, what's the purpose of this thread? Did you have a specific > point to start off with, or a question to ask? > > -- > \ "It seems intuitively obvious to me, which means that it might | > `\ be wrong." -- Chris Torek | > _o__) | > Ben Finney (Nice sig quote, by the way.) Mostly, I started this thread so any discussion of lower_case_with_underscores (l_c_w_u) vs. mixedCase naming styles would not (further) clutter up Steve Howell's thread. To recap: - I was surprised at the comments to convert Steve's example to l_c_w_u, as the last time I read PEP-8, it had the more liberal "use whichever you prefer, just be consistent" wording. - I posted one comment that I thought l_c_w_u looks old-fashioned, and was an odd choice in the face of mixedCase, which has been adopted as de facto practice in recent languages. - I also mused on the implications for l_c_w_u in the face of Py3K's recent acceptance of non-ASCII identifiers, and added as a related point my own personal experience with typing '_' on a non-US keyboard layout. - At this point, I tracked down the python-dev archive of the discussion thread that led to the stricter version of PEP-8, and I can see that this is a windmill (like the choice of '@' sign for decorators) that is not worth tilting at. It is a bit reassuring that I am not the only one who turns a blind eye to this part of the PEP, that l_c_w_u bothers others as well. But as to the further purpose for this thread, I think there is little to none. We will continue to see std lib code written using l_c_w_u. Ordinarily, this would little concern me, since I go to read std lib code about once/year. But it does mean that additions to the external API to the std lib will contain method calls such as get_files, send_message, delete_record, etc. I think this just promotes a perception of Python as "so last century." It would also seem we will continue to see 3rd party developers use whatever their personal taste and/or project coding standards dictate. So for these users, this part of the PEP is "not really a code, its more of a guideline."* -- Paul *same joke was in Ghostbusters and Pirates of the Caribbean, Pt.1 From tjreedy at udel.edu Wed May 9 11:14:05 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 9 May 2007 11:14:05 -0400 Subject: Towards faster Python implementations - theory References: <1210i.7468$2v1.2505@newssvr14.news.prodigy.net> <013d01c79210$5e441280$03000080@hendrik> Message-ID: "Hendrik van Rooyen" wrote in message news:013d01c79210$5e441280$03000080 at hendrik... | I am relatively new on this turf, and from what I have seen so far, it | would not bother me at all to tie a name's type to its first use, so that | the name can only be bound to objects of the same type as the type | of the object that it was originally bound to. | | But maybe I am missing the point of dynamism. | | Would an implementation of the above break lots of stuff in practice? For function local variables, if you mean 'originally bound to' in the current call invocation, that would sometimes be ok (and that is sort of what Psycho does). But if you mean in the original binding in the first call invocation, then that would cripple many functions. tjr From max at alcyone.com Thu May 24 15:54:01 2007 From: max at alcyone.com (Erik Max Francis) Date: Thu, 24 May 2007 12:54:01 -0700 Subject: 0 == False but [] != False? In-Reply-To: References: <1179982400.412340.178710@g4g2000hsf.googlegroups.com> <1179983482.452458.188690@q66g2000hsg.googlegroups.com> Message-ID: Donn Cave wrote: > Anyone who finds this surprising, might enjoy reading this > article from the time several years ago when the feature > was being considered. When you have some time - it's long, > but interesting. The present confusion is more directly > addressed towards the end. Yes, it's the Laura Creighton > article again: > > http://groups.google.com/group/comp.lang.python/msg/2de5e1c8384c0360 If so, be sure to click "More options," then "View thread," and then read the responses. There were many reasonable objections to her points. -- 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 Human salvation lies in the hands of the creatively maladjusted. -- Dr. Martin Luther King, Jr. From phishboh at gmail.com Tue May 15 09:38:45 2007 From: phishboh at gmail.com (phishboh at gmail.com) Date: 15 May 2007 06:38:45 -0700 Subject: Automatic login to website (newbie) Message-ID: <1179236324.976072.286530@k79g2000hse.googlegroups.com> I'm trying to use PAMIE to login to a website: import cPAMIE # python.org - just a test, works fine ie = cPAMIE.PAMIE() website = "http://www.python.org" ie.navigate(website) ie.textBoxSet('q', 'pamie') ie.buttonClick('submit') # expekt.com - this is what I want to do, but it fails ie = cPAMIE.PAMIE() website = "http://www.expekt.com/eng" ie.navigate(website) ie.textBoxSet('user', 'MyLogin') ie.textBoxSet('pass', 'MyPassword') ie.buttonClick('actn') The first part of the script works fine, i.e., I can successfully open IE, navigate to python.org, and do a search for "pamie". However, when trying to login to the Expekt website, nothing is entered in the text boxes, since they cannot be found. If I manually navigate to the Expekt website, right click next to the login boxes, and view source it looks like this:
    user:
    password:
    Forgot my password
    To my (limited) understanding, it looks like I have the correct names of the text boxes ("user" and "pass")? Problem with frames? Any ideas how to make it work? Is there a better way of automatically logging in to websites (and then navigating within the site)? Many thanks in advance! From hobel at belleombre.de Tue May 29 13:44:44 2007 From: hobel at belleombre.de (Holger Berger) Date: Tue, 29 May 2007 19:44:44 +0200 Subject: multiline regular expression (replace) References: <1180432000.953227.144690@i13g2000prf.googlegroups.com> Message-ID: Hi, yes: import re a=""" I Am Multiline but short anyhow""" b="(I[\s\S]*line)" print re.search(b, a,re.MULTILINE).group(1) gives I Am Multiline Be aware that . matches NO newlines!!! May be this caused your problems? regards Holger Zdenek Maxa wrote: > half.italian at gmail.com wrote: >> On May 29, 2:03 am, Zdenek Maxa wrote: >> >>> Hi all, >>> >>> I would like to perform regular expression replace (e.g. removing >>> everything from within tags in a XML file) with multiple-line pattern. >>> How can I do this? >>> >>> where = open("filename").read() >>> multilinePattern = "^ .... <\/tag>$" >>> re.search(multilinePattern, where, re.MULTILINE) >>> >>> Thanks greatly, >>> Zdenek >>> >> >> Why not use an xml package for working with xml files? I'm sure >> they'll handle your multiline tags. >> >> http://effbot.org/zone/element-index.htm >> http://codespeak.net/lxml/ >> >> ~Sean >> >> > > Hi, > > that was merely an example of what I would like to achieve. However, in > general, is there a way for handling multiline regular expressions in > Python, using presumably only modules from distribution like re? > > Thanks, > Zdenek From bbxx789_05ss at yahoo.com Sat May 19 18:00:45 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 19 May 2007 15:00:45 -0700 Subject: docs patch: dicts and sets In-Reply-To: References: <_5-dnU7aIN73j9LbnZ2dnUVZ_uCinZ2d@comcast.com> <1179593927.503393.127350@u30g2000hsc.googlegroups.com> <1179596822.923443.67500@k79g2000hse.googlegroups.com> <1179601094.940650.276120@w5g2000hsg.googlegroups.com> Message-ID: <1179612045.678939.260650@p47g2000hsd.googlegroups.com> >Actually, it would just move the "endless, petty discussions about what >minutiae are more important" into the docs. I don't see how that's an >improvement. Because it highlights the issues you will be faced with when using the described functions. People will post about an issue they had with a function, and then they will post their solution. Instead of having to search all over google for an answer, the most relevant discussions will be right in the docs. As you read the user comments, you would be able to quickly tell whether a comment pertains to the issue you are having trouble with, and if the comment isn't relevant, you can skip the comment and look at the next comment. If you wanted, you could limit yourself to reading just the official python description of the function and be no worse off. >And most will simply be confused. Then it's likely someone will post something to clear up the confusion. From mikeminer53 at hotmail.com Wed May 23 12:43:14 2007 From: mikeminer53 at hotmail.com (mkPyVS) Date: 23 May 2007 09:43:14 -0700 Subject: Resizing listbook's listview pane In-Reply-To: <1179932659.180278.72990@w5g2000hsg.googlegroups.com> Message-ID: <1179938594.283646.204460@k79g2000hse.googlegroups.com> Sorry, copied from wxpython submit as well.. I'm using wxpython 2.8... Primariy I want the resize to happen programatically during object creation/post creation... I can worry about app size changes later. Thanks, Mike From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue May 15 07:55:43 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 15 May 2007 13:55:43 +0200 Subject: Simulating simple electric circuits References: <5a9838F2nlbanU1@mid.individual.net> <5ae44aF2ku9rtU1@mid.individual.net> <5ak3u9F2odts2U1@mid.individual.net> <1178974027.175679.51130@k79g2000hse.googlegroups.com> <5aruivF2osbvdU1@mid.individual.net> Message-ID: <5atldvF2qunsoU2@mid.individual.net> Bjoern Schliessmann wrote: > class Source(object): Little bug: The __init__ method of class Source should look like this. def __init__(self, ID, neighbour = None): self.connections = [] self.ID = ID if neighbour: self.connections.append(neighbour) Regards, Bj?rn -- BOFH excuse #102: Power company testing new voltage spike (creation) equipment From mensanator at aol.com Wed May 16 13:26:33 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 16 May 2007 10:26:33 -0700 Subject: Interesting list Validity (True/False) In-Reply-To: References: <1179017740.656323.209590@e51g2000hsg.googlegroups.com> <1179020634.130689.171960@o5g2000hsb.googlegroups.com> <1179031812.090768.248750@l77g2000hsb.googlegroups.com> <1179168081.603409.39970@e51g2000hsg.googlegroups.com> <1179203827.881205.287910@l77g2000hsb.googlegroups.com> <1179248480.350553.4430@n59g2000hsh.googlegroups.com> <1179296218.969564.240220@k79g2000hse.googlegroups.com> Message-ID: <1179336393.574863.248040@w5g2000hsg.googlegroups.com> On May 16, 4:12 am, "Gabriel Genellina" wrote: > En Wed, 16 May 2007 03:16:59 -0300, mensana... at aol.com > escribi?: > > > > > > > On May 15, 7:07 pm, "Gabriel Genellina" > > wrote: > >> >>>> import gmpy > >> >>>> a = 2**177149-1 > >> >>>> b = gmpy.mpz(2**177149-1) > >> >>>> a==b > >> > True > >> >>>> print '%d' % (b) > > >> > Traceback (most recent call last): > >> > File "", line 1, in > >> > print '%d' % (b) > >> > TypeError: int argument required > > >> > So although the comparison operator is smart enough to realize > >> > the equivalency of numeric types and do the type conversion, > >> > the print statement isn't so smart. > > >> This is up to the gmpy designers/writers/maintainers. Anyone writing a > >> class chooses which features to implement, which ones to omit, how to > >> implement them, etc. The code may contain bugs, may not be efficient, > >> may > >> not behave exactly as the users expect, may not have anticipated all > >> usage > >> scenarios, a long etc. In this case, probably the gmpy writers have > >> chosen > >> not to allow to convert to int, and they may have good reasons to not do > >> that (I don't know what platform are you working in, but I feel that > >> your > >> b object is somewhat larger than sys.maxint...). > > > Then how does this work? > > >>>> print '%d' % (long(gmpy.mpz(2**177149-1))) > > 1454...<53320 digits snipped>...3311 > > > I honestly don't understand why there's a problem here. > > If print can handle arbitrary precision longs without > > a problem, why does it fail on mpzs > sys.maxint? > > If the gmpy writers are not allowing the conversion, > > then why do small mpz values work? Something smells > > inconsistent here. > > Python (builtin) "integral numbers" come on two flavors: int and long. > ints correspond to the C `long` type usually, and have a limited range, at > least from -2**31 to 2**31-1; most operations have hardware support (or at > least it's up to the C compiler). Long integers are a totally different > type, they have unlimited range but are a lot slower, and all operations > must be done "by hand". Seehttp://docs.python.org/ref/types.html > > If you say "%d" % something, Python first tries to see if `something` is a > long integer -not to *convert* it to a long integer, just to see if the > object *is* a long integer. If it's a long, it's formatted accordingly. > If not, Python sees if `something` is a plain integer. If not, it sees if > it's a number (in this context, that means that the structure describing > its type contains a non-NULL tp_as_number member) and tries to *convert* > it to an integer. Notice that if the object whas not originally a long > integer, no attempt is made to convert it to a long using the nb_long > member - just a plain integer conversion is attempted. > It's at this stage that a large mpz object may fail - when its value can't > fit in a plain integer, it raises an OverflowError and the "%d" formatting > fails. > If you force a conversion to long integer, using long(mpz(...)) as above, > the % operator sees a long integer from start and it can be formatted > without problems. > > I don't know if this asymmetric behavior is a design decision, a historic > relic, a change in protocol (is nb_int allowed now to return a > PyLongObject, but not before?), a "nobody cares" issue, or just a bug. > Perhaps someone else can give an opinion - and certainly I may be wrong, I > had never looked at the PyString_Format function internal details before > (thanks for providing an excuse!). Ah, thanks for the info, I know nothing about Python internals. That implies that although this works: >>> print '%d' %(1234567890.0) 1234567890 this does not: >>> print '%d' %(12345678901234567890.0) Traceback (most recent call last): File "", line 1, in print '%d' %(12345678901234567890.0) TypeError: int argument required So we can work around it by doing the long conversion ourselves since print only knows how to invoke int conversion. >>> print '%d' %(long(12345678901234567890.0)) 12345678901234567168 which demonstartes the problem is not with gmpy. > > As a workaround you can always write "%d" % long(mpznumber) when you want > to print them (or perhaps "%s" % mpznumber, which might be faster). > > > How is it that > > >>>> print '%d' % (1.0) > > 1 > > > doesn't make a type mismatch? Obviously, the float > > got changed to an int and this had nothing to do with > > gmpy. Is it the print process responsible for doing > > the conversion? Maybe I should say invoking the > > conversion? Maybe the gmpy call tries to literally > > convert to an integer rather than sneakily substitute > > a long? > > Same as above: is the argument a long integer? no. is it a number? yes. > Convert to int. No errors? Apply format. Thanks again, as long as I know why the behaviour is strange, I know how to work around it > > -- > Gabriel Genellina From carsten at uniqsys.com Mon May 7 09:16:49 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 07 May 2007 09:16:49 -0400 Subject: assisging multiple values to a element in dictionary In-Reply-To: <1178543184.846426.309770@y5g2000hsa.googlegroups.com> References: <1178535831.870912.44220@p77g2000hsh.googlegroups.com> <1178543184.846426.309770@y5g2000hsa.googlegroups.com> Message-ID: <1178543809.3360.14.camel@dot.uniqsys.com> On Mon, 2007-05-07 at 06:06 -0700, John Machin wrote: > Unlikely. "Turning it around" produces one key ('subfunction') with > *FIVE* different values. Whoops! I assumed the OP's problem was reasonably well-formed and didn't actually check if any of the values were duplicated. I guess the OP will just have to live with the suggestion of storing tuples or lists, or explain to us what he's actually trying to achieve. -- Carsten Haese http://informixdb.sourceforge.net From larry.bates at websafe.com Thu May 31 14:20:38 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 31 May 2007 13:20:38 -0500 Subject: FAQ: how to vary the byte offset of a field of a ctypes.Structure In-Reply-To: <1180634138.944362.88590@d30g2000prg.googlegroups.com> References: <1180634138.944362.88590@d30g2000prg.googlegroups.com> Message-ID: p.lavarre at ieee.org wrote: > How do I vary the byte offset of a field of a ctypes.Structure? > > How do I "use the dynamic nature of Python, and (re-)define the data > type after the required size is already known, on a case by case > basis"? > > \\\ > > For example, suppose sometimes I receive the value '\x03hi' + \x04bye' > for the struct: > > class Struct34(ctypes.Structure): > _pack_ = 1 > _fields_ = [('first', 3 * ctypes.c_ubyte), > ('second', 4 * ctypes.c_ubyte)] > > but then sometimes instead I receive the value '\x05left' + \x06right' > for the struct: > > class Struct56(ctypes.Structure): > _pack_ = 1 > _fields_ = [('first', 5 * ctypes.c_ubyte), > ('second', 6 * ctypes.c_ubyte)] > > Thus in general I receive (0xFF ** 2) possible combinations of field > lengths. > > /// > > How do I declare all those hugely many simply regular combinations as > one CTypes.structure? > > I also need to do series of 3 or 4 or 5 strings, not just 2 strings. > But always the byte offsets of the subsequent fields vary when the > byte sizes of the preceding fields vary. The byte size of the > enclosing packed struct varies as the length of the packed bytes it > contains. > > The errors I get as I try techniques that don't work include: > > AttributeError: '_fields_' must be a sequence of pairs > AttributeError: _fields_ is final > ValueError: Memory cannot be resized because this object doesn't own > it > TypeError: incompatible types, c_ubyte_Array_2 instance instead of > c_ubyte_Array_1 instance > > How do I change the offset of a field of a ctypes.Structure? > > Is the answer to contribute to the next version of CTypes? Or is this > feature already supported somehow? > > Curiously yours, thank in advance, > How about something like: class fooStruct(ctypes.Structure): _pack_ = 1 _fields_=[] def __init__(self, fields): self._fields_=fields ctypes.Structure.__init__(self) a=fooStruct([('first', 3*ctypes.c_ubyte), ('second', 4*ctypes.c_ubyte)]) print a._fields_ -Larry From hanser at club-internet.fr Mon May 14 12:54:57 2007 From: hanser at club-internet.fr (Pierre Hanser) Date: Mon, 14 May 2007 18:54:57 +0200 Subject: PEP 3131: Ascii-English is like coca-cola! In-Reply-To: <46488bce$0$4159$ba624c82@nntp02.dk.telia.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> <46488bce$0$4159$ba624c82@nntp02.dk.telia.net> Message-ID: <46489454$0$21145$7a628cd7@news.club-internet.fr> This pep is not technical, or at least not only. It has larger implications about society model we want. Let me explain with an analogy: let's compare 'ascii english' to coca-cola. It's available nearly everywhere. It does not taste good at first try, and is especially repulsive to young children. It's cheap and you don't expect much of it. You know you can drink some in case of real need. It's imperialist connotation is widely accepted(?) But it's not good as your favorite beverage, beer, wine, ... The world is full of other possibilities. Think, in case of necessity you could even have to drink tea with yack butter in himalaya! in normal circonstances, you should never see any, but in extreme situation you may have to! Were is freedom in such a world you could only drink coca? I DON'T WANT TO HAVE TO DRINK COCA AT HOME ALL THE TIME. and this pep is a glorious occasion to get free from it. [disclaimer: coca is used here as the generic name it became, and no real offense is intended] -- Pierre From andrew at nospam.com Tue May 15 16:10:25 2007 From: andrew at nospam.com (Andrew Holme) Date: Tue, 15 May 2007 21:10:25 +0100 Subject: Extended characters in MATPLOTLIB (newbie) References: Message-ID: "Andrew Holme" wrote in message news:f2d2mm$gjs$1$8300dec7 at news.demon.co.uk... > I'm using MATPLOTLIB on Windows. > > How can I get extended characters such as the micro symbol (greek letter > mu) to appear in my axis labels? > > I've tried: > > xlabel('?s', font) > > and > > xlabel('\xB5s', font) > > but it just appears as a box. > > TIA > Found it: xlabel(r'$\mu s$', fontsize=20) From brandon.mcginty at gmail.com Wed May 30 00:36:22 2007 From: brandon.mcginty at gmail.com (Brandon McGinty) Date: Tue, 29 May 2007 21:36:22 -0700 Subject: RDFXML Parser For "qualified Dublin Core" Database File Message-ID: <465cff21.09da2647.3a75.ffffb942@mx.google.com> Hi All, My goal is to be able to read the www.gutenberg.org rdf catalog, parse it into a python structure, and pull out data for each record. The catalog is a Dublin core RDF/XML catalog, divided into sections for each book and details for that book. I have done a very large amount of research on this problem. I've tried tools such as pyrple, sax/dom/minidom, and some others both standard and nonstandard to a python installation. None of the tools has been able to read this file successfully, and those that can even see the data can take up to half an hour to load with 2 gb of ram. So you all know what I'm talking about, the file is located at: http://www.gutenberg.org/feeds/catalog.rdf.bz2 Does anyone have suggestions for a parser or converter, so I'd be able to view this file, and extract data? Any help is appreciated. Thanks, Brandon McGinty Brandon.mcginty at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From S.Mientki-nospam at mailbox.kun.nl Mon May 14 17:24:23 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Mon, 14 May 2007 23:24:23 +0200 Subject: os.listdir() doesn't work ?? In-Reply-To: <1179173881.163830.54930@n59g2000hsh.googlegroups.com> References: <1179173881.163830.54930@n59g2000hsh.googlegroups.com> Message-ID: <91a85$4648d2cd$d443bb3a$3987@news.speedlinq.nl> timw.google wrote: > On May 14, 4:09 pm, Stef Mientki > wrote: >> hello, >> >> I want to find all files with the extension "*.txt". >> From the examples in "Learning Python, Lutz and Asher" and >> from the website I see examples where you also may specify a wildcard filegroup. >> >> But when I try this >> files = os.listdir('D:\\akto_yk\\yk_controle\\*.txt') >> >> I get an error message >> >> WindowsError: [Errno 123] The filename, directory name, or volume label syntax is incorrect: >> 'D:\\akto_yk\\yk_controle\\*.txt/*.*' >> >> What am I doing wrong ? >> >> thanks, >> Stef Mientki > > You want the glob module > > http://docs.python.org/lib/module-glob.html > > import glob > glob.glob('*.txt') thanks that works ! Still don't know why it's not allowed through listdir ;-) cheers, Stef Mientki From __peter__ at web.de Fri May 25 03:51:57 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 25 May 2007 09:51:57 +0200 Subject: Can I reference 1 instance of an object by more names ? rephrase References: <4654289a$0$2326$426a74cc@news.free.fr> <3dc25$4655ebd1$d443bb3a$31378@news.speedlinq.nl> <8c957$46568f73$d443bb3a$15533@news.speedlinq.nl> Message-ID: Stef Mientki wrote: >> Again, I'm confident, again I didn't test. > > I did, ... > ... and unfortunately it still gave errors. Strange. > So for the moment I'll just stick to my "lots of code solution", > and I'll try again, when I've some more understanding of these Python > "internals". Anyway, here's a self-contained example: """ >>> p = cpu_ports() >>> p cpu_ports(p1=0, p2=0, p3=0, p4=0, p5=0) >>> p.p3 = 1 >>> p cpu_ports(p1=0, p2=0, p3=1, p4=0, p5=0) >>> p.p4 = 1 >>> p cpu_ports(p1=0, p2=0, p3=1, p4=1, p5=0) >>> p.p3 = 0 >>> p cpu_ports(p1=0, p2=0, p3=0, p4=1, p5=0) """ def bit(index): def fset(self, value): value = ( value & 1L ) << index mask = ( 1L ) << index self._d = ( self._d & ~mask ) | value def fget(self): return ( self._d >> index ) & 1 return property(fget, fset) class cpu_ports(object) : def __init__(self): self._d = 0 def __str__(self): return "cpu_ports(%s)" % ", ".join( "%s=%s" % (n, getattr(self, n)) for n in ["p1", "p2", "p3", "p4", "p5"]) __repr__ = __str__ p1 = bit(1) p2 = bit(2) p3 = bit(3) p4 = bit(4) p5 = bit(5) if __name__ == "__main__": import doctest doctest.testmod() Peter From andymac at bullseye.apana.org.au Sat May 26 20:39:44 2007 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sun, 27 May 2007 11:39:44 +1100 Subject: Compiling python extension on amd64 for 32 bit In-Reply-To: References: Message-ID: <4658D350.7050008@bullseye.andymac.org> Mathias Waack wrote: > Andrew MacIntyre wrote: > >> Mathias Waack wrote: >>> After switching my development environment to 64 bit I've got a >>> problem with a python extension for a 32 bit application. >> {...} >> >>> Ok, thats fine. So why is python complaining? Or even more >>> interesting, what do I have to do to compile the code? >> Is the Python your toolchain is referencing 32 or 64 bit? Based on >> what I can see in pyport.h, I'd guess that you're finding a 64 bit >> Python (ie SIZEOF_LONG == 8). > > There is no such thing as "the Python". A biarch environment offers > both the 32 bit and the 64 bit versions of each library. And unique > headers, because its assumed that the headers are independent of the > architecture. Because of the -m32 Flag the pyport.h is used within a > 32 bit env. Every Python installation has an architecture dependent header (pyconfig.h), unless a vendor specifically creates a replacement which neutralises this; that header contains the definition (SIZEOF_LONG) that triggers your problem. -- ------------------------------------------------------------------------- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From efrat_regev at yahoo.com Tue May 1 14:23:40 2007 From: efrat_regev at yahoo.com (Efrat Regev) Date: Tue, 01 May 2007 21:23:40 +0300 Subject: Grabbing the output of a long-winded shell call (in GNU/Linux) Message-ID: <46378364$1@news.bezeqint.net> Hello, Suppose I want to run from within a Python GUI app some long-output shell call. For example, from within Python I might want to call g++ foo.cpp I already know there are many ways to do this, e.g., commands.getstatusoutput('g++ foo.cpp') to name one. The problem is that this might generate a ton of output (e.g., because of compilation errors), and might take a while to do so. In my GUI, I'd like to print out the output as it's being generated, not wait until all is done (as commands.getstatusoutput will do) and dump it at once. So my question is if there's a way to "grab" the output as it's being generated. It doesn't matter if the solution is blocking (as opposed to callback based), since threads can handle this. I just don't know how to "grab" the output. I appreciate your time in reading (and answering this), as I've been googling several hours for this. Many Thanks, E From eiwot at hotmail.com Sun May 27 21:26:05 2007 From: eiwot at hotmail.com (Eiwot) Date: Mon, 28 May 2007 01:26:05 +0000 Subject: Xml parser Message-ID: Let's try http://pyxml.sourceforge.net/ Cheers Python Articles at http://pyarticles.blogspot.com/> Date: Sat, 26 May 2007 10:02:06 +0200> From: stefan.behnel-n05pAM at web.de> Subject: Re: Xml parser> To: python-list at python.org> > XiaQ wrote:> > You can use DOM> > http://diveintopython.org/, Chapter 9> > "ashish" wrote> >> Hi All,> >>> >> I want to know weather is there any api available in python for parsing> >> xml(XML parser)> >>> >> Regards> >> Ashish> > Sure, you can use DOM, but if you want to get real work done with XML, lxml is> what you actually want.> > http://codespeak.net/lxml/dev/> > Stefan> -- > http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ Download Messenger. Start an i?m conversation. Support a cause. Join now. http://im.live.com/messenger/im/home/?source=TAGWL_MAY07 -------------- next part -------------- An HTML attachment was scrubbed... URL: From jtittsler at gmail.com Tue May 8 20:04:50 2007 From: jtittsler at gmail.com (Jim Tittsler) Date: 8 May 2007 17:04:50 -0700 Subject: Win32: shortpathname to longpathname Message-ID: <1178669090.118174.142670@y80g2000hsf.googlegroups.com> I wrap my cross platform application up with py2exe on Windows, and have the installer associate a particular file type with it. When a user double clicks on a document to launch my application, Windows appears to pass me the "short" Windows pathname. How can I convert to the long version of the pathname? (Ideally using the standard library rather than win32all AKA pywin32.) From thorsten at thorstenkampe.de Tue May 15 10:05:50 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 15 May 2007 15:05:50 +0100 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <464996b9$0$10193$9b4e6d93@newsspool4.arcor-online.net> <4649a72d$0$10186$9b4e6d93@newsspool4.arcor-online.net> <4649aca1$0$23148$9b4e6d93@newsspool1.arcor-online.net> <4649b6e0$0$23143$9b4e6d93@newsspool1.arcor-online.net> Message-ID: * Ren? Fleschenberg (Tue, 15 May 2007 15:34:26 +0200) > Thorsten Kampe schrieb: > > No, if you claim that something by itself is good and has to be > > encouraged then you are obliged to prove or give arguments for that. > > That would be well outside the scope of this newsgroup, and if you > cannot see the reaons for this yourself, I am afraid that I won't be > able to convince you anyway. You could actually try by giving some arguments for your opinion. Your rationale was "English only, please" because of "code sharing". > > Exactly. So whether this PEP encourages or discourages code sharing > > (and I don't think it does either) has nothing to do with the value of > > this PEP. > > That completely depends on how you look at code-sharing. My impression > always was that the Python community in general does regard code-sharing > as A Good Thing. I don't think the "Python community" does that because for something to be considered good it should actually be clear what it means. So what actually is "Code sharing"?! Wikipedia seems to know this term but in a slightly different meaning: http://en.wikipedia.org/wiki/Code_sharing > It is not as if we were talking about forcing people to > share code. Just about creating/keeping an environment that makes this > easily possible and encourages it. If the "Python community" would think that "code sharing" (whatever that means) is per se a good thing it would switch to spaces only allowed (instead of tabs and spaces allowed). Actually it would refrain from giving indentation and white space a syntactical meaning because this undoubtedly makes "code sharing" (on web pages or through news readers for instance) /a lot/ more difficult. Thorsten From tjreedy at udel.edu Tue May 15 03:07:09 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 15 May 2007 03:07:09 -0400 Subject: Trying to choose between python and java References: Message-ID: "Anthony Irwin" wrote in message news:f2bghg$4q0$1 at news-01.bur.connect.com.au... | #2 What database do people recommend for using with python that is | easy to distribute across linux, mac, windows. Check out the sqlite3 module. (But I have not used it yet). | #5 someone said that they used to use python but stopped because the | language changed or made stuff depreciated (I can fully remember | which) and old code stopped working. Is code written today likely to | still work in 5+ years or do they depreciate stuff and you have to update? Most versions of Python are still available. You are free to use and distribute your copies indefinitely. Several older versions are still in use. Recent releases have added features but removed very little except bugs. Unfortunately, bug removal sometimes breaks code. And feature additions occasionally introduce bugs or otherwise break code, but that is why there are alpha, beta, and candidate releases before a final release. Python3 will remove many things at once. A conversion tool is being written. And there is no expectation that production code should be immediately converted, if ever. Terry Jan Reedy From robert.rawlins at thinkbluemedia.co.uk Wed May 9 05:40:46 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Wed, 9 May 2007 10:40:46 +0100 Subject: Spotting Crashed Application Message-ID: <003501c7921e$204d4ec0$60e7ec40$@rawlins@thinkbluemedia.co.uk> Hello Guys, I've got an application that I've written, and it sits in an embedded system, from time to time the application will crash, I'm not quite sure what's causing this, but as we test it more and more we'll grasp a better understanding and fix the issues. However, until then I need a quick solution which can spot the crash and reboot the system. Is there any generic way of writing a separate application that'll spot the crash in my main application? If not then i was thinking about having my core application log itself as 'alive' every 5 minutes or so. My new 'spotter' application can check this log, if it's not been written too in say 6 minutes then the main app must have crashed, and it can reboot. Any suggestions on how best to handle this? Obviously finding the bug in my main app is paramount, but a failsafe will never hurt. Thanks again guys, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Sun May 27 11:07:43 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 27 May 2007 16:07:43 +0100 Subject: File monitoring for all drive In-Reply-To: <1180174451.826618.171020@n15g2000prd.googlegroups.com> References: <1180049186.804822.5060@a26g2000pre.googlegroups.com> <1180174451.826618.171020@n15g2000prd.googlegroups.com> Message-ID: <46599EBF.7020604@timgolden.me.uk> [rohit] >>> i want to detect all file change operations(rename,delete,create....) >>> on ALL THE DRIVES of the hard disk >>> using the method ReadDirectoryChanges API , i.e program no. 3 in the >>> webpagehttp://tgolden.sc.sabren.com/python/win32_how_do_i/watch_directory_fo... >>> . >>> Please suggest some modification to the program so that i can detect >>> changes to ALL the drives >>> (to detect changes on c:\ set >>> path_to_watch = "." to "c:\\" but this works for only one drive [Tim Golden] >> Well, to answer the question specifically: since the >> Windows filesstem has no concept of a "root" above >> the drive letters, the simplest thing to do is to >> kick off a thread or a subprocess or what-have-you >> for each drive letter. [rohit] > actually i want to implement a deamon monitoring file changes on the > system > so u suggesting i should implement the program with multithreading to > include all drives? That's one possibility, but again I'd ask whether this is really quite sane: you're asking the filesystem to tell you about every change to every file on the system which will naturally slow things down. It will get even more complicated if you're actually storing these "change logs" in a file somewhere, since that will then fire the monitoring mechanism itself! I suggest - again - that the NTFS change journal might be better suited to what you're trying to do. Try the threaded approach with the ReadDirectoryChanges API *on a small area of disk* to see how well it scales. Then you'll be better placed to decide if it will work well across all the disks in the system. TJG From dustin at v.igoro.us Wed May 2 10:38:57 2007 From: dustin at v.igoro.us (dustin at v.igoro.us) Date: Wed, 2 May 2007 09:38:57 -0500 Subject: Writing a nice formatted csv file In-Reply-To: <1178116112.446167.17960@q75g2000hsh.googlegroups.com> References: <1178115244.446071.317250@n76g2000hsh.googlegroups.com> <1178115967.124030.266090@o5g2000hsb.googlegroups.com> <1178116112.446167.17960@q75g2000hsh.googlegroups.com> Message-ID: <20070502143856.GI14710@v.igoro.us> On Wed, May 02, 2007 at 07:28:32AM -0700, redcic wrote: > Well then how can I format a file ? for row in rows: print "".join([ "%-6s" % ("%d," % cell) for cell in row ]) The "%-6s" formats each column to be no less than six characters long; the "%d," formats the number with a comma after it. This won't be quite what you want, since you've comma-aligned all of the fields after the first, but it should be readable. > > > Whereas what I'd like to get is: > > > 1, 2, 3, > > > 10, 20, 30 > > > > > which is more readable. > > > > cvs files are constructed for efficient processing not formatting so > > that you can read them easier. If you want a formatted file, then > > construct one. From gagsl-py2 at yahoo.com.ar Tue May 22 10:51:39 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 22 May 2007 11:51:39 -0300 Subject: pipe tutorial References: <6LOdndzGvuaCZ8_bnZ2dnUVZ_oDinZ2d@comcast.com> Message-ID: En Tue, 22 May 2007 11:11:45 -0300, Larry Bates escribi?: > Gigs_ wrote: >> does anyone know some good tutorial on pipes in python? > > Pipes is specific only to Windows (you can use sockets > on Windows/Linux/mac). The only specific treatment of > pipes I've seen is in Python Programming for Win32 by > Mark Hammond/Andy Robinson. There are pipes in Unix too, named and anonymous, and I think they predate its introduction in Windows (first on NT4 I believe). "Pipes" used to redirect standard input/output are certainly much older. To the OP: what do you want to do, exactly? -- Gabriel Genellina From walterbyrd at iname.com Fri May 18 22:01:01 2007 From: walterbyrd at iname.com (walterbyrd) Date: 18 May 2007 19:01:01 -0700 Subject: Python compared to other language In-Reply-To: References: Message-ID: <1179540061.598417.13870@y80g2000hsf.googlegroups.com> On May 18, 2:17 pm, Larry Bates wrote: > Python is Portable - C is probably the only more portable language Small quibble: IMO, although C runs on many platforms, I don't think C code is typically portable between platorms. Unless you are doing something very simple. If you write something with Visual Studio to do something fairly advanced on Windows, I don't think the same, unmodified, code will usually run on UNIX, or MS-DOS. Maybe if you use pure ANSI C, but I don't think many people do that. I'm just learning Python. FWIW: my opinions about Python: - good for many things, but probably not the most popular for any one thing. For example: PHP is more popular for web-dev, Perl is more popular for sys-admin. - IMO: the most comparable language to Python, is Perl. Both are scripting languages. Both are free, multi-platform, and multi-purpose. Both are also very popular. - although good for beginners, Python is also used for some very advanced stuff. - IMO: people are more likely to switch from Perl, to Python, than the other way around. - Python is generally considered to be more readable than Perl, and thereby, more maintainable. - I have managed to be fairly productive with Python in a very short time, if I get good at Python, I think I could be very productive. - although Python is considered one of the most popular languages, jobs as python programmers seem to be very rare. I think Python is often used as a tool by people who specialize in other things: data analysts, scientists, systems administrators, database administrators, software testers, etc. - some will tell you that you don't need to know anything about object oriented development to use Python. But, I don't think you will get far without some OO. Just my $0.02 From uriel.katz at gmail.com Wed May 2 17:09:30 2007 From: uriel.katz at gmail.com (urielka) Date: 2 May 2007 14:09:30 -0700 Subject: unittest dependencies Message-ID: <1178140170.849347.79190@h2g2000hsg.googlegroups.com> i am using unittest to test a project,and one thing i really want is a way to say that test a depends on test b,so it need to run before it and be successful in order to run this test. i just wanted to know if anyone have done it before(i searched for it but didn`t find something useful),i think it can be done easily using a decorator that will run the test which is depend on and mark it as successful,the only problem will be detecting circular test dependencies,but that can be fixed by keeping all the functions that the decorator have seen. what do you guys think? did someone did it before? From nufuhsus at gmail.com Fri May 11 16:36:31 2007 From: nufuhsus at gmail.com (nufuhsus at gmail.com) Date: 11 May 2007 13:36:31 -0700 Subject: Interesting list Validity (True/False) In-Reply-To: <1178914190.166662.285410@p77g2000hsh.googlegroups.com> References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> <1178914190.166662.285410@p77g2000hsh.googlegroups.com> Message-ID: <1178915791.584216.293130@l77g2000hsb.googlegroups.com> On May 11, 2:28 pm, nufuh... at gmail.com wrote: > > > > > > > Hello all, > > > First let me appologise if this has been answered but I could not find > > an acurate answer to this interesting problem. > > > If the following is true: > > C:\Python25\rg.py>python > > 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. > > >>> [] == [] > > True > > >>> ['-o'] == [] > > False > > >>> ['-o'] == False > > False > > > Then why do I get the following results: > > C:\Python25\rg.py>help.py -o > > print arg ['-o'] > > type(arg): > > arg is True? False > > help.py version 1.0 Copyright RDEG (c) 2007 > > ['-o'] is an unrecognized option. > > Progam Exit (0) > > > > > import sys > > > _ver_ = 1.00 > > > if '-h' in sys.argv or '--help' in sys.argv: > > print > > print " help.py Version", _ver_, "Copyright RDEG (c) 2007" > > print ''' > > > Options : -h, --help -- display this message > > Progam Exit (0)''' > > sys.exit(0) > > else: > > arg = sys.argv[1:] > > print 'print arg', arg > > print 'type(arg):', type(arg) > > print 'arg is True?', arg == True > > print " help.py version", _ver_, "Copyright RDEG (c) 2007" > > print " ", arg, "is an unrecognized option." > > print " Progam Exit (0)" > > sys.exit(0) > > > I hope this helps (I have tried to post this twice already but it seems to be going somewhere else) you help me. What I would like to happen is: else: arg = sys.argv[1:] print 'print arg', arg print 'type(arg):', type(arg) print 'arg is True?', arg == True if arg != True: print " No Option Provided" print " help.py version", _ver_, "Copyright RDEG (c) 2007" print " ", arg, "is an unrecognized option." print " Progam Exit (0)" sys.exit(0) But as you can see by my output ['-o'] seems to be False as well as [] so the if happens regardless. According to the "Book", ['-o'] should return True which should fail the if, no? From paul at boddie.org.uk Sat May 5 13:56:40 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 5 May 2007 10:56:40 -0700 Subject: Object interfaces and capabilities [was Re: File names and file objects [was Re: My Python annoyances]] In-Reply-To: References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> <1178202431.147195.249790@u30g2000hsc.googlegroups.com> <1hxkwj0.12jtj1v3b522bN%aleax@mac.com> Message-ID: <1178387800.333285.118060@n59g2000hsh.googlegroups.com> Steven D'Aprano wrote: > > What do people think about functions that accept either a file name or a > file object? > > > def handle_file(obj): > if type(obj) == str: > need_to_close = True > obj = file(obj, 'r') > else: > need_to_close = False > do_something_with(obj.read()) > if need_to_close: > data.close() > > > Good idea? Bad idea? Just a matter of personal preference? I sometimes write functions like this myself. However, the matter of testing for file-like objects can obviously vary somewhat in terms of personal preference and correctness. Some would argue that this is a situation which would benefit from interfaces: if isinstance(obj, FileLike): # or obj.implements(FileLike), perhaps do_something_with(obj.read()) In the original example, we can intuitively see that a file-like object need only support the read and close methods, and in the case of receiving a file-like object, only the read method need exist on the object. Consequently, we can write the following: if hasattr(obj, "read"): do_something_with(obj.read()) Some would rightly say that this is ridiculous: you're testing something which will be discovered straight away. However, there can be situations where you might want to know in advance whether the object is suitable, especially if you may perform more than one kind of operation on the object and where side-effects may occur - the "let the code fail" attitude arguably doesn't hold up very well in such cases. The problem can then be framed in terms of being able to express the set of required operations and whether something like interfaces is a flexible enough means of doing so. We might have something like this: if test_for_file(obj): do_something_with(obj) # not the string but the object itself Now, we have the choice of explicitly phrasing the test ourselves... def test_for_file(obj): return hasattr(obj, "read") and hasattr(obj, "close") # and ... ...or relying on an interface mechanism to do this for us, with the possible additional overhead of declaring such interface usage when defining or adopting classes. It seems to me that there's a gulf between the use of interfaces, with the cost of introducing declarations in the code and the benefit of relatively easy verification of object "capabilities", and the current situation where one might like to try and deduce the required capabilities of an object at any given point in the code. Without interfaces, such verification is difficult but there's less overhead for the programmer; with interfaces, verification is easier but the programmer has to work harder to do most of the work. I can't really see a good compromise. Paul From torriem at chem.byu.edu Tue May 22 12:15:02 2007 From: torriem at chem.byu.edu (Michael L Torrie) Date: Tue, 22 May 2007 10:15:02 -0600 Subject: Restart Linux System In-Reply-To: <002d01c79b81$aa748d40$ff5da7c0$@rawlins@thinkbluemedia.co.uk> References: <002d01c79b81$aa748d40$ff5da7c0$@rawlins@thinkbluemedia.co.uk> Message-ID: <1179850502.22230.6.camel@contra.chem.byu.edu> On Mon, 2007-05-21 at 09:25 +0100, Robert Rawlins - Think Blue wrote: > Hello Guys, > > > > I?m looking to restart a Linux system from my python application. > What?s the best way to achieve this, is there something in the OS > module? Probably not. You need to just spawn the "reboot" command, or run "init 6." This requires root, though. Without root there's no way to reboot a linux system. > > > > Thanks, > > > > Rob > > > -- > http://mail.python.org/mailman/listinfo/python-list From wildemar at freakmail.de Fri May 18 03:54:56 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Fri, 18 May 2007 09:54:56 +0200 Subject: (Modular-)Application Framework / Rich-Client-Platform in Python In-Reply-To: References: Message-ID: <464D5BD0.6080902@freakmail.de> Jarek Zgoda wrote: > There are few GUI frameworks building on various toolkits. I used to use > Kiwi for PyGTK, it's mature and stable, although the approach is not the > same as, for example, Delphi Thanks for the effort, but I think I'm not well understood. I'm not looking for a GUI framework (which, by the way, is most likely to be wxPython), but for a pure plugin architecture. A rich-client-platform, as it is sometimes called. Nothing specific about anythin in particular, just something that runs plugins. Like Eclipse does these days. It's beginning to dawn on me that I'll have to cook something up myself. *grumble* ;) W From andre.roberge at gmail.com Thu May 3 19:50:47 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 3 May 2007 16:50:47 -0700 Subject: When does input() return an empty string? In-Reply-To: <1178235780.197074.161700@h2g2000hsg.googlegroups.com> References: <1178235780.197074.161700@h2g2000hsg.googlegroups.com> Message-ID: <1178236247.729807.172790@y5g2000hsa.googlegroups.com> On May 3, 8:43 pm, noagbodjivic... at gmail.com wrote: > I'm filling an array with user input, I want an empty string to be > returned when nothing is entered; ie return key hit twice... How do I > do that? use raw_input(), not input(). input() attempts to evaluate the result, assuming it is a valid python expression. Andr? From sykora.skywave at gmail.com Thu May 3 04:50:54 2007 From: sykora.skywave at gmail.com (sykora) Date: 3 May 2007 01:50:54 -0700 Subject: Refreshing imported modules In-Reply-To: <1178115862.194846.126240@h2g2000hsg.googlegroups.com> References: <1178115862.194846.126240@h2g2000hsg.googlegroups.com> Message-ID: <1178182254.235615.166790@l77g2000hsb.googlegroups.com> On May 2, 7:24 pm, noagbodjivic... at gmail.com wrote: > I have the python interperter opened while editing a module. The > problem is that when I make changes, the module is not refreshed > whenever I import it again. I have to re-launch the interpreter, is > there a way to shortcut this? I believe you can use the 'reload' command. ie First import your module : >>> import module_name If you want to refresh the module after having changed it, >>> module_name = reload(module_name) That should work. However, any variables you have declared which arise from classes within your module must be redeclared. From jstroud at mbi.ucla.edu Sun May 20 04:09:02 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 20 May 2007 08:09:02 GMT Subject: converting strings to most their efficient types '1' --> 1, 'A' ---> 'A', '1.2'---> 1.2 In-Reply-To: <42T3i.29504$Um6.11611@newssvr12.news.prodigy.net> References: <1179529661.555196.13070@k79g2000hse.googlegroups.com> <464E6F32.7070200@lexicon.net> <61B3i.6880$H_.138@newssvr21.news.prodigy.net> <464F93C1.8030305@lexicon.net> <42T3i.29504$Um6.11611@newssvr12.news.prodigy.net> Message-ID: James Stroud wrote: > Now with one test positive for Int, you are getting pretty certain you > have an Int column. Now we take a second cell randomly from the same > column and find that it too casts to Int. > > P_2(H) = 0.9607843 --> Confidence its an Int column from round 1 > P(D|H) = 0.98 > P(D|H') = 0.02 > > P_2(H|D) = 0.9995836 > > > Yikes! But I'm still not convinced its an Int because I haven't even had > to wait a millisecond to get the answer. Lets burn some more clock cycles. > > Lets say we really have an Int column and get "lucky" with our tests (P > = 0.98**4 = 92% chance) and find two more random cells successfully cast > to Int: > > P_4(H) = 0.9999957 > P(D|H) = 0.98 > P(D|H') = 0.02 > > P(H|D) = 0.9999999 I had typos. P(D|H') should be 0.01 for all rounds. Also, I should clarify that 4 of 4 are positive with no fails observed. Integrating fails would use the last posterior as a prior in a similar scheme. Also, given a 1% false positive rate, after only 4 rounds you are 1 - (0.01**4) = 99.9999% sure your observations aren't because you accidentally pulled 4 of the false positives in succession. James From a.schmolck at gmail.com Mon May 21 08:44:27 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: Mon, 21 May 2007 13:44:27 +0100 Subject: Lists vs tuples (newbie) References: <1179749339.954399.322320@a26g2000pre.googlegroups.com> Message-ID: Szabolcs writes: > Thanks for all the replies! > > Phoe6 wrote: >> 1) Return values from a function. When you return multiple values >> from a function. You store them as a tuple and access them >> individually rather then in the list, which bear the danger of being >> modified. >> Look up the standard library itself and you will find many instances. >> >> (cin, cout, cerr) = os.popen3('man man') >> >> If you had the above as list, then you might end up spoiling things >> knowingly/unknowingly. > > Could you please elaborate on this (or give an explicit example how might one > do something bad unknowingly when returning multiple values in a list)? def f(input, defaultAnswer=[1,2,3]): if input == 1: return (4,5,6) else: return defaultAnswer print f(0).pop(), f(0).pop(), f(0).pop(), f(0) But that's a pretty pathological; just using unstructuring as in the open example above nothing bad can happen. > > Should I think of tuples simply as a safeguard and reminder (because I > consciously use them for different thing than lists, as the faq suggests)? Use them for hetoerogeneous data or when you need the immutability (so that people can't screw) 'as From bbxx789_05ss at yahoo.com Wed May 9 12:08:43 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 9 May 2007 09:08:43 -0700 Subject: which is more pythonic/faster append or +=[] In-Reply-To: <1hxtelz.7f6rvnw4cyxmN%aleax@mac.com> References: <1hxtelz.7f6rvnw4cyxmN%aleax@mac.com> Message-ID: <1178726923.909537.209300@l77g2000hsb.googlegroups.com> On May 8, 11:05 pm, a... at mac.com (Alex Martelli) wrote: > alf wrote: > > two ways of achieving the same effect > > > l+=[n] > > > or > > > l.append(n) > > > so which is more pythonic/faster? > > .append - easy to measure, too: > > brain:~ alex$ python -mtimeit 'L=range(3); n=23' 'x=L[:]; x.append(n)' > 1000000 loops, best of 3: 1.31 usec per loop > > brain:~ alex$ python -mtimeit 'L=range(3); n=23' 'x=L[:]; x+=[n]' > 1000000 loops, best of 3: 1.52 usec per loop > > Alex Ah, I see. The list would grow too large with all that appending, so you begin again with the original list for every loop. Is there any documentation for the syntax you are used with timeit? I checked 'man python', and I also read the example in the python docs, but you seem to be using a hybrid syntax. Thanks. From jn2007zq9mmbt77av7lijp at newsguy.com Sat May 19 12:20:14 2007 From: jn2007zq9mmbt77av7lijp at newsguy.com (Richard Hanson) Date: Sat, 19 May 2007 09:20:14 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <464D2B53.9090409@v.loewis.de> Message-ID: On Fri, 18 May 2007 06:28:03 +0200, Martin v. L?wis wrote: [excellent as always exposition by Martin] Thanks, Martin. > P.S. Anybody who wants to play with generating visualisations > of the PEP, here are the functions I used: [code snippets] Thanks for those functions, too -- I've been exploring with them and am slowly coming to some understanding. -- Richard Hanson "To many native-English-speaking developers well versed in other programming environments, Python is *already* a foreign language -- judging by the posts here in c.l.py over the years." ;-) __________________________________________________ From lyoshaM at gmail.com Thu May 17 19:33:52 2007 From: lyoshaM at gmail.com (Lyosha) Date: 17 May 2007 16:33:52 -0700 Subject: How to convert a number to binary? Message-ID: <1179444832.775573.55830@y80g2000hsf.googlegroups.com> Converting binary to base 10 is easy: >>> int('11111111', 2) 255 Converting base 10 number to hex or octal is easy: >>> oct(100) '0144' >>> hex(100) '0x64' Is there an *easy* way to convert a number to binary? From memracom at yahoo.com Thu May 17 14:41:20 2007 From: memracom at yahoo.com (memracom at yahoo.com) Date: 17 May 2007 11:41:20 -0700 Subject: omissions in python docs? In-Reply-To: <464C9038.6000109@v.loewis.de> References: <1179419983.750044.65030@n59g2000hsh.googlegroups.com> <464C9038.6000109@v.loewis.de> Message-ID: <1179427280.850561.72750@n59g2000hsh.googlegroups.com> > It often happened in the past that patches were admitted which don't > simultaneously update the documentation, hence they diverge. These > days, patches are regularly rejected for not providing proper > documentation changes. Nevertheless, the docs *ARE* old and poorly maintained. Sometimes you find the info that you need in the docs, and other times Google is a better source of information. I find that the weakest part of many module docs are the examples. From siona at chiark.greenend.org.uk Wed May 16 09:17:18 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 16 May 2007 14:17:18 +0100 (BST) Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179258692.237438.110860@p77g2000hsh.googlegroups.com> Message-ID: <+Yl*xeSKr@news.chiark.greenend.org.uk> Hendrik van Rooyen wrote: >I still don't like the thought of the horrible mix of "foreign" >identifiers and English keywords, coupled with the English >sentence construction. How do you think you'd feel if Python had less in the way of (conventionally used) English keywords/builtins. Like, say, Perl? -- \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 maric at aristote.info Mon May 28 04:20:55 2007 From: maric at aristote.info (Maric Michaud) Date: Mon, 28 May 2007 10:20:55 +0200 Subject: Can python create a dictionary from a list comprehension? In-Reply-To: <1180300058.809976.156650@p77g2000hsh.googlegroups.com> References: <1180299312.207986.4340@k79g2000hse.googlegroups.com> <1180300058.809976.156650@p77g2000hsh.googlegroups.com> Message-ID: <465A90E7.4040103@aristote.info> Pierre Quentel a ?crit : > On 27 mai, 22:55, erikcw wrote: >> Hi, >> >> I'm trying to turn o list of objects into a dictionary using a list >> comprehension. ... > > entries = dict([ (int(d.date.strftime('%m')),d.id) for d in links] ) > > With Python2.4 and above you can use a "generator expression" > > entries = dict( (int(d.date.strftime('%m')),d.id) for d in links ) > You can also create dictionaries knowing only the keys the same way (ie. a two-dimensional array) : In [77]: dict.fromkeys((a, b) for a in range(4) for b in range(2)) Out[78]: {(0, 0): None, (0, 1): None, (1, 0): None, (1, 1): None, (2, 0): None, (2, 1): None, (3, 0): None, (3, 1): None} From apatheticagnostic at gmail.com Tue May 1 05:08:30 2007 From: apatheticagnostic at gmail.com (kaens) Date: Tue, 1 May 2007 05:08:30 -0400 Subject: Master's Thesis Help Needed In-Reply-To: <1177898031.790447.253360@n76g2000hsh.googlegroups.com> References: <1177898031.790447.253360@n76g2000hsh.googlegroups.com> Message-ID: <163f0ce20705010208q69f7722aud1c66f43b1d523cd@mail.gmail.com> I'll check it out. I'm running kubuntu (really, should work for any linux unless you're giving out .deb files) On 29 Apr 2007 18:53:51 -0700, RobJ wrote: > Awhile ago I asked for your help in getting some ideas about setting > up an on-line course to learn how to use Python web frameworks. The > first section - Beginning Pylons is up and running and I would > appreciate your going through the course and taking my pre and post- > workshop surveys. The link to the site is: > > http://pyschool.robj.webfactional.com/ > > Thanks in advance for your help! > > Rob J > > -- > http://mail.python.org/mailman/listinfo/python-list > From Roland.Puntaier at br-automation.com Tue May 15 08:16:35 2007 From: Roland.Puntaier at br-automation.com (Roland Puntaier) Date: Tue, 15 May 2007 14:16:35 +0200 Subject: Antwort: How to calculate definite integral with python In-Reply-To: <46491984.4070908@gmail.com> Message-ID: Searching the web I have found: from numpy import * def simple_integral(func,a,b,dx = 0.001): return sum(map(lambda x:dx*x, func(arange(a,b,dx)))) simple_integral(sin,0,2*pi) Or in http://pylab.sourceforge.net/ quadrature.py Cheers. python-list-bounces+roland.puntaier=br-automation.com at python.org schrieb am 15.05.2007 04:23:00: > I'm trying to do some integral calculation. I have searched the web, but > haven't found any useful information. Will somebody point me to the > right resources on the web for this job ? > > Thanks a lot. > > ps. Can numpy be used for this job?* > * > -- > http://mail.python.org/mailman/listinfo/python-list From steve at holdenweb.com Tue May 15 21:09:39 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 15 May 2007 21:09:39 -0400 Subject: Interesting list Validity (True/False) In-Reply-To: <1179031812.090768.248750@l77g2000hsb.googlegroups.com> References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> <1178914190.166662.285410@p77g2000hsh.googlegroups.com> <1178915791.584216.293130@l77g2000hsb.googlegroups.com> <1178918808.091358.233740@o5g2000hsb.googlegroups.com> <1179017740.656323.209590@e51g2000hsg.googlegroups.com> <1179020634.130689.171960@o5g2000hsb.googlegroups.com> <1179031812.090768.248750@l77g2000hsb.googlegroups.com> Message-ID: mensanator at aol.com wrote: > On May 12, 11:02?pm, Steven D'Aprano [ ... ] > > But you can't trust a==d returning True to mean a and d are > "equal". To say the comparison means the two objects are > equal is misleading, in other words, wrong. It only takes one > turd to spoil the whole punchbowl. > Unfortunately that is the very *definition* of "equal". >> gmpy.mpz(1) on the other hand, is both a numeric type and a custom class. >> It is free to define equal any way that makes sense, and it treats itself >> as a numeric type and therefore says that it is equal to 1, just like 1.0 >> and 1+0j are equal to 1. > > They are equal in the mathematical sense, but not otherwise. > And to think that makes no difference is to be naive. > Perhaps so, but you are a long way from the original question now! 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From nagle at animats.com Sun May 20 23:45:49 2007 From: nagle at animats.com (John Nagle) Date: Mon, 21 May 2007 03:45:49 GMT Subject: Cycle detection and object memory usage? In-Reply-To: References: Message-ID: Jim Kleckner wrote: > cycles: > > I understand from the documentation that types with a finalizer method > that participate in cycles can't be collected. > > What is the best way to go about finding these cycles? > Googling gives a variety of methods none of which seem terribly > mainstream for such a common problem. Put the Python garbage collector into debug mode and find out what it reports as non-collectable. Use weak pointers where appropriate to avoid cycles. The general idea is that pointers back towards the root of a tree structure should be weak pointers, which will result in a cycle-free structure. I put that in BeautifulSoup, and it works quite well. John Nagle From erikwickstrom at gmail.com Sun May 27 16:58:04 2007 From: erikwickstrom at gmail.com (erikcw) Date: 27 May 2007 13:58:04 -0700 Subject: Why isn't this query working in python? In-Reply-To: References: <1180103946.552760.239200@p47g2000hsd.googlegroups.com> <6e42ec490705250751i89d3cf3v3a3062690d0284aa@mail.gmail.com> <1180207521.072958.322770@p47g2000hsd.googlegroups.com> <1180225290.235515.274000@q19g2000prn.googlegroups.com> <1180279833.131269.136770@w5g2000hsg.googlegroups.com> Message-ID: <1180299484.166372.115590@g4g2000hsf.googlegroups.com> On May 27, 4:01 pm, Steve Holden wrote: > erikcw wrote: > > On May 26, 8:21 pm, John Machin wrote: > >> On May 27, 5:25 am, erikcw wrote: > > >>> On May 25, 11:28 am, Carsten Haese wrote: > >>>> On Fri, 2007-05-25 at 09:51 -0500, Dave Borne wrote: > >>>>>> I'm trying to run the following query: > >>>>> ... > >>>>>> member_id=%s AND expire_date > NOW() AND completed=1 AND (product_id > >>>>> Shouldn't you be using the bind variable '?' instead of '%s' ? > >>>> The parameter placeholder for MySQLdb is, indeed and unfortunately, %s. > >>>> The OP is using parameter substitution correctly, though in an > >>>> obfuscated fashion. 'sql' is a misnamed tuple containing both the query > >>>> string *and* the parameters, which is being unpacked with '*' into two > >>>> arguments to the execute call. > >>>> The only problem I see is that the parameters should be a sequence, i.e. > >>>> (self.uid,) instead of just (self.uid). > >>>> HTH, > >>>> -- > >>>> Carsten Haesehttp://informixdb.sourceforge.net > >>> I tried adding the comma to make it a sequence - but now change. > >>> ('SELECT payment_id FROM amember_payments WHERE member_id=%s AND > >>> expire_date > NOW() AND completed=1 AND (product_id >11 AND product_id > >>> <21)', (1608L,)) > >>> () > >>> What else could it be? > >> Possibly a type mismatch. How is member_id declared in the CREATE > >> TABLE? For diagnostic purposes, try passing in (1608,) and ('1608',). > > > Here is a copy of the table schema and the first 2 rows. > > > -- phpMyAdmin SQL Dump > > -- version 2.9.0.2 > > --http://www.phpmyadmin.net > > -- > > -- Host: localhost > > -- Generation Time: May 27, 2007 at 11:29 AM > > -- Server version: 5.0.27 > > -- PHP Version: 4.4.2 > > -- > > -- Database: `lybp_lybp` > > -- > > > -- -------------------------------------------------------- > > > -- > > -- Table structure for table `amember_payments` > > -- > > > CREATE TABLE `amember_payments` ( > > `payment_id` int(11) NOT NULL auto_increment, > > `member_id` int(11) NOT NULL default '0', > > `product_id` int(11) NOT NULL default '0', > > `begin_date` date NOT NULL default '0000-00-00', > > `expire_date` date NOT NULL default '0000-00-00', > > `paysys_id` varchar(32) NOT NULL default '', > > `receipt_id` varchar(32) NOT NULL default '', > > `amount` decimal(12,2) NOT NULL default '0.00', > > `completed` smallint(6) default '0', > > `remote_addr` varchar(15) NOT NULL default '', > > `data` text, > > `time` timestamp NOT NULL default CURRENT_TIMESTAMP on update > > CURRENT_TIMESTAMP, > > `aff_id` int(11) NOT NULL default '0', > > `payer_id` varchar(255) NOT NULL default '', > > `coupon_id` int(11) NOT NULL default '0', > > `tm_added` datetime NOT NULL default '0000-00-00 00:00:00', > > `tm_completed` datetime default NULL, > > `tax_amount` decimal(12,2) NOT NULL default '0.00', > > PRIMARY KEY (`payment_id`), > > KEY `member_id` (`member_id`), > > KEY `payer_id` (`payer_id`), > > KEY `coupon_id` (`coupon_id`), > > KEY `tm_added` (`tm_added`,`product_id`), > > KEY `tm_completed` (`tm_completed`,`product_id`) > > ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=11020 ; > > > -- > > -- Dumping data for table `amember_payments` > > -- > > > INSERT INTO `amember_payments` VALUES (423, 107, 1, '2004-10-01', > > '2004-10-21', 'authorize_aim', '5687944', 3.95, 1, '', NULL, > > '2004-11-30 19:21:43', 0, '', 0, '2004-11-30 19:21:43', '2004-11-30 > > 19:21:43', 0.00); > > INSERT INTO `amember_payments` VALUES (422, 107, 1, '2004-10-22', > > '2004-11-21', 'authorize_aim', '5873225', 9.95, 1, '', NULL, > > '2004-11-30 19:22:18', 0, '', 0, '2004-11-30 19:20:13', '2004-11-30 > > 19:20:13', 0.00); > > > Thanks for your help! > > Erik > > I feel obliged to point out that there ARE no rows meeting the criteria > you query specified! > > mysql> SELECT expire_date, NOW() FROM amember_payments; > +-------------+---------------------+ > | expire_date | NOW() | > +-------------+---------------------+ > | 2004-10-21 | 2007-05-27 15:59:21 | > | 2004-11-21 | 2007-05-27 15:59:21 | > +-------------+---------------------+ > 2 rows in set (0.02 sec) > > mysql> > > So I am not sure how you managed to get a manual query to work, but do > be sure that the Python query you mentioned at the start of the thread > > sql = """SELECT payment_id FROM amember_payments WHERE > member_id=%s AND expire_date > NOW() AND completed=1 AND (product_id > > >11 AND product_id <21)""", (self.uid) > > doesn't stand a chance of returning any results unless you use a time > machine to go back almost three years! > > 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 your way to fame!! > holdenweb.blogspot.com squidoo.com/pythonology > tagged items: del.icio.us/steve.holden/python > All these services currently offer free registration! > -------------- Thank You for Reading ---------------- The rows I posted are just a small sample (the first 2). There are tens of thousands of rows in the table. Also, yes, the query does work when I run it manually against MySQL. From openopt at ukr.net Sat May 12 03:12:44 2007 From: openopt at ukr.net (dmitrey) Date: 12 May 2007 00:12:44 -0700 Subject: matplotlib: howto set title of whole window? In-Reply-To: <1178927552.965037.282360@u30g2000hsc.googlegroups.com> References: <1178923478.087792.101170@n59g2000hsh.googlegroups.com> <1178927552.965037.282360@u30g2000hsc.googlegroups.com> Message-ID: <1178953964.142782.67150@e51g2000hsg.googlegroups.com> No, it's just another one title it produces a figure with name "Figure 1" but I should somehow replace the string. It is possible in MATLAB via set(figureHandler, 'Name', 'my_string_here') D. On May 12, 2:52 am, attn.steven.... at gmail.com wrote: > On May 11, 3:44 pm, dmitrey wrote: > > > hi all, > > does anyone know howto set title of whole window? (I mean not just > > area above plot but string in the same line where buttons 'close', > > 'iconify', 'fullscreen' are situated) > > Use coordinates to set a title for the current figure. > E.g., > > from pylab import * > from matplotlib.font_manager import FontProperties > > figtitle = 'This is my title above all subplots' > > t = gcf().text(0.5, > 0.95, figtitle, > horizontalalignment='center', > fontproperties=FontProperties(size=16)) > > subplot(121) > subplot(122) > show() > > -- > Hope this helps, > Steven From deets at nospam.web.de Tue May 22 09:40:06 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 22 May 2007 15:40:06 +0200 Subject: Simple omniORBpy example throws exception with error 0x41540002 References: <1179833680.255391.198490@x18g2000prd.googlegroups.com> <5bg40hF2moliaU1@mid.uni-berlin.de> <1179839519.216407.124960@z24g2000prd.googlegroups.com> Message-ID: <5bga5mF2s4ps1U1@mid.uni-berlin.de> Samuel wrote: > On May 22, 1:54 pm, "Diez B. Roggisch" wrote: >> It indeed does open a connection - because it wants to register with a >> NameServer. > > Ah, I see now how this works. I happen to run Ubuntu here, so I tried > the following: > > - sudo apt-get install orbit-name-server-2 > - orbit-name-server-2 & > - Add to /etc/omniORB4.cfg: > InitRef = NameService=IOR:010000002b000000... > (where everything starting from "IOR:" is the output given by orbit- > name-server-2. > > However, this does not seem to change the behavior. Any hints? Not really. You might try the omniORB mailing list. I've used to be subscribed there when my CORBA-using project was under active development. It's a really helpful place, and not too busy so you won't get overwhelmed. diez From mcPas.De.Spam at mclaveauPas.De.Spam.com Mon May 14 17:21:48 2007 From: mcPas.De.Spam at mclaveauPas.De.Spam.com (Michel Claveau) Date: Mon, 14 May 2007 23:21:48 +0200 Subject: os.listdir() doesn't work ?? References: <1179173881.163830.54930@n59g2000hsh.googlegroups.com> Message-ID: Hi! > You want the glob module Warning: glob has "unix like behavior"; just a little different with windows's DIR -- @-salutations Michel Claveau From ebgssth at gmail.com Sun May 20 03:35:44 2007 From: ebgssth at gmail.com (js ) Date: Sun, 20 May 2007 16:35:44 +0900 Subject: Closing socket file descriptors In-Reply-To: References: Message-ID: Hello, Yang. You're not supposed to use os.open there. See the doc at http://docs.python.org/lib/os-fd-ops.html Is there any reason you want to use os.close? On 20 May 2007 04:26:12 GMT, Yang wrote: > Hi, I'm experiencing a problem when trying to close the file descriptor > for a socket, creating another socket, and then closing the file > descriptor for that second socket. I can't tell if my issue is about > Python or POSIX. > > In the following, the first time through, everything works. On the > second connection, though, the same file descriptor as the first > connection may be re-used, but for some reason, trying to do > os.read/close on that file descriptor will cause an error. > > Thanks in advance for any help on why this problem is occurring and/or > how to resolve it (preferrably, I can continue to use file descriptors > instead of resorting to socket.recv/socket.close). > > def handle( s ): > print id(s), s > print os.read( s.fileno(), 4096 ) # s.recv(4096) > os.close( s.fileno() ) # s.close() > svr = socket.socket() > svr.bind( ( 'localhost', 8003 ) ) > svr.listen( 1 ) > while True: > print 'accepting' > s,_ = svr.accept() > handle( s ) > > # Traceback (most recent call last): > # File "./normal_server_close_error.py", line 25, in > # handle( s ) > # File "./normal_server_close_error.py", line 13, in handle > # print os.read( s.fileno(), 4096 ) # s.recv(4096) > # OSError: [Errno 9] Bad file descriptor > -- > http://mail.python.org/mailman/listinfo/python-list > From osv at javad.com Mon May 28 11:45:17 2007 From: osv at javad.com (Sergei Organov) Date: Mon, 28 May 2007 19:45:17 +0400 Subject: Is PEP-8 a Code or More of a Guideline? References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> Message-ID: Roy Smith writes: [...] > On the other hand, I'm convinced that words_with_underscores, is easier to > read. This is especially true when abbreviations creep into variable > names. It's certainly easier to parse ip_address as compared to IPAddress. > Same with snmp_manager vs SNMPManager. Well, you don't capitalize abbreviations like that in a classic CamelCase, I believe. Those names ought to be SnmpManager and IpAddress. Though there is still problem with digits, e.g., Crc24Accum. -- Sergei. From ggrabler at gmail.com Tue May 8 06:07:28 2007 From: ggrabler at gmail.com (STiAT) Date: 8 May 2007 03:07:28 -0700 Subject: Python Binding In-Reply-To: References: Message-ID: <1178618848.423760.53420@p77g2000hsh.googlegroups.com> Hello, I've basically had plans on just extending python for the wrapper. That basically works fine, i just don't get along by the types provided (http://docs.python.org/ext/ext.html). Anyway, i want to extend python for types. The problem i currently experience is the following. Guess what - i have a base class, doing some wrapping. Currently, called pybtest (just testing around though). Now, i'd need a configuration object, accessable in python. By using the library, it should be possible to access it using pybtest.config.insertValue('xyz') as an example, but i havn't found any way to archive this yet. If i write config as an own (external) type, i can't get it into the pybtest object for some reason. It's compiled as an extra "config.so", and with the test script i need to do import config. Anyway, it's not in the pybtest object., i've to build up a config and pass it by to the pybtest binding, so it can set it's internal configuration structures. If i try to compile it within the pybtest, i can't use ext_modules, and as expected, i can't do another pybtestinit function, so it's quite useless, at least with the knowledge i could get out of the documentation. By just making a include file of the type, including the type definition adding up some functions to pybtest, i actually can access it, without the wanted functionality of pybtest.config. Why do you all suggest other things than the way suggested by python? I havn't got a real problem writing the code in C, actually, it looked as if it would give me several possibilities i wouldn't have with pyrex (like binding more library functions to one provided python function and so on). I havn't had a closer look to SWIG yet. It looks as if i could just provide single objects or modules, and no additional object into a module. Does anyone have closer knowledge on this? Btw: Sorry for the long delay time, i had to describe the things closer, and had to take a deeper look into the bindings than i had before. Kind regards, Georg From nis at superlativ.dk Mon May 28 04:34:49 2007 From: nis at superlativ.dk (=?ISO-8859-1?Q?Nis_J=F8rgensen?=) Date: Mon, 28 May 2007 10:34:49 +0200 Subject: unit testing In-Reply-To: References: Message-ID: <465a942e$0$90269$14726298@news.sunsite.dk> Steve Howell skrev: > And, really, if > you're not doing automated tests on your application > now, you don't know what you're missing. Quote of the day, IMO. Nis From Graham.Dumpleton at gmail.com Wed May 30 01:46:18 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: 29 May 2007 22:46:18 -0700 Subject: need advice on building core code for python and PHP In-Reply-To: <1180488264.224155.281830@p77g2000hsh.googlegroups.com> References: <1180025115.704410.250890@a35g2000prd.googlegroups.com> <1180028001.569139.317660@q66g2000hsg.googlegroups.com> <1180034698.387087.251590@o5g2000hsb.googlegroups.com> <1180047661.795384.295850@a26g2000pre.googlegroups.com> <1180488264.224155.281830@p77g2000hsh.googlegroups.com> Message-ID: <1180503978.272271.202910@a26g2000pre.googlegroups.com> On May 30, 11:24 am, digimotif wrote: > On May 24, 5:01 pm, Graham Dumpleton > wrote: > > > > > On May 25, 5:24 am, aspineux wrote: > > > > On 24 mai, 19:33, Szabolcs Nagy wrote: > > > > > > Is there a way I could code the base (core) code in Python and have > > > > > PHP call it? I've really liked using SQLAlchemy and there are other > > > > > * quick and dirty solution: > > > > in a shell: > > > > $ python yourscript.py pipe_out > > > > in the php script: > > > > fwrite(pipe_in, input_data); > > > > results = fread(pipe_out, sizeof_results); > > > > > * simple and nice solution: > > > > do not ever use php > > > > Write a CGI wrapper around your python script, and publish it usingmod_python. > > > And make the appropriate http requests from PHP. > > > You do not needmod_pythonto host CGI scripts written in Python, they > > are two separate things. > > > Depending on the complexity of what you are doing, you might be better > > off writing a backend server in Python that incorporates an XML-RPC > > server. Your PHP script can then use XML-RPC client to communicate to > > the backend Python server to do the real work. Over time you could > > even transition your web pages to being done in Python instead. In > > doing this your back end Python server doesn't have to change, you > > just make XML-RPC calls from the Python code for the web pages in > > place of where you would be doing it with PHP initially. You also > > wouldn't be restricted to web based front ends, you could also use GUI > > based front end as well. > > > Graham > > This sounds more like the direction I should go. Is XML-RPC the only > technology allowing this sort of setup? If I understand correctly, it > would basically mean going to a three tiered application approach. > I'd have the database, the python xml-rpc server, and the gui/web > interfaces. I'd also want to make sure I'm implementing technology > that will scale well. There is also Pyro, but by using that you limit yourself to Python clients as far as I know whereas XML-RPC has clients for lots of different languages. Other more complicated options are Corba and SOAP frameworks. Graham From simon.hibbs at gmail.com Wed May 30 12:19:20 2007 From: simon.hibbs at gmail.com (Simon Hibbs) Date: 30 May 2007 09:19:20 -0700 Subject: Creating a distro of python... What would you include in it? In-Reply-To: <1180538748.448426.182820@g4g2000hsf.googlegroups.com> References: <1180538748.448426.182820@g4g2000hsf.googlegroups.com> Message-ID: <1180541960.105577.268590@u30g2000hsc.googlegroups.com> On 30 May, 16:25, farksimm... at yahoo.com wrote: > I am creating a distro of Python to be licensed as GPL.... am > wondering, what would anyone suggest as to 3rd party modules being put > into it (non-commercial of course!)? I know I'd put MySQLdb into it at > the very least. Any suggestions? What you put in it will depend on what it's for. Which platforms will you support? Many Linux distros already provide comprehensive package management systems, so developers on those would probably be better off using the native package manager unless you're offering something distinctive. Does your distro target a particular developer community, such as web developers, database developers or desktop developers? These communities have very different requirements, but then again if you target web developers do you include Turbo Gears, or Django or both? Do you include an ORM and if so which one? If you can clarify what you are trying to achieve, or what defiiciencies in the existing distros that you're finding limiting then that would realy help. Super-distros can definitely have a place. In fact that's exactly what TurboGears is, but it has a very clear mission statement and adds significant value of it's own. It also acts as an add-on to the standard distro rather than an alternative and I recommend you consider that strategy. Simon Hibbs From gagsl-py2 at yahoo.com.ar Thu May 10 21:29:05 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 10 May 2007 22:29:05 -0300 Subject: File modes References: <1178830039.962239.245800@e51g2000hsg.googlegroups.com> <1178842276.692281.174370@e51g2000hsg.googlegroups.com> Message-ID: En Thu, 10 May 2007 21:11:16 -0300, Jon Pentland escribi?: > I don't really see the use for being able to do that. Have you tried > doing it with the 'app' mode?, But I am guessing that it is just an > advanced mode spawned from 'w'. So, no, I don't think you can do this. In fact you can read and write the same file, using the r+/w+/a+ modes. You may need a seek() when switching from reading to writing or viceversa (unless mode is a+ perhaps), but I can't find that in the docs; perhaps Python itself already takes care of this internally. -- Gabriel Genellina From dotancohen at gmail.com Sun May 20 16:05:57 2007 From: dotancohen at gmail.com (Dotan Cohen) Date: Sun, 20 May 2007 23:05:57 +0300 Subject: List Moderator In-Reply-To: <464F5E42.6090607@holdenweb.com> References: <880dece00705172218n71123b55q531ec0c5e500f208@mail.gmail.com> <880dece00705190012g4f3d3ef6v4e6c87a156708bb0@mail.gmail.com> <880dece00705191305m203bc8ep804d647c17438581@mail.gmail.com> <464F5E42.6090607@holdenweb.com> Message-ID: <880dece00705201305q6944986fj8f77c4b5cac09456@mail.gmail.com> On 19/05/07, Steve Holden wrote: > Dotan Cohen wrote: > > On 19/05/07, Steve Holden wrote: > >> I'm sorry, but you have no idea what you are talking about. Most of what > >> can be done *is* being done, which is why you see the relatively low > >> spam volumes you do. > > > > I hope that I don't. I receive no less than 700 spams a day to my > > regular address (not gmail, which I use for mailing lists), but then > > again I've only twice gone over 2000 spams in a single day. I can only > > imagine the efforts used to keep the list clean. Maybe spamassasin, a > > few hundred procmail filters, and a last swipe with bogofilter for > > good measure? > > > > I don't mean to be pushy, but every day I add another procmail filter > > based upon what's been getting through (and they still do, I try to > > err on 'false negative'). Four filters "britney", "spears", "boobs" > > and "tits" would show the spammers that the moderators are serious > > about keeping this list clean. > > > > I'll go back to reading and not writing now, at least until I get to > > the point where either I feel that I can contribute, or until I get > > myself real stuck. > > > All I am saying is that it's difficult to catch *everything* when so > much of the content comes in via Usenet. These posts never touch any > python.org infrastructure before being incorporated into the newsgroup > content on servers all over the world. Whose procmail filters will > protect you from that? > > You are right about some of the technologies being used, and Spambayes > also enters the picture. I'm not sure we are using bogofilter. > > Looking at the headers in one of the messages you were writing about it > appears they are being posted from Google groups, so maybe you could > complain to them. Good luck with that ;-). > > The Python list managers know what they are doing, and they *do* keep a > huge amount of spam off the list. The occasional piece gets through, but > this is Usenet. It will, from time to time. > Again, I appreciate the efforts made to reduce spam on the list of course. It's obvious that much effort is being put into it. The procmail filters that I'm referring to would be right before the mail gets handed to sendmail. I read this list as a mailing list, and I'm unfamiliar with the different interfaces. But it all goes through a central point from which is it diseminated. Right before that point is where I'd imagine the filters are. They do exist, no? Dotan Cohen http://what-is-what.com/what_is/aids.html http://kubuntufaq.com From carsten at uniqsys.com Fri May 4 18:14:09 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 04 May 2007 18:14:09 -0400 Subject: behavior difference for mutable and immutable variable in function definition In-Reply-To: <1178314206.701824.291560@n59g2000hsh.googlegroups.com> References: <1178314206.701824.291560@n59g2000hsh.googlegroups.com> Message-ID: <1178316849.3246.9.camel@localhost.localdomain> On Fri, 2007-05-04 at 14:30 -0700, jianbing.chen at gmail.com wrote: > Hi, > > Can anyone explain the following: > > Python 2.5 (r25:51908, Apr 9 2007, 11:27:23) > [GCC 4.1.1 20060525 (Red Hat 4.1.1-1)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> def foo(): > ... x = 2 > ... > >>> foo() > >>> def bar(): > ... x[2] = 2 > ... > >>> > >>> bar() > Traceback (most recent call last): > File "", line 1, in > File "", line 2, in bar > NameError: global name 'x' is not defined "x = 2" binds the name 'x' in foo's local namespace to the object '2'. For this, it doesn't matter whether the name 'x' was previously bound to anything. "x[2] = 2" is a shorthand notation for the method call "x.__setitem__(2,2)". This requires the name 'x' to be bound to some object that has a __setitem__ method. -Carsten From gagsl-py2 at yahoo.com.ar Mon May 28 04:39:40 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 28 May 2007 05:39:40 -0300 Subject: Can python create a dictionary from a list comprehension? References: <1180299312.207986.4340@k79g2000hse.googlegroups.com> <465a90a8$0$55856$dbd43001@news.wanadoo.nl> Message-ID: En Mon, 28 May 2007 05:20:16 -0300, Wim Vogelaar escribi?: >> Example: >> >> a = [1,2,3,4,5,6,7,8,9,10] >> >> aDict = dict([(x,x+1) for x in a if x%2==0]) >> >> print aDict >> > > When I run this program I get: > {8: 9, 2: 3, 4: 5, 10: 11, 6: 7} > > why this output isn't ordered, giving: > {2: 3, 4: 5, 6: 7, 8: 9, 10: 11 } A dictionary is not ordered, no matter how you create it. If you want to process the keys in order: for key in sorted(aDict): print key, '=', aDict[key] (Note that sorted(aDict) returns a *list*, not a dictionary!) -- Gabriel Genellina From DustanGroups at gmail.com Sun May 6 09:18:18 2007 From: DustanGroups at gmail.com (Dustan) Date: 6 May 2007 06:18:18 -0700 Subject: Did you read about that? In-Reply-To: References: <1178446711.502374.286790@l77g2000hsb.googlegroups.com> <1178452403.114975.249050@u30g2000hsc.googlegroups.com> Message-ID: <1178457498.639373.157350@y80g2000hsf.googlegroups.com> On May 6, 8:20 am, Steven D'Aprano wrote: > On Sun, 06 May 2007 04:53:23 -0700, Dustan wrote: > > SPAM! > > SPAM! > > SPAM! > > SPAM! > > SPAM! > > SPAM! > > SPAM! > > SPAM! > > Gosh, you think so? I'm glad we had you around to tell us, otherwise we > might have thought it was about Python programming. > > Actually, many of us wouldn't even have seen it in the first place, > because our ISPs do a good job of filtering out obvious spam before we > even see it. And then people like you come along, and reply to it, and we > see the reply -- complete with the original spam. Well, sorry. I didn't realize I'd get whacked around for making a joke. > -- > Steven. From fuzzyman at gmail.com Sat May 5 17:03:23 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 5 May 2007 14:03:23 -0700 Subject: How do I use the config parser? In-Reply-To: <1178392410.866037.179950@e65g2000hsc.googlegroups.com> References: <1178392410.866037.179950@e65g2000hsc.googlegroups.com> Message-ID: <1178399003.103665.49600@h2g2000hsg.googlegroups.com> On May 5, 8:13 pm, noagbodjivic... at gmail.com wrote: > Hi, > I need a specific example. I have seen the docs, but I don't all the > stuffs there. > > So basically, I need my config file to be created and read by my > script. > > Here is a snippet > > # read old actions > from ConfigParser import ConfigParser > > fp = open(makepath('App\qt_actions.conf')) > configdict = ConfigParser() > configdict.readfp(fp) > > Now I want to know how to read a section, a section attribute's value, > and to write thoses back after reading. > You could do it simply with ConfigObj ( http://www.voidspace.org.uk/python/configobj.html ): from configobj import ConfigObj config = ConfigObj(filename) section = config['Section Name'] value = section['value'] .... section['value'] = newValue config.write() All the best, Fuzzyman http://www.voidspace.org.uk/python/articles.shtml > Thanks From gagsl-py2 at yahoo.com.ar Fri May 18 21:42:53 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 18 May 2007 22:42:53 -0300 Subject: How to stop a scheduler stated using References: <1179471657.392581.251320@w5g2000hsg.googlegroups.com> Message-ID: En Fri, 18 May 2007 04:00:57 -0300, Nagendra Kumar escribi?: > import sched, time > s=sched.scheduler(time.time, time.sleep) > > event1=s.enter(60, 1, obj.scheduleAbuseAssignment1, ()) > event2=s.enter(60, 1, obj.scheduleAbuseAssignment2, ()) > event3=s.enter(60, obj.scheduleAbuseAssignment3, ()) > > Is there any way to stop these scheduled events?If so, can we do it > through a UI Using s.cancel(event1). The UI is up to you... See http://docs.python.org/lib/scheduler-objects.html -- Gabriel Genellina From aleax at mac.com Fri May 4 10:43:52 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 4 May 2007 07:43:52 -0700 Subject: My Python annoyances References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> <1178202431.147195.249790@u30g2000hsc.googlegroups.com> Message-ID: <1hxkvt9.7vpsc3eq6li9N%aleax@mac.com> Chris Mellon wrote: > > > I am unqualified to comment on the Python philosophy, but I would like > > > for my function to do some basic error checking on its arguments. > > > > By "basic error checking" I mean "verify that the file argument actually > > is a file-like object". By same interface, do you mean that I should > > check for the methods that I depend on? That sounds easy enough. > > You should "check" for the methods by calling them. If the object > doesn't support the method in question, you will get a runtime > exception. Premature inspection of an object is rarely useful and > often outright harmful. However, hoisting method extraction out of the loop is often useful, because it may speed up operations, and when you do that you might as well use a try/except AttributeError to provide better diagnostics if something is missing. E.g., suppose you have a need to slurp away one char at a time from a file until you get a 'Z': def readToZ(f): while True: c = f.read(1) if c == 'Z': return elif not c: raise ValueError, "No Z in file f" this may also raise IOError if the read fails, AttributeError if f does not have a read method, TypeError (or who knows what) if f.read is not callable, or does not let you call it with one int argument, etc, etc. A slightly faster approach: def readToZ(f): read = f.read while True: c = read(1) if c == 'Z': return elif not c: raise ValueError, "No Z in file f" this has exactly the same exception-behavior as the previous version. It's hardly an error to tweak that behavior slightly: def readToZ(f): try: read = f.read except AttributeError: raise TypeError, "%s has no read" % type(f) while True: c = read(1) if c == 'Z': return elif not c: raise ValueError, "No Z in file f" going to horrid amounts of trouble to check that the call to read(1) won't produce weird failures would be unwarranted, but making one case of AttributeError into a TypeError in this way is quite OK, for example. Alex From indy1000 at gmail.com Tue May 8 09:59:26 2007 From: indy1000 at gmail.com (indy1000 at gmail.com) Date: 8 May 2007 06:59:26 -0700 Subject: Setting up python socket server with non-standard termination string. Message-ID: <1178632766.853553.322660@q75g2000hsh.googlegroups.com> Hi, I'm trying to create a tcp/ip port listening socket server for various cellular devices that don't use the standard "\r\n" termination string at the end of their message. Instead, they use "-ND-". Do you know how I can setup such a server, preferably using either 'socket.py', 'serversocket.py' or 'twisted.py'? Many thanks, David Jones From tchur at optushome.com.au Fri May 18 19:11:47 2007 From: tchur at optushome.com.au (Tim Churches) Date: Sat, 19 May 2007 09:11:47 +1000 Subject: Anyone use PyPar (Python MPI implementation) recently? In-Reply-To: <000601c79923$ac78a000$f701a8c0@cuttlefish> References: <000601c79923$ac78a000$f701a8c0@cuttlefish> Message-ID: <464E32B3.9030907@optushome.com.au> Ole Nielsen wrote: > Cheers and thanks Now that it is possible to purchase servers from tier-1 manufacturers with dual quad-core processes (8 CPUs) for under $10k, complete with discs and lots of RAM - that is, no tedious-to-set-up, space-occupying, power-hungry and high-maintenance Beowulf-style cluster of commodity boxes necessary - we are very keen to use PyPar to re-visit parallelisation of our NetEpi epidemiological analysis code, but we are aware that both our code and PyPar need to be updated to use NumPy as opposed to the now deprecated Numeric Python. We still regard PyPar is still the easiest-to-use wrapper for MPI for Python. Tim C From bj_666 at gmx.net Thu May 31 09:44:11 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 31 May 2007 15:44:11 +0200 Subject: WEATHER PROGRAMMING IN PYTHON References: <1180618635.925002.282080@n15g2000prd.googlegroups.com> Message-ID: In <1180618635.925002.282080 at n15g2000prd.googlegroups.com>, sandeep patil wrote: > how to diplay the weather condiction on my webpage > suppose i want to read weather from www.bbc.co.uk/weather.html > how i can read it usin program It's hard to scrape information about weather from an 404 error page. ;-) Find some page with actual weather reports or forecasts and use the BeautifulSoup module to scrape the information you need. Ciao, Marc 'BlackJack' Rintsch From girodt at gmail.com Thu May 10 04:45:50 2007 From: girodt at gmail.com (TG) Date: 10 May 2007 01:45:50 -0700 Subject: Boost python : get the shape of a numpy ndarray in C++ code. In-Reply-To: References: <1178723326.174384.180690@y5g2000hsa.googlegroups.com> Message-ID: <1178786750.669715.132280@e65g2000hsc.googlegroups.com> What I'm trying to say here : a numpy array is supposed to have it's shape stored as a tuple. What I want to do is to access this information from my C++ code, in order to do some validity check. So, by looking around in the doc of boost/python/numeric.hpp I was able to do this : void Layer::set_potentials (numeric::array& array) { for (int h=0; hheight; h++){ for (int w=0; wwidth; w++){ units[w+h*map->width]->potential = extract(array[make_tuple(w,h)]); } } } which is fairly simple and actually works. Now, if I look further, I see there is a method called getshape() in array class, which gives back an object - I guess this object is a tuple, because the documentation is quite poor. So my idea is to get this object and use extract in order to get the actual dimensions as integers. but when I add this : void Layer::set_potentials (numeric::array& array) { object shape = array.getshape(); [...] } It compiles, and then on execution I get this error : AttributeError: 'numpy.ndarray' object has no attribute 'getshape' Does it still have nothing to do with Boost.Python ? From ramashish.lists at gmail.com Wed May 30 08:42:08 2007 From: ramashish.lists at gmail.com (Ramashish Baranwal) Date: 30 May 2007 05:42:08 -0700 Subject: SMTPAuthenticationError In-Reply-To: References: <1180469172.470577.185720@x35g2000prf.googlegroups.com> Message-ID: <1180528927.961870.62450@o11g2000prd.googlegroups.com> > To help debug this, you may want to try the following. > > 1) Copy smptlib.py into your local directory. On my > box, you can find it here, or import sys; print > sys.path to help find it on your box: > > /usr/local/lib/python2.3 > > 2) Go the login() method, add some print statements > there to see what's going on. > > I admit to not being an SMTP expert nor fully > understanding the code at first glance, but here is > some code iin smtplib.py that suggests you're close to > getting this working, to the extent that your server > wants base64 encoding: > > def encode_cram_md5(challenge, user, > password): > challenge = base64.decodestring(challenge) > response = user + " " + > hmac.HMAC(password, challenge).hexdigest() > return encode_base64(response, eol="") > > Hope this helps. Thanks Steve, that helped a lot. smtplib was trying to a CRAM-MD5 auth which wasn't working. I don't know why. But when I made it do a LOGIN auth by changing its preferred_auth list, it worked. Login has its own preferred list of auth methods which is nice except that not all servers which advertise a particular method may be capable of handling that. It would have been good if there was optionally a way to specify in login() what method to use. For now, I am simply going to derive SMTP to form a class that does LOGIN auth. Ram From see.signature at no.spam Tue May 15 10:23:15 2007 From: see.signature at no.spam (Eric Brunel) Date: Tue, 15 May 2007 16:23:15 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649BC4C.10200@web.de> Message-ID: On Tue, 15 May 2007 15:57:32 +0200, Stefan Behnel wrote: > George Sakkis wrote: >> After 175 replies (and counting), the only thing that is clear is the >> controversy around this PEP. Most people are very strong for or >> against it, with little middle ground in between. I'm not saying that >> every change must meet 100% acceptance, but here there is definitely a >> strong opposition to it. Accepting this PEP would upset lots of people >> as it seems, and it's interesting that quite a few are not even native >> english speakers. > > But the positions are clear, I think. > > Open-Source people are against it, as they expect hassle with people > sending > in code or code being lost as it can't go public as-is. > > Teachers are for it as they see the advantage of having children express > concepts in their native language. > > In-house developers are rather for this PEP as they see the advantage of > expressing concepts in the way the "non-techies" talk about it. No: I *am* an "in-house" developer. The argument is not public/open-source against private/industrial. As I said in some of my earlier posts, any code can pass through many people in its life, people not having the same language. I dare to say that starting a project today in any other language than english is almost irresponsible: the chances that it will get at least read by people not talking the same language as the original coders are very close to 100%, even if it always stays "private". -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From nufuhsus at gmail.com Wed May 9 15:00:31 2007 From: nufuhsus at gmail.com (nufuhsus at gmail.com) Date: 9 May 2007 12:00:31 -0700 Subject: preferred windows text editor? In-Reply-To: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> References: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> Message-ID: <1178737231.565326.12810@o5g2000hsb.googlegroups.com> On May 9, 2:06 pm, "T. Crane" wrote: > Right now I'm using Notepad++. What are other people using? I am very noob to this Python game (though it has been around since 1995 me thinks) and currently (I was using ActivePython and then IDLE) I have been using a combination of Notepad2 http://www.flos- freeware.ch/notepad2.html and the interpreter (Python 2.5) on a Windblows X[crement]P[roblem] SP2 machine. I like IDLE but it seems to stop working after the first few times and I would then re-install it and it would work a few times more. ActivePython was cool but I could not find a version of it that used Python 2.5 (as far as I can see, it only uses 2.4) Notepad2 allows you to launch your script directly from the editor (just like IDLE) and has configurable code highlighting. And it is FREE. From jstroud at mbi.ucla.edu Thu May 17 16:50:47 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 17 May 2007 13:50:47 -0700 Subject: Regexes: How to handle escaped characters In-Reply-To: <87irarqkz7.fsf@wilson.homeunix.com> References: <87tzubqniq.fsf@wilson.homeunix.com> <87irarqkz7.fsf@wilson.homeunix.com> Message-ID: Torsten Bronger wrote: > Hall?chen! > > James Stroud writes: > > >>Torsten Bronger wrote: >> >> >>>I need some help with finding matches in a string that has some >>>characters which are marked as escaped (in a separate list of >>>indices). Escaped means that they must not be part of any match. >>> >>>[...] >> >>You should probably provide examples of what you are trying to do >>or you will likely get a lot of irrelevant answers. > > > Example string: u"Hollo", escaped positions: [4]. Thus, the second > "o" is escaped and must not be found be the regexp searches. > > Instead of re.search, I call the function guarded_search(pattern, > text, offset) which takes care of escaped caracters. Thus, while > > re.search("o$", string) > > will find the second "o", > > guarded_search("o$", string, 0) > > won't find anything. But how to program "guarded_search"? > Actually, it is about changing the semantics of the regexp syntax: > "." doesn't mean anymore "any character except newline" but "any > character except newline and characters marked as escaped". And so > on, for all syntax elements of regular expressions. Escaped > characters must spoil any match, however, the regexp machine should > continue to search for other matches. > > Tsch?, > Torsten. > You will probably need to implement your own findall, etc., but this seems to do it for search: def guarded_search(rgx, astring, escaped): m = re.search(rgx, astring) if m: s = m.start() e = m.end() for i in escaped: if s <= i <= e: m = None break return m Here it is in use: py> def guarded_search(rgx, astring, escaped): ... m = re.search(rgx, astring) ... if m: ... s = m.start() ... e = m.end() ... for i in escaped: ... if s <= i <= e: ... m = None ... break ... return m ... py> import re py> escaped = [1, 5, 15] py> print guarded_search('abc', 'xyzabcxyz', escaped) None py> print guarded_search('abc', 'xyzxyzabcxyz', escaped) <_sre.SRE_Match object at 0x40379720> James From half.italian at gmail.com Tue May 29 05:46:41 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 29 May 2007 02:46:41 -0700 Subject: multiline regular expression (replace) In-Reply-To: References: Message-ID: <1180432000.953227.144690@i13g2000prf.googlegroups.com> On May 29, 2:03 am, Zdenek Maxa wrote: > Hi all, > > I would like to perform regular expression replace (e.g. removing > everything from within tags in a XML file) with multiple-line pattern. > How can I do this? > > where = open("filename").read() > multilinePattern = "^ .... <\/tag>$" > re.search(multilinePattern, where, re.MULTILINE) > > Thanks greatly, > Zdenek Why not use an xml package for working with xml files? I'm sure they'll handle your multiline tags. http://effbot.org/zone/element-index.htm http://codespeak.net/lxml/ ~Sean From steve at REMOVEME.cybersource.com.au Thu May 3 00:54:21 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Thu, 03 May 2007 14:54:21 +1000 Subject: Responding to Trolls [was Re: ignorance and intolerance in computing communties] References: <1178120019.271716.299590@e65g2000hsc.googlegroups.com> Message-ID: On Wed, 02 May 2007 21:23:13 -0700, James Stroud wrote: > Xah Lee wrote: >> Today, a motherfucker Christophe Rhodes (aka Xof in irc://chat.freenode.net/lisp >> ) kicked banned me. > > Are you aware that you are a troll? Have you considered that this has > anything to do with your being kick-banned? Why do 99.999999 % of the > people on the web not get treated like you? Answer: you are a troll and > they are not. Sometimes I dream of a world, a wonderful, far away world, where nobody was allowed to post to Usenet until they can correctly answer the following multiple-choice question: Q Verbally abusing trolls ... 1. gives them the attention they crave 2. fails to discourage their trollish behaviour 3. annoys the people who otherwise wouldn't have seen the troll's post 4. all of the above -- Steven D'Aprano From ken at theoryyalgebra.com Wed May 2 18:33:13 2007 From: ken at theoryyalgebra.com (Ken Tilton) Date: Wed, 02 May 2007 18:33:13 -0400 Subject: Microsoft's Dynamic Languages Runtime (DLR) In-Reply-To: <1178134181.059655.133010@q75g2000hsh.googlegroups.com> References: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> <1178134181.059655.133010@q75g2000hsh.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: > On May 2, 1:22 pm, sturlamolden wrote: > >>On Monday Microsoft announced a new runtime for dynamic languages, >>which they call "DLR". It sits on top of the conventional .NET runtime >>(CLR) and provides services for dynamically typed languages like >>Python or Lisp (thus the cross-posting). Apparently is is distributed >>under a BSD-like open-source license. >> >>I am curious to know how it performs in comparison to CPython and an >>efficient compiled Lisp like CMUCL. Speed is a major problem with >>CPython but not with .NET or CMUCL, so it will be interesting to see >>how the DLR performs in comparison. It would be great to finally see a >>Python that runs on steroids, but knowing M$ bloatware my expectations >>are not too high. >> >>Has anyone looked at the DLR yet? What are your impression? >> >>Jim Hugunin har written about the DLR in his blog: >> >>http://blogs.msdn.com/hugunin/ >> >>To cite one of the comments: "Fuck this microsoft bollocks! You just >>stole the Lisp runtime ideas and fucked them up by stupid it salesman >>lingo." (Khrishna) >> >>Sturla Molden > > > > I realize this is a stupid question, but why did you cite the most > offensive comment to this blog post? Most of them were positive. Yes, but everybody hates Microsoft, so there ya go. Anyway, here is the real question: "thin layer"? I wonder then if anything has changed since: http://groups.google.com/group/comp.lang.lisp/browse_thread/thread/2f9759fa3e8877eb/2b11ecfdc4a15fb4?q=rettig+clr&_done=%2Fgroups%3Fq%3Drettig+clr%26hl%3Den%26lr%3D%26c2coff%3D1%26safe%3Doff%26sa%3DN%26tab%3Dwg%26&_doneTitle=Back+to+Search&&d#2b11ecfdc4a15fb4 Anyway, doesn't matter, just fun to see MS running up the white flag after their ballsy attempt to get CL to do the same at ILC 2005. kt -- http://www.theoryyalgebra.com/ "Algebra is the metaphysics of arithmetic." - John Ray "As long as algebra is taught in school, there will be prayer in school." - Cokie Roberts "Stand firm in your refusal to remain conscious during algebra." - Fran Lebowitz "I'm an algebra liar. I figure two good lies make a positive." - Tim Allen From chris at simplistix.co.uk Wed May 9 03:51:40 2007 From: chris at simplistix.co.uk (Chris Withers) Date: Wed, 09 May 2007 08:51:40 +0100 Subject: MailingLogger 3.0.0 Released! Message-ID: <46417D8C.5010408@simplistix.co.uk> Mailinglogger enables log entries to be emailed either as the entries are logged or as a summary at the end of the running process. This pair of enhanced emailing handlers for the python logging framework is now available as a standard python package and as an egg. The handlers have the following features: - customisable and dynamic subject lines for emails sent - emails sent with an X-Mailer header for easy filtering - flood protection to ensure the number of emails sent is not excessive - fully documented and tested In addition, extra support is provided for configuring the handlers when using ZConfig, Zope 2 or Zope 3. Installation is as easy as: easy_install mailinglogger For more information, please see: http://www.simplistix.co.uk/software/python/mailinglogger cheers, Chris -- Simplistix - Content Management, Zope & Python Consulting - http://www.simplistix.co.uk From steven.bethard at gmail.com Mon May 28 10:33:50 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 28 May 2007 08:33:50 -0600 Subject: Is PEP-8 a Code or More of a Guideline? In-Reply-To: <87ps4lazor.fsf@pobox.com> References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <1180254338.292249.29520@h2g2000hsg.googlegroups.com> <87ps4lazor.fsf@pobox.com> Message-ID: John J. Lee wrote: > Paul McGuire writes: > [...] >> http://mail.python.org/pipermail/python-dev/2005-December/058750.html >> >> At first, Guido seemed ambivalent, and commented on the >> contentiousness of the issue, but it seems that the "non-English >> speakers can more easily find word breaks marked with underscores" >> justification tipped the scale in favor of >> lower_case_with_underscores. > [...] > > That rationale seems undermined by the frequent use of runtogether > names in the standard library. These can be confusing even to native > speakers. And every time you come up with a new name, or try to > remember an old one, you have to decide or remember whether it's > likethis or like_this. > > Even as a native English speaker, some of these are tricky -- > e.g. urllib has a private class named "addinfourl". "What's this > 'fourl' we're adding in?" > > (In fact, the method adds attributes named "info" and "url". Even > though I've read that name hundreds of times, my brain always insists > on reading it "add in fourl".) > > This is the worst of both worlds: inconsistent and hard to understand. Sounds like a good candidate for a rename in Python 3000. STeVe From apatheticagnostic at gmail.com Tue May 1 05:01:42 2007 From: apatheticagnostic at gmail.com (kaens) Date: Tue, 1 May 2007 05:01:42 -0400 Subject: playing sound in mac osx In-Reply-To: <59ob8dF2lbogtU1@mid.uni-berlin.de> References: <59ob8dF2lbogtU1@mid.uni-berlin.de> Message-ID: <163f0ce20705010201j313a06b1u22ffd76abeed6695@mail.gmail.com> Is there really no cross-platform audio capability in the standard library? On 5/1/07, Diez B. Roggisch wrote: > tooru honda schrieb: > > Hi, > > > > I am a newbie to mac and python. > > > > Is there an easy way to play wav or mp3 sound file ? I used to use > > winsound module before switching to mac, but that only works for windows. > > pygame might help. > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > From walterbyrd at iname.com Thu May 3 22:05:23 2007 From: walterbyrd at iname.com (walterbyrd) Date: 3 May 2007 19:05:23 -0700 Subject: Can I use Python instead of Joomla? In-Reply-To: References: <1178138925.498663.252920@o5g2000hsb.googlegroups.com> Message-ID: <1178244323.720365.94420@q75g2000hsh.googlegroups.com> On May 3, 7:49 pm, John Draper wrote: > I admit, Joomla is easy to use I admit, but very easy to vector into > a root exploit. I had no idea. Thank you for posting that. One thing I really like about joomla is the 1600+ extensions. But, I don't need those kinds of security issues. From wgwigw at gmail.com Wed May 30 08:47:06 2007 From: wgwigw at gmail.com (momobear) Date: 30 May 2007 05:47:06 -0700 Subject: How to print this character u'\u20ac' to DOS terminal In-Reply-To: <1180508736.598924.26170@r19g2000prf.googlegroups.com> References: <1180501468.957322.106650@z28g2000prd.googlegroups.com> <465D0A6B.1000203@v.loewis.de> <1180508736.598924.26170@r19g2000prf.googlegroups.com> Message-ID: <1180529226.842768.101210@j4g2000prf.googlegroups.com> On May 30, 3:05 pm, ?????????????????????????????? wrote: > On 5??30??, ????1??23??, "Martin v. Lo"wis" wrote: > > > > > ?????????????????????????????? schrieb: > > > > Who could explain the follow issue ? > > >>>> print u'\u0394' > > > ?? > > >>>> print u'\u20ac' > > > Traceback (most recent call last): > > > File "", line 1, in > > > UnicodeEncodeError: 'gbk' codec can't encode character u'\u20ac' in > > > position 0: > > > illegal multibyte sequence > > > > My terminal is cmd.exe under windows XP. > > > what's the different between the two character ? what can I do if I > > > want to print the u'\u20ac'? > > > The problem is that your terminal uses (some form of) the GBK encoding; > > seehttp://zh.wikipedia.org/wiki/GBKfordetails on GBK. > > > It seems that GBK (or, rather, code page 936) supports the delta > > character, but not the euro sign. > > > To change that, you can use "chcp" in your terminal window. > > For example, if you do "chcp 850", you should be able to > > display the euro sign (but will simultaneously use the ability > > to display the letter delta, and the chinese letters). > > > I don't know whether the terminal supports an UTF-8 code > > page; you can try setting the terminal's code page to > > 65001 (which should be UTF-8). > > > Regards, > > Martin > > Thanks, but it seems not work yet. > > ---------------------------------------------------- > C:\WINDOWS>chcp 850 > Active code page: 850 > > C:\WINDOWS>python > 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.>>> print u'\u20ac' > > Traceback (most recent call last): > File "", line 1, in > File "C:\Python25\lib\encodings\cp850.py", line 12, in encode > return codecs.charmap_encode(input,errors,encoding_map) > UnicodeEncodeError: 'charmap' codec can't encode character u'\u20ac' > in position > 0: character maps to > > C:\WINDOWS>chcp 65001 > Active code page: 65001 > > C:\WINDOWS>python > 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.>>> print u'\u20ac' > > Traceback (most recent call last): > File "", line 1, in > LookupError: unknown encoding: cp65001 > ----------------------------------------------- > I find that the u'\u20ac' related 'mbcs' encode is 0x80, I could print > it directly > > >>> print '\x80' > ? > > But the string contained the u'\u20ac' is get from remote host. Is > there any method to decode it to the local 'mbcs'? From manatlan at gmail.com Sun May 13 04:13:22 2007 From: manatlan at gmail.com (manatlan) Date: 13 May 2007 01:13:22 -0700 Subject: Dynamic subclassing ? In-Reply-To: References: <1178976888.443891.116090@y80g2000hsf.googlegroups.com> Message-ID: <1179044002.779419.159670@o5g2000hsb.googlegroups.com> On 12 mai, 20:47, Steven Bethard wrote: > manatlan wrote: > > I've got an instance of a class, ex : > > > b=gtk.Button() > > > I'd like to add methods and attributes to my instance "b". > > I know it's possible by hacking "b" with setattr() methods. But i'd > > like to do it with inheritance, a kind of "dynamic subclassing", > > without subclassing the class, only this instance "b" ! > > > In fact, i've got my instance "b", and another class "MoreMethods" > > > class MoreMethods: > > def sayHello(self): > > print "hello" > > > How could i write ... > > > "b = b + MoreMethods" > > You can simply bind the methods you want to add to the Button instance. > That means doing the equivalent of ``b.sayHello = sayHello.__get__(b)``. > For example:: > > >>> class Button(object): > ... def set_label(self, label): > ... print 'setting label:', label > ... > >>> def add_methods(obj, cls): > ... for name, value in cls.__dict__.items(): > ... if callable(value) and hasattr(value, '__get__'): > ... setattr(obj, name, value.__get__(obj, type(obj))) > ... > >>> b = Button() > >>> b.set_label('k') > setting label: k > >>> b.say_hello() > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'Button' object has no attribute 'say_hello' > >>> class MoreMethods(object): > ... def say_hello(self): > ... print 'hello' > ... > >>> add_methods(b, MoreMethods) > >>> b.set_label('m') > setting label: m > >>> b.say_hello() > hello > > HTH, > > STeVe Yes ! it seems very good ... I will try that too thanks a lot ... class MoreMethods: val=12 def hello(self): self.val=13 return self.get_label() def add_methods(obj, cls): for name, value in cls.__dict__.items(): if callable(value) and hasattr(value, '__get__'): setattr(obj, name, value.__get__(obj, type(obj))) else: setattr(obj, name, value) b=gtk.Button("the_label") add_methods(b,MoreMethods) print b.get_label() print b.val print b.hello() print b.val From jadestar at idiom.com Sat May 12 17:38:04 2007 From: jadestar at idiom.com (James T. Dennis) Date: Sat, 12 May 2007 21:38:04 -0000 Subject: Simple Python REGEX Question References: <1178898871.781501.135170@p77g2000hsh.googlegroups.com> Message-ID: <1179005883.980508@smirk> johnny wrote: > I need to get the content inside the bracket. > eg. some characters before bracket (3.12345). > I need to get whatever inside the (), in this case 3.12345. > How do you do this with python regular expression? I'm going to presume that you mean something like: I want to extract floating point numerics from parentheses embedded in other, arbitrary, text. Something like: >>> given='adfasdfafd(3.14159265)asdfasdfadsfasf' >>> import re >>> mymatch = re.search(r'\(([0-9.]+)\)', given).groups()[0] >>> mymatch '3.14159265' >>> Of course, as with any time you're contemplating the use of regular expressions, there are lots of questions to consider about the exact requirements here. What if there are more than such pattern? Do you only want the first match per line (or other string)? (That's all my example will give you). What if there are no matches? My example will raise an AttributeError (since the re.search will return the "None" object rather than a match object; and naturally the None object has no ".groups()' method. The following might work better: >>> mymatches = re.findall(r'\(([0-9.]+)\)', given).groups()[0] >>> if len(mymatches): >>> ... ... and, of couse, you might be better with a compiled regexp if you're going to repeast the search on many strings: num_extractor = re.compile(r'\(([0-9.]+)\)') for line in myfile: for num in num_extractor(line): pass # do whatever with all these numbers -- Jim Dennis, Starshine: Signed, Sealed, Delivered From josh at laculine.com Fri May 25 11:50:55 2007 From: josh at laculine.com (Josh West) Date: Fri, 25 May 2007 16:50:55 +0100 Subject: Proxying every function in a module In-Reply-To: References: Message-ID: <465705DF.8000007@laculine.com> Kind and wise fellows, I've got a web application with the following structure: 1) module of 100 functions corresponding to user actions (e.g. "update_profile()", "organisations_list()") 2) a wsgi callable which maps urls to functions eg /organisations/list/?sort=date_created is mapped to organisations_list("dateCreated") 3) mapping is performed using inspect.getargspec() 4) a bunch of html generating templates In the templates I want to generate urls by referencing the function to which they map, rather than the url, e.g. Sort By Date Created In other words, I want to always refer to functions, rather than mixing up function calls and urls I would like a class that proxies all the 100 functions in the user actions module. When a proxied function is called via this class it should return the url to which it is mapped rather than executing the user action function. Sort By Date Created should produce: Sort By Date Created Obviously, I don't want to write and maintain copies of these 100 functions in another class. My question is therefore: what is the best way to proxy these 100 functions? Thanks Tim Arnold wrote: > Hi, I'm using ElementTree which is wonderful. I have a need now to write out > an XML file with these two headers: > > > > My elements have the root named tocbody and I'm using: > newtree = ET.ElementTree(tocbody) > newtree.write(fname) > > I assume if I add the encoding arg I'll get the xml header: > newtree = ET.ElementTree(tocbody) > newtree.write(fname,encoding='utf-8') > > but how can I get the into the tree? > > python2.4.1,hpux10,ElementTree1.2.6 > > thanks, > --Tim > > > From apatheticagnostic at gmail.com Sat May 5 03:48:10 2007 From: apatheticagnostic at gmail.com (kaens) Date: Sat, 5 May 2007 03:48:10 -0400 Subject: Why stay with lisp when there are python and perl? In-Reply-To: References: <1178155239.007219.205020@y5g2000hsa.googlegroups.com> <1178219732.127815.3260@y80g2000hsf.googlegroups.com> Message-ID: <163f0ce20705050048y10d28bcao5fcc652788c89b8e@mail.gmail.com> Yes there is. On 5/3/07, Markus E Leypold wrote: > > Xah Lee writes: > > > (if there is some demand, i will add a concrept, little programing > > No. There ain't. > > - M > > -- > http://mail.python.org/mailman/listinfo/python-list > From rw at smsnet.pl Tue May 1 16:58:39 2007 From: rw at smsnet.pl (Rob Wolfe) Date: Tue, 01 May 2007 22:58:39 +0200 Subject: I wish that [].append(x) returned [x] References: <46379a41$0$25252$88260bb3@free.teranews.com> Message-ID: <87hcqwgt1c.fsf@smsnet.pl> Tobiah writes: > I wanted to do: > > query = "query text" % tuple(rec[1:-1].append(extra)) > > but the append() method returns none, so I did this: > > fields = rec[1:-1] > fields.append(extra) > query = "query text" % tuple(fields) What about this? query = "query text" % tuple(rec[1:-1] + [extra]) -- HTH, Rob From elventear at gmail.com Fri May 11 18:17:57 2007 From: elventear at gmail.com (elventear) Date: 11 May 2007 15:17:57 -0700 Subject: Recursion limit problems Message-ID: <1178921877.442519.165740@u30g2000hsc.googlegroups.com> Hello everyone, I am runing into recursion limit problems. I have found that the culprit was related to the __hash__ function that I had assigned to the objects that were added to a set. Basically my __hash__ function is the following: def __hash__(self): out_int = 0 for property,value in self: out_int ^= hash( property )^hash( value ) return out_int And the iterator for this object is: def __iter__(self): for property,value in self.__dict__.iteritems(): yield property,value After commenting the __hash__ function and using the default provided by Python (I suppose it is based on the position in memory of the object), the recursion limit problems went away. (This problem was happening even after increasing the recursion limit to the maximum of my platform, MacOSX). I am not that versed in Python, so I don't know exactly I could do to overcome this problem, any ideas are deeply appreciated. Thanks! From michael at jedimindworks.com Tue May 22 12:55:17 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Tue, 22 May 2007 11:55:17 -0500 Subject: Restart Linux System In-Reply-To: <1179850502.22230.6.camel@contra.chem.byu.edu> References: <002d01c79b81$aa748d40$ff5da7c0$@rawlins@thinkbluemedia.co.uk> <1179850502.22230.6.camel@contra.chem.byu.edu> Message-ID: On May 22, 2007, at 11:15 AM, Michael L Torrie wrote: >> I?m looking to restart a Linux system from my python application. >> What?s the best way to achieve this, is there something in the OS >> module? > > Probably not. You need to just spawn the "reboot" command, or run > "init > 6." This requires root, though. Without root there's no way to > reboot > a linux system. ...unless you run shutdown(8) or reboot(8) setuid root (reboot is kinda harsh though, btw). Regards, Michael --- Asking a person who he *is* ... is not Pythonic! --Anton Vredegoor From pythonnews at nospam.jmbc.fr Tue May 15 04:09:05 2007 From: pythonnews at nospam.jmbc.fr (jean-michel bain-cornu) Date: Tue, 15 May 2007 10:09:05 +0200 Subject: [ANN] Update to Python Quick Reference Card (for Python 2.4) (v0.67) In-Reply-To: <4bnh33pb644j9qsvij3citqrpb2bmqlsu4@4ax.com> References: <4bnh33pb644j9qsvij3citqrpb2bmqlsu4@4ax.com> Message-ID: <46496ada$0$21149$7a628cd7@news.club-internet.fr> > PC-cillin flagged this as a dangerous web site. An explanation would be fine about *why* the web site is flagged as dangerous... From martin at v.loewis.de Fri May 11 02:16:18 2007 From: martin at v.loewis.de (=?GB2312?B?Ik1hcnRpbiB2LiBMbyJ3aXMi?=) Date: Fri, 11 May 2007 08:16:18 +0200 Subject: how to refer to partial list, slice is too slow? In-Reply-To: <1178862631.470437.134180@h2g2000hsg.googlegroups.com> References: <1178862631.470437.134180@h2g2000hsg.googlegroups.com> Message-ID: <46440a32$0$9677$9b622d9e@news.freenet.de> ??????????????? schrieb: > I'm a python newbie. It seems the slice operation will do copy. > for example: >>>> a = [1,2,3,4,5,6,7,8,9,0] >>>> b = a[7:] >>>> b > [8, 9, 0] >>>> a.remove(9) >>>> a > [1, 2, 3, 4, 5, 6, 7, 8, 0] >>>> b > [8, 9, 0] > > if the list have large members, the slice operations will consume many > times. > for instance, I have a long string named it as S, the size is more > than 100K > I want to parser it one part-to-part. first, I process the first 100 > byte, and pass the remainder to the next parser function. I pass the > S[100:] as an argument of the next parser function. but this operation > will cause a large bytes copy. Is there any way to just make a > reference to the remainder string not copy? You can use itertools.islice: py> a = [1,2,3,4,5,6,7,8,9,0] py> b = itertools.islice(a, 7) py> b py> b.next() 1 py> b.next() 2 py> b.next() 3 py> b.next() 4 py> b.next() 5 py> b.next() 6 py> b.next() 7 py> b.next() Traceback (most recent call last): File "", line 1, in ? StopIteration HTH, Martin From beliavsky at aol.com Fri May 18 13:51:28 2007 From: beliavsky at aol.com (Beliavsky) Date: 18 May 2007 10:51:28 -0700 Subject: List Moderator In-Reply-To: <1179494546.468892.49460@l77g2000hsb.googlegroups.com> References: <880dece00705172218n71123b55q531ec0c5e500f208@mail.gmail.com> <1179494546.468892.49460@l77g2000hsb.googlegroups.com> Message-ID: <1179510688.186622.250760@e65g2000hsc.googlegroups.com> On May 18, 9:22 am, kyoso... at gmail.com wrote: > You're probably right, but this week has been pretty bad. Every few > posts there's another porn or boob related link. Sheesh! > > Mike I wish Google Groups were enhanced to let users block messages according to (1) "keywords" (2) average ranking of the message on Google groups. (3) sender name There are Python experts who work at Google ... From tinaweb at bestemselv.com Tue May 15 03:29:56 2007 From: tinaweb at bestemselv.com (Tina I) Date: Tue, 15 May 2007 09:29:56 +0200 Subject: Distributing programs depending on third party modules. Message-ID: Hi list, Is there a preferred way to distribute programs that depends on third party modules like PyQt, Beautifulsoup etc? I have used setuptools and just having the setup script check for the existence of the required modules. If they're not found I have it exit with a message that it need this or that installed. But this is not very convenient for the end user and I have got a few complaints about it. Am I missing something in setuptools or is there a better way to do it (except for bundling the modules in the package which seem like a rather nasty workaround)? Thanks Tina From napolpie at tin.it Fri May 4 08:45:22 2007 From: napolpie at tin.it (napolpie at tin.it) Date: 4 May 2007 05:45:22 -0700 Subject: using pyparsing to extract METEO DATAS Message-ID: <1178282721.458143.9460@u30g2000hsc.googlegroups.com> DISCUSSION IN USER nappie writes: Hello, I'm Peter and I'm new in python codying and I'm using parsying to extract data from one meteo Arpege file. This file is long file and it's composed by word and number arguments like this: GRILLE EURAT5 Coin Nord-Ouest : 46.50/ 0.50 Coin Sud-E Hello, I'm Peter and I'm new in python codying and I'm using parsying to extract data from one meteo Arpege file. This file is long file and it's composed by word and number arguments like this: [[code]] GRILLE EURAT5 Coin Nord-Ouest : 46.50/ 0.50 Coin Sud-Est : 44.50/ 2.50 MODELE PA PARAMETRE P NIVEAU MER 0 ECHEANCE 0.0 DATE 20020304000000 NB_POINTS 25 1020.91 1020.87 1020.91 1021.05 1021.13 1020.07 1020.27 1020.49 1020.91 1021.15 1019.37 1019.65 1019.79 1020.53 1020.77 1018.73 1018.89 1019.19 1019.83 1020.81 1018.05 1018.19 1018.75 1019.55 1020.27 NIVEAU MER 0 ECHEANCE 3.0 DATE 20020304000000 NB_POINTS 25 1019.80 1019.78 1019.92 1020.18 1020.34 1018.94 1019.24 1019.54 1020.08 1020.32 1018.24 1018.64 1018.94 1019.84 1019.98 1017.48 1017.88 1018.28 1018.98 1019.98 1016.62 1017.08 1017.66 1018.26 1018.34 NIVEAU MER 0 ECHEANCE 6.0 DATE 20020304000000 NB_POINTS 25 1019.37 1019.39 1019.57 ........ ........ ....... ......... ....... ....... ....... ....... ......... NIVEAU MER 0 ECHEANCE 48.0 DATE 20020304000000 NB_POINTS 25 1017.84 1017.46 1017.14 1016.86 1016.58 1017.28 1016.90 1016.46 1016.48 1016.34 1016.50 1016.06 1015.62 1015.90 1015.72 1015.94 1015.30 1014.78 1014.68 1014.86 1015.86 1015.10 1014.36 1014.00 1013.90 ............................. MODELE PA PARAMETRE T NIVEAU HAUTEUR 2 ECHEANCE 0.0 DATE 20020304000000 NB_POINTS 25 1.34 1.51 1.40 0.56 -0.36 1.73 1.43 0.89 -0.16 -0.99 2.06 1.39 1.14 -0.53 -0.99 2.12 2.22 2.15 0.76 -1.16 1.67 1.45 1.40 1.26 0.28 NIVEAU HAUTEUR 2 ECHEANCE 3.0 DATE 20020304000000 NB_POINTS 25 0.94 1.16 1.03 0.44 -0.41 0.95 0.61 0.22 ............................................. [[code]] I'am at the begginning of computation and for the moment I write this code to extract only number data in form of a string: [[code format="python"]] from pyparsing import * dec Combine (Optional( "-" ) + delimitedList( Word( nums ), ".", combine True )) datas = ZeroOrMore( dec ) f=file("arqal-Arpege.00", "r") g=file("out3", "w") for line in f: try: result = datas.parseString (line) add = result add1 = ";".join(add) print >> g,"(",add1,")" except ParseException, pe: print pe [[code]] This is the output result in file g=file("out3", "w") ( ) ( ) ( ) ( 1020.91;1020.87;1020.91;1021.05;1021.13 ) ( 1020.07;1020.27;1020.49;1020.91;1021.15 ) ( 1019.37;1019.65;1019.79;1020.53;1020.77 ) ( 1018.73;1018.89;1019.19;1019.83;1020.81 ) ( 1018.05;1018.19;1018.75;1019.55;1020.27 ) ( ) ( 1019.80;1019.78;1019.92;1020.18;1020.34 ) ( 1018.94;1019.24;1019.54;1020.08;1020.32 ) ( 1018.24;1018.64;1018.94;1019.84;1019.98 ) ( 1017.48;1017.88;1018.28;1018.98;1019.98 ) ( 1016.62;1017.08;1017.66;1018.26;1018.34 ) ( ) ( 1019.37;1019.39;1019.57;1019.9;......; ........ .........;1016.87) ( ) ( 1017.84;1017.46;1017.14;1016.86;1016.58 ) ( 1017.28;1016.90;1016.46;1016.48;1016.34 ) ( 1016.50;1016.06;1015.62;1015.90;1015.72 ) ( 1015.94;1015.30;1014.78;1014.68;1014.86 ) ( 1015.86;1015.10;1014.36;1014.00;1013.90 ) [[code]] So I don't have any word but the problem is that Now I have to put in order this numerical datas in a type of NESTED matrix emulated by python like a nested dictionary : [[code]] { 'P ' : { MER 0 : [ (1020.91;1020.87;........;1020.27 ) ; (.........) ; ( 1019.80;1019.78;........;1018.26;1018.34 ) ]; ......; SOL 0 : [ ( .......);.....;(........ ) ] } ; 'T' : { SOL 0 : [(.....;......) ; (ECHEANCE 3.0) ; (ECHEANCE 6.0) ; (.......;........) ]; HAUTEUR 2 : [(.......;......;......) ] } } = =>>>>>> { 'Parameter X' : { Level X : [ (predict step 3 hours from +0 to +48 hours ) ;]} } o the bigger shell is fixed by Dictionary PARAMETER in the example is P= 'Pressure' but thre are many of this Temperature T , Wind U and V ecc... the second nested shell is setted by another Dictionary NIVEAU MER 0 in the example is MER 0 sea level or SOL 0, but can be HAUTER 2,10 (HEIGHT 2,10 METERS)ecc..... (soil level , 1;0 meter from soil) ecc (from French language) and after every Level is associated with a LIST OF TUPLE: [(....);(....);(....)] to rappresented every step hours of prediction or expiration hours in French language: ECHEANCE XX.X predicted hour +3.0 +6.0 until 48H is setted of a list of tuple [(ECHEANCE 3.0);(ECHEANCE 6.0); (ECHEANCE XX.0);.........;(ECHEANCE 48.0)] like so: [1019.37;1019.39;........;1020.27 );(.........); (1019.80;1019.78;........;1018.26;1018.34 )] where every list is at the end the is the datas grill: (5 x 5 points)= 25 datas 1020.91 1020.87 1020.91 1021.05 1021.13 1020.07 1020.27 1020.49 1020.91 1021.15 1019.37 1019.65 1019.79 1020.53 1020.77 1018.73 1018.89 1019.19 1019.83 1020.81 1018.05 1018.19 1018.75 1019.55 1020.27 [[code]] So I ask you wich is the best way to begin to code the grammar parsying to make recognize him the 'word' inside of the data file and put the data in the form of nested dictionary and list of tuple illustrated before. in attached file there is meteo datas file Thanks a lot for everyone can said me anything to solve this big problem (for me)!!!! REPLY BY USER: ptmcg http://pyparsing.wikispaces.com/message/ Posted Yesterday 4:00 pm Peter - Your first attempt at pyparsing is a good step - just get something working! You've got a first pattern working that detects and extracts all decimal numbers. (I think you are the first one to model a decimal number as a delimited list of integers with "." as the delimiter.) The next step is to start looking for some higher-level text groups or patterns. Your data is well structured as an n-level hierarchy, that looks to me like: [[code]] - model+parameter - level - nb_points - level - nb_points - level - nb_points - model+parameter - level - nb_points - level - nb_points ... [[code]] You can build your pyparsing grammar from the ground up, first to parse individual terminal expressions (such as decimal numbers which you already have), and then buld up to more and more complex structures within your data. The first thing to change about your approach is to start looking at this data as a whole, instead of line by line. Instead of extracting this first line of 5 point values: [[code]] 1020.91 1020.87 1020.91 1021.05 1021.13 [[code]] look at this as one piece of a larger structure, a data set for a given niveau: [[code]] NIVEAU MER 0 ECHEANCE 0.0 DATE 20020304000000 NB_POINTS 25 1020.91 1020.87 1020.91 1021.05 1021.13 1020.07 1020.27 1020.49 1020.91 1021.15 1019.37 1019.65 1019.79 1020.53 1020.77 1018.73 1018.89 1019.19 1019.83 1020.81 1018.05 1018.19 1018.75 1019.55 1020.27 [[code]] So let's create a parser for this structure that is the next step up in the data hierarchy. NIVEAU, ECHEANCE, DATE, and NB_POINTS are helpful labels for marking the data, but not really important to return in the parsed results. So I will start by creating definitions for these labels which will parse them, but leave out (suppress) them from the returned data: [[code]] NIVEAU, ECHEANCE, DATE, NB_POINTS = \ map(Suppress,"NIVEAU ECHEANCE DATE NB_POINTS" .split()) [[code]] You stated that there are several options for what a niveau identifier can look like, so this should be its own expression: [[code]] niveau_ref = Literal("MER 0") | Literal("SOL 0") | \ Combine(Literal("HAUTEUR ") + eurodec) [[code]] (I defined eurodec as you defined dec, but with a comma delimiter.) I'll also define a dateString as a Word(nums) of exactly 14 digits, but you can come back to this later and refine this as you like (build in parse-time conversion for example). [[code]] dateString = Word(nums,exact=14) [[code]] And then you can create an expression for a full niveau's-worth of data: [[code]] niveau = NIVEAU + niveau_ref + ECHEANCE + dec + DATE + dateString + NB_POINTS + countedArray(dec) [[code]] Notice that we can use the pyparsing built-in countedArray to capture all of the data point values, since NB_POINTS gives the number of points to follow, and these are followed immediately by the points themselves. Pyparsing will convert all of these into a nice n-element list for us. You astutely requested that these values should be accessible like values in a dict, so we do this in pyparsing by adding results names: [[code]] niveau = NIVEAU + niveau_ref.setResultsName("niveau") + \ ECHEANCE + dec.setResultsName("echeance") + \ DATE + dateString.setResultsName("date") + \ NB_POINTS + countedArray(dec).setResultsName("nb_points") [[code]] Now you should be able to search through your data file, extracting all of the niveaux (?) and their related data: [[code]] f=file("arqal-Arpege.00", "r") fdata = f.read() # read the entire file, instead of going line- by- line for n in niveau.searchString(fdata): print n.niveau print n.dump() pointValues = map(float,n.nb_points[0]) print "- NB_POINTS mean:", sum(pointValues) / len(pointValues) print [[code]] (I also added some examples of extracting data using the results names. You can also use dict-style notation, n["niveau"], if you prefer.) Gives this output (I've truncated with '...' for the sake of posting, but the actual program gives the full lists of values): [[code]] MER 0 ['MER 0', '0.0', '20020304000000', ['1020.91', '1020.87', ... - date: 20020304000000 - echeance: 0.0 - nb_points: [['1020.91', '1020.87', '1020.91', '1021.05', ... - niveau: MER 0 - NB_POINTS mean: 1020.0052 [[code]] [[code]] MER 0 ['MER 0', '3.0', '20020304000000', ['1019.80', '1019.78', ... - date: 20020304000000 - echeance: 3.0 - nb_points: [['1019.80', '1019.78', '1019.92', '1020.18', ... - niveau: MER 0 - NB_POINTS mean: 1018.9736 [[code]] [[code]] MER 0 ['MER 0', '48.0', '20020304000000', ['1017.84', '1017.46', ... - date: 20020304000000 - echeance: 48.0 - nb_points: [['1017.84', '1017.46', '1017.14', '1016.86', ... - niveau: MER 0 - NB_POINTS mean: 1015.9168 [[code]] [[code]] HAUTEUR 2 ['HAUTEUR 2', '0.0', '20020304000000', ['1.34', '1.51', '1.40', ... - date: 20020304000000 - echeance: 0.0 - nb_points: [['1.34', '1.51', '1.40', '0.56', '-0.36', '1.73', ... - niveau: HAUTEUR 2 - NB_POINTS mean: 0.9028 [[code]] [[code]] HAUTEUR 2,4 ['HAUTEUR 2,4', '3.0', '20020304000000', ['1.34', '1.51', '1.40', ... - date: 20020304000000 - echeance: 3.0 - nb_points: [['1.34', '1.51', '1.40', '0.56', '-0.36', '1.73', ... - niveau: HAUTEUR 2,4 - NB_POINTS mean: 0.9028 [[code]] Now I'll let you take this the next step: compose the expression for the model+parameter hierarchy level (hint: the body of each model +parameter value will be an expression of OneOrMore( Group( niveau ) ) - be sure to give this a results name, too). From half.italian at gmail.com Fri May 18 04:50:18 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 18 May 2007 01:50:18 -0700 Subject: i/o prob revisited In-Reply-To: <1179471963.303052.136690@q23g2000hsg.googlegroups.com> References: <1179471963.303052.136690@q23g2000hsg.googlegroups.com> Message-ID: <1179478218.518917.309490@u30g2000hsc.googlegroups.com> On May 18, 12:06 am, saif.shak... at gmail.com wrote: > Hi, > I am parsing an xml file ,before that i have replaced a string in > the original xml file with another and made a new xml file which will > now be parsed.I am also opening some more files for output.The > following code shows some i/o commands. > file_input = raw_input("Enter The ODX File Path:") > input_xml = open(file_input,'r') > > (shortname,ext)=os.path.splitext(file_input) > f_open_out=shortname+".ini" > log=shortname+".xls" > test_file=shortname+"testxml.xml" > > saveout = sys.stdout > > xmlcont=input_xml.read() > input_xml.close() > > xmlcont=xmlcont.replace('localId','dataPackageId') > > output_file = open(test_file,"w") > output_file.write(xmlcont) > output_file.close() > > f_open=open(f_open_out, 'w') > logfile=open(log,"w") > sys.stdout = f_open > > After this i have to parse the new xml file which is in > output_file .hence > > input_xml_sec = open(output_file,'r') > xmldoc = minidom.parse(input_xml_sec) > > But i am getting an error on this line > (input_xml_sec = open(output_file,'r')).I have tried to figure out > but > not able to debug.Can someone throw some light or anything they feel > could be going wrong somewhere. > How do i capture the error as it vanishes very > qucikly when i run through command prompt,(the idle envir gives > indentation errors for no reason(which runs perfectly from cmd > prompt),hence i dont run using conventional F5. http://docs.python.org/tut/ Read carefully. From gagsl-py2 at yahoo.com.ar Wed May 30 14:52:59 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 30 May 2007 15:52:59 -0300 Subject: How can an Exception pass over an "except" clause ? References: <1180540010.548057.220270@m36g2000hse.googlegroups.com> <1180549843.351694.279660@p77g2000hsh.googlegroups.com> Message-ID: En Wed, 30 May 2007 15:30:43 -0300, Nebur escribi?: > @Tijs: I think when re-raising, the backtrace will always point to the > line where it was re-raised but not to line 1265. (Or can we re-raise > an exception so that it preserves the backtrace of the "original" > exception?) I think Tijs is right. raise (with no arguments) will raise the *last* exception, not the one that was active when you entered the except clause; it preserves the traceback. Either replace the inner try/except using getattr, or save the full exception details (including traceback) and use the 3-argument form of the raise statement. See http://docs.python.org/ref/raise.html -- Gabriel Genellina From facundo at taniquetil.com.ar Mon May 14 08:48:23 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Mon, 14 May 2007 12:48:23 +0000 (UTC) Subject: multi threaded SimpleXMLRPCServer References: <46483122.2030901@swsoft.com> Message-ID: Vyacheslav Maslov wrote: > I need multi threaded version of SimpleXMLRPCServer. Does python library > already have implementation of this one? Or i need to implement multi > threading by myself? Don't know, but maybe this helps. Here's a framework I implemented, where you have a job with multiple parts. You have a server that you deploy in several machines, and a client that feeds the jobs to the servers, actually getting distributed processing. http://www.taniquetil.com.ar/plog/post/1/59 Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From kyosohma at gmail.com Tue May 15 09:16:59 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 15 May 2007 06:16:59 -0700 Subject: Get a control over a window In-Reply-To: <1179234413.915336.263660@n59g2000hsh.googlegroups.com> References: <1179234413.915336.263660@n59g2000hsh.googlegroups.com> Message-ID: <1179235019.400818.250040@o5g2000hsb.googlegroups.com> On May 15, 8:06 am, Tom Gur wrote: > Hi, > > I was wondering how do I get control over a window (Win32). > to be more specific, I need to find a handle to a window of a certain > program and minimize the window. It sounds pretty complicated to me, but here's what I found: http://mail.python.org/pipermail/python-list/2005-November/352639.html http://forums.devshed.com/python-programming-11/using-python-to-control-windows-132273.html That should get you started. If you figure it out, post your code so the rest may benefit. Mike From adonis at REMOVETHISearthlink.net Sun May 27 18:37:13 2007 From: adonis at REMOVETHISearthlink.net (Adonis Vargas) Date: Sun, 27 May 2007 22:37:13 GMT Subject: ten small Python programs In-Reply-To: References: Message-ID: Steve Howell wrote: > I've always thought that the best way to introduce new > programmers to Python is to show them small code > examples. You could try this wiki page: http://rosettacode.org/wiki/Main_Page It has a fair amount of Python examples as well as many more other languages (doing the same algorithm). Hope this helps. Adonis From aleax at mac.com Fri May 18 00:48:29 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 17 May 2007 21:48:29 -0700 Subject: Interesting list Validity (True/False) References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> <1178914190.166662.285410@p77g2000hsh.googlegroups.com> <1178915791.584216.293130@l77g2000hsb.googlegroups.com> <1178918808.091358.233740@o5g2000hsb.googlegroups.com> <1179017740.656323.209590@e51g2000hsg.googlegroups.com> <1179020634.130689.171960@o5g2000hsb.googlegroups.com> <1179031812.090768.248750@l77g2000hsb.googlegroups.com> <1179168081.603409.39970@e51g2000hsg.googlegroups.com> <1179203827.881205.287910@l77g2000hsb.googlegroups.com> <1179248480.350553.4430@n59g2000hsh.googlegroups.com> Message-ID: <1hya1ot.nv08e511bp1wiN%aleax@mac.com> Gabriel Genellina wrote: > >>>> import gmpy > >>>> a = 2**177149-1 > >>>> b = gmpy.mpz(2**177149-1) > >>>> a==b > > True > >>>> print '%d' % (b) > > > > Traceback (most recent call last): > > File "", line 1, in > > print '%d' % (b) > > TypeError: int argument required > > > > So although the comparison operator is smart enough to realize > > the equivalency of numeric types and do the type conversion, > > the print statement isn't so smart. > > This is up to the gmpy designers/writers/maintainers. Anyone writing a > class chooses which features to implement, which ones to omit, how to > implement them, etc. The code may contain bugs, may not be efficient, may > not behave exactly as the users expect, may not have anticipated all usage > scenarios, a long etc. In this case, probably the gmpy writers have chosen > not to allow to convert to int, and they may have good reasons to not do > that (I don't know what platform are you working in, but I feel that your > b object is somewhat larger than sys.maxint...). The gmpy designer, writer and maintainer (all in the singular -- that's me) has NOT chosen anything of the sort. gmpy.mpz does implement __int__ and __long__ -- but '%d'%somempzinstance chooses not to call either of them. sys.maxint has nothing to do with the case: '%d'%somelonginstance DOES work just fine -- hey, even a *float* instance formats just fine here (it gets truncated). I personally consider this a bug in %d-formatting, definitely NOT in gmpy. Alex From svenrech at gmx.de Sat May 12 21:30:56 2007 From: svenrech at gmx.de (Sven Rech) Date: Sun, 13 May 2007 03:30:56 +0200 Subject: Problems with thread safety Message-ID: <1179019856.8748.4.camel@sven-laptop> Hi, In my C program, I want to use python scripts. This scripts should also have the ability to start threads. So at the initilisation phase I do: PyEval_InitThreads(); PyEval_ReleaseLock(); With the second call I want to release lock, for that the python threads can also do their work. But then, when I call a method in a script which starts a thread then, I get the following error: Fatal Python error: PyEval_AcquireThread: non-NULL old thread state Aborted (core dumped) What did I wrong? From showell30 at yahoo.com Sun May 27 10:41:35 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 27 May 2007 07:41:35 -0700 (PDT) Subject: Newbie question - better way to do this? In-Reply-To: <1180273441.455227.120170@g4g2000hsf.googlegroups.com> Message-ID: <964221.21674.qm@web33506.mail.mud.yahoo.com> --- Eric wrote: > I have some working code, but I realized it is just > the way I would > write it in C, which means there is probably a > better (more pythonic) > way of doing it. > > Here's the section of code: > > accumulate = firstIsCaps = False > accumStart = i = 0 > while i < len(words): > firstIsCaps = firstIsCapitalized(words[i]) > if firstIsCaps and not accumulate: > accumStart, accumulate = i, True > elif accumulate and not firstIsCaps: > doSomething(words[accumStart : i]) > accumulate = False > i += 1 > > words is a big long array of strings. What I want > to do is find > consecutive sequences of words that have the first > letter capitalized, > and then call doSomething on them. (And you can > ignore the fact that > it won't find a sequence at the very end of words, > that is fine for my > purposes). > Try out this program: def doSomething(stuff): print stuff def firstIsCapitalized(word): return 'A' <= word[0] <= 'Z' def orig_code(words): print 'C-style' accumulate = firstIsCaps = False accumStart = i = 0 while i < len(words): firstIsCaps = firstIsCapitalized(words[i]) if firstIsCaps and not accumulate: accumStart, accumulate = i, True elif accumulate and not firstIsCaps: doSomething(words[accumStart : i]) accumulate = False i += 1 def another_way(words): print 'more idiomatic, with minor bug fix' group = [] for word in words: if firstIsCapitalized(word): group.append(word) elif group: doSomething(group) group = [] if group: doSomething(group) orig_code(['foo', 'Python', 'Ruby', 'c', 'xxx', 'Perl']) another_way(['foo', 'Python', 'Ruby', 'c', 'xxx', 'Perl']) See also the groupby method in itertools. http://docs.python.org/lib/itertools-functions.html ____________________________________________________________________________________Get the Yahoo! toolbar and be alerted to new email wherever you're surfing. http://new.toolbar.yahoo.com/toolbar/features/mail/index.php From bscrivener42 at gmail.com Tue May 29 14:54:07 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: 29 May 2007 11:54:07 -0700 Subject: wxpython demo error on debian etch In-Reply-To: <1180462154.551455.83010@k79g2000hse.googlegroups.com> References: <1180445918.523446.133300@g4g2000hsf.googlegroups.com> <1180446704.521350.72450@k79g2000hse.googlegroups.com> <1180459989.799593.243960@u30g2000hsc.googlegroups.com> <1180462154.551455.83010@k79g2000hse.googlegroups.com> Message-ID: <1180464847.666043.12810@q75g2000hsh.googlegroups.com> On May 29, 1:09 pm, kyoso... at gmail.com wrote: > The newer versions of wxPython won't make your Debian crash or > anything. Thanks, mike, i'll try it. rick From cam.ac.uk at mh391.invalid Wed May 2 10:06:46 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 02 May 2007 15:06:46 +0100 Subject: open("output/mainwindow.h",'w') doesn't create a folder for me In-Reply-To: <1178114705.586725.295480@n76g2000hsh.googlegroups.com> References: <1178114705.586725.295480@n76g2000hsh.googlegroups.com> Message-ID: noagbodjivictor at gmail.com wrote: > Hello > I have done python for some time now. I'm forgetting things. > > This is the faulty line : outfile = open("output/mainwindow.h",'w') > > I thought it would have created the folder ouput and the file > mainwindow.h for me but it's throwing an error No, you have to create the folder first. Try os.makedirs() -- Michael Hoffman From rurpy at yahoo.com Sun May 20 22:04:12 2007 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 20 May 2007 19:04:12 -0700 Subject: Newbie Question: python mysqldb performance question In-Reply-To: <1179705306.956396.261700@a26g2000pre.googlegroups.com> References: <1179705306.956396.261700@a26g2000pre.googlegroups.com> Message-ID: <1179713052.615330.58200@n15g2000prd.googlegroups.com> On May 20, 5:55 pm, cjl wrote: ...snip... > conn = MySQLdb.connect(db="database", host="localhost", user="root", > passwd="password") > c = conn.cursor() > > reader = csv.reader(open(sys.argv[1])) > for row in reader: > data1, data2, data3, data4 = row > data = (data1,data2,data3,data4) > c.execute("""insert into datatable values (%s, %s, %s, %s)""", > data) > conn.commit() > > This takes a really long time to execute, on the order of minutes. > Directly importing the csv file into mysql using 'load infile' takes > seconds. > > What am I doing wrong? What can I do to speed up the operation? In addition to the previous poster's suggestions, if you have indexes, foreign keys, or other constraints on the table, and you are sure that you are loading "good" data, you may want to drop them before doing the inserts, and recreate them after. Updating indexes and checking contraints can be time consuming. But you will probabably never get your code to run as fast as the mysql "load" command, which (I'm guessing here, don't use mysql much) skips all the sql machinery and writes directly to the table. From carsten at uniqsys.com Tue May 8 08:52:52 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 08 May 2007 08:52:52 -0400 Subject: interesting exercise In-Reply-To: <1178601624.812907.23550@u30g2000hsc.googlegroups.com> References: <1178595952.641173.76540@y80g2000hsf.googlegroups.com> <1178601624.812907.23550@u30g2000hsc.googlegroups.com> Message-ID: <1178628772.3357.7.camel@dot.uniqsys.com> On Mon, 2007-05-07 at 22:20 -0700, sherry wrote: > On May 8, 9:31 am, Steven D'Aprano > wrote: > > [snip Steven's response about a programming exercise...] > > [snip Sherrybove's spam about physical exercise...] And today's award for the most conspicuous failure of the Turing test goes to the Spambot posting as Sherrybove! (*applause*) Fortunately, it's not programmed to deliver acceptance speeches, so it will accept the award silently. I-know-this-isn't-on-topic-either-but-I-couldn't-resist'ly yours, Carsten. From graemeglass at gmail.com Wed May 23 05:41:58 2007 From: graemeglass at gmail.com (Graeme Glass) Date: 23 May 2007 02:41:58 -0700 Subject: trying to gzip uncompress a StringIO In-Reply-To: <1179880643.556124.93910@p47g2000hsd.googlegroups.com> References: <46536E01.2080702@lexicon.net> <1179880643.556124.93910@p47g2000hsd.googlegroups.com> Message-ID: <1179913318.279935.186890@p77g2000hsh.googlegroups.com> On May 23, 2:37 am, b... at snee.com wrote: > Perfect, thanks! Now I have a working WMF file and everything. > > Bob Now you just got to get your reply button working :-D From tjreedy at udel.edu Mon May 7 15:55:09 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 7 May 2007 15:55:09 -0400 Subject: Simulating simple electric circuits References: <5a9838F2nlbanU1@mid.individual.net> Message-ID: "Bjoern Schliessmann" wrote in message news:5a9838F2nlbanU1 at mid.individual.net... Hello all, | I'm trying to simulate simple electric logic (asynchronous)circuits. [snip] Some network simulators use connection objects in addition to node objects, with connections joined to nodes but not the same type to each other. But I do not see this as applying here. Another 'trick' is to make all connections one-way, so a two-way connection is a pair of opposite one-way connections. This might make it easier to keep track of what is turning on (or off) what. tjr From stargaming at gmail.com Tue May 1 12:47:34 2007 From: stargaming at gmail.com (Stargaming) Date: Tue, 01 May 2007 18:47:34 +0200 Subject: Having problems accepting parameters to a function In-Reply-To: <1178037488.163487.114930@l77g2000hsb.googlegroups.com> References: <1178037488.163487.114930@l77g2000hsb.googlegroups.com> Message-ID: rh0dium schrieb: > Hi Experts!! > > I am trying to get the following little snippet to push my data to the > function func(). What I would expect to happen is it to print out the > contents of a and loglevel. But it's not working. Can someone please > help me out. > > ----------------------- > #!/usr/bin/env python > > import random > > def func(*args, **kwargs): > print kwargs.get('a', "NOPE") > print kwargs.get('loglevel', "NO WAY") > > def main(): > b = [] > for x in range(5): > b.append({'a':random.random(), "loglevel":10}) > > for y in b: > apply(func,y) > > # First attempt - didn't work > # for y in b: > # func(y) > > if __name__ == '__main__': > main() > ``apply()`` is deprecated -- use the asterisk-syntax_ instead. >>>> dic = {'a': 5, 'loglevel': 10} >>> def foo(*args, **kwargs): ... print kwargs ... >>> foo(**dic) {'a': 5, 'loglevel': 10} So, your first attempt was close -- just two signs missing. :-) HTH, Stargaming .. _asterisk-sytax: http://docs.python.org/tut/node6.html#SECTION006740000000000000000 From bignose+hates-spam at benfinney.id.au Fri May 18 06:43:17 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 18 May 2007 20:43:17 +1000 Subject: (Modular-)Application Framework / Rich-Client-Platform in Python References: Message-ID: <878xbm5s56.fsf@benfinney.id.au> Wildemar Wildenburger writes: > Thanks for the effort, but I think I'm not well understood. I'm not > looking for a GUI framework (which, by the way, is most likely to be > wxPython), but for a pure plugin architecture. A > rich-client-platform, as it is sometimes called. Nothing specific > about anythin in particular, just something that runs plugins. Like > Eclipse does these days. I've never used Eclipse (beyond proving that it runs on various computers). Can you please describe what behaviour you're looking for? "Just runs plugins" is very vague, and would seem to be satisfied on the face of it by loading Python modules. If there's something more specific, you'll have to specify. -- \ "I hope if dogs ever take over the world, and they chose a | `\ king, they don't just go by size, because I bet there are some | _o__) Chihuahuas with some good ideas." -- Jack Handey | Ben Finney From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue May 15 04:33:28 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 15 May 2007 10:33:28 +0200 Subject: Distributing programs depending on third party modules. In-Reply-To: References: Message-ID: <4649704d$0$3257$426a74cc@news.free.fr> Tina I a ?crit : > Hi list, > > Is there a preferred way to distribute programs that depends on third > party modules like PyQt, Beautifulsoup etc? I have used setuptools and > just having the setup script check for the existence of the required > modules. If they're not found I have it exit with a message that it need > this or that installed. > > But this is not very convenient for the end user and I have got a few > complaints about it. Am I missing something in setuptools EasyInstall, perhaps ? http://peak.telecommunity.com/DevCenter/EasyInstall HTH From walterbyrd at iname.com Sat May 19 02:36:14 2007 From: walterbyrd at iname.com (walterbyrd) Date: 18 May 2007 23:36:14 -0700 Subject: Python compared to other language In-Reply-To: <1hybvdz.1qnlesglcv0vcN%aleax@mac.com> References: <1179540061.598417.13870@y80g2000hsf.googlegroups.com> <1hybvdz.1qnlesglcv0vcN%aleax@mac.com> Message-ID: <1179556574.341550.229190@q23g2000hsg.googlegroups.com> On May 18, 10:24 pm, a... at mac.com (Alex Martelli) wrote: > > I think that Ruby, which roughly speaking sits somewhere between Python > and Perl, is closer to Python than Perl is. I don't know much about Ruby, but it does not seem to be commonly used for anything other than web-development. It may be that Ruby could be used for other purposes, but I don't seem to see it happen much. I know that PHP can used at the command line, and could be used for the same sort of sys-admin tasks for which, Perl and Python are often used, but I don't seem to see that happening either. I'm not sure if Ruby, or PHP, are as general purpose as Perl or Python. From thorsten at thorstenkampe.de Tue May 15 08:27:09 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 15 May 2007 13:27:09 +0100 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> <4648294F.2000704@web.de> <46487a6c$0$2400$426a74cc@news.free.fr> <4649a1b6$0$23131$9b4e6d93@newsspool1.arcor-online.net> Message-ID: * Ren? Fleschenberg (Tue, 15 May 2007 14:04:07 +0200) > Thorsten Kampe schrieb: > > Because keywords are not meant meant to extended or manipulated or > > something similar by the programmers. Keywords are well known and only > > a limited set of words. That's why you can't use keywords as > > identifiers. > > This is true for keywords, but not for the stdlib. Are you suggesting > that the stdlib should be "internationalized"? No, because it's the /Standard/ Library to be used by everyone. And the lowest common denominator is ASCII and English. > > There really is no difference to allow strings or comments in non- > > english languages and non-ASCII characters. > > Comments in a non-English language are a bad idea. No, they're not. It depends on the purpose of the code. For a lot of projects comments in English might be a bad idea. > And of course there is a difference between strings (data) and > identifiers (program logic). It's not about identifiers but about identifiers' names. Identifiers' names are a kind of API where the programmers "plug in" their own individuality or nationality. Just like string data and comments. You're not supposed to understand nor read nor even display this code. If you are then it's the programmer's responsibility to enable you to do so. From edoherty at darwinsuzsoft.com Thu May 10 13:56:42 2007 From: edoherty at darwinsuzsoft.com (Erin) Date: 10 May 2007 10:56:42 -0700 Subject: Soultions deployment engineer Message-ID: <1178819802.514399.87770@l77g2000hsb.googlegroups.com> I am trying to find someone to fill a position that involves developing deployment scripts in Jython. I am having a tough time. I have talked to a lot of consultants who say this is an obscure skill. I am looking for suggetstions on where to find the person I need for this position. Any ideas? Does anyone know anyone looking? From wildemar at freakmail.de Thu May 17 15:38:13 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Thu, 17 May 2007 21:38:13 +0200 Subject: (Modular-)Application Framework / Rich-Client-Platform in Python In-Reply-To: <1179427045.561519.234620@w5g2000hsg.googlegroups.com> References: <1179427045.561519.234620@w5g2000hsg.googlegroups.com> Message-ID: <464CAF25.3010906@freakmail.de> memracom at yahoo.com wrote: >> There seem to loads of python frameworks for Web-Apps, but I have a hard >> time finding one for desktop-apps. >> I imagine it wouldn't be too hard (if still time consuming) whipping up >> something simple myself, but I thought, I'd ask here before diving into it. >> > > Sounds like you should look at DABO > http://dabodev.com/ > Thanks, just glanced over it and as I expected, DABO seems a bit much. But then again, I should have made my point clearer in the first place. I'm looking for something like the eclipse plugin kernel. Just a simple module that allows for easy loading and unloading of discrete bits of functionality. That doesn't seem to be the objective of DABO (correct me if I'm wrong). > But remember, that by combining something like YUI with any WSGI > framework and a Python web server (PASTE, FAPWS) you can use a web > browser as the client for an application that runs on the same > computer. > Though I like the idea of distibuted applications, I want to write an app (a couple of, actually) targeted at the home user that sets up the software herself/himself. So this might get a bit to complicated for Joe Schmoe. Secondly, I'm going for apps that don't quite adhere to the "form" metaphor of most software (specifically DB-apps). I think doing "unusual" UI features might get a bit messy when done with web technology. I have thought about an actionsctipt-based approach, but I'd very much like to try it with python first. thx for the ideas, still. :) W From noagbodjivictor at gmail.com Wed May 2 10:13:59 2007 From: noagbodjivictor at gmail.com (noagbodjivictor at gmail.com) Date: 2 May 2007 07:13:59 -0700 Subject: open("output/mainwindow.h",'w') doesn't create a folder for me In-Reply-To: References: <1178114705.586725.295480@n76g2000hsh.googlegroups.com> Message-ID: <1178115239.608041.258760@y5g2000hsa.googlegroups.com> On May 2, 10:06 am, Michael Hoffman wrote: > noagbodjivic... at gmail.com wrote: > > Hello > > I have done python for some time now. I'm forgetting things. > > > This is the faulty line : outfile = open("output/mainwindow.h",'w') > > > I thought it would have created the folder ouput and the file > > mainwindow.h for me but it's throwing an error > > No, you have to create the folder first. Try os.makedirs() > -- > Michael Hoffman Thanks Mike From steve at holdenweb.com Tue May 29 16:45:27 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 29 May 2007 16:45:27 -0400 Subject: How to set a class inheritance at instance creation? In-Reply-To: <1180453971.556244.91370@q69g2000hsb.googlegroups.com> References: <1180453971.556244.91370@q69g2000hsb.googlegroups.com> Message-ID: <465C90E7.2080108@holdenweb.com> glomde wrote: > Hi I wonder if you can set what subclass a class should > have at instance creation. > > The problem is that I have something like: > > class CoreLang(): > def AssignVar(self, var, value): > pass > > class Lang1(CoreLang): > def AssignVar(self, var, value): > return var, "=", value > > class Lang2(CoreLang): > def AssignVar(self, var, value): > return var, "<=", value > > class WriteStruct(): > def Generate(self, vars): > for var in vars: > print self.AssignVar() > > The problem is that I want WriteStruct to sometimes be a subclass of > Lang1 and sometimes > of Lang2. > In the above example I could but the Generate Method in CoreLang. But > in my real > example I also want to able to subclass WriteStruct to be able to easy > customize WriteStruct. > Which I wouldnt be able to do if it was a method in CoreLang. > > So in code I would like to write something like: > > WriteStruct(Lang1).Generate(vars) > > Even better would be that if I in the Lang1 class could > just do WriteStruct().Generate(vars) and Lang1 class would > magically make WriteStruct a subclass of itself. > > You should rethink your program design. It seems that when you create a WriteStruct you should really be passing its __init__() method the class that you want it to be a "subclass" of, creating an instance of that class, and then using generic delegation to that subclass (using a modified __getattr__()) to handle methods that aren't found in the WriteStruct. I can see there are circumstances in which this might not work, but I believe your current ugly intentions reveal a design smell that you really need to get rid of if you want a clean program. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From manatlan at gmail.com Sat May 12 12:54:16 2007 From: manatlan at gmail.com (manatlan) Date: 12 May 2007 09:54:16 -0700 Subject: Dynamic subclassing ? In-Reply-To: References: <1178976888.443891.116090@y80g2000hsf.googlegroups.com> Message-ID: <1178988856.774715.272120@e51g2000hsg.googlegroups.com> On 12 mai, 18:38, "Daniel Nogradi" wrote: > > I've got an instance of a class, ex : > > > b=gtk.Button() > > > I'd like to add methods and attributes to my instance "b". > > I know it's possible by hacking "b" with setattr() methods. But i'd > > like to do it with inheritance, a kind of "dynamic subclassing", > > without subclassing the class, only this instance "b" ! > > > In fact, i've got my instance "b", and another class "MoreMethods" > > > class MoreMethods: > > def sayHello(self): > > print "hello" > > > How could i write ... > > > "b = b + MoreMethods" > > > so "b" will continue to be a gtk.Button, + methods/attributs of > > MoreMethods (it's what i call "dynamic inheritance") ...so, things > > like this should work : > > > - b.set_label("k") > > - b.sayHello() > > > I can't find the trick, but i'm pretty sure it's possible in an easy > > way. > > How about: > > class MoreMethods: > def sayHello(self): > print "hello" > > class myButton( gtk.Button, MoreMethods ): > pass > > b = myButton( ) > > isinstance( b, gtk.Button ) # True > b.sayHello( ) # "hello" yes, but it needs to recreate an instance (of mybutton) ... i can't do that, in my context. The only things i've got is my instance "b" (which can be whatever object). i'd like to add methods/attributes to this instance, by adding a heritage of another class. > Daniel thanks From roman.yakovenko at gmail.com Tue May 8 00:19:24 2007 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Tue, 8 May 2007 07:19:24 +0300 Subject: [ANN]Py++ 0.9.0 In-Reply-To: <7465b6170705072112q639a50acwcda287e7b4ffb103@mail.gmail.com> References: <7465b6170705072112q639a50acwcda287e7b4ffb103@mail.gmail.com> Message-ID: <7465b6170705072119x410cb33cq50f88eb1baba11c6@mail.gmail.com> Hello! I'm pleased to announce the 0.9.0 release of Py++. What is Py++? ============= Py++ is an object-oriented framework for creating a code generator for Boost.Python library. Where is Py++? ============== Site: http://language-binding.net/pyplusplus/pyplusplus.html Download: http://language-binding.net/pyplusplus/download.html What's new? =========== Features -------- * Added exposing of copy constructor, ``operator=`` and ``operator<<``. * ``operator=`` is exposed under "assign" name * ``operator<<`` is exposed under "__str__" name * Added new call policies: * as_tuple * custom_call_policies * return_range * Added an initial support for multi-module development. Now you can mark your declarations as ``already_exposed`` and `Py++`_ will do the rest. * `input_c_buffer`_ - new functions transformation, which allows to pass a Python sequence to C++ function, instead of pair of arguments: pointer to buffer and size. * Added ability to control generated "include" directives. Now you can ask Py++ to include a header file, when it generates code for some declaration. * Code generation improvements: system header files (Boost.Python or Py++ defined) will be included from the generated files only in case the generated code depends on them. * Performance: Py++ runs 1.5 - 2 times faster. * Py++ will generate documentation for automatically constructed properties. * Added iteration functionality to Boost.Python Indexing Suite V2 ``std::map`` and ``std::multimap`` containers. -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From luismgz at gmail.com Thu May 17 00:03:27 2007 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M=2E_Gonz=E1lez?=) Date: 16 May 2007 21:03:27 -0700 Subject: Python Web Programming - looking for examples of solid high-traffic sites In-Reply-To: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> Message-ID: <1179374607.174960.309370@q75g2000hsh.googlegroups.com> On May 16, 6:04 pm, Victor Kryukov wrote: > Hello list, > > our team is going to rewrite our existing web-site, which has a lot of > dynamic content and was quickly prototyped some time ago. > > Today, as we get better idea of what we need, we're going to re-write > everything from scratch. Python is an obvious candidate for our team: > everybody knows it, everybody likes it, it has *real* objects, nice > clean syntax etc. > > Our main requirement for tools we're going to use is rock-solid > stability. As one of our team-members puts it, "We want to use tools > that are stable, has many developer-years and thousands of user-years > behind them, and that we shouldn't worry about their _versions_." The > main reason for that is that we want to debug our own bugs, but not > the bugs in our tools. > > Our problem is - we yet have to find any example of high-traffic, > scalable web-site written entirely in Python. We know that YouTube is > a suspect, but we don't know what specific python web solution was > used there. > > TurboGears, Django and Pylons are all nice, and provides rich features > - probably too many for us - but, as far as we understand, they don't > satisfy the stability requirement - Pylons and Django hasn't even > reached 1.0 version yet. And their provide too thick layer - we want > something 'closer to metal', probably similar to web.py - > unfortunately, web.py doesn't satisfy the stability requirement > either, or so it seems. > > So the question is: what is a solid way to serve dynamic web pages in > python? Our initial though was something like python + mod_python + > Apache, but we're told that mod_python is 'scary and doesn't work very > well'. > > And althoughhttp://www.python.org/about/quotes/lists many big names > and wonderful examples, be want more details. E.g. our understanding > is that Google uses python mostly for internal web-sites, and > performance is far from perfect their. YouTube is an interesting > example - anybody knows more details about that? > > Your suggestions and comments are highly welcome! > > Best Regards, > Victor. Reddit.com was built with webpy, and it's amongst the top 1000 websites in volume of traffic. So if you liked it, go with it... I believe one of the authors of reddit is also webpy's developer. Luis From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon May 14 07:44:57 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 14 May 2007 13:44:57 +0200 Subject: __dict__ for instances? In-Reply-To: References: <46472764$0$23138$9b4e6d93@newsspool1.arcor-online.net> <46477c9d$0$1408$426a74cc@news.free.fr> Message-ID: <46484bb9$0$22850$426a74cc@news.free.fr> Ivan Voras a ?crit : > Bruno Desthuilliers wrote: > >>> "WARNING: "on_button_clicked" not callable or a tuple" >> Please post the relevant code and the full traceback. > > The code: > > Class W: > def __init__(self): > self.xml = gtk.glade.XML("glade/mainwin.glade") > self.window = self.xml.get_widget("mainwin") > self.xml.signal_autoconnect(self) > > w = W() > gtk.main() > > The error (not an exception, only the message appears and the handler > doesn't work): > > ** (finstall.py:7551): WARNING **: handler for 'on_button_next_clicked' > not callable or a tuple Is this the full message, or did you skip the preceding lines ? > (the file has some 20 lines, not 7551) > Is "finstall.py" the name of your file ? If yes, I'd suspect something wrong with your sys.path or like... From http Mon May 14 00:21:57 2007 From: http (Paul Rubin) Date: 13 May 2007 21:21:57 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <20070513160046.GC29172@v.igoro.us> <7x646wa9wz.fsf@ruckus.brouhaha.com> <7xfy608bkk.fsf@ruckus.brouhaha.com> <7xejlk3xpk.fsf@ruckus.brouhaha.com> Message-ID: <7xy7jsjaqi.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > password_is_correct is all ASCII. How do you know that? What steps did you take to ascertain it? Those are steps you currently don't have to bother with. From thorsten at thorstenkampe.de Fri May 25 08:08:04 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Fri, 25 May 2007 13:08:04 +0100 Subject: How to do this in python with regular expressions References: <1180093895.743196.75510@b40g2000prd.googlegroups.com> Message-ID: * Jia Lu (25 May 2007 04:51:35 -0700) > I'm trying to parsing html with re module. > [...] > Can anyone tell me how to do it with regular expression in python? Just don't. Use an HTML parser like BeautifulSoup From S.Mientki-nospam at mailbox.kun.nl Wed May 23 14:51:20 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Wed, 23 May 2007 20:51:20 +0200 Subject: Can I reference 1 instance of an object by more names ? rephrase In-Reply-To: <4654289a$0$2326$426a74cc@news.free.fr> References: <4654289a$0$2326$426a74cc@news.free.fr> Message-ID: hi Bruno, after study it carefully, it's much more complex than I thought (I can't understand it completely, which is of less importance). Your solution works great, but I need one little extension, which I can create, but just at the cost of a lot of code. Maybe you can give me another hint. > In the first case, this is *really* a binding, and that's one of the few > things that Python won't let you mess with. In the two last cases, it's > in fact a method call - as the use of __[get|set]item__ should make > obvious. > > here's an example using a property: > > class cpu_ports(object): > def __init__(self, value=0): > self._d = value > @apply > def value(): > def fset(self, value): > print 'vv' > self._d = value > def fget(self): > return self._d > return property(**locals()) # I need to read and write the individual bits of the byte object # so I can create 8 blocks of code like this, one for each bit position # I use it, like this # name1 = cpu_ports() # name1.p5 = True # or # name1.p[5] = True @apply # read / write bit 5 def p5(): def fset(self, value): index = 5 value = ( value & 1L ) << index mask = ( 1L ) << index self._d = ( self._d & ~mask ) | value def fget(self): index = 5 return ( self._d >> index ) & 1 return property(**locals()) I can optimize the above code a little bit, but I've the feeling that I don't need to repeat this code 8 times. cheers, Stef Mientki From rw at smsnet.pl Wed May 9 17:10:12 2007 From: rw at smsnet.pl (Rob Wolfe) Date: Wed, 09 May 2007 23:10:12 +0200 Subject: Unzip then Zip help References: <1178739362.137264.251600@e65g2000hsc.googlegroups.com> Message-ID: <87lkfxsnyj.fsf@merkury.smsnet.pl> sdoty044 at gmail.com writes: > I am a true n00b... and I just using Python to complete some very > small uneventful task, but need help with one last thing. > > Basically, this I what I am trying to do. > > make a temp directory (this part I can do) > > Need help with: > ***unzip a JAR file with the complete list of subdirectories w/ > files**** > > modify the a set of XML files (this part I can do) > > Need help with: > ***then zip the entire contents of the temp directory with sub > directories*** > > The only thing I am having trouble with is the whole directory stuff, > if this was just straight files, no problem. > > Any help would be appreciated > Try this: import os from os.path import dirname, exists, splitext, join from zipfile import ZipFile, ZIP_DEFLATED def unpack(archname): arch = ZipFile(archname, 'r') for path in arch.namelist(): print path dname = dirname(path) if not exists(dname): os.makedirs(dname) if splitext(path)[1]: f = open(path, 'wb') f.write(arch.read(path)) f.close() arch.close() def pack(archname, paths): arch = ZipFile(archname, 'w', ZIP_DEFLATED) for path in paths: for root, dirs, files in os.walk(path): for fname in files: fname = join(root, fname) print fname arch.write(fname) arch.close() unpack('test.jar') pack('test2.jar', ['com', 'META-INF']) -- HTH, Rob From apatheticagnostic at gmail.com Tue May 29 19:25:38 2007 From: apatheticagnostic at gmail.com (kaens) Date: Tue, 29 May 2007 19:25:38 -0400 Subject: updates in sqlite3 do not work In-Reply-To: <1068189.31888.BlRUCl8VTQA=.1180478638.squirrel@webmailer.hosteurope.de> References: <723eb6930705291530w190a7818i71f49d976217f38@mail.gmail.com> <1068189.31888.BlRUCl8VTQA=.1180478638.squirrel@webmailer.hosteurope.de> Message-ID: <163f0ce20705291625i30c6eb83naae6b585366a057b@mail.gmail.com> On 5/29/07, Stefan Sonnenberg-Carstens wrote: > Did you try a commit() ? > > SQLite3 works in autocommit mode by default, > so it would help to see your code. > > > On Mi, 30.05.2007, 00:30, Chris Fonnesbeck wrote: > > I have a script set up to perform UPDATE commands on an sqlite database > > using the sqlite3 module. Everything appears to run fine (there are no > > error > > messages), except that none of the UPDATE commands appear to have actually > > updated the table. If I run each command on its own in a sqlite session, > > the > > UPDATE command works fine, so it is not a SQL syntax issue. UPDATE simply > > seems not to work. Any idea what the problem might be? > > > > Thanks, > > Chris > > -- > > http://mail.python.org/mailman/listinfo/python-list > > -- > http://mail.python.org/mailman/listinfo/python-list > As the other people said, you need to issue db.commit() (or whatever you're database variable is). I just ran into this after converting a MyISAM table to InnoDB, and was annoyed as crap for a while, until I found out that you need to explicitly commit on InnoDB tables, then I felt stupid. I was using MySQLdb, not sqlite3, but I'm sure it's got right around the same functionality. From stefan.behnel-n05pAM at web.de Sun May 13 15:01:21 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sun, 13 May 2007 21:01:21 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <46476081.7080609@web.de> Anton Vredegoor wrote: >> In summary, this PEP proposes to allow non-ASCII letters as >> identifiers in Python. If the PEP is accepted, the following >> identifiers would also become valid as class, function, or >> variable names: L?ffelstiel, chang?, ??????, or ??? >> (hoping that the latter one means "counter"). > > I am against this PEP for the following reasons: > > It will split up the Python user community into different language or > interest groups without having any benefit as to making the language > more expressive in an algorithmic way. We must distinguish between "identifiers named in a non-english language" and "identifiers written with non-ASCII characters". While the first is already allowed as long as the transcription uses only ASCII characters, the second is currently forbidden and is what this PEP is about. So, nothing currently keeps you from giving names to identifiers that are impossible to understand by, say, Americans (ok, that's easy anyway). For example, I could write def zieheDreiAbVon(wert): return zieheAb(wert, 3) and most people on earth would not have a clue what this is good for. However, someone who is fluent enough in German could guess from the names what this does. I do not think non-ASCII characters make this 'problem' any worse. So I must ask people to restrict their comments to the actual problem that this PEP is trying to solve. Stefan From aboudouvas at panafonet.gr Tue May 22 11:23:17 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 22 May 2007 08:23:17 -0700 Subject: 'int' object is not callable in an threaded app Message-ID: <1179847397.417381.269570@a26g2000pre.googlegroups.com> Hi, i have a problem with the following piece of code that id just drive me nuts (from the morning...) I think is more Python specific than Qt, folks from Qt forum have already give me directions of how to do it but that Python error message is just impossible for me to figure out. And i am sure that it something just under my nose... So, i have a form with 2 spin boxes, a button and a progress bar. When i hit the button i expect to see the progressbar filled with the values of spFrom and spTo (the 2 spinboxes) I was given help if how to setup correctly the Signals and Slots mechanism but i am stuck at this Python error at the "worker.start()" command: TypeError: 'int' object is not callable Before i go and suicide, has anybody an idea what is going on here ??... import sys from PyQt4 import QtCore, QtGui from calculatorform_ui import Ui_CalculatorForm from ui_countNumbers import Ui_MainWindow from time import sleep class WorkerThread(QtCore.QThread): def __init__(self, start, end): QtCore.QThread.__init__(self) self.start = start self.end = end def run(self): for x in range(start, end): self.emit(QtCore.SIGNAL("updateProgress"), x) class CountNumbersForm(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) @QtCore.pyqtSignature("") def on_start_clicked(self): worker.start() def updateProgress(self, val): self.ui.progres.setValue(val) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) count = CountNumbersForm(); worker = WorkerThread(count.ui.spFrom.value(), count.ui.spTo.value() + 1); QtCore.QObject.connect(worker, QtCore.SIGNAL("updateProgress"), count.updateProgress, QtCore.Qt.QueuedConnection) count.show() sys.exit(app.exec_()) From whamil1 at entergy.com Wed May 30 17:59:04 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Wed, 30 May 2007 16:59:04 -0500 Subject: c[:]() Message-ID: <588D53831C701746A2DF46E365C018CE01D2CAB6@LITEXETSP001.etrsouth.corp.entergy.com> > From: Warren Stringer > Hmmm, this is for neither programmer nor computer; this is for a user. If > I > wanted to write code for the benefit for the computer, I'd still be > flipping > switches on a PDP-8. ;-) > > This is inconsistent: > > why does c[:][0]() work but c[:]() does not? > Why does c[0]() has exactly the same results as c[:][0]() ? > Moreover, c[:][0]() implies that a slice was invoked c[:] is a copy of c, if c is a list, tuple, string, or other object that supports slicing. c[:][0] points to the same object as c[0]. If that object is a function, then c[:][0]() and c[0]() do the same thing, because they both point to the same function. c[:]() does not make sense, because c is a tuple and not a function. Similarly, c[0:1]() will not make sense because while c is a tuple of one object, it is still a tuple and not a function. Note that c[0] is not the same as c[0:1]: the former is the object pointed to by the first member of the tuple, while the second is a tuple containing a single member pointing to the first member of the original tuple. There isn't an inconsistency because the two notations mean completely different things. > So, tell me, for scheduling a lot of asynchronous events, what would be > more > readable than this: > > bidders = [local_members] + [callin_members] > bidders[:].sign_in(roster) > ... Does bidders[:].sort() make sense? In your scheme, would this tell the various contents of bidders to sort their own contents, or would it do the currently valid action of sorting a copy of the bidders list? I think you misunderstand how the slice operator works. A slice of a tuple is itself a tuple. If you want to act on the contents of that tuple, you need to act on those contents individually either by indexing them (c[0]) or iterating over them (for f in c:). -- -Bill Hamilton From george.sakkis at gmail.com Wed May 23 17:01:22 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 23 May 2007 14:01:22 -0700 Subject: Parallel/distributed generator In-Reply-To: <5bjee5F2qu0euU1@mid.uni-berlin.de> Message-ID: <1179954082.823582.313470@q69g2000hsb.googlegroups.com> On May 23, 2:11 pm, "Diez B. Roggisch" wrote: > George Sakkis wrote: > > I'm looking for any existing packages or ideas on how to implement the > > equivalent of a generator (in the Python sense, i.e. > >http://www.python.org/dev/peps/pep-0255/) in a parallel/distributed > > way. As a use case, imagine a function that generates a range of > > primes. I'd like to be able to do something along the following lines: > > > def iterprimes(start=1, end=None): > > # ... > > yield prime > > > # rpc-related initialization > > ... > > rpc_proxy = some_rpc_lib(iterprimes, start=1e6, end=1e12) > > for prime in proxy: > > print prime > > > Is there any module out there that does anything close to this ? > > Have you tried using pyro to just return a generator? After all, it's just > an object with a next()-method, that raises a certain exception. I can't > see why pyro shouldn't be able to handle that. Just tried it: cPickle.PicklingError: Can't pickle : attribute lookup __builtin__.generator failed George From steve at REMOVEME.cybersource.com.au Wed May 2 23:38:01 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Thu, 03 May 2007 13:38:01 +1000 Subject: SEO - Search Engine Optimization - Seo Consulting References: <1177808356.681710.42980@n76g2000hsh.googlegroups.com> <#O8fXGAjHHA.3700@TK2MSFTNGP06.phx.gbl> <1178160448.699851.227600@p77g2000hsh.googlegroups.com> Message-ID: On Wed, 02 May 2007 19:47:28 -0700, Huck Phin wrote: > I understand how top posting is annoying, and when you check any > usenet group message, everyone seems to just jump at the chance to > yell at someone for doing it. What I do not understand is how > everyone is attacking the top poster, and not the spammer. It seems > that the real issue of this post is not being addressed. Spammers don't hang around to read replies to their garbage, and even if they did, asking them to stop is almost as pointless as writing a letter to newspapers saying "Dear muggers, burglars and other criminals, please stop, pretty please with sugar on top". Has *any* spammer ever said "Oh gosh, somebody asked me to stop flooding Usenet with ads for my crappy products and pyramid scams, I guess I'll have to go out and get a real job now"? As it turns out, my ISP does a reasonably good job of filtering spam from this newsgroup, and I never received the original message. I wouldn't have see it at all except Alvin Bruney [MVP] (Most Valuable Player? Minimum Viable Population? Mitral Valve Prolapse?) replied to it, AND KEPT THE ORIGINAL SPAM IN HIS EMAIL. Excuse the shouting. In other words, Bruney himself forwarded that spam on to potentially millions of people who never would have seen it except for his stupidity and laziness. You know, if I were more evil, and wanted to spam people, I would write my spam ("By these stocks, their realy kool!!! Get tehm before the prise tripples!!!"), then quote it and add a completely false "Please don't spam" message and send it out. I'd get my spam out there, and millions of people would think I was the good guy. Or, for that matter, if I wanted to spam half a dozen newsgroups about, say, my .Net book on Lulu... It's no worse than other spammer tricks. > We all should be a little more considerate of each other. And if the hippy hug fest fails to stop spamming, perhaps we'll be allowed to hunt them down like rabid dogs and stick their heads up on pikes as a warning to others. Hey, a man can dream can't he??? *wink* -- Steven D'Aprano From bulliver at badcomputer.org Sun May 27 12:00:51 2007 From: bulliver at badcomputer.org (darren kirby) Date: Sun, 27 May 2007 10:00:51 -0600 Subject: PHP5 programmer learning Python In-Reply-To: <1180280496.946434.26760@q69g2000hsb.googlegroups.com> References: <1180280496.946434.26760@q69g2000hsb.googlegroups.com> Message-ID: <200705271000.51967.bulliver@badcomputer.org> quoth the romiro: > Hi all, ... > Anyway, my first question was if anyone knows of a tutorial that > focuses on PHP -> Python learning, in such that there might be a block > of PHP code alongside an example of how to do the same thing in > Python. One example of something I've already mapped a comparison to > thanks to standard tutorials is a PHP numeric indexed array being > similar to a list and a PHP associative array being similar to a > dictionary. Of course finding such of a tutorial isn't a deal breaker > by any means, but I figured that having it available would be a boon > for me to actually make some headway in my Python learning adventure. Not a tutorial, and the code is not alongside each other, but the PLEAC [1] website may serve as a decent code comparison between PHP and Python. As for a tutorial, if you are already experienced you will probably want to check out "Dive into Python. [2] Have fun, -d [1] http://pleac.sourceforge.net/ [2] http://diveintopython.org/toc/index.html -- 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 aleax at mac.com Mon May 7 10:39:24 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 7 May 2007 07:39:24 -0700 Subject: how do you implement a reactor without a select? References: <1178543812.260333.39280@w5g2000hsg.googlegroups.com> Message-ID: <1hxqfgq.4sjxga1dz7vv3N%aleax@mac.com> Michele Simionato wrote: > I wonder if real mainloops are done in this way and how bad/good is > this implementation compared to a serious one. Any suggestion/hint/ > advice is well appreciated. Thanks, Module sched in Python's standard library may suggest one clearly-better approach: when you know in advance when future events are scheduled for, sleep accordingly (rather than polling every millisecond). sched's sources are simple enough to study, and its architecture clean and strong enough that it's easy to extend to other cases, e.g. where previously-unscheduled events may be delivered from other threads, without necessarily hacking the sources. Specifically, sched implements the Dependency Injection DP: rather than just calling time.time and time.sleep, it accepts those two callables upon initialization. This makes it easy, among many other customizations, to pass instead of time.sleep a user-coded callable (typically a bound method) that "sleeps" by a wait-with-timeout on a Queue (so that other threads, by putting an event on the Queue in question, immediately wake up the scheduler, etc, etc). Alex From michael at jedimindworks.com Thu May 17 19:40:34 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Thu, 17 May 2007 18:40:34 -0500 Subject: How to convert a number to binary? In-Reply-To: <1179444832.775573.55830@y80g2000hsf.googlegroups.com> References: <1179444832.775573.55830@y80g2000hsf.googlegroups.com> Message-ID: <26096503-5E35-4C0C-A93A-64E5E4AAAFB8@jedimindworks.com> On May 17, 2007, at 6:33 PM, Lyosha wrote: > Converting binary to base 10 is easy: >>>> int('11111111', 2) > 255 > > Converting base 10 number to hex or octal is easy: >>>> oct(100) > '0144' >>>> hex(100) > '0x64' > > Is there an *easy* way to convert a number to binary? def to_base(number, base): 'converts base 10 integer to another base' number = int(number) base = int(base) if base < 2 or base > 36: raise ValueError, "Base must be between 2 and 36" if not number: return 0 symbols = string.digits + string.lowercase[:26] answer = [] while number: number, remainder = divmod(number, base) answer.append(symbols[remainder]) return ''.join(reversed(answer)) Hope this helps, Michael --- "I would rather use Java than Perl. And I'd rather be eaten by a crocodile than use Java." ? Trouser From charl.loubser at gmail.com Sat May 5 04:46:54 2007 From: charl.loubser at gmail.com (Merrigan) Date: 5 May 2007 01:46:54 -0700 Subject: progress Message-ID: <1178354814.884102.194790@q75g2000hsh.googlegroups.com> Hi All, I have posted yesterday about an ftplib issue, this has been resolved. I actually want to ask something here... The script that that ftplib error was from...I was wondering - What do I need to do to print the stats (speed/s, percentage done) of the upload that is running on the monitor. This script runs on a Fedora Machine. Thanx for the help guys! -- Merrigan From kyosohma at gmail.com Mon May 7 10:18:37 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 7 May 2007 07:18:37 -0700 Subject: Can Python Parse an MS SQL Trace? In-Reply-To: References: <1178544236.856685.288740@y80g2000hsf.googlegroups.com> Message-ID: <1178547517.938939.201490@w5g2000hsg.googlegroups.com> On May 7, 8:34 am, Tim Golden wrote: > kyoso... at gmail.com wrote: > > Can Python parse a trace file created with MS SQL's profiler? There > > are a few thousand lines in the trace file and I need to find the > > insert statements and the stored procedures. Unfortunately, I am not > > an SQL guru and was hoping Python could help. > > Mike > > Mike, > > Can I suggest that, since the answer is more to > do with parsing and less to do with MSSQL (which > simply generated the output) that you post an example > of a trace file to some web location to see if anyone > wants to pick up the challenge? > > I'm not at work so I don't have access to MSSQL, but > I seem to remember that you can output/save as XML, > which may make things easier (or at least interest a > different group of people in having a look). > > I'm quite certain it can by done by Python; I did > consider it myself a couple of months back, but my > colleague spotted the problem before I'd really got > into the code! > > TJG Good point. Unfortunately, I think our SQL Server must be too old for xml (we have version 8). The only save options I see is Trace Template, Trace File, Trace Table and SQL Script. Mike From ramashish.lists at gmail.com Tue May 29 13:20:27 2007 From: ramashish.lists at gmail.com (Ramashish Baranwal) Date: 29 May 2007 10:20:27 -0700 Subject: How to set a class inheritance at instance creation? In-Reply-To: <1180453971.556244.91370@q69g2000hsb.googlegroups.com> References: <1180453971.556244.91370@q69g2000hsb.googlegroups.com> Message-ID: <1180459227.403312.176370@j4g2000prf.googlegroups.com> On May 29, 8:52 pm, glomde wrote: > Hi I wonder if you can set what subclass a class should > have at instance creation. > > The problem is that I have something like: > > class CoreLang(): > def AssignVar(self, var, value): > pass > > class Lang1(CoreLang): > def AssignVar(self, var, value): > return var, "=", value > > class Lang2(CoreLang): > def AssignVar(self, var, value): > return var, "<=", value > > class WriteStruct(): > def Generate(self, vars): > for var in vars: > print self.AssignVar() > > The problem is that I want WriteStruct to sometimes be a subclass of > Lang1 and sometimes > of Lang2. > In the above example I could but the Generate Method in CoreLang. But > in my real > example I also want to able to subclass WriteStruct to be able to easy > customize WriteStruct. > Which I wouldnt be able to do if it was a method in CoreLang. > > So in code I would like to write something like: > > WriteStruct(Lang1).Generate(vars) class WriteStruct: def __init__(self, SubClass): self._sub = SubClass() def Generate(self, vars): for var in vars: print self._sub.AssignVar() This does what you want but isn't inheritance. > Even better would be that if I in the Lang1 class could > just do WriteStruct().Generate(vars) and Lang1 class would > magically make WriteStruct a subclass of itself. > I don't think I understood what you want here. Ram From vatamane at gmail.com Wed May 9 20:07:46 2007 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 9 May 2007 17:07:46 -0700 Subject: Questions about bsddb In-Reply-To: <1178740902.495700.60310@p77g2000hsh.googlegroups.com> References: <1178713407.968873.260950@n59g2000hsh.googlegroups.com> <1178720648.233560.319570@p77g2000hsh.googlegroups.com> <1178740902.495700.60310@p77g2000hsh.googlegroups.com> Message-ID: <1178755666.788336.232640@h2g2000hsg.googlegroups.com> On May 9, 4:01 pm, sinoo... at yahoo.com wrote: > Thanks for the info Nick. I plan on accessing the data in pretty much > random order, and once the database is built, it will be read only. > At this point Im not too concerned about access times, just getting > something to work. I've been messing around with both bt and hash with > limited success, which led me to think that maybe I was going beyond > some internal limit for the data size.It works great on a limited set > of data, but once I turn it loose on the full set, usually several > hours later, it either causes a hard reset of my machine or the HD > grinds on endlessly with no apparent progress. Is there a limit to > the size of data you can place per key? > > Thanks for the MySQL suggestion, I'll take a look. > > -JM JM, If you want, take a look at my PyDBTable on www.psipy.com. The description and the examples section is being finished but the source API documentation will help you. It is a fast Python wrapper around MySQL, PostgreSQL or SQLite. It is very fast and buffers queries and insertions. You just set up the database and then pass the connection parameters to the initializer method. After that you can use the pydb object as a dictionary of { primary_key : list_of_values }. You can even create indices on individual fields and query with queries like : --------------------------------------------------------------------------------------------------------- pydb.query( ['id','data_field1'], ('id','<',10), ('data_field1','LIKE','Hello%') ) -------------------------------------------------------------------------------------------------------- Which will translate into the SQL query like : ---------------------------------------------------------------------------------------------------------------------- SELECT id, data_field1 FROM ... WHERE id<10 AND data_field1 LIKE 'Hello %' ---------------------------------------------------------------------------------------------------------------------- and return an __iterator__. The iterator as a the result is excellent because you can iterate over results much larger than your virtual memory. But in the background PyDBTable will retrieve rows from the database in large batches and cache them as to optimise I/O. Anyway, on my machine PyDBTable saturates the disk I/O (it runs as fast as a pure MySQL query). Take care, -Nick Vatamaniuc From dontemailme at ntlworld.com Tue May 1 14:08:36 2007 From: dontemailme at ntlworld.com (funfly3) Date: Tue, 01 May 2007 18:08:36 GMT Subject: SEO - Search Engine Optimization - Seo Consulting In-Reply-To: <#O8fXGAjHHA.3700@TK2MSFTNGP06.phx.gbl> References: <1177808356.681710.42980@n76g2000hsh.googlegroups.com> <#O8fXGAjHHA.3700@TK2MSFTNGP06.phx.gbl> Message-ID: David wrote: > I am not going to join the argument, except you have except to say that as you can see, I > top post. In outlook express, you can see the messages as a thread, so you > read the initial message, come to the reply and you read the response > without having to scroll. Bottom posting would be fine if the previous > message that promted the response was removed from the server, but it isn't, > therefore, top posting is very logical. > only of you top post its logical as we all don't top post its not A bird Q name an animal that fly's see top posting is illogical From nagle at animats.com Wed May 9 13:02:15 2007 From: nagle at animats.com (John Nagle) Date: Wed, 09 May 2007 17:02:15 GMT Subject: Towards faster Python implementations - theory In-Reply-To: <1178705421.711371.182770@e65g2000hsc.googlegroups.com> References: <1210i.7468$2v1.2505@newssvr14.news.prodigy.net> <1178705421.711371.182770@e65g2000hsc.googlegroups.com> Message-ID: Paul Boddie wrote: > On 9 May, 08:09, "Hendrik van Rooyen" wrote: > >>I am relatively new on this turf, and from what I have seen so far, it >>would not bother me at all to tie a name's type to its first use, so that >>the name can only be bound to objects of the same type as the type >>of the object that it was originally bound to. > > > But it's interesting to consider the kinds of names you could restrict > in this manner and what the effects would be. In Python, the only kind > of name that can be considered difficult to arbitrarily modify "at a > distance" - in other words, from outside the same scope - are locals, > and even then there are things like closures and perverse > implementation-dependent stack hacks which can expose local namespaces > to modification, although any reasonable "conservative Python" > implementation would disallow the latter. Modifying "at a distance" is exactly what I'm getting at. That's the killer from an optimizing compiler standpoint. The compiler, or a maintenance programmer, looks at a block of code, and there doesn't seem to be anything unusual going on. But, if in some other section of code, something does a "setattr" to mess with the first block of code, something unusual can be happening. This is tough on both optimizing compilers and maintenance programmers. Python has that capability mostly because it's free in an "everything is a dictionary" implementation. ("When all you have is a hash, everything looks like a dictionary".) But that limits implementation performance. Most of the time, nobody is using "setattr" to mess with the internals of a function, class, or module from far, far away. But the cost for that flexibility is being paid, unnecessarily. I'm suggesting that the potential for "action at a distance" somehow has to be made more visible. One option might be a class "simpleobject", from which other classes can inherit. ("object" would become a subclass of "simpleobject"). "simpleobject" classes would have the following restrictions: - New fields and functions cannot be introduced from outside the class. Every field and function name must explicitly appear at least once in the class definition. Subclassing is still allowed. - Unless the class itself uses "getattr" or "setattr" on itself, no external code can do so. This lets the compiler eliminate the object's dictionary unless the class itself needs it. This lets the compiler see all the field names and assign them fixed slots in a fixed sized object representation. Basically, this means simple objects have a C/C++ like internal representation, with the performance that comes with that representation. With this, plus the "Shed Skin" restrictions, plus the array features of "numarray", it should be possible to get computationally intensive code written in Python up to C/C++ levels of performance. Yet all the dynamic machinery of Python remains available if needed. All that's necessary is not to surprise the compiler. John Nagle From showell30 at yahoo.com Sun May 27 02:30:37 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sat, 26 May 2007 23:30:37 -0700 (PDT) Subject: ten small Python programs In-Reply-To: Message-ID: <580542.54794.qm@web33509.mail.mud.yahoo.com> --- Steven D'Aprano wrote: > On Sat, 26 May 2007 18:48:45 -0700, Steve Howell > wrote: > > > It also has a ComplexNumber class, but I don't > want to > > scare away mathphobes. > > Is it as short as this one-liner? > > ComplexNumber = complex > The "It" above refers to *the* Python Tutorial, written by Guido van Rossum. Here is an excerpt: >>> class Complex: ... def __init__(self, realpart, imagpart): ... self.r = realpart ... self.i = imagpart ... >>> x = Complex(3.0, -4.5) >>> x.r, x.i (3.0, -4.5) Obviously, it's not surprising that a useful class in a tutorial would have a corresponding implementation in the standard library, but I'm not sure newbies would learn much about classes from this statement: ComplexNumber = complex ____________________________________________________________________________________ Need Mail bonding? Go to the Yahoo! Mail Q&A for great tips from Yahoo! Answers users. http://answers.yahoo.com/dir/?link=list&sid=396546091 From mangabasi at gmail.com Wed May 23 14:22:55 2007 From: mangabasi at gmail.com (Mangabasi) Date: 23 May 2007 11:22:55 -0700 Subject: Inheriting from Python list object(type?) In-Reply-To: Message-ID: <1179944575.618308.107320@q66g2000hsg.googlegroups.com> On May 23, 12:47 pm, "Jerry Hill" wrote: > On 23 May 2007 09:58:36 -0700, Mangabasi wrote: > > > There must be a way to inherit from the list type without having to > > redefine all the methods and attributes that regular lists have. > > Like this: > > class Point(list): > def __init__(self, x, y, z = 1): > list.__init__(self, [x, y, z]) > > def __getattr__(self, name): > if name == 'x': return self[0] > if name == 'y': return self[1] > if name == 'z': return self[2] > > def __setattr__(self, name, value): > if name == 'x': self[0] = value > if name == 'y': self[1] = value > if name == 'z': self[2] = value > > Does that show you what you need? > > -- > Jerry Hi Jerry, It is very close. It worked for many operations except when I tried >>> from numpy import array >>> p = Point(4,5) >>> a = array(p) Traceback (most recent call last): File "", line 1, in ? ValueError: invalid __array_struct__ >>> a = array([4, 5, 1]) >>> I can define an __array__ method for this to work but I am wondering if we can make this behave like a real list? Thanks for your help. From 2007 at jmunch.dk Mon May 14 12:15:44 2007 From: 2007 at jmunch.dk (Anders J. Munch) Date: Mon, 14 May 2007 18:15:44 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> Message-ID: <46488bce$0$4159$ba624c82@nntp02.dk.telia.net> Hendrik van Rooyen wrote: > And we have been through the Macro thingy here, and the consensus > seemed to be that we don't want people to write their own dialects. Macros create dialects that are understood only by the three people in your project group. It's unreasonable to compare that to a "dialect" such as Mandarin, which is exclusive to a tiny little clique of one billion people. - Anders From larry.bates at websafe.com Wed May 16 11:26:37 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 16 May 2007 10:26:37 -0500 Subject: remove all elements in a list with a particular value In-Reply-To: <1179328873.105705.95580@l77g2000hsb.googlegroups.com> References: <1179328873.105705.95580@l77g2000hsb.googlegroups.com> Message-ID: <464B22AD.5050103@websafe.com> Lisa wrote: > I am reading in data from a text file. I want to enter each value on > the line into a list and retain the order of the elements. The number > of elements and spacing between them varies, but a typical line looks > like: > > ' SRCPARAM 1 6.35e-07 15.00 340.00 1.10 3.0 ' > > Why does the following not work: > > line = ' SRCPARAM 1 6.35e-07 15.00 340.00 1.10 3.0 ' > li = line.split(' ') > for j,i in enumerate(li): > if i == '': > li.remove(i) > > After the original split I get: > ['', '', '', 'SRCPARAM', '', '', '1', '6.35e-07', '15.00', '', > '340.00', '', '', '1.10', '', '', '', '', '', '3.0', '', '', ''] > > And after the for loop I get: > ['SRCPARAM', '1', '6.35e-07', '15.00', '340.00', '1.10', '', '', '', > '3.0', '', '', ''] > > It doesn't remove all of the empty elements. Is there a better way to > split the original string? Or a way to catch all of the empty > elements? > > Thanks > When you split on a space (' ') multiple spaces will return empty list elements between them. Change to: line = ' SRCPARAM 1 6.35e-07 15.00 340.00 1.10 3.0 ' li = line.split() And you will get what you want: ['SRCPARAM', '1', '6.35e-07', '15.00', '340.00', '1.10', '3.0'] -Larry From mail at microcorp.co.za Sat May 26 03:13:09 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 26 May 2007 09:13:09 +0200 Subject: Reading a file and resuming reading. References: Message-ID: <005a01c79f65$5148fe80$03000080@hendrik> "Karim Ali" wrote: > Hi, > > Simple question. Is it possible in python to write code of the type: > > ----------------------------- > while not eof <- really want the EOF and not just an empty line! readline() reads to the next newline - an empty line *is* EOF - a blank line has at least a newline. > readline by line > end while; > ----------------------------- > > What I am using now is the implicit for loop after a readlines(). I don't > like this at all as a matter of opinion (my background is C++). > use readline() in a while true loop, or iterate over the file. > But also, in case for one reason or another the program crashes, I want to > be able to rexecute it and for it to resume reading from the same position > as it left. If a while loop like the one above can be implemented I can do > this simply by counting the lines! Biggest problem is saving the count so that you can get at it again after the crash You could write to a file and flush and close after every line, but if there is a crash, you have no guarantee that you will get the exact place back, and whatever you are doing with the lines could get a duplicate or two if you recover automatically after the crash. - it depends on what your OS does to keep buffers in ram and data on disk congruent. Overwriting the file like this is dangerous also as the crash could come after the OS has deleted the directory entry, before making the new file, so you could end with nothing saved... You could also keep a more detailed journal, with entries like: I am going to read line 0 I have successfully read line 0 I have processed line 0 I am going to write the output of line 0 I have written the output of line 0 I am going to read line 1 etcetera... You do this by opening and closing the journal file in append mode for every entry in it. Even with this, it can get tricky, because there is the same uncertainty referred to earlier - but you could get close. Have a look at databases and commit - they are made to solve this exact problem. Is there not another way to see how far you actually got, by examining the output? Is it not easier to simply start again and do the whole job over, after turfing the output? Why bother about it at all - if you can use readlines, it means the file fits into memory now - so it is not humongous, so it is probably not "that" expensive to just do it all over. I suppose it depends on what it is you are actually trying to achieve. HTH - Hendrik From aleax at mac.com Fri May 4 10:55:25 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 4 May 2007 07:55:25 -0700 Subject: My Python annoyances References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> <1178202431.147195.249790@u30g2000hsc.googlegroups.com> Message-ID: <1hxkwj0.12jtj1v3b522bN%aleax@mac.com> Ben Collver wrote: > Chris Mellon wrote: > > You should "check" for the methods by calling them. If the object > > doesn't support the method in question, you will get a runtime > > exception. Premature inspection of an object is rarely useful and > > often outright harmful. > > That makes sense, thank you for the response. > > What about the case where I have an array of objects that represent some > particular binary file format. If the object is a file, then I want to > copy its contents. If the object is a string, then I want to write the > string. And so forth. "Type-switching" in this way is a rather dubious practice in any language (it can't respect the "open-closed" principle). Can't you have those objects wrapped in suitable wrappers with a "copyorwrite" method that knows what to do? For example, StringIO.StringIO is a standard library wrapper type that makes a string look like a file. It's a reasonable request you can make to whatever code is putting stuff in that container: make the container "weakly homogeneous" by having it stuffed only with "suitably file-like" objects. Dealing with totally and weirdly heterogeneous containers is not a sensible task, because there will be infinite types that COULD be in the container and about which your code just can't be expected to guess right what to do. Alex From rrr at ronadam.com Thu May 10 07:42:45 2007 From: rrr at ronadam.com (Ron Adam) Date: Thu, 10 May 2007 06:42:45 -0500 Subject: PYDOC replacement. (Was:Sorting attributes by catagory) In-Reply-To: <1178786444.529360.195910@h2g2000hsg.googlegroups.com> References: <1178755860.993987.312700@e51g2000hsg.googlegroups.com> <1178786444.529360.195910@h2g2000hsg.googlegroups.com> Message-ID: Nick Vatamaniuc wrote: > Thanks for the info, Ron. I had no idea pydoc was that powerful! > -Nick Change *was* to *will be*. It really needed to be re factored. ;-) Cheers, Ron From carsten at uniqsys.com Fri May 11 17:07:22 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 11 May 2007 17:07:22 -0400 Subject: Interesting list Validity (True/False) In-Reply-To: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> Message-ID: <1178917642.1820.33.camel@dot.uniqsys.com> On Fri, 2007-05-11 at 12:28 -0700, nufuhsus at gmail.com wrote: > Hello all, > > First let me appologise if this has been answered but I could not find > an acurate answer to this interesting problem. > > If the following is true: > C:\Python25\rg.py>python > 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. > >>> [] == [] > True > >>> ['-o'] == [] > False > >>> ['-o'] == False > False > >>> Your confusion stems from the fact that for a given object, the answer to the following three questions can be vastly different: a) Is the object identical to True? b) Is the object equal to True? c) Is the object considered to be True in an "if" statement? Observe: >>> def check_trueness(obj): ... if obj is True: print repr(obj), "is identical to True." ... else: print repr(obj), "is not identical to True." ... if obj == True: print repr(obj), "is equal to True." ... else: print repr(obj), "is not equal to True." ... if obj: print repr(obj), "is considered to be True by if." ... else: print repr(obj), "is not considered to be True by if." ... >>> check_trueness(True) True is identical to True. True is equal to True. True is considered to be True by if. >>> check_trueness(1) 1 is not identical to True. 1 is equal to True. 1 is considered to be True by if. >>> check_trueness([1]) [1] is not identical to True. [1] is not equal to True. [1] is considered to be True by if. >>> check_trueness([]) [] is not identical to True. [] is not equal to True. [] is not considered to be True by if. Testing whether an object is equal to True is a much stronger test than whether it is considered to be True in an 'if' statement, and the test for identity is stronger still. Testing whether an object is equal to True or identical to True is useless in most Python programs. So, rather than doing this: if thing==True: # blah Just do this: if thing: # blah Hope this helps, -- Carsten Haese http://informixdb.sourceforge.net From arkanes at gmail.com Fri May 4 08:49:42 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 4 May 2007 07:49:42 -0500 Subject: Why are functions atomic? In-Reply-To: <1178260571.160570.299160@p77g2000hsh.googlegroups.com> References: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> <1178044821.864741.235260@o5g2000hsb.googlegroups.com> <1178063341.779617.289690@o5g2000hsb.googlegroups.com> <1178065685.161372.81790@y80g2000hsf.googlegroups.com> <1178083318.404304.76100@q75g2000hsh.googlegroups.com> <1178260571.160570.299160@p77g2000hsh.googlegroups.com> Message-ID: <4866bea60705040549t413bdfcfs3c7c56ca7a791bed@mail.gmail.com> On 3 May 2007 23:36:11 -0700, Michael wrote: > On May 2, 6:08 am, Carsten Haese wrote: > > On Tue, 2007-05-01 at 22:21 -0700, Michael wrote: > > > Is there a reason for using the closure here? Using function defaults > > > seems to give better performance:[...] > > > > It does? Not as far as I can measure it to any significant degree on my > > computer. > > I agree the performance gains are minimal. Using function defaults > rather than closures, however, seemed much cleaner an more explicit to > me. For example, I have been bitten by the following before: > > >>> def f(x): > ... def g(): > ... x = x + 1 > ... return x > ... return g > >>> g = f(3) > >>> g() > Traceback (most recent call last): > File "", line 1, in > File "", line 3, in g > UnboundLocalError: local variable 'x' referenced before assignment > > If you use default arguments, this works as expected: > >>> def f(x): > ... def g(x=x): > ... x = x + 1 > ... return x > ... return g > >>> g = f(3) > >>> g() > 4 > You aren't getting "bit" by any problem with closures - this is a syntax problem. Assigning to x within the scope of g() makes x a local variable. x = x+1 doesn't work, then, because "x+1" can't be evaluated. If you just used "return x+1" or if you named the local variable in g something other than "x", the closure approach would also work as expected. From martin at v.loewis.de Tue May 8 02:41:31 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 08 May 2007 08:41:31 +0200 Subject: getmtime differs between Py2.5 and Py2.4 In-Reply-To: <463fb305$0$326$e4fe514c@news.xs4all.nl> References: <463FA51D.1060600@v.loewis.de> <463fb305$0$326$e4fe514c@news.xs4all.nl> Message-ID: <46401B9B.1020705@v.loewis.de> > This is python 2.4.4 and Python 2.5.1 on windows XP. > The reported time clearly differs. Interesting. They don't for me: C:\temp>dir test_os.diff Volume in drive C has no label. Volume Serial Number is 7414-6FC4 Directory of C:\temp 04.04.2007 18:41 3.661 test_os.diff 1 File(s) 3.661 bytes 0 Dir(s) 5.595.955.200 bytes free Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.path.getmtime(r"c:\temp\test_os.diff") 1175704875 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 os >>> os.path.getmtime(r"c:\temp\test_os.diff") 1175704875.1825342 Is your file system FAT, by any chance? Regards, Martin From __peter__ at web.de Tue May 22 04:21:24 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 22 May 2007 10:21:24 +0200 Subject: Printing dots in sequence ('...') References: <1179820951.288587.142670@h2g2000hsg.googlegroups.com> Message-ID: beertje wrote: > This is a very newbie question for my first post, perhaps > appropriately. > > I want to print '....' gradually, as a progress indicator. I have a > for-loop that every 10 steps executes: > print '.', > > This results in something like 'Loading. . . .', whereas I want > 'Loading....' > > A pet peeve, I can't for the life of me figure out how to get this > desired output. I love understatement. > How do I print dots - or anything for that matter - in > sequence without a space being inserted in between? >>> import sys, time >>> for i in range(10): ... sys.stdout.write(".") ... sys.stdout.flush() ... time.sleep(.1) ... ..........>>> write() does the writing, flush() is to defeat the buffering; without it the dots would be withhold until the next newline. The time.sleep() call is that you can see it is actually one dot at a time. Peter From david.trem at gmail.com Mon May 21 14:43:40 2007 From: david.trem at gmail.com (David Tremouilles) Date: Mon, 21 May 2007 20:43:40 +0200 Subject: Python and GUI In-Reply-To: <129e1cd10705211140n32e808e2vd41c63a99aaa677a@mail.gmail.com> References: <1179761984.704369.116310@b40g2000prd.googlegroups.com> <129e1cd10705211140n32e808e2vd41c63a99aaa677a@mail.gmail.com> Message-ID: <129e1cd10705211143y6138b8a8pa53d4cbddc4a3c71@mail.gmail.com> Hello, My 2 cents contribution: To me all toolkits offer nice features. It's just a matter of choice depending on your needs. I've personally chosen pyGTK and I use it successfully on Linux/windows/MacOsX for my home grown softs. The reasons of my choice: - It looks the same on all platform (actualy I want to use the softs on different platform and I definitly prefer that it look the same on all of them!) - It's easy to develop with (Glade3,...) - It works perfectly on all platform and it's no difficult to install (even compile!) on all of them. - It looks nice (GTK is the Gimp ToolKit) Let me say that I also tried TkInter (ugly :-( ), pyQt (a mess to understand what kind of license you are allowed to use for you soft), wxpython (it's GTK on Linux but not on other platform and thus not looking the same on all platform...) Just a personal view... David 21 May 2007 08:39:44 -0700, sdoty044 at gmail.com : > > Just wondering on what peoples opinions are of the GUIs avaiable for > Python? > > All I am doing is prompting users for some data (listbox, radio > buttons, text box, ect...). Then I will have some text output, maybe > a scrolling text message as things are happening. > > I have some minor things I need to do, for example, if Checkbutton X > is clicked, I need to disable TextBox Y, and I would like to display > the scrolling text (output) > > Ultimately, is it worth downloading and learning some of the packages > avaiable for Python, or should I just stick to the Tkinter stuff that > is included. > > More specifically, has anyone used the Qt stuff for python, easy to > use? > > -- > http://mail.python.org/mailman/listinfo/python-list > From kylancal at gmail.com Tue May 8 11:26:58 2007 From: kylancal at gmail.com (kylancal at gmail.com) Date: 8 May 2007 08:26:58 -0700 Subject: XLRD Python 2.51 Question Message-ID: <1178638018.606763.162650@e51g2000hsg.googlegroups.com> I am trying to read an Excel book with XLRD and I am getting the following error Traceback (most recent call last): File "C:\temp\ReadGoldmanExcelFiles.py", line 62, in startRow = 0, sh_idx = 0, path2 = '//otaam.com/root/SharedFiles/ GlobeOp/Risk/Cal Projects/temp/') File "C:\temp\ReadGoldmanExcelFiles.py", line 36, in excelTocsv book = xlrd.open_workbook(infile) File "C:\Python25\lib\site-packages\xlrd\__init__.py", line 362, in open_workbook formatting_info=formatting_info, File "C:\Python25\lib\site-packages\xlrd\__init__.py", line 791, in __init__ cd = compdoc.CompDoc(filestr) File "C:\Python25\lib\site-packages\xlrd\compdoc.py", line 122, in __init__ "MSAT extension: accessing sector %d but only %d in file" % (sid, mem_data_secs) CompDocError: MSAT extension: accessing sector 1717046 but only 2887 in file I am not sure what this means at all, can anyone help here? Thanks alot From jadestar at idiom.com Sun May 13 03:44:26 2007 From: jadestar at idiom.com (James T. Dennis) Date: Sun, 13 May 2007 07:44:26 -0000 Subject: Change serial timeout per read References: <1178754931.060029.135800@w5g2000hsg.googlegroups.com> Message-ID: <1179042266.797609@smirk> rowan at sylvester-bradley.org wrote: > I'm writing a driver in Python for an old fashioned piece of serial > equipment. Currently I'm using the USPP serial module. From what I can > see all the serial modules seem to set the timeout when you open a > serial port. This is not what I want to do. I need to change the > timeout each time I do a "read" on the serial port, depending on > which part of the protocol I've got to. Sometimes a return character > is expected within half a second, sometimes within 2 seconds, and > sometimes within 20 seconds. How do I do this in USPP, or Pyserial, or > anything else? Currently I'm working in Windows, but I'd prefer a > platform independent solution if possible... > Thanks - Rowan I'm not familiar with the USPP serial module. However, I used the PySerial package successfully for several months on one job to write a full regression testing framework and suite for testing a series of different VOIP/SIP phone models (little embedded Linux systems) via their diagnostics/JTAG serial headers. It had timeout and writeTimeout settings which I recall were fully configurable to fractions of a second, None, and 0 (non-blocking). Under Debian it's available as a simple: apt-get -f install python-serial. ... and I seem to recall that it worked fine under MS Windows, too. (In fact it was written in pure Python, no C-lib or .so/.DLL under it). Ahh ... here's the URL: http://pyserial.sourceforge.net/ ... with backends for CPython (Windows and Linux/UNIX/Posix), and Jython. Under Python just use: >>> import serial ... then use something like: >>> s0 = serial.Serial(0) # Open first serial port: default settings ... or: >>> s0 = serial.Serial('/dev/ttyS0', 38400, timeout=None) \ # port by device node/name, setting speed and no timeout >>> s1 = serial.Serial(3, 19200, timeout=0) \ # another by number, non-blocking Then use: >>> s0.read() # or s0.readline() for '\n' terminated ... and various other methods on these ports. BTW: you can change the timeouts on these connection objects simply by using s0.timeout=X ... and you can set them to floating point values --- so you can use tenths of a second. I remember I was also able to adapt my framework classes to add support for telnetlib in about an hour of spare time one evening; so we could use the serial port to manage testing on one block of phones and we could enable the optional telnet port access built-into a bank of the other phones and use almost all the same test code with them. (The only difference was that we couldn't capture reboot output over the telnet interface; while I could capture and log it via the serial ports --- in other words it was a natural limitation of the hardware --- and their embedded system didn't enable something like a dmesg to capture that after the fact). The reason I mention the telnetlib angle serves some purpose other than mere rambling and bragging ... I seem to recall that the methods supported by the two modules were very closely matched ... so my adaptation was extremely straightforward. I see that USPP (univ. serial port for Python) is available at: http://ibarona.googlepages.com/uspp ... and it's supposed to have most of the same features (from a quick glance at the web page). However, there's much more info available at the PySerial page ... and PySerial seems to be far more recently maintained (with 2.2 "slots' support, for example). In addition PySerial seems to be linked to a PyParallel package that's "under development" (presumably by the same author). (I'm guessing that this latter development can't be done in pure Python, though). -- Jim Dennis, Starshine: Signed, Sealed, Delivered From j25bravo at gmail.com Sun May 27 06:19:15 2007 From: j25bravo at gmail.com (mark) Date: 27 May 2007 03:19:15 -0700 Subject: totally lost newbie Message-ID: <1180261154.969654.147850@n15g2000prd.googlegroups.com> Hi all I posted earlier on this but have changed my approach so here is my latest attempt at solving a problem. I have been working on this for around 12 hours straight and am still struggling with it. Write a program that reads the values for a random list of cards from a file, where each line in the file specifies a single card with the rank and then the suit separated by a space. The rank should be an integer in the range of 1 to 13 (Ace:1, King:13), while the suit should be a lower case character in the set { 'h', 'd', 'c', 's' }. Sort the card entries into suits ordered by rank, and print out the ordered list. Hint: sort the list first by rank, and then by suit. The format of the cards.txt file is; 1 h 1 d 13 c 10 s and so on for the whole deck. Can someone help me to get the mycomp function to work. Any help appreciated J def read_cards(filename): cards = [] for card in open(filename, 'r'): # strip the trailing newline character cards.append(card.strip()) return cards filename = 'cards.txt' cards = read_cards(filename) def cards_str2tup(cards): cards_tup = [] for card in cards: rank, suit = card.split() cards_tup.append((suit, int(rank))) return cards_tup def cards_tup2str(cards_tup): cards = [] space = ' ' for tup in cards_tup: suit, rank = tup s = str(rank) + space + suit cards.append(s) return cards def mycmp( a, b): #define the order in which the characters are to be sorted order = [ 'h', 'd', 'c', 's' ] # if the characters from each element ARENT the same if a[1] <> b[1]: #return the result of comparing the index of each elements character in the order list return cmp( order.index( a[1] ), order.index( b[1] ) ) #otherwise else : #return the result of comparing each elements number return cmp( a[0], b[0] ) cards.sort( mycmp ) #print cards From eric.devolder at gmail.com Thu May 31 09:55:42 2007 From: eric.devolder at gmail.com (Eric) Date: 31 May 2007 06:55:42 -0700 Subject: with ctypes, how to parse a multi-string In-Reply-To: References: <1180563125.783144.34260@m36g2000hse.googlegroups.com> Message-ID: <1180619742.017855.183750@o5g2000hsb.googlegroups.com> On May 31, 2:52 pm, Thomas Heller wrote: > Eric schrieb: > > > > > Hi, > > > I am currently dealing with ctypes, interfacing with winscard libbrary > > (for smart card access). > > > Several APIs (e.g. SCardListReaderGroupsW ) take a pointer to an > > unicode string as a parameter , which points at function return to a > > "sequence" of unicode strings, NULL terminated. The last string is > > double NULL terminated. (of course buffer length is also returned as > > another parameter). > > > e.g. it could return something like > > 'group1\x00group2\x00group3\x00\x00' > > > What should I use as argtypes to my function prototype in order to > > gain access to the full list? using c_wchar_p works, but it resolves > > the string until it reaches the first \x00, resulting in having access > > to the first entry of the list only. > > A c_wchar_p instance represent a (one!) zero-terminated string, as you > already know. A POINTER(c_wchar) instance is more flexible, you should > use that instead. It can be indexed/sliced with arbitrary indexes. > > Here is a simple script to get you started: > > """ > from ctypes import * > > # Normally, the function call will fill the buffer: > buf = create_unicode_buffer("first\0second\0third\0") > > # The pointer you will pass to the function call > ptr = cast(buf, POINTER(c_wchar)) > > # function call omitted > > # Print the raw result > print ptr[:len(buf)] > > # Print a list of strings > print ptr[:len(buf)].split("\0") > """ > > Thomas Thanks Thomas, it works as expected! Regards, Eric From vinay_sajip at yahoo.co.uk Thu May 10 16:49:15 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 10 May 2007 13:49:15 -0700 Subject: RotatingFileHandler bugs/errors and a general logging question. In-Reply-To: <1178818660.168705.90650@q75g2000hsh.googlegroups.com> References: <1178668334.588946.256490@e51g2000hsg.googlegroups.com> <1178696252.753583.34150@q75g2000hsh.googlegroups.com> <1178818660.168705.90650@q75g2000hsh.googlegroups.com> Message-ID: <1178830155.194949.63070@u30g2000hsc.googlegroups.com> On May 10, 6:37 pm, nicholas.petre... at gmail.com wrote: > On May 9, 12:37 am, Vinay Sajip wrote: > > Our biggest concerns with the network solution is having a single > point of failure and the need for scalability. We could have > potentially thousands of machines doingloggingacross multiple > geographic sites. Our fear with the network solution is overwhelming > the server or group of servers as well as having a single point of > failure for thelogginginterface. In addition using a server or > servers would require added support for the logigng server machines. > Our NFS infrastructure is very well supported and can handle the load > generated by these machines already (A load which would be many times > more than what theloggingwould generate) which is why we would like > to log directly to file system without going through a separate > server. Also adding in aloggingserver introduces one more level > where we could potentially have failure. We would like to keep the > infrastructure for ourloggingas simple as possible as we rely on log > files to give us critical information when troubleshooting issues. > > It sounds like my only option may be using a server in order to handle > theloggingfrom different hosts. That or possibly having individual > log files for each host. > There are other options - you don't necessarily need a separate logging server. For example, you could (a) Have a single network receiver process per host which writes to disk and avoids the problem of contention for the file. Although this process could be a point of failure, it's a pretty simple piece of software and it should be possible to manage the risks. (b) If you wanted to centralize log information, you could move the log files from each host onto a central NFS disk using standard tools such as e.g. rsync, and then manipulate them for reporting purposes however you want. Regards, Vinay Sajip From gagsl-py2 at yahoo.com.ar Tue May 8 20:33:54 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 08 May 2007 21:33:54 -0300 Subject: 1.#QNAN Solution References: <10379999.post@talk.nabble.com> Message-ID: En Tue, 08 May 2007 14:14:58 -0300, Greg Corradini escribi?: > I'm running descriptive stats on mileages from a database (float numbers, > about a million records). My sum returns 1.#QNAN, which I understand from > searching this forum is an error. > > While I'm looking for help in solving this problem, I'm more interested > in a > general explanation about the cause of this problem. Any ideas? If you are summing a million floating point numbers, using a naive algorithm may give you wrong results. Look for "Kahan summation algorithm" (even discussed some weeks ago in this group). -- Gabriel Genellina From mitko at qlogic.com Fri May 18 19:49:33 2007 From: mitko at qlogic.com (Mitko Haralanov) Date: Fri, 18 May 2007 16:49:33 -0700 Subject: Compiling Python code within a module In-Reply-To: <1179528700.031053.307480@k79g2000hse.googlegroups.com> References: <1179528700.031053.307480@k79g2000hse.googlegroups.com> Message-ID: <20070518164933.21bd8b91@opal.pathscale.com> On 18 May 2007 15:51:40 -0700 ici wrote: > exec it :) Thank you! That works when I compile/exec it in the main body of the program. However, when I try to do that in a separate module it doesn't. For example: Module Foo: import compiler class Foo: def __init__ (self): return def register (self, text): exec (compiler.compile (text, "", "exec")) File Bar: import Foo f = Foo.Foo () f.register ("def blah():\n\tprint 'blah'\n") In this case, the function 'blah' is nowhere to be found. I've tried looking in 'f', in the class 'Foo', in the module 'Foo' and it's nowhere. -- Mitko Haralanov mitko at qlogic.com Senior Software Engineer 650.934.8064 System Interconnect Group http://www.qlogic.com ========================================== ((lambda (foo) (bar foo)) (baz)) From rridge at caffeine.csclub.uwaterloo.ca Tue May 15 08:54:41 2007 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Tue, 15 May 2007 08:54:41 -0400 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: wrote: >So, please provide feedback, e.g. perhaps by answering these >questions: >- should non-ASCII identifiers be supported? why? I think the biggest argument against this PEP is how little similar features are used in other languages and how poorly they are supported by third party utilities. Your PEP gives very little thought to how the change would affect the standard Python library. Are non-ASCII identifiers going to be poorly supported in Python's own library and utilities? Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From tijs_news at artsoftonline.com Thu May 31 02:20:58 2007 From: tijs_news at artsoftonline.com (Tijs) Date: Thu, 31 May 2007 08:20:58 +0200 Subject: c[:]() References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180504773.374529.161740@q66g2000hsg.googlegroups.com> Message-ID: <465e694a$0$333$e4fe514c@news.xs4all.nl> Warren Stringer wrote: >>>>c[:]() # i wanna > TypeError: 'tupple' object is not callable > c[:] equals c (in expressions), so c[:]() is equivalent to c() >>>>c[:][0] # huh? > a c[:][0] is c[0] is a >>>> [i() for i in c] # too long and ...huh? > a > b > [None,None] > #------------------------------------------ > [None, None] is the result of the operation. for i in c: i() If that is too long, reconsider what you are doing. -- Regards, Tijs From bj_666 at gmx.net Fri May 25 14:03:09 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 25 May 2007 20:03:09 +0200 Subject: Large Amount of Data References: Message-ID: In , Jack wrote: > I need to process large amount of data. The data structure fits well > in a dictionary but the amount is large - close to or more than the size > of physical memory. I wonder what will happen if I try to load the data > into a dictionary. Will Python use swap memory or will it fail? What about putting the data into a database? If the keys are strings the `shelve` module might be a solution. Ciao, Marc 'BlackJack' Rintsch From noagbodjivictor at gmail.com Sun May 6 17:11:46 2007 From: noagbodjivictor at gmail.com (noagbodjivictor at gmail.com) Date: 6 May 2007 14:11:46 -0700 Subject: c macros in python. In-Reply-To: <1178485789.001461.204710@y80g2000hsf.googlegroups.com> References: <1178485280.394666.51970@n76g2000hsh.googlegroups.com> <1178485789.001461.204710@y80g2000hsf.googlegroups.com> Message-ID: <1178485906.870395.320950@y5g2000hsa.googlegroups.com> Great python!!! From hanser at club-internet.fr Tue May 15 14:50:03 2007 From: hanser at club-internet.fr (Pierre Hanser) Date: Tue, 15 May 2007 20:50:03 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46499a54$0$10199$9b4e6d93@newsspool4.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <4648252D.5020704@web.de> <46483740.4050406@web.de> <46498cb1$0$6411$9b4e6d93@newsspool2.arcor-online.net> <46499273.6050806@web.de> <46499a54$0$10199$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <464a00cc$0$21149$7a628cd7@news.club-internet.fr> Ren? Fleschenberg a ?crit : > Your example does not prove much. The fact that some people use > non-ASCII identifiers when they can does not at all prove that it would > be a serious problem for them if they could not. > i have to make orthograph mistakes in my code to please you? -- Pierre From gagsl-py2 at yahoo.com.ar Mon May 28 11:47:30 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 28 May 2007 12:47:30 -0300 Subject: Issue of redirecting the stdout to both file and screen References: <1180343858.903251.182490@x35g2000prf.googlegroups.com> Message-ID: En Mon, 28 May 2007 09:10:40 -0300, Peter Otten <__peter__ at web.de> escribi?: > Gabriel Genellina wrote: > >> En Mon, 28 May 2007 06:17:39 -0300, ??????????????? >> escribi?: >> >>> def __init__(self, name, mode): >>> file.__init__(self, name, mode) >>> self.stdout = sys.stdout >>> sys.stdout = self >>> >>> Tee('logfile', 'w') >>> print >>sys.stdout, 'abcdefg' >>> >>> I found that it only output to the file, nothing to screen. Why? >>> It seems the 'write' function was not called when I *print* something. >> >> You create a Tee instance and it is immediately garbage collected. > > It is not garbage collected until the next assignment to sys.stdout. Yes, sorry, this was my first guess. Later I discovered the real reason -you pointed it too-, I should have removed the whole first paragraph on my reply. -- Gabriel Genellina From warren at muse.com Thu May 31 13:48:49 2007 From: warren at muse.com (Warren Stringer) Date: Thu, 31 May 2007 10:48:49 -0700 Subject: c[:]() In-Reply-To: References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> <135tobve86qj808@corp.supernews.com> <135tru124pie2b3@corp.supernews.com> <135tv1bjqgbmsc9@corp.supernews.com> Message-ID: <003301c7a3ab$f2bdf960$240110ac@Muse> > >> c[:] holds many behaviors that change dynamically. > > > > I've absolutely no clue what that sentence means. If c[:] does > > behave differently than c, then somebody's done something > > seriously weird and probably needs to be slapped around for > > felonious overriding. I'm still a bit new at this, was wondering why c[:]() doesn't work, and implicitly wondering why it *shouldn't* work. > >> So c[:]() -- or the more recent go(c)() -- executes all those > >> behaviors. Oops meant to say do(c)(), not "go", which matches a prior post. > > Still no clue. > > > >> This is very useful for many performers. > > > > What are "performers"? Real people, like musicians, and their proxies in code that passes around real-time events that may be rendered, recorded, and played back. > >> The real world example that I'm working one is a collaborative > >> visual music performance. So c can contain wrapped MIDI events > >> or sequencer behaviors. c may get passed to a scheduler to > >> execute those events, or c may get passed to a pickler to > >> persist the performance. > > > > I still don't see how c[:] is any different from c. > > > It isn't. The OP is projecting a wish for a function call on a list to > be interpreted as a call on each member of the list with the same > arguments. The all-members slice notation is a complete red herring. Just looked up "red herring wiki" hope I wasn't being misleading -- at least not intentionally. c[:] is the simplest case for a broad range of behaviors. Perhaps, I should have said c[selector()]() ??? but, no, that makes the question more complex ... still > It would require a pretty fundamental re-think to give such a construct > sensible and consistent semantics, I think. What do you mean? If c[:]() works, the so does this, using real world names orchestra[:].pickle() orchestra[conductor()].sequence() Though, I'm already starting to prefer: do(orchestra).pickle() do(orchestra(conductor)).sequence() Perhaps, this is what you mean by "sensible and consistent semantics" I just read Alex Martelli's post in the "rats! Varargs" thread about how list and tupples are implemented. I want to understand implementation before suggesting changes. Maybe c[:]() isn't so simple to fix, after all? From kinch1967 at gmail.com Sat May 19 20:18:56 2007 From: kinch1967 at gmail.com (bullockbefriending bard) Date: 19 May 2007 17:18:56 -0700 Subject: regex matching question In-Reply-To: <464F86F0.8080100@lexicon.net> References: <1179595319.239229.262160@l77g2000hsb.googlegroups.com> <464F86F0.8080100@lexicon.net> Message-ID: <1179620336.327038.253920@h2g2000hsg.googlegroups.com> > Instead of the "or match.group(0) != results" caper, put \Z (*not* $) at > the end of your pattern: > mobj = re.match(r"pattern\Z", results) > if not mobj: as the string i am matching against is coming from a command line argument to a script, is there any reason why i cannot get away with just $ given that this means that there is no way a newline could find its way into my string? certainly passes all my unit tests as well as \Z. or am i missing the point of \Z ? From john at datavoiceint.com Wed May 2 13:00:56 2007 From: john at datavoiceint.com (HMS Surprise) Date: 2 May 2007 10:00:56 -0700 Subject: Time functions Message-ID: <1178125256.640115.26480@o5g2000hsb.googlegroups.com> I wish to generate a datetime string that has the following format. '05/02/2007 12:46'. The leading zeros are required. I found '14.2 time' in the library reference and have pulled in localtime. Are there any formatting functions available or do I need to make my own? Perhaps there is something similar to C's printf formatting. Thanks, jvh (whose newbieism is most glaring) From paddy3118 at googlemail.com Sun May 20 06:52:11 2007 From: paddy3118 at googlemail.com (Paddy) Date: 20 May 2007 03:52:11 -0700 Subject: converting strings to most their efficient types '1' --> 1, 'A' ---> 'A', '1.2'---> 1.2 In-Reply-To: <464FA156.2070704@lexicon.net> References: <1179529661.555196.13070@k79g2000hse.googlegroups.com> <1179551680.283157.19000@y80g2000hsf.googlegroups.com> <464FA156.2070704@lexicon.net> Message-ID: <1179658331.911424.173140@e65g2000hsc.googlegroups.com> On May 20, 2:16 am, John Machin wrote: > On 19/05/2007 3:14 PM, Paddy wrote: > > > > > On May 19, 12:07 am, py_genetic wrote: > >> Hello, > > >> I'm importing large text files of data using csv. I would like to add > >> some more auto sensing abilities. I'm considing sampling the data > >> file and doing some fuzzy logic scoring on the attributes (colls in a > >> data base/ csv file, eg. height weight income etc.) to determine the > >> most efficient 'type' to convert the attribute coll into for further > >> processing and efficient storage... > > >> Example row from sampled file data: [ ['8','2.33', 'A', 'BB', 'hello > >> there' '100,000,000,000'], [next row...] ....] > > >> Aside from a missing attribute designator, we can assume that the same > >> type of data continues through a coll. For example, a string, int8, > >> int16, float etc. > > >> 1. What is the most efficient way in python to test weather a string > >> can be converted into a given numeric type, or left alone if its > >> really a string like 'A' or 'hello'? Speed is key? Any thoughts? > > >> 2. Is there anything out there already which deals with this issue? > > >> Thanks, > >> Conor > > > You might try investigating what can generate your data. With luck, > > it could turn out that the data generator is methodical and column > > data-types are consistent and easily determined by testing the > > first or second row. At worst, you will get to know how much you > > must check for human errors. > > Here you go, Paddy, the following has been generated very methodically; > what data type is the first column? What is the value in the first > column of the 6th row likely to be? > > "$39,082.00","$123,456.78" > "$39,113.00","$124,218.10" > "$39,141.00","$124,973.76" > "$39,172.00","$125,806.92" > "$39,202.00","$126,593.21" > > N.B. I've kindly given you five lines instead of one or two :-) > > Cheers, > John John, I've had cases where some investigation of the source of the data has completely removed any ambiguity. I've found that data was generated from one or two sources and been able to know what every field type is by just examining a field that I have determined wil tell me the source program that generated the data. I have also found that the flow generating some data is subject to hand editing so have had to both put in extra checks in my reader, and on some occasions created specific editors to replace hand edits by checked assisted hand edits. I stand by my statement; "Know the source of your data", its less likely to bite! - Paddy. From tartifola at gmail.com Fri May 25 03:35:51 2007 From: tartifola at gmail.com (Tartifola) Date: Fri, 25 May 2007 09:35:51 +0200 Subject: No Python for Blackberry? References: <1179537588.505753.275200@q75g2000hsh.googlegroups.com> Message-ID: <20070525093551.53a184a8.tartifola@gmail.com> Hi, > > I could not find a version of Python that runs on a Blackberrry. I'm in the process to buy one of this smart phone and very interested in Python for Blackberry. Any success in installing it? > > > ------------------------------------- > This sig is dedicated to the advancement of Nuclear Power > Tommy Nordgren > tommy.nordgren at comhem.se > > > From max at alcyone.com Thu May 24 01:14:13 2007 From: max at alcyone.com (Erik Max Francis) Date: Wed, 23 May 2007 22:14:13 -0700 Subject: 0 == False but [] != False? In-Reply-To: <1179982400.412340.178710@g4g2000hsf.googlegroups.com> References: <1179982400.412340.178710@g4g2000hsf.googlegroups.com> Message-ID: Rajarshi wrote: > This is a slightly naive question, but I know that 0 can be used to > represent False. So > >>>> 0 == False > True > > But, I know I can use [] to represent False as in > >>>> if not []: print 'empty' > ... > empty > > But then doing the following gives a surprising (to me!) result > >>>> [] == False > False > > Could anybody point out why this is the case? Because "representing False" (i.e., being false) and "being the same as False" are not the same thing. if x: ... is not the same thing as if x == True: ... it's the same as if bool(x): ... So a more meaningful comparison of your two tests are: >>> bool(0) == bool(False) True >>> bool([]) == bool(False) True -- 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 Woman was God's _second_ mistake. -- Friedrich Nietzsche From nagle at animats.com Mon May 14 00:35:22 2007 From: nagle at animats.com (John Nagle) Date: Sun, 13 May 2007 21:35:22 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <7xiraw3xt8.fsf@ruckus.brouhaha.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <7x4pmg716p.fsf@ruckus.brouhaha.com> <7xiraw3xt8.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Neil Hodgson writes: > >>>>Plenty of programming languages already support unicode identifiers, >>> >>>Could you name a few? Thanks. >> >> C#, Java, Ecmascript, Visual Basic. > > > Java (and C#?) have mandatory declarations so homoglyphic identifiers aren't > nearly as bad a problem. Ecmascript is a horrible bug-prone language and > we want Python to move away from resembling it, not towards it. VB: well, > same as Ecmascript, I guess. That's the first substantive objection I've seen. In a language without declarations, trouble is more likely. Consider the maintenance programmer who sees a variable name and retypes it elsewhere, not realizing the glyphs are different even though they look the same. In a language with declarations, that generates a compile-time error. In Python, it doesn't. John Nagle From bbxx789_05ss at yahoo.com Thu May 17 21:23:15 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 17 May 2007 18:23:15 -0700 Subject: omissions in python docs? In-Reply-To: References: <1179419983.750044.65030@n59g2000hsh.googlegroups.com> Message-ID: <1179451395.440662.127760@y80g2000hsf.googlegroups.com> On May 17, 5:24 pm, "Gabriel Genellina" wrote: > At least for 2) you're late. It's already documented on 2.5.1:http://sourceforge.net/tracker/index.php?func=detail&aid=1630844&grou... > Darn. I could have been somebody! >Nit-pickingly yours, >John No so. I checked the downloaded docs on my computer and the supposedly up to date docs here: http://docs.python.org/lib/module-fnmatch.html before posting. I rechecked them after reading Gabriel Genellina's post, and I couldn't find translate() in the fnmatch module. There's still time! From jstroud at mbi.ucla.edu Thu May 17 15:25:53 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 17 May 2007 12:25:53 -0700 Subject: Regexes: How to handle escaped characters In-Reply-To: <87tzubqniq.fsf@wilson.homeunix.com> References: <87tzubqniq.fsf@wilson.homeunix.com> Message-ID: Torsten Bronger wrote: > Hall?chen! > > I need some help with finding matches in a string that has some > characters which are marked as escaped (in a separate list of > indices). Escaped means that they must not be part of any match. > > My current approach is to look for matches in substrings with the > escaped characters as boundaries between the substrings. However, > then ^ and $ in the patterns are treated wrongly. (Although I use > startpos and endpos parameters for this and no slicing.) > > Another idea was to have a special unicode character that never > takes part in a match. The docs are not very promising regarding > such a thing, or did I miss something? > > Any other ideas? > > Tsch?, > Torsten. > You should probably provide examples of what you are trying to do or you will likely get a lot of irrelevant answers. James From vatamane at gmail.com Tue May 15 15:04:22 2007 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 15 May 2007 12:04:22 -0700 Subject: Splitting a string In-Reply-To: <1179253692.110024.96330@w5g2000hsg.googlegroups.com> References: <1179253692.110024.96330@w5g2000hsg.googlegroups.com> Message-ID: <1179255862.021110.248520@o5g2000hsb.googlegroups.com> On May 15, 2:28 pm, HMS Surprise wrote: > The string s below has single and double qoutes in it. For testing I > surrounded it with triple single quotes. I want to split off the > portion before the first \, but my split that works with shorter > strings does not seem to work with this one. > > Ideas? > > Thanks, > jvh > > s = ''''D132258\',\'\', > \'status=no,location=no,width=630,height=550,left=200,top=100\')" > target="_blank" class="dvLink" title="Send an Email to selected > employee">''' > > t = s.split('\\') jvh, For your split operation to work you would need your string to be in raw format (add an 'r' in front of it). That way all your back slashes won't be interpreted. Or you'll just have to split on ',' instead of '\'. The first '\' is not there technically because it just escapes the ( ' ). So when your actual string just has a quote ( ' ) an not '\'. If it were a raw string, then all your backslashes would have been there. (just print s and see what you get!). >>> s=r''''D132258\',\'\', ....: \'status=no,location=no,width=630,height=550,left=200,top=100\')" ....: target="_blank" class="dvLink" title="Send an Email to selected ....: employee">''' >>> s '\'D132258\\\',\\\'\\\',\n\\ \'status=no,location=no,width=630,height=550,left=200,top=100\\ \')"\ntarget="_blank" class="dvLink" title="Send an Email to selected \nemployee">' >>> print s 'D132258\',\'\', \'status=no,location=no,width=630,height=550,left=200,top=100\')" target="_blank" class="dvLink" title="Send an Email to selected employee"> >>> s.split('\\') ["'D132258", "',", "'", "',\n", "'status=no,location=no,width=630,height=550,left=200,top=100", '\')"\ntarget="_blank" class="dvLink" title="Send an Email to selected \nemployee">'] -Nick Vatamaniuc From apatheticagnostic at gmail.com Thu May 3 02:27:01 2007 From: apatheticagnostic at gmail.com (kaens) Date: Thu, 3 May 2007 02:27:01 -0400 Subject: FInd files with .so extension In-Reply-To: <163f0ce20705022324s5953335v1c5d5337442a36a0@mail.gmail.com> References: <1178168321.581307.284750@y5g2000hsa.googlegroups.com> <180b672e0705022310i3ad709f8w6590e6aaffd884cc@mail.gmail.com> <163f0ce20705022324s5953335v1c5d5337442a36a0@mail.gmail.com> Message-ID: <163f0ce20705022327o95219a3tabea54207c54d19b@mail.gmail.com> do YOU mean hit "reply to all" not "reply?" On 5/3/07, kaens wrote: > do you mean > filelst.append(i)? > > On 5/3/07, rishi pathak wrote: > > May be this would work > > import os > > grep="so" > > dir="." > > lst = os.listdir(dir) > > filelst=[] > > for i in lst: > > if i.split(".")[len(i.split("."))-1] == grep: > > lst.append(i) > > print lst > > > > > > > > On 2 May 2007 21:58:41 -0700, pradeep nair wrote: > > > HI, > > > > > > > > > How do i find files with .so extension using python . > > > > > > -- > > > http://mail.python.org/mailman/listinfo/python-list > > > > > > > > > > > -- > > Regards-- > > Rishi Pathak > > National PARAM Supercomputing Facility > > Center for Development of Advanced Computing(C-DAC) > > Pune University Campus,Ganesh Khind Road > > Pune-Maharastra > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > From bj_666 at gmx.net Mon May 21 09:56:55 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 21 May 2007 15:56:55 +0200 Subject: re.compile for names References: Message-ID: In , brad wrote: > I am developing a list of 3 character strings like this: > > and > bra > cam > dom > emi > mar > smi > ... > > The goal of the list is to have enough strings to identify files that > may contain the names of people. Missing a name in a file is unacceptable. Then simply return `True` for any file that contains at least two or three ASCII letters in a row. Easily written as a short re. ;-) > I may end up with a thousand or so of these 3 character strings. Is that > too much for an re.compile to handle? Also, is this a bad way to > approach this problem? Any ideas for improvement are welcome! Unless you can come up with some restrictions to the names, just follow the advice above or give up. I saw a documentation about someone with the name "Scary Guy" in his ID papers recently. What about names with letters not in the ASCII range? Ciao, Marc 'BlackJack' Rintsch From steve at REMOVE.THIS.cybersource.com.au Wed May 9 22:55:38 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 10 May 2007 12:55:38 +1000 Subject: change of random state when pyc created?? References: <5ae25fF2oggbqU1@mid.uni-berlin.de> Message-ID: On Wed, 09 May 2007 21:18:25 -0500, Robert Kern wrote: > Actually, the root cause of Peter's specific example is the fact that the > default implementation of __hash__() and __eq__() rely on identity comparisons. > Two separate invocations of the same script give different objects by identity > and thus the "history of insertions and deletions" is different. The history is the same. The objects inserted are the same (by equality). The memory address those objects are located at is different. Would you expect that "hello world".find("w") should depend on the address of the string "w"? No, of course not. Programming in a high level language like Python, we hope to never need to think about memory addresses. And that's the gotcha. -- Steven. From duncan.booth at invalid.invalid Tue May 1 13:28:04 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 May 2007 17:28:04 GMT Subject: SilverLight, a new way for Python? References: Message-ID: Michel Claveau wrote: > Hi! > > SilverLight ("MS flash killer"), is a plug-in for InternetExplorer > (Win), FireFox (Win), and Safari (Mac). > The release 1.1-Alpha come with JScript & Python (or ironPython?) IronPython. > Perhaps SilverLight is a new substitute for Python-Active-Scripting in > IE. It can do much more than active scripting. > > But, I don't had try SilverLight... Have you at least run the demos? To run the demos you just need Windows or a Mac (or a virtual machine running windows) and install the Silverlight 1.1 alpha. > > Who had try it? > There are some nice demos at http://silverlight.net/themes/silverlight/community/gallerydetail.aspx?cat=2 In particular the DLRconsole (http://silverlight.net/Samples/1.1/DLR-Console/python/index.htm) gives you an interactive prompt to play with IronPython (or JScript) and XAML. The big drawback is that despite being trumpeted as cross-platform it runs on Windows and Mac but not Linux. The technology looks very tempting, so much so that I can see a lot of people are going to use it. I balked at downloading the full 5.6Gb Visual Studio beta, but once you have the plugin installed in your browser you can run IronPython + xaml directly from your local disc (or a web server). e.g. Download the PhotoViewer demo and unzip and you can then immediately start hacking the Python file. I haven't tried running it from an Apache server yet but there since the code is just client-side it should all work (although until it gets out of Alpha you can't actually use it for anything real). From ruoyu0088 at gmail.com Tue May 15 06:49:43 2007 From: ruoyu0088 at gmail.com (HYRY) Date: 15 May 2007 03:49:43 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46473267$0$31532$9b622d9e@news.freenet.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <1179226183.215907.140450@q75g2000hsh.googlegroups.com> > - should non-ASCII identifiers be supported? why? Yes. I want this for years. I am Chinese, and teaching some 12 years old children learning programming. The biggest problem is we cannot use Chinese words for the identifiers. As the program source becomes longer, they always lost their thought about the program logic. English keywords and libraries is not the problem, because we only use about 30 - 50 of these words for teaching programming idea. They can remember these words in one week. But for the name of variable or function, it is difficult to remember all the English word. For example, when we are doing numbers, maybe these words: [odd, even, prime, minus ...], when we are programming for drawing: [line, circle, pixel, ...], when it's for GUI: [ button, event, menu...]. There are so many words that they cannot just remeber and use these words to explain there idea. Eventlly, when these children go to high school and study enough English, I think they can use English words for programming. But as the beginning step, it is difficult to learn both programming and English. So, I made a little program, just replace all the Chinese words in the program to some sequency identifiers such as [a1, a2, a3, ...], So we can do programming in Chinese, and Python can still run it. If non-ASCII identifiers becomes true, I think it will be the best gift for Children who donot know English. From milliondollarexecutive at gmail.com Wed May 2 23:32:48 2007 From: milliondollarexecutive at gmail.com (Midex) Date: 2 May 2007 20:32:48 -0700 Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? In-Reply-To: <57li33hegq8g81bbcru09gagbpqp6eq3cp@4ax.com> References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> <57li33hegq8g81bbcru09gagbpqp6eq3cp@4ax.com> Message-ID: <1178163168.661168.19700@p77g2000hsh.googlegroups.com> On 3 maio, 00:20, Sup... at ssiveBlackHoleAtTheCenterOfTheMilkyWayGalaxy.org wrote: > On 2 May 2007 20:05:23 -0700, Midex Gave us: > > >100% EVIDENCE > > You AND Rosie are fucking retarded! Sure, you have firefighters and all the first responders telling you LIVE in the video that the building is going to be pulled down. Thats all we want the authoirities to admit. They keep denying it and claiming that there were no explosives or pulling done, that the building just decided to collapse itself!!!!!! By the way, I think you meant to say that me and Rosie and 70 Million Voting Age Americans are fucking retarded: http://www.zogby.com/search/ReadNews.dbm?ID=855 http://www.911truth.org/article.php?story=20060522022041421 Here is Zogby's client list in case you're too lazy (which I safely assume you are) to check their reputation yourself: http://www.zogby.com/about/clients.cfm From paul at boddie.org.uk Thu May 17 11:35:29 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 17 May 2007 08:35:29 -0700 Subject: Python Web Programming - looking for examples of solid high-traffic sites In-Reply-To: References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> Message-ID: <1179416129.774534.150050@q23g2000hsg.googlegroups.com> John Nagle wrote: > Victor Kryukov wrote: > > > > Our main requirement for tools we're going to use is rock-solid > > stability. As one of our team-members puts it, "We want to use tools > > that are stable, has many developer-years and thousands of user-years > > behind them, and that we shouldn't worry about their _versions_." The When settling on an environment you need to have a clear strategy about component versions and compatibility. Although Python provides a fairly reasonable backwards compatibility story, one still needs to be aware of changes between versions and their implications, but this is the case for a large proportion of the software produced today. Despite the baggage maintained by Microsoft so that ancient applications might still run in recent versions of Windows, to choose a fairly extreme example in certain respects, there are still many things to be aware of when maintaining or upgrading your environment. Saying that something needs "Python plus Windows/Linux plus some database system" isn't going to be enough if you're emphasizing stability. > > main reason for that is that we want to debug our own bugs, but not > > the bugs in our tools. > > You may not be happy with Python, then. > > Having spent the last several months implementing a reasonably complex > web site in Python, I now have an understanding of the problems involved. > Which are non-trivial. I'm sure they are, which is why I attempt to use the tools and services available to reduce the impact of those problems on myself. > Some key web site components, like the SSL interface and the > MySQL interface, are written in C and maintained by third parties, > often by a single person. Getting the correct version for your > platform and making it work can be difficult. Getting the right > versions of MySQL, OpenSSL, and Python to all play together is > non-trivial. Expect to have to build from source, debug the build > process, look at source repositories, submit bug reports, fix > library bugs yourself, and maintain a local set of library patches. I think we went through this before, but to what extent did you rely on your distribution to handle many of these issues? Or was this on Windows? If so, you're the master of your own distribution rather than a group of helpful people who've probably already done most of that work. > Few hosting companies will have these modules available for you. > It's not like Perl or PHP, where it works out of the box. WebFaction > claims to support Python well, but few other hosting companies bother. > Most Linux distributions ship with older versions of Python, and > that's what most hosting companies will give you. Python 2.4 > is par for the course. There's nothing wrong with Python 2.4. Perhaps you've inadvertently highlighted an issue with the Python community: that everyone wants the latest and greatest, and sees the CPython distribution as the primary means of delivering it. If so, you've just included yourself in the group causing yourself all those problems described above. Paul P.S. The inquirer may wish to visit sites representing the different frameworks in order to seek testimonials, and to look for sites using those frameworks in order to assess their popularity. Zope, Plone, Django, TurboGears, Webware and many others have delivered high- profile sites at various times, as far as I recall. From thorsten at thorstenkampe.de Tue May 15 09:26:35 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 15 May 2007 14:26:35 +0100 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476081.7080609@web.de> <46498514$0$6402$9b4e6d93@newsspool2.arcor-online.net> <4649882E.3060005@web.de> <46499940$0$10199$9b4e6d93@newsspool4.arcor-online.net> <46499BF9.30209@web.de> <4649a2c1$0$10193$9b4e6d93@newsspool4.arcor-online.net> <4649A429.3010406@web.de> <4649ae4a$0$20289$9b4e6d93@newsspool3.arcor-online.net> <4649b336$0$10191$9b4e6d93@newsspool4.arcor-online.net> Message-ID: * Ren? Fleschenberg (Tue, 15 May 2007 15:18:48 +0200) > Thorsten Kampe schrieb: > > GOTOs are not understable. Identifiers in foreign languages are > > perfectly understable. Just not to you. > > For coding problems better solutions (approaches) exist than using > > GOTOs (procedural programming, modules). For identifier naming > > problems it's not a better approach to stick to English or ASCII. It's > > just a different approach. > > Just by stating your personal opinion that it is not a better but just > different approach, you won't convince anyone. There are important > arguments for why it actually *is* a better approach -- these have been > brought up in this thread many times now. Yeah. For code sharing for instance *chuckle*. From google at mrabarnett.plus.com Thu May 10 16:48:08 2007 From: google at mrabarnett.plus.com (MRAB) Date: 10 May 2007 13:48:08 -0700 Subject: Newbie (but improving) - Passing a function name with parameters as aparameter In-Reply-To: References: <1178785638.736644.312970@e51g2000hsg.googlegroups.com> Message-ID: <1178830088.766699.241950@h2g2000hsg.googlegroups.com> On May 10, 6:33 pm, "Terry Reedy" wrote: > "mosscliffe" wrote in message > > news:1178785638.736644.312970 at e51g2000hsg.googlegroups.com... > > Asun Friere pointed out the central flaw in your program. Since passing > functions as arguments is an important concept, here, for any newbies who > did not understand, is a restatement of the problem and the fix. > > | timeloop(lookup(myrecs,mypatts), 10) > > This does not pass the lookup function to timeloop. Rather it calls lookup > and passes the boolean result. The attempt to 'call' that boolean gives > > |I am trying to time a function's execution, but I get 'TypeError: > | 'bool' object is not callable' when I try to run it. > > | I suspect it is my calling of 'timeloop' with the function name > | 'lookup' and its associated variables > > Yes. Make the following changes and all should be well. > > | def timeloop(dofunction,iters=10): > > def timeloop(func, args, iters=10) > > | import datetime > | print "->-> Start of test", "LOOPS=", iters, > | datetime.datetime.now().ctime() > | for x in xrange(iters): > | print x > | dofunction() > > func(*args) > > | print "<-<- End of test", "LOOPS=", iters, > | datetime.datetime.now().ctime() > | > | def lookup(recs,patterns): > | matchcount = 0 > | pattcount = 0 > | for patt in patterns: > | if matchcount < pattcount: > | break > | pattcount += 1 > | for rec in recs: > | # print "PATT:", patt, " REC:", rec, " PATTCOUNT=", pattcount > | if patt in rec: > | matchcount +=1 > | break > | # print"MATCHCOUNT=",matchcount, "PATTCOUNT=", pattcount > | if matchcount == pattcount: > | return True > | else: > | return False > | > | > | > | myrecs = ['This is a title for Brian', 'this is detail one for brian', > | 'this is detail two for brian', 'this is another detail one for > | brian'] > | > | test1 = ['one', 'nomatch'] > | test2 = ['one', 'two'] > | test3 = ['title', 'two', 'nomatcheither'] > | > | mypatts = test1 > | > | timeloop(lookup(myrecs,mypatts), 10) > > timeloop(lookup, (myrecs, mypaths), 10) > A smaller change would be: timeloop(lambda: lookup(myrecs,mypatts), 10) From maksim.kasimov at gmail.com Fri May 25 10:11:02 2007 From: maksim.kasimov at gmail.com (Maksim Kasimov) Date: Fri, 25 May 2007 17:11:02 +0300 Subject: just a bug In-Reply-To: References: <1179841504.782279.86490@u36g2000prd.googlegroups.com> <1180082137.329142.45350@p77g2000hsh.googlegroups.com> <1180090985.066935.218250@h2g2000hsg.googlegroups.com> Message-ID: Carsten Haese: > On Fri, 2007-05-25 at 04:03 -0700, sim.sim wrote: > UnicodeDecodeError: 'utf8' codec can't decode bytes in position 176-177: invalid data >>>> iMessage[176:178] > '\xd1]' > > And that's your problem. In general you can't just truncate a utf-8 > encoded string anywhere and expect the result to be valid utf-8. The > \xd1 at the very end of your CDATA section is the first byte of a > two-byte sequence that represents some unicode code-point between \u0440 > and \u047f, but it's missing the second byte that says which one. in previous message i've explain already that the situation widely appears with memory limited devices, such as mobile terminals of Nokia, SonyEriccson, Siemens and so on. and i've notice you that it is a part of a splited string. Splited content it is a _standard_ in mobile world, and well described at http://www.openmobilealliance.org and is _not_ contradicts xml-spec. the problem is that pyexpat works _unproperly_. > > Whatever you're using to generate this data needs to be smarter about > splitting the unicode string. Rather than encoding and then splitting, > it needs to split first and then encode, or take some other measures to > make sure that it doesn't leave incomplete multibyte sequences at the > end. > > HTH, > -- Maksim Kasimov From mkent at acm.org Sun May 27 14:03:12 2007 From: mkent at acm.org (Mike Kent) Date: Sun, 27 May 2007 14:03:12 -0400 Subject: Announcing: ACM SIGAPL apl 2007 -- Arrays and Objects Message-ID: <5btvf0F2tndakU1@mid.individual.net> The APL 2007 conference, sponsored by ACM SIGAPL, has as its principal theme "Arrays and Objects" and, appropriately, is co-located with OOPSLA 2007, in Montreal this October. APL 2007 starts with a tutorial day on Sunday, October 21, followed by a two-day program on Monday and Tuesday, October 22 and 23. APLers are welcome to attend OOPSLA program events on Monday and Tuesday (and OOPSLA attendees are welcome to come to APL program events). Registrants at APL 2007 can add full OOPSLA attendance at a favorable price. Dates: Sunday Oct 21 Tutorials Monday, Tuesday Oct 22,23 APL 2007 program Monday-Friday Oct 22-26 OOPSLA program APL 2007 keynote speaker: Guy Steele, Sun Microsystems Laboratories Tutorials Using objects within APL Array language practicum Intro to [language] for other-language users ( We expect that there will be at least one introductory tutorial on "classic" APL, and hope to have introductions to a variety of array languages ) We solicit papers and proposals for tutorials, panels and workshops on all aspects of array-oriented programming and languages; this year we have particular interest in the themes of integrating the use of arrays and objects languages that support the use of arrays as a central and thematic technique marketplace and education: making practitioners aware of array thinking and array languages Our interest is in the essential use of arrays in programming in any language (though our historical concern has been the APL family of languages: classic APL, J, K, NIAL, ....). Dates: Tutorial, panel, and workshop proposals, and notice of intent to submit papers, are due by Friday June 15, to the Program Chair. Contributed papers, not more than 10 pages in length, are due by Monday, July 23, to the Program Chair. Details of form of submission can be obtained from the program chair. Deadline for detailed tutorial/panel/workshop information TBA. Cost (to SIGAPL and ACM members, approximate $US, final cost TBA) APL2007 registration $375 Tutorial day $250 Single conference days $200 Social events: Opening reception Monday Others TBA Conference venue: Palais de Congres, Montreal, Quebec, CANADA Conference hotel: Hyatt Regency Montreal Committee General Chair Guy Laroque Guy.Laroque at nrcan.gc.ca Program Chair Lynne C. Shaw Shaw at ACM.org Treasurer Steven H. Rogers Steve at SHRogers.com Publicity Mike Kent MKent at ACM.org Links APL2007 http://www.sigapl.org/apl2007 OOPSLA 2007 http://www.oopsla.org/oopsla2007 Palais de Congres http://www.congresmtl.com/ Hyatt Regency Montreal http://montreal.hyatt.com Guy Steele http://research.sun.com/people/mybio.php?uid=25706 ACM SIGAPL http://www.sigapl.org From stargaming at gmail.com Fri May 18 02:29:43 2007 From: stargaming at gmail.com (Stargaming) Date: Fri, 18 May 2007 08:29:43 +0200 Subject: A new project. In-Reply-To: <1179302989.142733.257910@n59g2000hsh.googlegroups.com> References: <1179302989.142733.257910@n59g2000hsh.googlegroups.com> Message-ID: <464D47D7.2090504@gmail.com> colin.barnette at gmail.com schrieb: > I am interested in organizing and taking part in a project that would > create a virtual world much like the one described in Neal > Stephenson's 'Snow Crash'. I'm not necessarily talking about > something 3d and I'm not talking about a game either. Like a MOO, > only virtual. And each 'user' is allocated space with which they are > free to edit in any way, within the confines of that space. I know > Second Life and others come to mind when you think of this, but > Frankly Second Life came off as sloppy to me. I want people to be > able to code their own objects and environments with the ease of > Python. > > I don't know forget the suggestions, anything is on the table, but > there are just so many half-hearted and weak commercial attempts at > this I feel that it's time to get Python involved in the game and do > it right. > > If anyone has any interest, ideas, comments or otherwise, e-mail me. > If some interest is shown we'll start a board, a site, an IRC channel > or whatever we have to do to meet and get the ball rolling. :) > > Thanks. > IMO, this sounds pretty interesting. Got any sources set up yet? Thinking of this as something like a "community effort" sounds nice. Interestedly, Stargaming From martin at v.loewis.de Fri May 18 00:28:03 2007 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Fri, 18 May 2007 06:28:03 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <464D2B53.9090409@v.loewis.de> > Currently, in Python 2.5, identifiers are specified as starting with > an upper- or lowercase letter or underscore ('_') with the following > "characters" of the identifier also optionally being a numerical digit > ("0"..."9"). > > This current state seems easy to remember even if felt restrictive by > many. > > Contrawise, the referenced document "UAX-31" is a bit obscure to me It's actually very easy. The basic principle will stay: the first character must be a letter or an underscore, followed by letters, underscores, and digits. The question really is "what is a letter"? what is an underscore? what is a digit? > 1) Will this allow me to use, say, a "right-arrow" glyph (if I can > find one) to start my identifier? No. A right-arrow (such as U+2192, RIGHTWARDS ARROW) is a symbol (general category Sm: Symbol, Math). See http://unicode.org/Public/UNIDATA/UCD.html for a list of general category values, and http://unicode.org/Public/UNIDATA/UnicodeData.txt for a textual description of all characters. Now, there is a special case in that Unicode supports "combining modifier characters", i.e. characters that are not characters themselves, but modify previous characters, to add diacritical marks to letters. Unicode has great flexibility in applying these, to form characters that are not supported themselves. Among those, there is U+20D7, COMBINING RIGHT ARROW ABOVE, which is of general category Mn, Mark, Nonspacing. In PEP 3131, such marks may not appear as the first character (since they need to modify a base character), but as subsequent characters. This allows you to form identifiers such as v? (which should render as a small letter v, with an vector arrow on top). > 2) Could an ``ID_Continue`` be used as an ``ID_Start`` if using a RTL > (reversed or "mirrored") identifier? (Probably not, but I don't know.) Unicode, and this PEP, always uses logical order, not rendering order. What matters is in what order the characters appear in the source code string. RTL languages do pose a challenge, in particular since bidirectional algorithms apparently aren't implemented correctly in many editors. > 3) Is or will there be a definitive and exhaustive listing (with > bitmap representations of the glyphs to avoid the font issues) of the > glyphs that the PEP 3131 would allow in identifiers? (Does this > question even make sense?) It makes sense, but it is difficult to implement. The PEP already links to a non-normative list that is exhaustive for Unicode 4.1. Future Unicode versions may add additional characters, so the a list that is exhaustive now might not be in the future. The Unicode consortium promises stability, meaning that what is an identifier now won't be reclassified as a non-identifier in the future, but the reverse is not true, as new code points get assigned. As for the list I generated in HTML: It might be possible to make it include bitmaps instead of HTML character references, but doing so is a licensing problem, as you need a license for a font that has all these characters. If you want to lookup a specific character, I recommend to go to the Unicode code charts, at http://www.unicode.org/charts/ Notice that an HTML page that includes individual bitmaps for all characters would take *ages* to load. Regards, Martin P.S. Anybody who wants to play with generating visualisations of the PEP, here are the functions I used: def isnorm(c): return unicodedata.normalize("NFC", c) def start(c): if not isnorm(c): return False if unicodedata.category(c) in ('Ll', 'Lt', 'Lm', 'Lo', 'Nl'): return True if c==u'_': return True if c in u"\u2118\u212E\u309B\u309C": return True return False def cont_only(c): if not isnorm(c): return False if unicodedata.category(c) in ('Mn', 'Mc', 'Nd', 'Pc'): return True if 0x1369 <= ord(c) <= 0x1371: return True return False def cont(c): return start(c) or cont_only(c) The isnorm() aspect excludes characters from the list which change under NFC. This excludes a few compatibility characters which are allowed in source code, but become indistinguishable from their canonical form semantically. From nospam at invalid.com Fri May 25 13:50:13 2007 From: nospam at invalid.com (Jack) Date: Fri, 25 May 2007 10:50:13 -0700 Subject: Large Amount of Data Message-ID: I need to process large amount of data. The data structure fits well in a dictionary but the amount is large - close to or more than the size of physical memory. I wonder what will happen if I try to load the data into a dictionary. Will Python use swap memory or will it fail? Thanks. From wrb302 at gmail.com Wed May 23 02:25:07 2007 From: wrb302 at gmail.com (wrb) Date: Wed, 23 May 2007 14:25:07 +0800 Subject: how to execute a system command? Message-ID: <18b5879f0705222325u3104b727la114a403971c44cf@mail.gmail.com> i want to open a excel file in a button click event. i found that os.popen4("excel.xls") would work but it is too slow (much slower than i execute "excel.xls" in command line. ) even worse, until excel is closed, the GUI has no response to user action. any advice would be helpful. From cjlesh at gmail.com Fri May 25 14:49:41 2007 From: cjlesh at gmail.com (cjl) Date: 25 May 2007 11:49:41 -0700 Subject: csv.reader length? Message-ID: <1180118981.024036.163590@p47g2000hsd.googlegroups.com> P: Stupid question: reader = csv.reader(open('somefile.csv')) for row in reader: do something Any way to determine the "length" of the reader (the number of rows) before iterating through the rows? -CJL From showell30 at yahoo.com Wed May 30 22:17:42 2007 From: showell30 at yahoo.com (Steve Howell) Date: Wed, 30 May 2007 19:17:42 -0700 (PDT) Subject: Examples of high-quality python code? In-Reply-To: <163f0ce20705301910y11e2a1cdw17160b8d7f1ca1d6@mail.gmail.com> Message-ID: <269887.64827.qm@web33515.mail.mud.yahoo.com> --- kaens wrote: > > Anyhow, I'm looking to expand my understanding of > python, and I feel > that one of the best ways to do that is looking at > other peoples code. > A lot of the built-in Python modules are implemented in pure Python. If you are using any of those so far and find them useful, you could read the source code for those. ____________________________________________________________________________________ Moody friends. Drama queens. Your life? Nope! - their life, your story. Play Sims Stories at Yahoo! Games. http://sims.yahoo.com/ From duncan.booth at invalid.invalid Fri May 4 16:46:45 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 4 May 2007 20:46:45 GMT Subject: how to find a lable quickly? References: Message-ID: "wang frank" wrote: > Hi, > > I am a new user on Python and I really love it. > > I have a big text file with each line like: > > label 3 > teststart 5 > endtest 100 > newrun 2345 > > I opened the file by uu=open('test.txt','r') and then read the data as > xx=uu.readlines() First suggestion: never use readlines() unless you really want all the lines in a list. Iterating over the file will probably be faster (especially if some of the time you can abort the search without reading all the way to the end). > > In xx, it contains the list of each line. I want to find a spcefic > labels and read the data. Currently, I > do this by > for ss in xx: > zz=ss.split( ) > if zz[0] = endtest: > index=zz[1] Ignoring the fact that what you wrote wouldn't compile, you could try: if ss.startwith('endtest '): ... > > Since the file is big and I need find more lables, this code runs > slowly. Are there anyway to speed up the process? I thought to convert > the data xx from list to a dictionay, so I can get the index quickly > based on the label. Can I do that effeciently? > Yes, if you need to do this more than once you want to avoid scanning the file repeatedly. So long as you are confident that every line in the file is exactly two fields: lookuptable = dict(s.split() for s in uu) is about as efficient as you are going to get. From steve at holdenweb.com Thu May 17 17:32:39 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 17 May 2007 17:32:39 -0400 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <464C5382.6080403@v.loewis.de> <1179423799.254286.294930@w5g2000hsg.googlegroups.com> Message-ID: Gregor Horvath wrote: > Istvan Albert schrieb: >> After the first time that your programmer friends need fix a trivial >> bug in a piece of code that does not display correctly in the terminal >> I can assure you that their mellow acceptance will turn to something >> entirely different. >> > > Is there any difference for you in debugging this code snippets? > > class T?rstock(object): > h?he = 0 > breite = 0 > tiefe = 0 > > def _get_fl?che(self): > return self.h?he * self.breite > > fl?che = property(_get_fl?che) > > #----------------------------------- > > class Tuerstock(object): > hoehe = 0 > breite = 0 > tiefe = 0 > > def _get_flaeche(self): > return self.hoehe * self.breite > > flaeche = property(_get_flaeche) > > > I can tell you that for me and for my costumers this makes a big difference. > So you are selling to the clothing market? [I think you meant "customers". God knows I have no room to be snitty about other people's typos. Just thought it might raise a smile]. > Whether this PEP gets accepted or not I am going to use German > identifiers and you have to be frightened to death by that fact ;-) > That's fine - they will be at least as meaningful to you as my English ones would be to your countrymen who don't speah English. I think we should remember that while programs are about communication there's no requirement for (most of) them to be universally comprehensible. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From steven at REMOVE.THIS.cybersource.com.au Mon May 7 20:58:52 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 08 May 2007 00:58:52 -0000 Subject: randomly write to a file References: <1178567497.042096.82940@w5g2000hsg.googlegroups.com> <1178574062.496137.11640@y5g2000hsa.googlegroups.com> Message-ID: On Mon, 07 May 2007 14:41:02 -0700, Nick Vatamaniuc wrote: > Rohit, > > Consider using an SQLite database. It comes with Python 2.5 and higher. > SQLite will do a nice job keeping track of the index. You can easily > find the line you need with a SQL query and your can write to it as > well. When you have a file and you write to one line of the file, all of > the rest of the lines will have to be shifted to accommodate, the > potentially larger new line. Using an database for tracking line number and byte position -- isn't that a bit overkill? I would have thought something as simple as a list of line lengths would do: offsets = [35, # first line is 35 bytes long 19, # second line is 19 bytes long... 45, 12, 108, 67] To get to the nth line, you have to seek to byte position: sum(offsets[:n]) -- Steven. From bj_666 at gmx.net Mon May 14 06:49:04 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 14 May 2007 12:49:04 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: In , Nick Craig-Wood wrote: > My initial reaction is that it would be cool to use all those great > symbols. A variable called OHM etc! This is a nice candidate for homoglyph confusion. There's the Greek letter omega (U+03A9) ? and the SI unit symbol (U+2126) ?, and I think some omegas in the mathematical symbols area too. Ciao, Marc 'BlackJack' Rintsch From miki.tebeka at gmail.com Fri May 4 17:10:11 2007 From: miki.tebeka at gmail.com (Miki) Date: 4 May 2007 14:10:11 -0700 Subject: Newbie and Page Re-Loading In-Reply-To: <1178302555.479739.227920@o5g2000hsb.googlegroups.com> References: <1178275290.158007.248180@h2g2000hsg.googlegroups.com> <463b6678$0$10433$426a34cc@news.free.fr> <1178302555.479739.227920@o5g2000hsb.googlegroups.com> Message-ID: <1178313011.279170.292200@u30g2000hsc.googlegroups.com> Hello Richard, > I do not want to run a framework yet. I would like to understand > python at script level, before adding more aspects to learn, like > frameworks. The way CGI works is that your script is called every time the corresponding HTML is loaded. You can access all the parameters sent to the script using cgi.FieldStorage. > I think I get your idea about hidden fields and how to alter them. Note that hidden fields are passed in plain text format from/to the server, don't send anything sensitive in them. > My single page script should work something like this > > DisplayHTMLHeaderandBodyHeader > Check if this is a Re-Load (HiddenField would not exist first time I > am assuming) It could be None: cgi.FieldStorage().getvalue("hidden_attribute") == None > Display SearchSection with previous SearchRequest > If SearchRequest is True: Get and Display Results > Display TrailerHTMLandTrailerBody > > ......... Wait for NewSearch or NextPage In CGI you don't wait, the script exists and called again when use hits a button/refresh ... > Does the above make sense or is there a better way ? There are many other ways (AJAX, Web frameworks, FastCGI ...). However I'd recommend you start with plain CGI which is *simple*. Here is a small example: #!/usr/local/bin/python import cgitb; cgitb.enable() # Show errors in HTML output from cgi import FieldStorage FUNNY = [ "mickey", "donald", "daisy", "minnie", "goofy" ] def main(): print "Content-Type: text/html" print form = FieldStorage() query = form.getvalue("query", "") print '''

    Disney Search

    ''' % query if query: for someone in FUNNY: if query in someone: print "
    %s" % someone print "
    " if __name__ == "__main__": main() > How do I get the directory of my modules into the Python Path import sys sys.path.append("/path/to/my/modules") Note that your script directory is automatically added to the path. > Is there a lightweight Https Server I could run locally (WINXP), which > would run .py scripts, without lots of installation modifications ? http://lighttpd.net. Make sure "mod_cgi" is uncommented, set your document root and set right python interpreter in cgi.assign HTH, -- Miki http://pythonwise.blogspot.com From john at datavoiceint.com Tue May 15 15:26:36 2007 From: john at datavoiceint.com (HMS Surprise) Date: 15 May 2007 12:26:36 -0700 Subject: Splitting a string In-Reply-To: References: <1179253692.110024.96330@w5g2000hsg.googlegroups.com> Message-ID: <1179257196.719701.120020@e51g2000hsg.googlegroups.com> Thanks everyone. The shell's display really threw me off. Don't really understand why it looks different typing t vs print t. Now that I can see past that split works just as advertised. Not real clear on triple quotes but I have seen it used and I can see where triple is needed to differentiate from the usage of double quotes. jvh From cesar.gomes at gmail.com Sat May 12 12:18:06 2007 From: cesar.gomes at gmail.com (Cesar G. Miguel) Date: 12 May 2007 09:18:06 -0700 Subject: Basic question Message-ID: <1178986686.510137.195490@p77g2000hsh.googlegroups.com> I've been studying python for 2 weeks now and got stucked in the following problem: for j in range(10): print j if(True): j=j+2 print 'interno',j What happens is that "j=j+2" inside IF does not change the loop counter ("j") as it would in C or Java, for example. Am I missing something? []'s Cesar From DustanGroups at gmail.com Thu May 3 07:07:27 2007 From: DustanGroups at gmail.com (Dustan) Date: 3 May 2007 04:07:27 -0700 Subject: How to check if a string is empty in python? In-Reply-To: References: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> Message-ID: <1178190447.290370.59360@u30g2000hsc.googlegroups.com> On May 2, 5:50 pm, Steven D'Aprano wrote: > On Wed, 02 May 2007 13:35:47 -0700, noagbodjivictor wrote: > > How to check if a string is empty in python? > > if(s == "") ?? > > In no particular order, all of these methods will work: > > # test s is equal to another empty string > if s == "": > > # assuming s is a string, test that it is empty > if not s: > > # test s is a string and it is empty > if isinstance(s, str) and not s: > > # test s has length 0 > if len(s) == 0: > > # test the length of s evaluates as false > if not len(s): > > # a long way to test the length of s > if s.__len__() < 1: > > # a stupid way to test s is empty > if bool(s) == False: > > # a REALLY stupid way to test s is empty > if (bool(s) == False) == True: > > # test that appending s to itself is itself > if s+s == s: Being the slow person that I am, it really did take me this long to find a mistake. s+s != 'appending' s+s == 'concatenation' > # test that s has none of any character > if not filter(None, [1 + s.find(chr(n)) for n in range(256)]): > > That last one is really only good for wasting CPU cycles. > > -- > Steven. From google at mrabarnett.plus.com Sun May 13 17:31:00 2007 From: google at mrabarnett.plus.com (MRAB) Date: 13 May 2007 14:31:00 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476081.7080609@web.de> Message-ID: <1179091860.624385.14320@k79g2000hse.googlegroups.com> On May 13, 8:49 pm, Michael Torrie wrote: > On Sun, 2007-05-13 at 21:01 +0200, Stefan Behnel wrote: > > For example, I could write > > > def zieheDreiAbVon(wert): > > return zieheAb(wert, 3) > > > and most people on earth would not have a clue what this is good for. However, > > someone who is fluent enough in German could guess from the names what this does. > > > I do not think non-ASCII characters make this 'problem' any worse. So I must > > ask people to restrict their comments to the actual problem that this PEP is > > trying to solve. > > I think non-ASCII characters makes the problem far far worse. While I > may not understand what the function is by it's name in your example, > allowing non-ASCII characters makes it works by forcing all would-be > code readers have to have all kinds of necessary fonts just to view the > source code. Things like reporting exceptions too. At least in your > example I know the exception occurred in zieheDreiAbVon. But if that > identifier is some UTF-8 string, how do I go about finding it in my text > editor, or even reporting the message to the developers? I don't happen > to have that particular keymap installed in my linux system, so I can't > even type the letters! > > So given that people can already transliterate their language for use as > identifiers, I think avoiding non-ASCII character sets is a good idea. > ASCII is simply the lowest denominator and is support by *all* > configurations and locales on all developers' systems. > Perhaps there could be the option of typing and showing characters as \uxxxx, eg. \u00FC instead of ? (u-umlaut), or showing them in a different colour if they're not in a specified set. From obaudys at gmail.com Wed May 16 01:44:51 2007 From: obaudys at gmail.com (obaudys at gmail.com) Date: 15 May 2007 22:44:51 -0700 Subject: Quote aware split In-Reply-To: References: <41749080705151750m3367c65dy4d1ae6ca66c2a16b@mail.gmail.com> Message-ID: <1179294291.873901.70220@l77g2000hsb.googlegroups.com> On May 16, 1:18 pm, "Gabriel Genellina" wrote: > The "is" operator checks object *identity*, that is, if both operands are > actually the same object. It may or may not work here, depending on many > implementation details. You really should check if they are *equal* > instead: > > if c == quote: > qcount += 1 > if c == sep and qcount % 2 == 0: > splitpoints.append(index) I was always under the impression the 'a' and 'a' were always the same object and *is* and == were interchangeble with strings, since they were immutable. But sure enough running your code snippet example: > See: > py> x='a' > py> y='A'.lower() > py> y > 'a' > py> x==y > True > py> x is y > False I got the same result as you. Point taken, thank you! Interestingly: py> id('a') -1209815264 py> id(x) -1209815264 py> id(y) -1210219808 py> id('A'.lower()) -1210219712 So there are at least three 'a' string objects registered in whatever hashtable implementation lies underneath Python's string datatype. From johnjsal at NOSPAMgmail.com Wed May 9 10:35:37 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 09 May 2007 10:35:37 -0400 Subject: Suggestions for how to approach this problem? In-Reply-To: References: <4640ca5b$0$23392$c3e8da3@news.astraweb.com> <4640d69b$0$31446$c3e8da3@news.astraweb.com> Message-ID: <4641dc0c$0$8784$c3e8da3@news.astraweb.com> James Stroud wrote: > If you can count on the person not skipping any numbers in the > citations, you can take an "AI" approach to hopefully weed out the rare > circumstance that a number followed by a period starts a line in the > middle of the citation. I don't think any numbers are skipped, but there are some cases where a number is followed by a period within a citation. But this might not matter since each reference number begins at the start of the line, so I could use the RE to start at the beginning. From ramen at lackingtalent.com Mon May 28 23:12:58 2007 From: ramen at lackingtalent.com (Dave Benjamin) Date: Mon, 28 May 2007 20:12:58 -0700 Subject: Resize image NO PIL!! In-Reply-To: <1180406398.615904.22230@g4g2000hsf.googlegroups.com> References: <1180406398.615904.22230@g4g2000hsf.googlegroups.com> Message-ID: cbmeeks wrote: > I have created an image hosting site and when a user uploads an image, > I want a service to run on the server to create a few thumbnails while > the user does other things. > > My stupid host (pair.com) doesn't have PIL installed and I'm too much > of a stupid newbie to figure out how to get it to work with them > (access denied while installing it, of course). > > Also, they don't have any python interface setup for GD. > > Anyway, I don't know what my options are. I'm thinking: > > 1) Find another host with mod_python, PIL, and other Python goodies > 2) use PHP to create the thumbnails > 3) Open the images into a buffer and try to do the calculations > myself Have you checked to see if Imagemagick is available? You could use the "convert" command via os.system or something along those lines... Dave From jzgoda at o2.usun.pl Fri May 18 18:22:38 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Sat, 19 May 2007 00:22:38 +0200 Subject: (Modular-)Application Framework / Rich-Client-Platform in Python In-Reply-To: <3750e$464e1bda$d443bb3a$11610@news.speedlinq.nl> References: <8ea03$464dc950$d443bb3a$5229@news.speedlinq.nl> <3750e$464e1bda$d443bb3a$11610@news.speedlinq.nl> Message-ID: Stef Mientki napisa?(a): > I took a look at some of the examples build with eclipse, > and I might be wrong, but it's just another IDE, > (like Delphi, Lazarus, Visual Basic, Kylix, Pida, Envisage, VisualWX, > wxGlade, ...) > what am I missing ? I think you miss the difference between Eclipse IDE and Eclipse Platform. The IDE is and application built using RCP. As Azureus or RSSOwl, which aren't IDE-type applications. One of the tutorials mentioned int the RCP wiki takes user through creating an email client application, which is not an IDE, definitely. Eclipse RCP allows building applications as a set of pluggable features over common runtime. While not a "mark-and-drop" solution yet, it's a great leap forward in Java desktop applications. There's more to Eclipse that just IDE. ;) -- Jarek Zgoda http://jpa.berlios.de/ From zubeido at yahoo.com.br Sat May 19 12:14:17 2007 From: zubeido at yahoo.com.br (aiwarrior) Date: 19 May 2007 09:14:17 -0700 Subject: Writelines() a bit confusing In-Reply-To: References: <1179578195.565952.244110@u30g2000hsc.googlegroups.com> Message-ID: <1179591257.631363.198410@k79g2000hse.googlegroups.com> On May 19, 2:46 pm, "Gre7g Luterman" wrote: > "aiwarrior" wrote in message > > news:1179578195.565952.244110 at u30g2000hsc.googlegroups.com... > > > If file.WriteLines( seq ) accepts a list and it says it writes lines, > > why does it write the whole list in a single line. Be cause of that > > the reverse of file.writelines(seq) is not file.readlines(). > > Are the assumptions i made correct? If yes why is this so? > > readlines() and writelines() are complimentary. readlines() leaves the line > terminators intact. It does not strip them off. writelines() does not add in > carriage returns for the same reason. For example: > > >>> D=open("temp.txt").readlines() > >>> D > > ['the quick\n', 'brown fox\n', 'jumps over\n', 'the lazy dog.'] > > >>> open("temp2.txt","w").writelines(D) > > will create temp2.txt to be identical to temp.txt. I Haven't seen that way before thanks, both of you :D From gagsl-py2 at yahoo.com.ar Mon May 14 16:54:25 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 14 May 2007 17:54:25 -0300 Subject: Time References: <1178916216.893542.257320@y80g2000hsf.googlegroups.com> <1178916422.065108.312920@l77g2000hsb.googlegroups.com> <1178920014.621031.301860@n59g2000hsh.googlegroups.com> <1178927105.482975.174760@y5g2000hsa.googlegroups.com> <1179151205.987222.54910@k79g2000hse.googlegroups.com> <1179152573.315362.37040@u30g2000hsc.googlegroups.com> <1179152855.424498.274820@p77g2000hsh.googlegroups.com> <134hdehnrd73bef@corp.supernews.com> <134hdjrq1jkd4a4@corp.supernews.com> Message-ID: En Mon, 14 May 2007 16:20:27 -0300, Grant Edwards escribi?: >>>> On May 14, 9:22 am, HMS Surprise wrote: >>>> >>>> Oops +=1, should be: >>>> hrMn[0] = int(hrMn[0] >>>> if t[2] == 'PM': >>>> hrMn[0] += 12 >>>> >>>> Need more starter fluid, coffee please!!! >>> >>> Still won't work for 12 AM nor 12 PM... >> >> Do you mean 12 Noon or 12 Midnight? 12AM and 12PM don't exist, >> do they? > > http://www.astronomy.net/articles/13/ No. Even ignoring that exact instant at Noon or Midnight, 12:01 PM translates into itself, 12:01, on a 24 hr clock; and 12:01 AM becomes 0:01 on a 24 hr clock. For hours between 01 PM and 11 PM, yes, you can follow the rule "add 12". -- Gabriel Genellina From Eric_Dexter at msn.com Sat May 26 08:55:53 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 26 May 2007 05:55:53 -0700 Subject: How to get started as a xhtml python mysql freelancer ? In-Reply-To: <1180140942.239003.94640@h2g2000hsg.googlegroups.com> References: <1180136893.220560.49340@q75g2000hsh.googlegroups.com> <1180140942.239003.94640@h2g2000hsg.googlegroups.com> Message-ID: <1180184153.675202.272320@p77g2000hsh.googlegroups.com> On May 25, 7:55 pm, gert wrote: > On May 26, 2:09 am, Paul McNett wrote: > > > > > > > gert wrote: > > > I made something that i was hoping it could make people happy enough > > > so i could make a living by providing support for commercial use of > > >http://sourceforge.net/projects/dfo/ > > > > But in reality i am a lousy sales men and was wondering how you people > > > sell stuff as a developer ? > > > In my experience, you don't make money by selling support unless you are > > a large company selling support for a large project or a wide array of > > projects. The people that will use your library will mostly be > > developers and not end-users, after all. > > > To make money from things you develop, I think you need to take your > > library and either build an application that has wide appeal and sell > > that, or sell yourself as a custom developer that can build the > > application the customer needs, using the tools you are comfortable > > with. You can then build in the cost of developing your library that you > > will reuse for the custom applications. > > And where do you find customers, most people i talk too fall a sleep > let alone understand when i say the word xhtml ? > > > What does it do exactly. > > Forum, shop, appointments, invoice, EAN13 barcode or just simple sql > statements web based. Code is very straight forward. Applications > included are just examples of what mod_python basically can do for you.- Hide quoted text - > > - Show quoted text - People do put python stuff up for bid at rentacoder. What I am seeing is general stuff, I would say as part of my web presentation That I do custom work or whatever, part of it is to be that person and then do it... You might try google I have an add on the side of my screen that says freelance web designers part-time or Full-time Earn up to $40 an hour.. When I was looking at your page I couldn't tell what it was, I see that as a problem from a promotional standpoint (I do google adds so I am big on self promotion)... I would add to that you are available for custom work... maybe do some stuff with paypal or some payment system. You may want a wider focus, and screen shots of stuff you have done From rene at korteklippe.de Wed May 16 04:36:31 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Wed, 16 May 2007 10:36:31 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464AC16E.1010609@web.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <46478694$0$1412$426a34cc@news.free.fr> <1hy252p.1anf7sr1p4yp12N%aleax@mac.com> <464988a4$0$20289$9b4e6d93@newsspool3.arcor-online.net> <464aaee8$0$10188$9b4e6d93@newsspool4.arcor-online.net> <464ab811$0$10185$9b4e6d93@newsspool4.arcor-online.net> <464AC16E.1010609@web.de> Message-ID: <464ac28e$0$20297$9b4e6d93@newsspool3.arcor-online.net> Stefan Behnel schrieb: > *Your* logic can be used to justify dropping *any* feature. No. I am considering both the benefits and the problems. You just happen to not like the outcome of my considerations [again, please don't reply by E-Mail, I read the NG]. -- Ren? From michael at jedimindworks.com Sun May 20 08:41:45 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Sun, 20 May 2007 07:41:45 -0500 Subject: Unable to strip \n characters In-Reply-To: <1179658203.040541.220800@p77g2000hsh.googlegroups.com> References: <1179658203.040541.220800@p77g2000hsh.googlegroups.com> Message-ID: On May 20, 2007, at 5:50 AM, aiwarrior wrote: > files = f.readlines() > for upload in files: > upload.strip("\n") > final_args = "./rsapiresume.pl %s prem user password" % (upload) > print upload > #os.system( final_args ) for upload in f: final_args = "./rsapiresume.pl %s prem user password" % (upload.strip()) print final_args #os.system(final_args) From xah at xahlee.org Wed May 30 03:00:53 2007 From: xah at xahlee.org (Xah Lee) Date: 30 May 2007 00:00:53 -0700 Subject: The Concepts and Confusions of Prefix, Infix, Postfix and Fully Functional Notations In-Reply-To: <1179936917.652372.24780@q69g2000hsb.googlegroups.com> References: <1179936917.652372.24780@q69g2000hsb.googlegroups.com> Message-ID: <1180508453.226022.44230@q19g2000prn.googlegroups.com> Prefix, Infix, Postfix notations in Mathematica 2000-02-21, 2007-05 [In the following essay, I discuss prefix, infix, postfix notations and Mathematica's syntax for them. The full HTML formatted article is available at: http://xahlee.org/UnixResource_dir/writ/notations.html ] THE HEAD OF EXPRESSIONS Lisp's nested parenthesis syntax is a Functional Notation. It has the general form of ?(f a b ...)? where any of the symbols inside the matching parenthesis may again be that form. For example, here's a typical code from Emacs Lisp. ; Recursively apply (f x i), where i is the ith element in the list li. ; For example, (fold f x '(1 2)) computes (f (f x 1) 2) (defun fold (f x li) (let ((li2 li) (ele) (x2 x)) (while (setq ele (pop li2)) (setq x2 (funcall f x2 ele)) ) x2 ) ) Vast majority of computer languages, interpret source code in a one- dimensional, linear nature. Namely, from left to right, line by line, as in written text. (Examples of computer languages's source code that are not linear in nature, are spread sheets, cellular automata, graphical programing languages) For languages that interprets source code linearly, the logics of their syntax necessarily have a hierarchical structure (i.e. tree). The lisp's notation, is the most effective in visually showing the logics of the syntax. This is because, a function and its arguments, are simply laid out inside a parenthesis. The level of nesting corresponds to the ?precedence? in evaluating the expression. The first element inside the matching parenthesis, is called the ?head? of the expression. For example, in ?(f a b)?, the ?f? is the head. The head is a function, and the rest of the symbols inside the matching parenthesis are its arguments. The head of lisp's notation needs not to be defined as the first element inside the parenthesis. For example, we can define the ?head? to be the last element inside the parenthesis. So, we write ?(arg1 arg2 ... f)? instead of the usual ?(f arg1 arg2 ...)? and its syntactical analysis remains unchanged. Like wise, you can move the head outside of the parenthesis. In Mathematica, the head is placed in front of the parenthesis, and square brackets are used instead of parenthesis for the enclosing delimiter. For example, lisp's ?(f a b c)? is syntactically equivalent to Mathematica's ?f[a,b,c]?. Other examples: ?(sin ?)? vs ?Sin[?]?, ?(map f list)? vs ?Map[f,list]?. Placing the head in front of the matching bracket makes the notation more familiar, because it is a conventional math notation. However, there is a disadvantage in moving the head of a expression from inside the matching bracket to outside. Namely: The nesting of the matching delimiters, no longer corresponds to the logics of the syntax, when the head is itself a compound expression. For example, suppose Reflection(vectorV,pointP) is function that returns a function f, such that f(graphicsData) will reflect the graphicsData along a line passing pointP and parallel to vectorV. In lisp, we would write ?((Reflection vectorV pointP) graphicsData)?. In Mathematica, we would write ?Reflection[vectorV,pointP] [graphicsData]?. In lisp's version, the nesting corresponds to the logics of the evaluation. In the Mathematica's form, that is no longer so. For another example, suppose Deriv is a function that takes a function f and returns a function g (the derivative of f), and we want to apply g to a variable x. In lisp, we would write ?((Deriv f) x)?. In Mathematica, we would write ?Deriv[f][x]?. In lisp's version, the nesting corresponds to the logics of the evaluation. In the Mathematica's form, the logics of the evaluation no longer corresponds to the nesting level, because now the head is outside of the enclosing delimiters, so the head of expressions no longer nests. PREFIX, POSTFIX, INFIX A prefix notation in Mathematica is represented as ?f at arg?. Essentially, a prefix notation in this context limits it to uses for functions on only one argument. For example: ?f at a@b at c? is equivalent to ?f[a[b[c]]]? or in lispy ?(f (a (b c)))?. Mathematica also offers a postfix notation using the operator ?//?. For example, ?c//b//a//f? is syntactically equivalent to ?f[a[b[c]]]?. (unix's pipe ?|? syntax, is a form of postfix notation. e.g. ?c | b | a | f?). For example, ?Sin[List[1,2,3]]? can be written in postfix as ?List[1,2,3]//Sin?, or prefix ?Sin at List[1,2,3]?. (by the way, they are semantically equivalent to ?Map[Sin, List[1,2,3]]? in Mathematica) For infix notation, the function symbol is placed between its arguments. In Mathematica, the generic form for infix notation is by sandwiching the tilde symbol around the function name. e.g. ?Join[List[1,2],List[3,4]]? is syntactically equivalent to ?List[1,2] ~Join~ List[3,4]?. In Mathematica, there is quite a lot syntax variations beside the above mentioned systematic constructs. For example, Plus[a,b,c] can be written as ?a+b+c?, ?Plus[a+b,c]?, ?Plus[Plus[a,b],c]?, or ?(a +b)~Plus~c?. ?List[a,b,c]? can be written as ?{a,b,c}?, and ?Map[f,List[a,b,c]]? can be written as ?f /@ {a,b,c}?. The gist being that certain functions are given a special syntactical construct to emulate the irregular and inefficient but nevertheless well-understood conventional notations. Also, it reduces the use of deep nesting that is difficult to type and manage. For example, the ?Plus? function is given a operator ?+?, so that Plus[3,4] can be written with the more familiar ?3+4?. The ?List? function is given a syntax construct of ?{}?, so that, List[3,4] can be more easily written as ?{3,4}?. The boolean ?And? function is given the operator ?&&?, so that And[a,b] can be written with the more familiar and convenient ?a && b?. Combining all these types of syntax variations, it can make the source code easier to read than a purely nested structure. For example, common math expressions such as ?3+2*5>7? don't have to be written as ?Greater[Plus[3,Times[2,5]],7]? or the lispy ?(> (+ 3 (* 2 5)) 7)?. C and Perl When we say that C is a infix notation language, the term ?infix notation? is used loosely for convenience of description. C and other language's syntaxes derived from it (e.g. C++, Java, Perl, Javascript...) are not based on a notation system, but takes the approach of a ad hoc syntax soup. Things like ?i++?, ?++i?, ?for(;;) {}?, ?while(){}?, 0x123, ?sprint(...%s...,...)?, ... are syntax whimsies. As a side note, the Perl mongers are proud of their slogan of ?There Are More Than One Way To Do It? in their gazillion ad hoc syntax sugars but unaware that in functional languages (such as Mathematica, Haskell, Lisp) that there are consistent and generalized constructs that can generate far more syntax variations than the ad hoc inflexible Perl both in theory AND in practice. (in lisp, its power of syntax variation comes in the guise of macros.) And, more importantly, Perlers clamor about Perl's ?expressiveness? more or less on the syntax level but don't realize that semantic expressibility is far more important. Xah xah at xahlee.org ? http://xahlee.org/ From claird at lairds.us Sat May 19 21:54:14 2007 From: claird at lairds.us (Cameron Laird) Date: Sun, 20 May 2007 01:54:14 +0000 Subject: [dfwPython] A Few More Forrester Survey Questions References: <464DC49F.1090608@taupro.com> Message-ID: <6bm4i4-9a4.ln1@lairds.us> In article , Brad Allen wrote: >At 10:22 AM -0500 5/18/07, Jeff Rush wrote: . . . >>3) What is the value of the language to developers? >> >> Yeah, a very common, slippery question. Toss me some good >> explanations of why -you- value Python. Readable, free, >> cross-platform, powerful. What else? I'll synthesize >> something out of everyone's answers. > >Learn once, use everywhere: web apps, GUI apps, command line scripts, >systems integration glue, wrapping libraries from other languages, > >Wide range of scale: from quick and dirty tasks to large complex systems. > >Wide range of skill: accessible to beginners, but supports advanced >concepts experienced developers require. > >Practical syntax which emphasizes elegance and clarity through minimalism > >Dynamic language features allow high level and flexible design approach, >boosting productivity. > >Robustness - bugs in Python itself are rare due to maturity from long >widespread use. > >No IDE required: you go far with simple text editors, but good IDEs are >available. > >Good community support due to widespread use and open source nature. > >Great as glue language, due to flexible options for calling external binary >apps > >Mature ecosystem of libraries, both cross platform and platform native, >and good options for accessing libraries in other languages. > >Professional opportunities: Python is in production use in a lot of companies, >who realize it costs less than static languages and is more generally useful >than PHP or Ruby. The only real competitor is Perl, which can be difficult >to manage due to readability problems. . . . Also important: correct Unicode handling. From iltchevi at gmail.com Sun May 6 17:56:03 2007 From: iltchevi at gmail.com (ici) Date: 6 May 2007 14:56:03 -0700 Subject: Did you read about that? In-Reply-To: <1178474101.930602.77770@n59g2000hsh.googlegroups.com> References: <1178446711.502374.286790@l77g2000hsb.googlegroups.com> <1178452403.114975.249050@u30g2000hsc.googlegroups.com> <1178457498.639373.157350@y80g2000hsf.googlegroups.com> <463dd72e$0$331$e4fe514c@news.xs4all.nl> <1178474101.930602.77770@n59g2000hsh.googlegroups.com> Message-ID: <1178488563.299751.270890@n59g2000hsh.googlegroups.com> On May 6, 8:55 pm, gene tani wrote: > On May 6, 6:26 am, "Martin P. Hellwig" wrote: > > > > > Dustan wrote: > > > On May 6, 8:20 am, Steven D'Aprano > > > wrote: > > >> On Sun, 06 May 2007 04:53:23 -0700, Dustan wrote: > > >>> SPAM! > > >>> SPAM! > > >>> SPAM! > > >>> SPAM! > > >>> SPAM! > > >>> SPAM! > > >>> SPAM! > > >>> SPAM! > > >> Gosh, you think so? I'm glad we had you around to tell us, otherwise we > > >> might have thought it was about Python programming. > > > >> Actually, many of us wouldn't even have seen it in the first place, > > >> because our ISPs do a good job of filtering out obvious spam before we > > >> even see it. And then people like you come along, and reply to it, and we > > >> see the reply -- complete with the original spam. > > > > Well, sorry. I didn't realize I'd get whacked around for making a > > > joke. > > > >> -- > > >> Steven. > > > Aren't jokes supposed to be funny? > > > > > -- > > mph > > >http://martinphellwig.blogspot.com/ > > What you can do: > > complain to Google adsense about the site's "advertising" > complain to Google groups about the post > > it would be #complete unethical# for me to suggest that OP posted an > apparently unrelated topic because he wanted the site's performance > "ab" tested, like, y'know > > ab -n 100000 -kc 200http://yourspamsitehere.com No way :( I did many times, ... RE: Google is not moderator bla, bla, shits... From ready.or.special2 at gmail.com Mon May 14 03:09:36 2007 From: ready.or.special2 at gmail.com (ready.or.special2 at gmail.com) Date: 14 May 2007 00:09:36 -0700 Subject: Jessica Simpson Sports new "Boob Job"!!!@ Message-ID: <1179126576.229946.109600@k79g2000hse.googlegroups.com> http://jessicasboobs.blogspot.com/2007/05/jessica-simpson-furious-after-john.html - Have a look and see what I mean its a boob job you just can't afFORD to miss out on!! From erikwickstrom at gmail.com Sat May 26 15:25:21 2007 From: erikwickstrom at gmail.com (erikcw) Date: 26 May 2007 12:25:21 -0700 Subject: Why isn't this query working in python? In-Reply-To: References: <1180103946.552760.239200@p47g2000hsd.googlegroups.com> <6e42ec490705250751i89d3cf3v3a3062690d0284aa@mail.gmail.com> Message-ID: <1180207521.072958.322770@p47g2000hsd.googlegroups.com> On May 25, 11:28 am, Carsten Haese wrote: > On Fri, 2007-05-25 at 09:51 -0500, Dave Borne wrote: > > > I'm trying to run the following query: > > ... > > > member_id=%s AND expire_date > NOW() AND completed=1 AND (product_id > > > Shouldn't you be using the bind variable '?' instead of '%s' ? > > The parameter placeholder for MySQLdb is, indeed and unfortunately, %s. > The OP is using parameter substitution correctly, though in an > obfuscated fashion. 'sql' is a misnamed tuple containing both the query > string *and* the parameters, which is being unpacked with '*' into two > arguments to the execute call. > > The only problem I see is that the parameters should be a sequence, i.e. > (self.uid,) instead of just (self.uid). > > HTH, > > -- > Carsten Haesehttp://informixdb.sourceforge.net I tried adding the comma to make it a sequence - but now change. ('SELECT payment_id FROM amember_payments WHERE member_id=%s AND expire_date > NOW() AND completed=1 AND (product_id >11 AND product_id <21)', (1608L,)) () What else could it be? Thanks! Erik From seyensubs at yahoo.com Mon May 14 13:36:33 2007 From: seyensubs at yahoo.com (seyensubs at yahoo.com) Date: 14 May 2007 10:36:33 -0700 Subject: Sorting troubles In-Reply-To: <1179162617.578315.133640@h2g2000hsg.googlegroups.com> References: <1179158708.433792.127150@h2g2000hsg.googlegroups.com> <1179162617.578315.133640@h2g2000hsg.googlegroups.com> Message-ID: <1179164193.047412.231310@n59g2000hsh.googlegroups.com> I see. I figured that list comprehensions made another list(duh), but I thought I could relink the object(List) to the new list and keep it once the function ended. Is it possible to pass a reference(to an object.. Like 'List', basically) to a function and change the reference to point to something created inside a function? Or all data unreturned from a function is lost and no references kept?(The second, I'd guess, since it's local temporary scope, but you never know, maybe Python can :) ) From carsten at uniqsys.com Mon May 7 10:50:47 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 07 May 2007 10:50:47 -0400 Subject: problem with quoted strings while inserting into varchar field of database. In-Reply-To: <1178548015.856661.308070@u30g2000hsc.googlegroups.com> References: <1178475772.423687.118800@e65g2000hsc.googlegroups.com> <1178526655.933789.294700@h2g2000hsg.googlegroups.com> <1178530363.516882.228380@l77g2000hsb.googlegroups.com> <1178548015.856661.308070@u30g2000hsc.googlegroups.com> Message-ID: <1178549447.3360.24.camel@dot.uniqsys.com> On Mon, 2007-05-07 at 07:26 -0700, Daniele Varrazzo wrote: > > >> >> > cur.execute("INSERT INTO datatable (data) VALUES (%s);", > > >> >> > (pickled_data,)) > > > %s is not a placeholder IMHO. > > > What happens when using %s is, that the string given will be inserted where > > %s is; that is something python does as with every print or such. > > It is indeed. The behavior you describe would be true if i had used > the "%" operator. Read better what i have written: There is no "%" > operator. This confusion is precisely why I think the (py)format paramstyles should be deprecated in a future version of the DB-API spec. Question marks make it immediately obvious that something other than string formatting is happening, and if I'm not mistaken, question marks are SQL standard. -- Carsten Haese http://informixdb.sourceforge.net From stargaming at gmail.com Thu May 17 14:20:00 2007 From: stargaming at gmail.com (Stargaming) Date: Thu, 17 May 2007 20:20:00 +0200 Subject: Is wsgi ready for prime time? In-Reply-To: References: Message-ID: Ron Garret wrote: > The wsgiref module in Python 2.5 seems to be empty: > > [ron at mickey:~/Sites/modpy]$ python > Python 2.5 (r25:51908, Mar 1 2007, 10:09:05) > [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>>>import wsgiref >>>>dir(wsgiref) > > ['__builtins__', '__doc__', '__file__', '__name__', '__path__'] > > > So... is wsgi considered ready for production use, or is it still on the > bleeding edge? And if the former, which implementation should one use? > > rg >>> help(wsgiref) Help on package wsgiref: NAME wsgiref - wsgiref -- a WSGI (PEP 333) Reference Library DESCRIPTION Current Contents: * util -- Miscellaneous useful functions and wrappers * headers -- Manage response headers * handlers -- base classes for server/gateway implementations * simple_server -- a simple BaseHTTPServer that supports WSGI * validate -- validation wrapper that sits between an app and a server to detect errors in either To-Do: * cgi_gateway -- Run WSGI apps under CGI (pending a deployment standard) * cgi_wrapper -- Run CGI apps under WSGI * router -- a simple middleware component that handles URL traversal PACKAGE CONTENTS handlers headers simple_server util validate Reading the documentation can be useful sometimes. Recommending http://docs.python.org/lib/module-wsgiref.html, too. From robert.kern at gmail.com Thu May 17 15:55:08 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 17 May 2007 14:55:08 -0500 Subject: FreeType In-Reply-To: <1179431247.954420.219690@q75g2000hsh.googlegroups.com> References: <1179422948.600593.117310@p77g2000hsh.googlegroups.com> <1179431247.954420.219690@q75g2000hsh.googlegroups.com> Message-ID: Glich wrote: > I've been there. All the code is in C/C++, don't I need it in python? > I will explore the software. I dismissed this because there was no > python. I am knew to all of this. Thanks for your reply. matplotlib has extension modules that wrap the C library. You will need to install libfreetype, then build matplotlib. -- 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 charles.vejnar at isb-sib.ch Fri May 25 15:40:33 2007 From: charles.vejnar at isb-sib.ch (Charles Vejnar) Date: Fri, 25 May 2007 21:40:33 +0200 Subject: Long double in Python Message-ID: <200705252140.34353.charles.vejnar@isb-sib.ch> Hi, I have a C library using "long double" numbers. I would like to be able to keep this precision in Python (even if it's not portable) : for the moment I have to cast the "long double" numbers to "double" numbers. 1st solution . Is it possible that by re-compiling Python, Python Float object becomes "long double" C type instead of "double" ? 2nd solution : Numpy. In memory, a "numpy.longdouble" is a C "long double" or a string ? Thank you. Charles From exarkun at divmod.com Fri May 4 07:21:37 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 4 May 2007 07:21:37 -0400 Subject: Non blocking sockets with select.poll() ? In-Reply-To: Message-ID: <20070504112137.19381.249713413.divmod.quotient.8262@ohm> On Fri, 4 May 2007 13:04:41 +0300, Maxim Veksler wrote: >Hi, > >I'm trying to write a non blocking socket port listener based on >poll() because select is limited to 1024 fd. > >Here is the code, it never gets to "I did not block" until I do a >telnet connection to port 10000. > What were you expecting? Jean-Paul From laxmikiran.bachu at gmail.com Thu May 24 08:43:41 2007 From: laxmikiran.bachu at gmail.com (laxmikiran.bachu at gmail.com) Date: 24 May 2007 05:43:41 -0700 Subject: Changing Unicode object to Tuple Type In-Reply-To: <5bldo8F2tlcqfU1@mid.uni-berlin.de> References: <1180007144.514744.188090@q75g2000hsh.googlegroups.com> <5bldo8F2tlcqfU1@mid.uni-berlin.de> Message-ID: <1180010621.001281.268800@g4g2000hsf.googlegroups.com> On May 24, 5:11 pm, "Diez B. Roggisch" wrote: > laxmikiran.ba... at gmail.com schrieb: > > > Can we have change a unicode string Type object to a Tuple type > > object.. If so how ???? > > Why? Are you getting an error that makes you think that's a good idea? > > Tuples are basically structs, unicode objects are strings. There is no > canonical way to convert them. Tell us more about the problem you want > to be solved, and we might help you better. > > diez ********** I have to get few strings from an application(strings of different languages..ex: korean,japanese,french etc.,). The data returned by the application was in the format of the xml. Hence I was using pyRXP to get the data. I was not able to get all the strigs in different languages. Now I wanted to use pyRXPU to get all the strings of that application.When Iam using pyRXPU iam getting the following error. Traceback (most recent call last): File "D:\LanguageScripts\Screens.py", line 106, in test_1_01_DoSomething TitlenSoftkeyfn() File "D:\LanguageScripts\EventLog_Screens.py", line 66, in TitlenSoftkeyfn titleBar = root.TitleBar.currentText File "D:\LanguageScripts\XmlWrapper.py", line 35, in __getattr__ tagName, attrs, children, spare = child ValueError: need more than 1 value to unpack Here the child is of the format unicode.. When pyRXP is used it was of the format tuple... I was just trying to find out if there is some way that I make this code work. From toby at tobiah.org Wed May 2 18:30:18 2007 From: toby at tobiah.org (Tobiah) Date: Wed, 02 May 2007 15:30:18 -0700 Subject: Slicing Arrays in this way In-Reply-To: <1178144792.759932.313190@l77g2000hsb.googlegroups.com> References: <4638fe20$0$16403$88260bb3@free.teranews.com> <1178144792.759932.313190@l77g2000hsb.googlegroups.com> Message-ID: <4639046a$0$10194$88260bb3@free.teranews.com> John Machin wrote: > On May 3, 8:03 am, Tobiah wrote: >> >>> elegant_solution([1,2,3,4,5,6,7,8,9,10]) >> [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] >> > > What is your definition of "elegant"? What about other dimensions of > code quality like "robust" and "fast"? > > What have you tried? > > Here's one possibility: > zip(source[::2], source[1::2]) > [I'm presuming you won't be upset by getting tuples instead of lists] I like it, and it fits my definition of elegant. -- Posted via a free Usenet account from http://www.teranews.com From kw at codebykevin.com Mon May 21 13:38:22 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Mon, 21 May 2007 13:38:22 -0400 Subject: A few questions In-Reply-To: References: Message-ID: <4651D90E.2040806@codebykevin.com> jay wrote: > 3. Currently, I write most of my code with Xcode (on the Mac platform) > using Applescript. This gives me GUI capabilities. Is there anything > you'd recommend that I could use for Python that would give me a GUI > interface? PyObjC allows you to write Cocoa GUI's from Python using Xcode and Interface Builder, much as AppleScript Studio does. However, that's not a cross-platform solution. Tkinter runs on Windows as well as OS X. Out-of-the-box, however, Tkinter is somewhat limited. To build rich GUI's with Tkinter, you will need to install several additional Tk libraries and their associated Python wrappers. Tkinter is my toolkit of choice, and I've released a Python shareware application on OS X that uses it: see http://www.codebykevin.com/phynchronicity-running.png for a screenshot. wxPython is also a very reasonable solution, and will probably give you more out of the box than Tkinter. My main reason for using Tk is that I already know it well. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From apatheticagnostic at gmail.com Fri May 25 20:44:44 2007 From: apatheticagnostic at gmail.com (kaens) Date: Fri, 25 May 2007 20:44:44 -0400 Subject: conditionally creating functions within a class? Message-ID: <163f0ce20705251744j5c728e9fn53585fe0c9250827@mail.gmail.com> So, I have a class that has to retrieve some data from either xml or an sql database. This isn't a problem, but I was thinking "hey, it would be cool if I could just not define the functions for say xml if I'm using sql", so I did some fiddling around with the interpreter. First, I try conditionally creating a function, period: a = 'a' if(a == 'a') def b: print "hello" else: def c: print "goodbye" this works fine. b is defined, c is not. change the value of a and b gets defined and not c (sorry for the one-letter variables here, but for these little examples I don't think they detract much) then I try doing this within a function: class test: def __init__(self,which): self.which = which if(self.which == 'a'): def b: print "hello" else: def c: print "goodbye" tester = test('a') tester.b() This doesn't "compile", says "Name 'self' is not defined". I assume this is because of scope, something like it hasn't made the object yet, so there is no self attribute. . . but I thought that python wouldn't even bother reading that class statement until I tried to make a test object, and that it would do the __init__ function before anything else, so I'm a bit fuzzy here. Next I try creating the functions through functions: class test: def __init__(self, which): self.which = which self.chooser() def chooser(self): if( self.which == 'a'): def b(self): print "hello" else: def c(self): print "goodbye" tester = test('a') tester.b() this tells me "instance has no attribute b. I'm pretty sure this is all a scoping error of some sort (I could be wrong), but I don't have my head wrapped around it at all. Anyone with more knowledge care to explain what's going on? Also, would there be a way to conditionally create functions in a class? It doesn't really matter, but it'd be nice if I weren't creating functions that I absolutely will not need for certain instances at runtime From kylotan at gmail.com Wed May 30 11:20:59 2007 From: kylotan at gmail.com (Ben Sizer) Date: 30 May 2007 08:20:59 -0700 Subject: Windows build of PostgreSQL library for 2.5 In-Reply-To: <1180536164.370773.183140@q69g2000hsb.googlegroups.com> References: <1180534505.421166.83700@q66g2000hsg.googlegroups.com> <1180536164.370773.183140@q69g2000hsb.googlegroups.com> Message-ID: <1180538458.993024.173510@g4g2000hsf.googlegroups.com> On 30 May, 15:42, Frank Millman wrote: > On May 30, 4:15 pm, Ben Sizer wrote: > > > I've been looking for a Windows version of a library to interface to > > PostgreSQL, but can only find ones compiled under Python version 2.4. > > Is there a 2.5 build out there? > > Is this what you are looking for? > > http://stickpeople.com/projects/python/win-psycopg/ It may well be, thanks. -- Ben Sizer From nagle at animats.com Sun May 6 01:27:18 2007 From: nagle at animats.com (John Nagle) Date: Sun, 06 May 2007 05:27:18 GMT Subject: My newbie annoyances so far In-Reply-To: <1178400807.051103.95690@q75g2000hsh.googlegroups.com> References: <1177688082.758043.133920@r30g2000prh.googlegroups.com> <_9pYh.1787$uJ6.894@newssvr17.news.prodigy.net> <1178400807.051103.95690@q75g2000hsh.googlegroups.com> Message-ID: igouy2 at yahoo.com wrote: > On Apr 27, 9:07 am, John Nagle wrote: > >>The CPython implementation is unreasonably slow compared >>to good implementations of other dynamic languages such >>as LISP and JavaScript. > > > Why do you say CPython is slower than JavaScript? Please provide > examples. See http://www.mozilla.org/projects/tamarin/faq.html Tamarin is a just-in-time compiler for Javascript. Franz LISP at one time held the speed record for LISP implementations, being only slightly slower than C. Python is generally considered to be about 60x slower than C, which is about par for the course for a naive byte code interpreter. John Nagle From openopt at ukr.net Mon May 21 09:13:02 2007 From: openopt at ukr.net (dmitrey) Date: 21 May 2007 06:13:02 -0700 Subject: howto get function from module, known by string names? In-Reply-To: References: <1179228596.349933.168610@l77g2000hsb.googlegroups.com> Message-ID: <1179753182.107111.94060@y2g2000prf.googlegroups.com> And howto check does module 'asdf' exist (is available for import) or no? (without try/cache of course) Thx, D. Carsten Haese wrote: > On 15 May 2007 04:29:56 -0700, dmitrey wrote > > hi all, > > can anyone explain howto get function from module, known by string > > names? > > I.e. something like > > > > def myfunc(module_string1, func_string2, *args): > > eval('from ' + module_string1 + 'import ' + func_string2') > > return func_string2(*args) > > To find a module by its name in a string, use __import__. To find an object's > attribute by its name in a string, use getattr. > > Together, that becomes something like this: > > >>> def myfunc(module_string1, func_string2, *args): > ... func = getattr(__import__(module_string1), func_string2) > ... return func(*args) > ... > >>> myfunc("math", "sin", 0) > 0.0 > >>> myfunc("operator", "add", 2, 3) > 5 > > Hope this helps, > > -- > Carsten Haese > http://informixdb.sourceforge.net From steven at REMOVE.THIS.cybersource.com.au Tue May 8 00:31:04 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 08 May 2007 04:31:04 -0000 Subject: interesting exercise References: <1178595952.641173.76540@y80g2000hsf.googlegroups.com> Message-ID: On Mon, 07 May 2007 20:45:52 -0700, Michael Tobis wrote: > I have a reasonably elegant solution but it's a bit verbose (a couple > dozen lines which I'll post later if there is interest). Is there some > clever Pythonism I didn't spot? Peering into my crystal ball, I see that your algorithm does the wrong thing, and contains bugs too. You certainly don't need to partion the sequence into three sub-sequences, or do that trick with the metaclass, and it is more efficient to use list.extend() than sum. Hang on... stupid crystal ball... that's somebody else's code. Maybe you should just post your code here, so we can look at it? In the meantime, here's a simple generator to do permutations with repetition: def permute_with_repetitions(seq): if len(seq) <= 1: yield list(seq) else: for i, item in enumerate(seq): for tail in permute_with_repetitions(seq[:i] + seq[i+1:]): yield [item] + tail It doesn't do a test for the sequence containing duplicates, and I leave it as an exercise to do selections of fewer items. -- Steven. From mail at microcorp.co.za Tue May 15 02:20:50 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 15 May 2007 08:20:50 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> <46488bce$0$4159$ba624c82@nntp02.dk.telia.net> Message-ID: <015701c796c8$31bddae0$03000080@hendrik> "Anders J. Munch" wrote: > Hendrik van Rooyen wrote: > > And we have been through the Macro thingy here, and the consensus > > seemed to be that we don't want people to write their own dialects. > > Macros create dialects that are understood only by the three people in your > project group. It's unreasonable to compare that to a "dialect" such as > Mandarin, which is exclusive to a tiny little clique of one billion people. > A bit out of context here - I was trying to address the dichotomy of reserved words and native identifiers - so if you want Mandarin or Russian or Cantonese or Afrikaans or Flemish or German or Hebrew identifiers, will you really be happy with the hassle of "for", "while", "in" - as plain old English ASCII? How are you going to allow the native speaker to get those into his mother's tongue without something like macros? Are you suggesting separate parsers for each language? Table driven parsers? And if you go the macro route, how are you going to stop it being abused for purposes that have nothing to do with language translation? Do I have to draw a picture? - Hendrik From peter_7003 at yahoo.com Tue May 8 03:03:26 2007 From: peter_7003 at yahoo.com (Peter Fischer) Date: Tue, 8 May 2007 00:03:26 -0700 (PDT) Subject: Specification for win32com.client package Message-ID: <332916.34962.qm@web63414.mail.re1.yahoo.com> Hello, (sorry, the first message bounced; because it is urgent and I wait since yesterday, here it's again): I am searching for documentation about the interface the win32com package provides, especially win32com.client. I searched the web and Mark Hammond?s homepage but only found example code using Dispatch() and DispatchEx() etc. Isn?t there a full list of the functions win32.com.client provides? Or do I have to use makepy to somehow generate documentation (how)? I would be thankful if someone could give me a hook about that. Best regards, Peter. --------------------------------- Ahhh...imagining that irresistible "new car" smell? Check outnew cars at Yahoo! Autos. -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnoreg at gmail.com Wed May 30 17:32:05 2007 From: arnoreg at gmail.com (Arno Stienen) Date: Wed, 30 May 2007 23:32:05 +0200 Subject: xmlrpclib hangs execution In-Reply-To: <465d9040$0$326$e4fe514c@news.xs4all.nl> References: <45AC0631.8080601@ctw.utwente.nl> <465890FB.4030405@utwente.nl> <465A9DC7.2010708@gmail.com> <465d9040$0$326$e4fe514c@news.xs4all.nl> Message-ID: <465DED55.6040106@gmail.com> Tijs wrote: >> Arno Stienen wrote: >>> Perhaps I should be a bit more specific. When using this code to connect >>> to a remote XML-RPC server (C++, xmlrpc++0.7 library): >>> >>> import xmlrpclib >>> server = xmlrpclib.Server("http://10.10.101.62:29500") >>> print server.Connection_Request("roberto") >>> >>> the Python command line 'hangs' until I kill the server. Then, the >>> correct output is suddenly displayed: >>> >>> {'state': 0, 'id_session': '2Z3EUSLJFA13', 'port': 29501, >>> 'str': 'Connection accepted. Session attached.'} >>> >>> Yet a slightly simpler call works flawlessly: >>> >>> import xmlrpclib >>> server = xmlrpclib.Server("http://10.10.101.62:29500") >>> print server.Info_RT('Master') >>> >>> {'state': 0, 'str': 'Info_RT'} >>> > > After having a quick look at your files, I conclude that the problem is in a > combination of two problems: > > 1. Your server is crap. It answers an HTTP/1.0 request by an HTTP/1.1 > response without specifying any Connection header and without closing the > connection. Normally, a simple client that is not HTTP/1.1-aware expects > the connection to close. HTTP/1.1 leaves the connection open by default. > > 2. The Python implementation of xmlrpc is not very robust. It just waits for > the connection to close. A well-written client (like your Java client) > would detect the presence of a Content-Length header and use that. I'll now try this to fool the client into thinking the server 'should' keep the connection open: http://www.velocityreviews.com/forums/t329401-re-xmlrpc-httplib-and-ssl-http-11-xmlrpc-client.html Bye, Arno. From chris.cavalaria at free.fr Tue May 15 11:31:54 2007 From: chris.cavalaria at free.fr (Christophe) Date: Tue, 15 May 2007 17:31:54 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <4649BC4C.10200@web.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649BC4C.10200@web.de> Message-ID: <4649d26e$0$10775$426a74cc@news.free.fr> Stefan Behnel a ?crit : > George Sakkis wrote: >> After 175 replies (and counting), the only thing that is clear is the >> controversy around this PEP. Most people are very strong for or >> against it, with little middle ground in between. I'm not saying that >> every change must meet 100% acceptance, but here there is definitely a >> strong opposition to it. Accepting this PEP would upset lots of people >> as it seems, and it's interesting that quite a few are not even native >> english speakers. > > But the positions are clear, I think. > > Open-Source people are against it, as they expect hassle with people sending > in code or code being lost as it can't go public as-is. I'm an Open-Source guy too but I'm for that proposal. Anyway, this is a bad argument as was show already. When accepting code in a project, you already HAVE to make some rule as to how the code is writen, and 99% of the time those rules include "All identifiers in correct english (or rather, american) and all comments in english". Recieving a patch containing identifiers you cannot read is simple enouth to reject. From aleax at mac.com Thu May 3 01:06:20 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 2 May 2007 22:06:20 -0700 Subject: Microsoft's Dynamic Languages Runtime (DLR) References: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> <1178151313.421106.43130@o5g2000hsb.googlegroups.com> Message-ID: <1hxiakv.1qs950g1a2j6zfN%aleax@mac.com> Kevin Haynes wrote: > Isn't python cross platform? Sure -- why is that relevant? Alex From deepbroke6 at gmail.com Tue May 15 22:36:00 2007 From: deepbroke6 at gmail.com (deepbroke6 at gmail.com) Date: 15 May 2007 19:36:00 -0700 Subject: ^? Britney Defaults for Boob Job!!!!!! Message-ID: <1179282960.742434.213360@w5g2000hsg.googlegroups.com> http://scargo.in/2007/05/mortgage-defaults-increase-arkansas.html - Britney Spears Naked Boob Job defaults after she can't afford it, Doctors take back their silconon valley start up in this IOU scandal. Britney goes for gold and can't afford BOOB JOB!!!!!! From aleax at mac.com Wed May 2 00:02:24 2007 From: aleax at mac.com (Alex Martelli) Date: Tue, 1 May 2007 21:02:24 -0700 Subject: relative import broken? References: <1hxa9x3.c0unyd1jw7vu9N%aleax@mac.com> <1hxcdkq.47p2r6beuctcN%aleax@mac.com> <1hxeg2v.1ct59rv3oyq87N%aleax@mac.com> <7nNZh.4420$st3.1414@trnddc06> Message-ID: <1hxgczy.1itzbnb1hfpt66N%aleax@mac.com> Alan Isaac wrote: > > "Alex Martelli" wrote in message > > news:1hxeg2v.1ct59rv3oyq87N%aleax at mac.com... > > > I don't know of any "pretty" way -- I'd do it by path manipulation > > > (finding mypackage from os.path.abspath(__file__) and inserting its > > > _parent_ directory in sys.path). > > > > "Alan Isaac" wrote in message > news:7nNZh.4420$st3.1414 at trnddc06... > > Yes, that seems to be the standard solution. > > I find it ugly. > > Just to confirm that I am right to find it ugly: > does this not clearly introduce the possibility of name clashes? > Or am I overlooking some trick? If you use sys.path.insert(0, ...), not sys.path.append, I'm not sure what "name clashes" you're thinking of -- as long as you avoid naming your modules the same as ones in the standard library (which is a good practice I heartily recommend), of course, what scenario do you fear? You can have more control about _where_ stuff can get imported from by directly calling the __import__ builtin, but that's not often needed. Alex From joshua at eeinternet.com Mon May 14 16:38:36 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Mon, 14 May 2007 12:38:36 -0800 Subject: How to do basic CRUD apps with Python References: <1179098458.333666.307750@e65g2000hsc.googlegroups.com> Message-ID: <4648bc77$0$16355$88260bb3@free.teranews.com> On Sunday 13 May 2007 15:20, walterbyrd wrote: > With PHP, libraries, apps, etc. to do basic CRUD are everywhere. Ajax > and non-Ajax solutions abound. > > With Python, finding such library, or apps. seems to be much more > difficult to find. > > I thought django might be a good way, but I can not seem to get an > answer on that board. > > I would like to put together a CRUD grid with editable/deletable/ > addable fields, click on the headers to sort. Something that would > sort-of looks like an online spreadsheet. It would be nice if the > fields could be edited in-line, but it's not entirely necessary. > > Are there any Python libraries to do that sort of thing? Can it be > done with django or cherrypy? > > Please, don't advertise your PHP/Ajax apps. Turbogears has catwalk, which is already an interface to a database, but there is a CRUD template for TG: http://docs.turbogears.org/1.0/CRUDTemplate Might be what you're looking for. j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE -- Posted via a free Usenet account from http://www.teranews.com From evenprimes at gmail.com Tue May 15 11:36:20 2007 From: evenprimes at gmail.com (Chris Cioffi) Date: Tue, 15 May 2007 11:36:20 -0400 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46473267$0$31532$9b622d9e@news.freenet.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: +1 for the pep There are plenty of ways projects can enforce ASCII only if they are worried about "contamination" and since Python supports file encoding anyway, this seems like a fairly minor change. pre-commit scripts can keep weird encoding out of existing projects and everything else can be based on per-project agreed on standards. For those who complain that they can't read the weird characters, for any reason, maybe you aren't meant to read that stuff? There may be some fragmentation and duplication of effort (A Hindi module X, a Mandarin module X and the English module X) but that seems a small price to pay for letting Python fulfill it's purpose: letting people be expressive and get the job done. People are usually more expressive in their native languages, and thinking in different languages may even expose alternative ways of doing things to the greater Python community. Chris -- "A little government and a little luck are necessary in life, but only a fool trusts either of them." -- P. J. O'Rourke From eiwot at hotmail.com Wed May 23 23:55:33 2007 From: eiwot at hotmail.com (Eiwot) Date: Thu, 24 May 2007 03:55:33 +0000 Subject: Can not access pygame.org Message-ID: Hi all, I can not access pygame.org. Anyone saw this problem ? Check out http://pyarticles.blogspot.com Cheers _________________________________________________________________ Download Messenger. Start an i?m conversation. Support a cause. Join now. http://im.live.com/messenger/im/home/?source=TAGWL_MAY07 -------------- next part -------------- An HTML attachment was scrubbed... URL: From sickcodemonkey at gmail.com Fri May 18 21:08:55 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Fri, 18 May 2007 21:08:55 -0400 Subject: wxpython - button question Message-ID: <2adc542f0705181808j35d124f2p8882202ece248f7c@mail.gmail.com> I have the following code which will basically take an image file and create a bitmap image. I am having one problem though in that there is a white border around the image. Does anyone know how to take that off? imageFile2 = "image.png" image2 = wx.Image(imageFile2, wx.BITMAP_TYPE_ANY).ConvertToBitmap() self.button2 = wx.BitmapButton(self, id=-1, bitmap=image2, pos=(10, 140), size = (image2.GetWidth()-2, image2.GetHeight())) self.button2.SetMargins(0,0) self.button2.Bind(wx.EVT_BUTTON, self.button2Click) -------------- next part -------------- An HTML attachment was scrubbed... URL: From revuesbio at gmail.com Sun May 20 14:59:55 2007 From: revuesbio at gmail.com (revuesbio) Date: 20 May 2007 11:59:55 -0700 Subject: TIFF to PDF Message-ID: <1179687595.142454.23850@z24g2000prd.googlegroups.com> Hello, I'm looking for : 1/ the best method to convert tiff files to PDF. 2/ and I want to merge these pdf files. thank you for your help From jackson at hotmail.com Sat May 26 15:39:14 2007 From: jackson at hotmail.com (Bill Jackson) Date: Sat, 26 May 2007 12:39:14 -0700 Subject: matplotlib, usetex In-Reply-To: References: Message-ID: Alexander Schmolck wrote the following on 05/25/2007 02:33 PM: > I have no idea whether this will resolve your problem, but you could try > updating to 0.90 (BTW what happens if you do axis([0,128,0,128])). The problem appears to be with a matplotlibrc file. If I delete the matplotlibrc file, then I am able to plot perfectly. Thus, it appears that I am unable to specify usetex from my configuration file. Why is this happening? ---- ~/.matplotlib/matplotlibrc ---- text.usetex : True ---- test.py ---- import matplotlib import pylab matplotlib.rc('text', usetex=True) pylab.plot(range(10)) pylab.show() Running 'python test.py' with the above matplotlibrc causes the errors in my original post. Deleting matplotlibrc resolves the problem. From doulos05 at gmail.com Tue May 1 20:04:08 2007 From: doulos05 at gmail.com (JonathanB) Date: 1 May 2007 17:04:08 -0700 Subject: Read and Write the same file In-Reply-To: References: <1178060601.700099.263240@y5g2000hsa.googlegroups.com> Message-ID: <1178064248.678198.113100@q75g2000hsh.googlegroups.com> > Well the most straight forward approach is to read data from the file > into memory. Let the user make any changes. Then save the data back to > the file, overwriting the oringinal copy. Now, this only really works > if you're dealing with small files. > > Regardless though, you never really need to have a file open for both > reading and writing. Since they occur (so it sounds) at distinct times > during your program flow, just open it twice: the first to read, the > second to write. > > Ian That makes sense. The largest document is >10K, so it shouldn't be a problem. From steven.klass at gmail.com Wed May 2 12:41:56 2007 From: steven.klass at gmail.com (rh0dium) Date: 2 May 2007 09:41:56 -0700 Subject: Is it possible to determine what a function needs for parameters - In-Reply-To: References: <1178115727.932794.100390@h2g2000hsg.googlegroups.com> <1178118792.289104.212670@l77g2000hsb.googlegroups.com> Message-ID: <1178124116.362731.248260@c35g2000hsg.googlegroups.com> On May 2, 8:25 am, Gary Herron wrote: > rh0dium wrote: > >> This is far more work than you need. Push an (args, kwargs) tuple into > >> your arguments queue and call self.function(*args, **kwargs). > > > No see I tried that and that won't work. > > Won't work? How does it fail?> I'm assuming what you are referring to is this (effectively) > > > Q.put(((),{a:"foo", b:"bar})) > > > input = Q.get() > > self.function( *input[0], **input[1]) > > > This will obviously fail if several conditions aren't met - hence the > > kludge. Am I missing something here? > > Obviously? Conditions? What conditions? > > We do things like this constantly, and in fact, it *does* work. > > Please tell us how it fails, or what is unsatisfactory about it. > > Gary Herron Good - It looks like I am the one who is clueless.. If I do this: def funcA(input): pass Then I run the code for x in range(lod):myQ.put(random.random()) myQ.put(None) a=WorkerB(requestQ=myQ, function=funcA).start() This will fail because there isn't an input[1] From tjreedy at udel.edu Fri May 18 00:40:43 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 18 May 2007 00:40:43 -0400 Subject: omissions in python docs? References: <1179419983.750044.65030@n59g2000hsh.googlegroups.com><1179451395.440662.127760@y80g2000hsf.googlegroups.com><1179452448.886371.169000@q75g2000hsh.googlegroups.com> Message-ID: "Anthony Irwin" wrote in message news:f2j8sr$s3h$1 at news-01.bur.connect.com.au... | 7stud wrote: | > On May 17, 7:23 pm, 7stud wrote: | > | > By the way, have the python doc keepers ever visited the php docs? In | > my opinion, they are the best docs of any language I've encountered | > because users can add posts to any page in the docs to correct them or | > post code showing how to get around various idiosyncrasies when using | > the functions. | > | I also like the php docs and love that you can type any function into | the search at php.net and the documentation just comes up and there is | example code and then user comments also. Reactions to php docs are rather idiosyncratic. I did visit in response to such positive recommendations and and consider them to be pretty bad, and posted why at the time. tjr From kkylheku at gmail.com Fri May 4 12:27:16 2007 From: kkylheku at gmail.com (Kaz Kylheku) Date: 4 May 2007 09:27:16 -0700 Subject: Microsoft's Dynamic Languages Runtime (DLR) In-Reply-To: <1178151574.302703.205560@l77g2000hsb.googlegroups.com> References: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> <1178151313.421106.43130@o5g2000hsb.googlegroups.com> <1178151574.302703.205560@l77g2000hsb.googlegroups.com> Message-ID: <1178296035.993859.183720@n59g2000hsh.googlegroups.com> On May 2, 5:19 pm, sturlamolden wrote: > On May 3, 2:15 am, Kaz Kylheku wrote: > > > Kindly refrain from creating any more off-topic, cross-posted threads. > > Thanks. > > The only off-topic posting in this thread is your own (and now this > one). You are making a very clumsy entrance into these newsgroups. So far you have started two cross-posted threads. The first is only topical in comp.lang.python (how to emulate macros in Python). This one is topical in neither one, since it is about Microsoft DLR. It's quite possible that some Lisp and Python programmers have a strong interest in Microsoft DLR. Those people who have such an interest (regardless of whether they are Lisp and Python user also) and who like to read Usenet will almost certainly find a Microsoft DLR newsgroup for reading about and discussing Microsoft DLR. Do you not agree? Also note that there is very rarely, if ever, any good reason for starting a thread which is crossposted among comp.lang.* newsgroups, even if the subject contains elements that are topical in all of them (yours does not). > Begone. You are childishly beckoning Usenet etiquette to be gone so that you may do whatever you wish. But I trust that you will not, out of spite for being rebuked, turn a few small mistakes into a persistent style. From tjreedy at udel.edu Thu May 10 15:49:18 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 10 May 2007 15:49:18 -0400 Subject: searching algorithm References: Message-ID: "Neil Cerutti" wrote in message news:slrnf46ph1.1hg.horpner at FIAD06.norwich.edu... | On 2007-05-10, Gigs_ wrote: | > if user type: "abs" program should list all words above in | > english and in croatian if user type: "absorb" than program | > should list last 3 words in english and in croatian | | A solution that solves the problem with a data structure might be | a multi-tree. Specific computer science terms are prefix tree or trie (from reTRIEval). http://en.wikipedia.org/wiki/Trie gives an introduction. | Each node points at a set of following letters, and a set of | croatian translations, either of which might be empty, making the | node a leaf. | | For the above (abrideged) dictionary, you would generate (use a | fixed-width "programmers" font so the tree looks good): | | a | | | b | | | s | / \ | i o | / / \ | n l r | / / \ \ | t u v b->(absorbirati, crpisti) | / | | | (pelin)<-h t e->(odrije?iti, osloboditi) | | | | (pelin)<-e e->(apsolutan, apsolutni kod) | | As the user enter letters, you just march down the tree, printing | all the words held in leaf nodes held in the current node. tjr | From jmg3000 at gmail.com Thu May 10 13:13:43 2007 From: jmg3000 at gmail.com (jmg3000 at gmail.com) Date: 10 May 2007 10:13:43 -0700 Subject: append In-Reply-To: <1178817077.591054.318230@e51g2000hsg.googlegroups.com> References: <1178816546.689849.255070@y5g2000hsa.googlegroups.com> <1178817077.591054.318230@e51g2000hsg.googlegroups.com> Message-ID: <1178817223.413670.279600@y5g2000hsa.googlegroups.com> On May 10, 1:11 pm, HMS Surprise wrote: > Found list popping at > > http://en.wikibooks.org/wiki/Python_Programming/Lists:) You can find terse info on the list methods by doing: >>> help(list) ---John From gagsl-py2 at yahoo.com.ar Thu May 17 21:27:27 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 17 May 2007 22:27:27 -0300 Subject: newbie question: retrieving values of variables through C API References: <1179430673.372668.217350@h2g2000hsg.googlegroups.com> Message-ID: En Thu, 17 May 2007 16:37:53 -0300, escribi?: > I've got an application that embeds the Python interpreter. I have the > following command in my code: > > PyRun_SimpleString("a = \"hello\""); > > My question is, what is the C API function call for retrieving the > value of the variable "a"? The code is run in the context of the __main__ module. So you could do something like this: PyObject *m, *d, *v, *value; m = PyImport_AddModule("__main__"); if (m == NULL) return -1; d = PyModule_GetDict(m); value = PyDict_GetItemString(d, "a") (The code above is mostly copied from PyRun_SimpleStringFlags) You may find other variants of PyRun_XXX more convenient to use. -- Gabriel Genellina From tim.leslie at gmail.com Tue May 8 21:54:31 2007 From: tim.leslie at gmail.com (Tim Leslie) Date: Wed, 9 May 2007 11:54:31 +1000 Subject: String parsing In-Reply-To: <1178672992.522463.228620@l77g2000hsb.googlegroups.com> References: <1178672992.522463.228620@l77g2000hsb.googlegroups.com> Message-ID: On 8 May 2007 18:09:52 -0700, HMS Surprise wrote: > > The string below is a piece of a longer string of about 20000 > characters returned from a web page. I need to isolate the number at > the end of the line containing 'LastUpdated'. I can find > 'LastUpdated' with .find but not sure about how to isolate the > number. 'LastUpdated' is guaranteed to occur only once. Would > appreciate it if one of you string parsing whizzes would take a stab > at it. > Does this help? In [7]: s = '' In [8]: int(s.split("=")[-1].split('"')[1]) Out[8]: 1178658863 There's probably a hundred different ways of doing this, but this is the first that came to mind. Cheers, Tim > Thanks, > > jh > > > > > > > > > > > align="center" > > -- > http://mail.python.org/mailman/listinfo/python-list > From marco.colombo at gmail.com Tue May 15 07:11:25 2007 From: marco.colombo at gmail.com (Marco Colombo) Date: 15 May 2007 04:11:25 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46473267$0$31532$9b622d9e@news.freenet.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <1179227485.499015.115300@u30g2000hsc.googlegroups.com> On 13 Mag, 17:44, "Martin v. L?wis" wrote: > - should non-ASCII identifiers be supported? why? Yes. For the same reason non-ASCII source files are supported. > - would you use them if it was possible to do so? in what cases? Yes. In the same cases I'd use: 1) non-English comments; 2) non-English string literals; 3) a source file that is already non-ASCII. Not that I usually do that. I speak Italian natively, but write programs with English identifiers, English comments, English output most of the time and usually the encoding is ASCII. Yet we support other encoding for the source file, that is non-ASCII comments, literals, and so on. And non-ASCII means non-English. There may be very few reasons to use non-ASCII, non-English words in a python program, _anywhere_, but that's not the issue. We already support people writing program with, say, Italian comments, Italian words in string literals (natively utf-8 encoded, not with escape sequences), no matter if they are right or wrong doing so. The following is a valid source file: # coding=utf-8 # stampa il nome della citt? citta = "Milano" print "Citt?:", citta We support people doing that. While we're at it, why not support this one as well: # coding=utf-8 # stampa il nome della citt? citt? = "Milano" print "Citt?:", citt? (for people unable to see it: there's a "LATIN SMALL LETTER A WITH GRAVE" at the end of "citta" instead of a plain "LATIN SMALL LETTER A" - in the second program, that's true for the identifier as well). Question is: if we support the former (right or wrong, we do), what do we loose in supporting the latter? Most arguments against this PEP I saw here apply to both programs, I'd like to see one that applies only to the second one. .TM. From nogradi at gmail.com Sun May 20 14:55:06 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Sun, 20 May 2007 20:55:06 +0200 Subject: model browser Message-ID: <5f56302b0705201155j706cc8e0ydc62a436e4c86299@mail.gmail.com> Hi list, I'm looking for an sqlobject based model browser with a web interface (is this the thing called CRUD these days?). Searching all over the place turned up of course django's automatic admin interface and turbogears' catwalk but I wouldn't want to buy into any of these two frameworks because they are too complicated and complex. I don't know about django but since tg is sqlobject based catwalk might still be a good candidate if it can be decoupled from the rest of tg. By looking at the source of catwalk it seems that this decoupling requires quite some work; did anyone do something like this? Or does anyone know if catwalk was originally written for tg or was general purpose before and became integrated into tg later? Are there other options I overlooked? Daniel From michael.forbes at gmail.com Tue May 1 14:40:21 2007 From: michael.forbes at gmail.com (Michael) Date: 1 May 2007 11:40:21 -0700 Subject: Why are functions atomic? In-Reply-To: References: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> Message-ID: <1178044821.864741.235260@o5g2000hsb.googlegroups.com> On May 1, 9:34 am, John Nagle wrote: > Michael wrote: > > Why are functions atomic? (I.e. they are not copied.) > > Because Python has objects for when you need to associate > state with a function. > > John Nagle Then why are functions mutable? I can understand to some extent why functions are not picklable, because the bytecode may not be the same across python implementations (is that true?), but I do not understand why copying functions is a problem. The patch that allows copy to pass-through functions just emulates pickle, but I can find no discussion or justification for not allowing functions to be copied: http://thread.gmane.org/gmane.comp.python.devel/76636 Michael. From gh at gregor-horvath.com Wed May 16 12:54:23 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Wed, 16 May 2007 18:54:23 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179333797.634234.245830@k79g2000hse.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179333797.634234.245830@k79g2000hse.googlegroups.com> Message-ID: Istvan Albert schrieb: > Here is something that just happened and relates to this subject: I > had to help a student run some python code on her laptop, she had > Windows XP that hid the extensions. I wanted to set it up such that > the extension is shown. I don't have XP in front of me but when I do > it takes me 15 seconds to do it. Now her Windows was set up with some > asian fonts (Chinese, Korean not sure), looked extremely unfamiliar > and I had no idea what the menu systems were. We have spent quite a > bit of time figuring out how to accomplish the task. I had her read me > back the options, but something like "hide extensions" comes out quite > a bit different. Surprisingly tedious and frustrating experience. > So the solution is to forbid Chinese XP ? Gregor From george.sakkis at gmail.com Wed May 23 17:08:28 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 23 May 2007 14:08:28 -0700 Subject: Parallel/distributed generator In-Reply-To: <1179948932.314833.34930@a35g2000prd.googlegroups.com> Message-ID: <1179954508.077700.102410@q75g2000hsh.googlegroups.com> On May 23, 3:35 pm, half.ital... at gmail.com wrote: > On May 23, 11:00 am, George Sakkis wrote: > > > > > I'm looking for any existing packages or ideas on how to implement the > > equivalent of a generator (in the Python sense, i.e.http://www.python.org/dev/peps/pep-0255/) in a parallel/distributed > > way. As a use case, imagine a function that generates a range of > > primes. I'd like to be able to do something along the following lines: > > > def iterprimes(start=1, end=None): > > # ... > > yield prime > > > # rpc-related initialization > > ... > > rpc_proxy = some_rpc_lib(iterprimes, start=1e6, end=1e12) > > for prime in proxy: > > print prime > > > Is there any module out there that does anything close to this ? > > > George > > Parellel Python? > > http://www.parallelpython.com/content/view/17/31/#SUM_PRIMES > > I've never used it, but looks like it does what you are looking for. Looked promising, until I saw that it requires you to pass explicitly the dependent functions and the modules to be imported for the callable to work. I guess this has to be done recursively for all the dependent functions/modules, which is impractical for anything but toy examples. George From martin at v.loewis.de Mon May 14 18:14:17 2007 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Tue, 15 May 2007 00:14:17 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179153757.844925.14230@p77g2000hsh.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179153757.844925.14230@p77g2000hsh.googlegroups.com> Message-ID: <4648DF39.70901@v.loewis.de> > Not providing an explicit listing of allowed characters is inexcusable > sloppiness. That is a deliberate part of the specification. It is intentional that it does *not* specify a precise list, but instead defers that list to the version of the Unicode standard used (in the unicodedata module). > The XML standard is an example of how listings of large parts of the > Unicode character set can be provided clearly, exactly and (almost) > concisely. And, indeed, this is now recognized as one of the bigger mistakes of the XML recommendation: they provide an explicit list, and fail to consider characters that are unassigned. In XML 1.1, they try to address this issue, by now allowing unassigned characters in XML names even though it's not certain yet what those characters mean (until they are assigned). >> ``ID_Continue`` is defined as all characters in ``ID_Start``, plus >> nonspacing marks (Mn), spacing combining marks (Mc), decimal number >> (Nd), and connector punctuations (Pc). > > Am I the first to notice how unsuitable these characters are? Probably. Nobody in the Unicode consortium noticed, but what do they know about suitability of Unicode characters... Regards, Martin From ptmcg at austin.rr.com Wed May 23 16:22:19 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 23 May 2007 13:22:19 -0700 Subject: Parallel/distributed generator In-Reply-To: <1179950286.087794.5430@x18g2000prd.googlegroups.com> References: <1179943256.575473.62610@q66g2000hsg.googlegroups.com> <1179950286.087794.5430@x18g2000prd.googlegroups.com> Message-ID: <1179951739.408556.129420@h2g2000hsg.googlegroups.com> On May 23, 2:58 pm, half.ital... at gmail.com wrote: > On May 23, 11:00 am, George Sakkis wrote: > > > > > > > I'm looking for any existing packages or ideas on how to implement the > > equivalent of a generator (in the Python sense, i.e.http://www.python.org/dev/peps/pep-0255/) in a parallel/distributed > > way. As a use case, imagine a function that generates a range of > > primes. I'd like to be able to do something along the following lines: > > > def iterprimes(start=1, end=None): > > # ... > > yield prime > > > # rpc-related initialization > > ... > > rpc_proxy = some_rpc_lib(iterprimes, start=1e6, end=1e12) > > for prime in proxy: > > print prime > > > Is there any module out there that does anything close to this ? > > > George > > DOLT!- Hide quoted text - > > - Show quoted text - I thought you were making a joke about parallel processing. I thought you were making a joke about parallel processing. I thought you were making a joke about parallel processing. I thought you were making a joke about parallel processing. -- Paul From RonVick at Nospam.com Sun May 13 12:12:05 2007 From: RonVick at Nospam.com (RonV) Date: Sun, 13 May 2007 16:12:05 GMT Subject: How to installo???? References: <1178830444.735169.324830@p77g2000hsh.googlegroups.com> Message-ID: On 10 May 2007 13:54:04 -0700, kyosohma at gmail.com wrote: >I would recommend using the command line. Open that up and then type >something like this: > >python pathToWinExt\setup.py > >That should run it and when it's done, your command window should stay >open. Hopefully it will tell you what happened. > >Since I don't have Vista and don't know if it will recognize the name >"python", you may need to specify a path to it too. > >Good luck! > >Mike Thanks, Mike. I'd forgotten about the command line technique, having used point & click in XP. I found it was actually: setup.py install However, I'm getting the message that setup cannot find an installed platform SDK, ' I have VB6 installed, so that should have done it. It's like the script cannot locate the SDK, any ideas?? Ron From rw at smsnet.pl Sat May 12 18:58:58 2007 From: rw at smsnet.pl (Rob Wolfe) Date: Sun, 13 May 2007 00:58:58 +0200 Subject: Popen and wget, problems References: <4645a6a6$0$8615$dbd49001@news.wanadoo.nl> Message-ID: <87d515ejil.fsf@merkury.smsnet.pl> "Jesse" writes: > Hi all, I have a problem using wget and Popen. I hope someone can help. > > > -- Problem -- > I want to use the command: > wget -nv -O "dir/cpan.txt" "http://search.cpan.org" > and capture all it's stdout+stderr. > (Note that option -O requires 'dir' to be existing before wget is executed) > > Popen doesn't work, while os.system and shell do. Popen will give the error: > dir/cpan.txt: No such file or directory > > While os.system and shell will give the correct result: > 06:52:40 URL:http://search.cpan.org/ [3657/3657] -> "dir1/cpan.txt" [1] [...] > -- Python Code using Popen with cmd arg list -- > # imports > import os > from subprocess import Popen, PIPE > > # vars and create dir > cmd_set = ['wget', '-nv', '-O dir/cpan.txt', 'http://search.span.org'] > cmd = ' '.join(cmd_set) > print "cmd: " + cmd > try: > os.makedirs('dir') > except: > print 'dir already exists' > > > # execute using Popen (does NOT work) > proc = Popen(cmd_set, stdout=PIPE, stderr=PIPE) > return_code = proc.wait() > if return_code == 0: > print "Success:\n%s" % (proc.stdout.read() + proc.stderr.read()) > else: > print "Failure %s:\n%s" % (return_code, proc.stderr.read() + > proc.stdout.read()) > > > # execute using os.system (does work) > os.system(cmd) > > > -- Python code output of Popen -- > Failure 1: > dir/cpan.txt: No such file or directory > > > -- Question -- > Why is Popen unable to correctly execute the wget, while os.system can? I don't know exactly why in this case Popen doesn't work, but the counterpart of os.system is Popen with option shell=True and the first parameter should be a string instead of list. That seems to work: proc = Popen("wget -nv -O dir/cpan.txt http://search.span.org", shell=True, stdout=PIPE, stderr=PIPE) and this variant seems to work too: cmd_set = ['wget', '-nv', '-O', 'dir/cpan.txt', 'http://search.span.org'] -- HTH, Rob From bj_666 at gmx.net Thu May 31 08:29:32 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 31 May 2007 14:29:32 +0200 Subject: Is PEP-8 a Code or More of a Guideline? References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <5c1jpkF2tl0ilU1@mid.individual.net> <1180539790.654176.26900@q75g2000hsh.googlegroups.com> <646aw86i.fsf@mail.com> Message-ID: In <646aw86i.fsf at mail.com>, kc wrote: > "Joe Riopel" writes: > >> Using camel case instead of the under_score means less typing. I am lazy. >> >> fooBar >> foo_bar > Each requires exactly the same number of key strokes when I do the > math. (Too lazy to explain further...) Let's leave 'foo' and 'ar': 1. B = + = 2 key strokes. 2. _b = + <-> and = 3 key strokes. At least on my keyboard + layout. Ciao, Marc 'BlackJack' Rintsch From Mattia.Gentilini_REMOVE_ at _REMOVE_CNAF.INFN.IT Thu May 3 06:33:01 2007 From: Mattia.Gentilini_REMOVE_ at _REMOVE_CNAF.INFN.IT (Mattia Gentilini (CNAF)) Date: Thu, 03 May 2007 12:33:01 +0200 Subject: 32 OS on 64-bit machine In-Reply-To: <1178183424.548438.303170@y80g2000hsf.googlegroups.com> References: <1178183424.548438.303170@y80g2000hsf.googlegroups.com> Message-ID: SamG ha scritto: > If anyone has a x86_64 machine and is running a 32bit OS on top of > that.... could you tell me what output would you get for the following > program I have a Athlon64 X2 with Debian unstable i386: [mg at Galvatron pts/0 ~]$ python Python 2.4.4 (#2, Apr 26 2007, 00:02:45) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import platform >>> print platform.processor() >>> print platform.architecture() ('32bit', '') >>> I also have a MacBook with a Core 2 Duo and Mac OS X 10.4.9 : [MG55 at dot1x-056 ttyp4 ~/Desktop/ETICS]$ python Python 2.3.5 (#1, Aug 19 2006, 21:31:42) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import platform >>> print platform.processor() i386 >>> print platform.architecture() ('32bit', '') >>> -- Mattia Gentilini Collaborator for ETICS project - http://eu-etics.org/ INFN - CNAF - R&D Division - Bologna, Italy * Using Mac OS X 10.4.9 powered by Cerebros (Core 2 Duo) * From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed May 30 07:43:19 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 30 May 2007 13:43:19 +0200 Subject: Rats! vararg assignments don't work In-Reply-To: <1180496033.608791.35840@g37g2000prf.googlegroups.com> References: <1180496033.608791.35840@g37g2000prf.googlegroups.com> Message-ID: <465d634e$0$27205$426a74cc@news.free.fr> Matimus a ?crit : (snip) > Remember, in Python "there is only one way to do it". Actually, it's : "There should be one-- and preferably only one --obvious way to do it.". ... Which is quite different. Please notice the "should", "preferably" and "obvious". From mensanator at aol.com Thu May 3 13:29:42 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 3 May 2007 10:29:42 -0700 Subject: How to check if a string is empty in python? In-Reply-To: <1hxia3n.19x773917p8esxN%aleax@mac.com> References: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> <1178138964.503290.254060@o5g2000hsb.googlegroups.com> <1178139155.260722.153750@n59g2000hsh.googlegroups.com> <463917d1$0$2415$426a74cc@news.free.fr> <1178149602.018706.309200@o5g2000hsb.googlegroups.com> <1hxia3n.19x773917p8esxN%aleax@mac.com> Message-ID: <1178213382.832065.136600@c35g2000hsg.googlegroups.com> On May 2, 11:59 pm, a... at mac.com (Alex Martelli) wrote: > mensana... at aol.com wrote: > > ... > > > >>> import gmpy > > >>> gmpy.mpz(11) > > mpz(11) > > >>> gmpy.mpz('11',10) > > mpz(11) > > >>> gmpy.mpz(11,10) > > > Traceback (most recent call last): > > File "", line 1, in > > gmpy.mpz(11,10) > > TypeError: gmpy.mpz() with numeric argument needs exactly 1 argument > > > The mpz conversion takes two arguments if and only if s is a string, > > else it takes 1 argument. So being non-empty is insufficient. > > Being a string AND being non-empty is insufficient too -- just try > > gmpy.mpz("Hello, I am a string and definitely not empy!", 10) > > on for size. > > Alex >>> import gmpy >>> gmpy.mpz("Hello, I am a string and definitely not empy!", 10) Traceback (most recent call last): File "", line 1, in gmpy.mpz("Hello, I am a string and definitely not empy!", 10) ValueError: invalid digits But you don't get a TypeError, you get a ValueError. And you might scratch your head over >>> gmpy.mpz('zzz',26) Traceback (most recent call last): File "", line 1, in gmpy.mpz('zzz',26) ValueError: invalid digits until you remember that base 26 is 0-9a-p, not a-z. From steve at holdenweb.com Thu May 24 11:14:06 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 24 May 2007 11:14:06 -0400 Subject: configobj - use of In-Reply-To: <1180012522.847219.278310@q69g2000hsb.googlegroups.com> References: <1180012522.847219.278310@q69g2000hsb.googlegroups.com> Message-ID: Bruce wrote: > I assume that you know the module configobj. I use it like this: > I have a config_file : > > [sec1] > [[subsec1]] > a = 1 > b = 2 > [[subsec2]] > a = 3 > b = 1 > > .. ans so on > > Then in the code I have c = configobj.ConfigObj(path_to_config file) > > then I go like for instance > > for s in c['sec1']: > print c['sec1'][s]['a'] > > Just think its awkward that its neccessary to use the c['sec1'] again > inside the loop, > guess I`d like it to be like > print s.a > > instead > > Is this the right way to use configobj? > So bind a variable to the section, and write csec = c['sec1'] for s in csec: print csec[s]['a'] I don't think configobj support attribute-based access to the section values, in which case print csec[s].a won't work. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From mangabasi at gmail.com Wed May 23 14:31:56 2007 From: mangabasi at gmail.com (Mangabasi) Date: 23 May 2007 11:31:56 -0700 Subject: Inheriting from Python list object(type?) In-Reply-To: Message-ID: <1179945116.372121.24770@m36g2000hse.googlegroups.com> On May 23, 12:47 pm, "Jerry Hill" wrote: > On 23 May 2007 09:58:36 -0700, Mangabasi wrote: > > > There must be a way to inherit from the list type without having to > > redefine all the methods and attributes that regular lists have. > > Like this: > > class Point(list): > def __init__(self, x, y, z = 1): > list.__init__(self, [x, y, z]) > > def __getattr__(self, name): > if name == 'x': return self[0] > if name == 'y': return self[1] > if name == 'z': return self[2] > > def __setattr__(self, name, value): > if name == 'x': self[0] = value > if name == 'y': self[1] = value > if name == 'z': self[2] = value > > Does that show you what you need? > > -- > Jerry Somebody else emailed me another solution. This is what he suggested: class Point(list): def __init__(self,x,y): super(Point, self).__init__() self.x = x self.y = y When I modified this to: class Point(list): def __init__(self,x,y): super(Point, self).__init__([x, y]) self.x = x self.y = y It worked. From ratchetgrid at googlemail.com Wed May 9 04:40:35 2007 From: ratchetgrid at googlemail.com (Nathan Harmston) Date: Wed, 9 May 2007 09:40:35 +0100 Subject: Using the CSV module Message-ID: <676224240705090140k2525224ch541a5740a19a6f3f@mail.gmail.com> Hi, I ve been playing with the CSV module for parsing a few files. A row in a file looks like this: some_id\t|\tsome_data\t|t\some_more_data\t|\tlast_data\t\n so the lineterminator is \t\n and the delimiter is \t|\t, however when I subclass Dialect and try to set delimiter is "\t|\t" it says delimiter can only be a character. I know its an easy fix to just do .strip("\t") on the output I get, but I was wondering a) if theres a better way of doing this when the file is actually being parsed by the csv module b) Why are delimiters only allowed to be one character in length. Many Thanks in advance Nathan From ramashish.lists at gmail.com Tue May 29 06:43:11 2007 From: ramashish.lists at gmail.com (Ramashish Baranwal) Date: 29 May 2007 03:43:11 -0700 Subject: Periodic tasks. In-Reply-To: <87lkf8nfem.fsf@benfinney.id.au> References: <1180420430.610215.96330@a26g2000pre.googlegroups.com> <87lkf8nfem.fsf@benfinney.id.au> Message-ID: <1180435391.326438.209320@n15g2000prd.googlegroups.com> > > I am trying to execute some tasks periodically, those familiar with > > unix can think of it as equivalent to cron jobs. > > Can you not use cron? If not, why not? Is there an equivalent service > you can use? I can, but the work I want to do is written in Python. This is not an issue but I would have more than one such tasks running at different periods and it will be desirable to control or monitor all of them from a single process. If I use cron, all of them will execute independently. > > > I have tried looking around, but couldn't find a way. > > Using the services provided by the operating system would be far > preferable to re-inventing a scheduler service. Agreed, but my requirement is a little different. There is a TaskKit package (http://webware.sourceforge.net/Webware-0.7/TaskKit/Docs/ QuickStart.html) that has such a scheduler. Does anyone have any experience with it? Ram From see.signature at no.spam Wed May 16 03:57:03 2007 From: see.signature at no.spam (Eric Brunel) Date: Wed, 16 May 2007 09:57:03 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649BC4C.10200@web.de> <4649D32F.4010209@web.de> Message-ID: On Tue, 15 May 2007 17:35:11 +0200, Stefan Behnel wrote: > Eric Brunel wrote: >> On Tue, 15 May 2007 15:57:32 +0200, Stefan Behnel >>> In-house developers are rather for this PEP as they see the advantage >>> of >>> expressing concepts in the way the "non-techies" talk about it. >> >> No: I *am* an "in-house" developer. The argument is not >> public/open-source against private/industrial. As I said in some of my >> earlier posts, any code can pass through many people in its life, people >> not having the same language. I dare to say that starting a project >> today in any other language than english is almost irresponsible: the >> chances that it will get at least read by people not talking the same >> language as the original coders are very close to 100%, even if it >> always stays "private". > > Ok, so I'm an Open-Source guy who happens to work in-house. And I'm a > supporter of PEP 3131. I admit that I was simplifying in my round-up. :) > > But I would say that "irresponsible" is a pretty self-centered word in > this > context. Can't you imagine that those who take the "irresponsible" > decisions > of working on (and starting) projects in "another language than English" > are > maybe as responsible as you are when you take the decision of starting a > project in English, but in a different context? It all depends on the > specific > constraints of the project, i.e. environment, developer skills, domain, > ... > > The more complex an application domain, the more important is clear and > correct domain terminology. And software developers just don't have > that. They > know their own domain (software development with all those concepts, > languages > and keywords), but there is a reason why they develop software for those > who > know the complex professional domain in detail but do not know how to > develop > software. And it's a good idea to name things in a way that is > consistent with > those who know the professional domain. > > That's why keywords are taken from the domain of software development and > identifiers are taken (mostly) from the application domain. And that's > why I > support PEP 3131. You keep eluding the question: even if the decisions made at the project start seem quite sensible *at that time*, if the project ends up maintained in Korea, you *will have* to translate all your identifiers to something displayable, understandable and typable by (almost) anyone, a.k.a ASCII-English... Since - as I already said - I'm quite convinced that any application bigger than the average quick-n-dirty throwable script is highly likely to end up in a different country than its original coders', you'll end up losing the time you appeared to have gained in the beginning. That's what I called "irresponsible" (even if I admit that the word was a bit strong...). Anyway, concerning the PEP, I've finally "put some water in my wine" as we say in French, and I'm not so strongly against it now... Not for the reasons you give (so we can continue our flame war on this ;-) ), but mainly considering Python's usage in a learning context: this is a valid reason why non-ASCII identifiers should be supported. I just wish I'll get a '--ascii-only' switch on my Python interpreter (or any other means to forbid non-ASCII identifiers and/or strings and/or comments). -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From sbassi at clubdelarazon.org Wed May 2 10:28:17 2007 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Wed, 2 May 2007 11:28:17 -0300 Subject: Writing a nice formatted csv file In-Reply-To: <1178115244.446071.317250@n76g2000hsh.googlegroups.com> References: <1178115244.446071.317250@n76g2000hsh.googlegroups.com> Message-ID: <9e2f512b0705020728m290555ek503e0c4f6a1e61b@mail.gmail.com> On 2 May 2007 07:14:04 -0700, redcic wrote: > And i get an out.txt file looking like: > 1,2,3 > 10,20,30 > Whereas what I'd like to get is: > 1, 2, 3, > 10, 20, 30 > which is more readable. The idea behind csv module is to produce and read csv files that are "machine readable" rather than "human readable", so I think you should write the file "by hand" to take into account those whitespace. -- Sebasti?n Bassi (???????) Diplomado en Ciencia y Tecnolog?a. GPG Fingerprint: 9470 0980 620D ABFC BE63 A4A4 A3DE C97D 8422 D43D Club de la raz?n (www.clubdelarazon.org) From george.sakkis at gmail.com Wed May 23 17:56:58 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 23 May 2007 14:56:58 -0700 Subject: Parallel/distributed generator In-Reply-To: <1179951739.408556.129420@h2g2000hsg.googlegroups.com> References: <1179943256.575473.62610@q66g2000hsg.googlegroups.com> <1179950286.087794.5430@x18g2000prd.googlegroups.com> <1179951739.408556.129420@h2g2000hsg.googlegroups.com> Message-ID: <1179957418.549743.116060@w5g2000hsg.googlegroups.com> On May 23, 4:22 pm, Paul McGuire wrote: > On May 23, 2:58 pm, half.ital... at gmail.com wrote: > > > > > On May 23, 11:00 am, George Sakkis wrote: > > > > I'm looking for any existing packages or ideas on how to implement the > > > equivalent of a generator (in the Python sense, i.e.http://www.python.org/dev/peps/pep-0255/) in a parallel/distributed > > > way. As a use case, imagine a function that generates a range of > > > primes. I'd like to be able to do something along the following lines: > > > > def iterprimes(start=1, end=None): > > > # ... > > > yield prime > > > > # rpc-related initialization > > > ... > > > rpc_proxy = some_rpc_lib(iterprimes, start=1e6, end=1e12) > > > for prime in proxy: > > > print prime > > > > Is there any module out there that does anything close to this ? > > > > George > > > DOLT!- Hide quoted text - > > > - Show quoted text - > > I thought you were making a joke about parallel processing. > I thought you were making a joke about parallel processing. > I thought you were making a joke about parallel processing. > I thought you were making a joke about parallel processing. > > -- Paul No, he probably sent it from Google groups as I did, which claimed that "your message has not been sent, please try again later". Go figure. George From eric.brunel at pragmadev.com Fri May 4 03:55:23 2007 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Fri, 04 May 2007 09:55:23 +0200 Subject: tkinter listboxes References: <1178249216.774940.141950@p77g2000hsh.googlegroups.com> Message-ID: On Fri, 04 May 2007 05:26:56 +0200, wrote: > I will give a simplified example of the problem at hand -- > > I have a case in which I have two listboxes - listbox1 and listbox2, > if I click on an item in listbox1 the item gets highlighted as > expected. Now if I click on an item in listbox2 the selected item in > listbox1 loses its highlight. My question is how do I keep the > listbox1 item from losing its highlight if I select an item in > listbox2 or to that matter any other widget. By default, the 'highlighting' is considered as a selection. Since you can't have two items selected at the same time, the second cancels the first. To avoid this behaviour, make each list keep its selection to itself by using the 'exportselection=0' option when you create the Listbox instance. This should work as you expect. HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From nyamatongwe+thunder at gmail.com Wed May 16 10:29:27 2007 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Wed, 16 May 2007 14:29:27 GMT Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <7x4pmg716p.fsf@ruckus.brouhaha.com> <4648EC26.8020907@v.loewis.de> Message-ID: Eric Brunel: > Have you ever tried to enter anything more than 2 or 3 characters like > that? No, only for examples. Lengthy texts are either already available digitally or are entered by someone skilled in the language. > I did. It just takes ages. Come on: are you really serious about > entering *identifiers* in a *program* this way? Are you really serious about entry of identifiers in another language being a problem? Most of the time your identifiers will be available by selection from an autocompletion list or through cut and paste. Less commonly, you'll know what they sound like. Even more rarely you'll only have a printed document. Each of these can be handled reasonably considering their frequency of occurrence. I have never learned Japanese but have had to deal with Japanese text at a couple of jobs and it isn't that big of a problem. Its certainly not "virtually impossible" nor is there "absolutely no way of entering the word" (???). I think you should moderate your exaggerations. Is there a realistic scenario in which foreign character set identifier entry would be difficult for you? Neil From wgwigw at gmail.com Sun May 27 06:56:42 2007 From: wgwigw at gmail.com (momobear) Date: 27 May 2007 03:56:42 -0700 Subject: a bug in python windows service? In-Reply-To: References: <1180231245.444827.171390@g37g2000prf.googlegroups.com> Message-ID: <1180263402.556292.199390@z28g2000prd.googlegroups.com> > No, this is not a bug. You must not call Thread.run(), use Thread.start() > instead - else your code won't run in a different thread of execution. See http://docs.python.org/lib/thread-objects.htmlon how to use Thread > objects - and note that you should *only* override __init__ and run, if > any. > Instead of extending join(), write a specific method to signal the > quitEvent or just let the caller signal it. And I don't see in this > example why do you need two different events (one on the thread, another > on the service controller), a single event would suffice. > > -- > Gabriel Genellina Thanks for help, It works now:D From rabbitsfriendsandrelations at hotmail.com Thu May 3 08:53:39 2007 From: rabbitsfriendsandrelations at hotmail.com (Eeyore) Date: Thu, 03 May 2007 13:53:39 +0100 Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> <1178162456.929395.139390@q75g2000hsh.googlegroups.com> <4639ce3e$0$29937$afc38c87@news.optusnet.com.au> Message-ID: <4639DB53.397D6243@hotmail.com> Peter Webb wrote: > > Ask yourself WHY havn't I seen this footage before? > > > > **************************** > > OK, why haven't you seen this footage before? Nice response ! Graham From fdu.xiaojf at gmail.com Sun May 20 05:38:24 2007 From: fdu.xiaojf at gmail.com (fdu.xiaojf at gmail.com) Date: Sun, 20 May 2007 17:38:24 +0800 Subject: questions about programming styles Message-ID: <46501710.6090904@gmail.com> Hi all, I'm not skilled at programming, so sorry for my ignorance. My questions: (1) which is the better way to calculate the value of attributes of a class ? for example: (A) def cal_attr(self, args): #do some calculations self.attr = calculated_value and then if the vlue of attribute is needed, self.cal_attr(args) some_var = self.attr or I can define cal_attr() as follows: (B) def cal_attr(self, args): #do some calculations return calculated_value and then, if the value of attribute is needed, self.attr = self.cal_attr(args) some_var = self.attr (2) when to use class methods and when to use functions ? In my opinion, both of class methods and functions have advantages and disadvantages. I have to pass many arguments to a function, which is annoying. When using class methods, the arguments can be stored as attributes of the class, which is convenient for later use. But I have to create an object in advance. I have googled the web, but haven't found too much specific answers. Can somebody kindly answer my questions or point me to the resources available on the web ? Thanks a lot. From jstroud at mbi.ucla.edu Wed May 2 03:37:46 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 02 May 2007 07:37:46 GMT Subject: Tcl-tk 8.5? In-Reply-To: <46382248$0$5105$ba4acef3@news.orange.fr> References: <46382248$0$5105$ba4acef3@news.orange.fr> Message-ID: M?ta-MCI wrote: > Hi! > > > See http://wiki.tcl.tk/10630 > > Any plan to integrate Tcl 8.5 in standard Python? > > > > @+ > > MCI > Better would be to outegrate it and instead use another gui kit as the standard. James From antroy at gmail.com Thu May 10 06:42:58 2007 From: antroy at gmail.com (Ant) Date: 10 May 2007 03:42:58 -0700 Subject: Newbie (but improving) - Passing a function name with parameters as a parameter In-Reply-To: <1178785638.736644.312970@e51g2000hsg.googlegroups.com> References: <1178785638.736644.312970@e51g2000hsg.googlegroups.com> Message-ID: <1178793778.002765.50660@y80g2000hsf.googlegroups.com> As Stephan said, you can investigate the timeit module. If you want to test it your way, wrap up your function call in another function: On May 10, 9:27 am, mosscliffe wrote: ... > def timeloop(dofunction,iters=10): ... > > def lookup(recs,patterns): ... > myrecs = ... > def test1(): lookup(myrecs, ['one', 'nomatch']) def test2(): lookup(myrecs, ['one', 'two']) > timeloop(test1, 10) Using timeit: t = timeit.Timer("lookup(myrecs, ['one', 'nomatch'])", "from __main__ import *") print t.timeit(10) -- Ant. From a.h.a.stienen at utwente.nl Sat May 26 15:56:43 2007 From: a.h.a.stienen at utwente.nl (Arno Stienen) Date: Sat, 26 May 2007 21:56:43 +0200 Subject: Using RTAI-XML with Python hangs Python execution In-Reply-To: <45AC0631.8080601@ctw.utwente.nl> References: <45AC0631.8080601@ctw.utwente.nl> Message-ID: <465890FB.4030405@utwente.nl> Hello all, It has been a while, but I finally found the time to further investigate my problems with connecting Python to a RTAI-XML server. As I cannot tell if the problems I'm facing are caused by RTAI-XML (or more precisely, the xmlrpc++0.7 library) or Python (xmlrpclib), I'm posting this message on both the RTAI as the Python mailing list. Just to recap, here are the symptoms I described earlier. I am using two computers. One is running the RTAI-patched real-time linux kernel, and this computer controls my robotic hardware. On this RTAI computer I installed the RTAI-XML server, which uses incoming XML-RPC calls to control real-time processes on the server. RTAI-XML is programmed in C++, using the xmlrpc++0.7 library. The second is a desktop machine (Windows XP or Ubuntu), from which a XML-RPC connection can be made to the RTAI computer. Although in theory it should make no difference if I use C, C++, Java or Python to make the connection, in practise I can get the Java connection running, but have problems using Python. And I really like to use Python to quickly create interfaces! When connecting with Python on the desktop computer to the RTAI-XML server running on my RTAI machine, I used the following code. import xmlrpclib server = xmlrpclib.Server("http://10.10.101.62:29500") print server.Info_RT('Master') This results in the correct output: {'state': 0, 'str': 'Info_RT'} Yet, this is only an information call. The really interesting part should comes when I ask the server to open a connection: import xmlrpclib server = xmlrpclib.Server("http://10.10.101.62:29500") print server.Connection_Request("roberto") But then nothing happens. Python just hangs and is unresponsive. Until, I kill the RTAI-XML server on the RTAI computer! And then suddenly the correct output appears on the desktop command line: {'state': 0, 'id_session': '2Z3EUSLJFA13', 'port': 29501, 'str': 'Connection accepted. Session attached.'} (Using an alternative Python XML-RPC library '#import pyxmlrpclib as xmlrpclib' makes no difference to the result.) So what happens? I did some experiments. I did some package sniffing with Wireshark and I did Python tracing. I stored the sniffing results in both the Wireshark as plain text format. The files for the first Info_RT examples are here: http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-infort-python.ws http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-infort-python-ws.txt http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-infort-trace.txt The files for the second, not correctly working example are here: http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-conreq-python.ws http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-conreq-python-ws.txt http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-conreq-trace.txt http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-conreq-trace-hardbreak.txt The first three files all include killing the server after ~30 seconds, thus resulting in the correct output. In the fourth files, tracing is stopped before the server is killed. It is therefor the trace up to the 'hanging point'. Any, really any, suggestions are appreciated! Kind regards, Arno Stienen. From pmuller at redhat.com Mon May 21 12:23:18 2007 From: pmuller at redhat.com (Petr Muller) Date: Mon, 21 May 2007 18:23:18 +0200 Subject: Python and GUI In-Reply-To: <1179761984.704369.116310@b40g2000prd.googlegroups.com> References: <1179761984.704369.116310@b40g2000prd.googlegroups.com> Message-ID: <4651C776.30105@redhat.com> sdoty044 at gmail.com wrote: > Just wondering on what peoples opinions are of the GUIs avaiable for > Python? > > All I am doing is prompting users for some data (listbox, radio > buttons, text box, ect...). Then I will have some text output, maybe > a scrolling text message as things are happening. > > I have some minor things I need to do, for example, if Checkbutton X > is clicked, I need to disable TextBox Y, and I would like to display > the scrolling text (output) > > Ultimately, is it worth downloading and learning some of the packages > avaiable for Python, or should I just stick to the Tkinter stuff that > is included. > > More specifically, has anyone used the Qt stuff for python, easy to > use? > There's PyQt thingy, imho very good and easy to learn/use, but still powerful. I've used it for a small gui-oriented project with almost no problems and it worked like a charm. However, sometimes I had troubles finding useful documentation for it. I've also tried to play with PyGTK, it's quite nice and easy (and you have the advantage of Glade), but I don't like GTK way of creating GUI. I haven't used Tkinter a lot, only looked at it. And I didn't like it much. I would really suggest PyQt. (with a big IMHO :) Petr From antroy at gmail.com Mon May 21 05:13:34 2007 From: antroy at gmail.com (Ant) Date: 21 May 2007 02:13:34 -0700 Subject: Translating some Java to Python In-Reply-To: <1179692679.422164.27700@r3g2000prh.googlegroups.com> References: <1179692679.422164.27700@r3g2000prh.googlegroups.com> Message-ID: <1179738814.282655.192700@r3g2000prh.googlegroups.com> On May 20, 9:24 pm, Daniel Gee wrote: ... > The Java version has static methods for common roll styles (XdY and XdY > +Z) for classes that just want a result but don't want to bother > keeping an object around for later. > > So the question is, assuming that I wanted to keep the static method > behavior (which I'm not really sure I do), how does one format the > method header on a 'static' method in Python? Is it just something > like: > > class Foo: > def statAdd(self,a): > return a+5 > > or do you drop the 'self' bit and just use a 1 variable parameter list? Herman has shown you *how* to do static methods in Python, but typically they are not used. Since Python has first class functions, and they can be defined at the module level, there is no need to use static methods. There is a distinction in Python not present in Java between class and static methods, class methods get the class passed in as the first parameter, and can be useful if you want a function that acts on data that the class provides. Static methods in Python are merely normal functions that are associated with the class - for conceptual reasons rather than practical ones, and are rarely used as far as I can tell. I've certainly never bothered with them. In the case of your statAdd above, self is never used in the method body, and so this is a clear indication that a module level function would be more appropriate. -- Ant... http://antroy.blogspot.com/ From tom at finland.com Thu May 10 09:38:40 2007 From: tom at finland.com (tom at finland.com) Date: Thu, 10 May 2007 13:38:40 GMT Subject: keyword checker - keyword.kwlist Message-ID: Hi I try to check whether a given input is keyword or not. However this script won't identify keyword input as a keyword. How should I modify it to make it work? #!usr/bin/env python import keyword input = raw_input('Enter identifier to check >> ') if input in keyword.kwlist: print input + "is keyword" else: print input + "is not keyword" From carsten at uniqsys.com Mon May 21 10:55:44 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 21 May 2007 10:55:44 -0400 Subject: howto get function from module, known by string names? In-Reply-To: <1179753182.107111.94060@y2g2000prf.googlegroups.com> References: <1179228596.349933.168610@l77g2000hsb.googlegroups.com> <1179753182.107111.94060@y2g2000prf.googlegroups.com> Message-ID: <1179759344.3387.9.camel@dot.uniqsys.com> On Mon, 2007-05-21 at 06:13 -0700, dmitrey wrote: > And howto check does module 'asdf' exist (is available for import) or > no? (without try/cache of course) Why would you need to do that? What are you planning to do when you have determined that the module doesn't exist? Surely you're not planning on swallowing the error silently, because that would make your program very hard to debug. The Pythonic response is to raise an exception, but then you might as well just propagate the exception that __import__ already raises: >>> def myfunc(module_string1, func_string2, *args): ... func = getattr(__import__(module_string1), func_string2) ... return func(*args) ... >>> myfunc("asdf", "spam") Traceback (most recent call last): File "", line 1, in ? File "", line 2, in myfunc ImportError: No module named asdf Hope this helps, -- Carsten Haese http://informixdb.sourceforge.net From kyosohma at gmail.com Thu May 10 15:12:02 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 10 May 2007 12:12:02 -0700 Subject: SQLObject 0.9.0 In-Reply-To: References: Message-ID: <1178824322.008520.239540@y5g2000hsa.googlegroups.com> On May 10, 10:25 am, Oleg Broytmann wrote: > Hello! > > I'm pleased to announce the 0.9.0 release of SQLObject, the first stable > release of the 0.9 branch. > > What is SQLObject > ================= > > SQLObject is an object-relational mapper. Your database tables are described > as classes, and rows are instances of those classes. SQLObject is meant to be > easy to use and quick to get started with. > > SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and > Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also > known as SAPDB). > > Where is SQLObject > ================== > > Site:http://sqlobject.org > > Development:http://sqlobject.org/devel/ > > Mailing list:https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss > > Archives:http://news.gmane.org/gmane.comp.python.sqlobject > > Download:http://cheeseshop.python.org/pypi/SQLObject/0.9.0 > > News and changes:http://sqlobject.org/News.html > > What's New > ========== > > Features & Interface > -------------------- > > * Support for Python 2.2 has been declared obsolete. > > * Removed actively deprecated attributes; > lowered deprecation level for other attributes to be removed after 0.9. > > * SQLite connection got columnsFromSchema(). Now all connections fully support > fromDatabase. There are two version of columnsFromSchema() for SQLite - > one parses the result of "SELECT sql FROM sqlite_master" and the other > uses "PRAGMA table_info"; the user can choose one over the other by using > "use_table_info" parameter in DB URI; default is False as the pragma is > available only in the later versions of SQLite. > > * Changed connection.delColumn(): the first argument is sqlmeta, not > tableName (required for SQLite). > > * SQLite connection got delColumn(). Now all connections fully support > delColumn(). As SQLite backend doesn't implement "ALTER TABLE DROP COLUMN" > delColumn() is implemented by creating a new table without the column, > copying all data, dropping the original table and renaming the new table. > > * Versioning - seehttp://sqlobject.org/Versioning.html > > * MySQLConnection got new keyword "conv" - a list of custom converters. > > * Use logging if it's available and is configured via DB URI. > > * New columns: TimestampCol to support MySQL TIMESTAMP type; > SetCol to support MySQL SET type; > TinyIntCol for TINYINT; SmallIntCol for SMALLINT; > MediumIntCol for MEDIUMINT; BigIntCol for BIGINT. > > Small Features > -------------- > > * Support for MySQL INT type attributes: UNSIGNED, ZEROFILL. > > * Support for DEFAULT SQL attribute via defaultSQL keyword argument. > > * cls.tableExists() as a shortcut for conn.tableExists(cls.sqlmeta.table). > > * cls.deleteMany(), cls.deleteBy(). > > Bug Fixes > --------- > > * idName can be inherited from the parent sqlmeta class. > > * Fixed a longstanding bug with .select() ignoring 'limit' parameter. > > * Fixed a bug with absent comma in JOINs. > > * Fixed sqlbuilder - .startswith(), .endswith() and .contains() assumed > their parameter must be a string; now you can pass an SQLExpression: > Table.q.name.contains(func.upper('a')), for example. > > * Fixed a longstanding bug in sqlbuilder.Select() with groupBy being a > sequence. > > * Fixed a bug with Aliases in JOINs. > > * Yet another patch to properly initialize MySQL connection encoding. > > * Fixed a minor comparison problem in test_decimal.py. > > * Fixed a bug in SQLRelatedJoin that ignored per-instance connection. > > Docs > ---- > > * Added documentation about 'validator' Col constructor option. > > * Added an answer and examples to the FAQ on how to use sqlmeta.createSQL. > > * Added an example on how to configure logging. > > * More documentation about orderBy. > > For a more complete list, please see the news:http://sqlobject.org/News.html > > Oleg. > -- > Oleg Broytmann http://phd.pp.ru/ p... at phd.pp.ru > Programmers don't die, they just GOSUB without RETURN. Why was this released 3 times with different version numbers in less than an hour? Mike From bjourne at gmail.com Wed May 16 06:51:56 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Wed, 16 May 2007 12:51:56 +0200 Subject: Quote aware split In-Reply-To: <41749080705151750m3367c65dy4d1ae6ca66c2a16b@mail.gmail.com> References: <41749080705151750m3367c65dy4d1ae6ca66c2a16b@mail.gmail.com> Message-ID: <740c3aec0705160351x1c348a15o56e517f6586ef0a6@mail.gmail.com> How is the code different from shlex.split? -- mvh Bj?rn From horpner at yahoo.com Thu May 17 11:50:52 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 17 May 2007 15:50:52 GMT Subject: searching algorithm References: <7dydnfjNWbo9H97bnZ2dnUVZ_oupnZ2d@comcast.com> Message-ID: On 2007-05-11, Terry Reedy wrote: > > "Neil Cerutti" wrote in message > news:lNM0i.34412$G23.27437 at newsreading01.news.tds.net... >| Every node is a tuple of its letter, a list of its children, and >| a list of its words. So the two 'pelin' nodes would be (with 'e' >| referenced in the 'h' node): >| >| ('h', [('e', [], ['pelin'])], ['pelin']) >| >| That would in turn be "stored" in the t, n, i and s nodes. > [snip] > > At the outer level, I would use a list in order to build the > structure in pieces, one for each letter, and then add them in. > > At the top level, the letters do not need explicit storage. > The first subtree is for words starting with 'a', etc. In > other words, the position of each subtree indicates its > starting letter. For most letters, this can be carried on > another level. Here's a proof of concept prototype of the dictionary searching algorithm. The dictionary I found to test with has roughly 5,000 words, and I didn't attempt any optimizations at all. I'm guessing it can't be sped up very much, even though I wrote the simplest possible implementation. Lookup in the worst case is O(N), where N is the number of letters in your prefix. First, a sample of input/output. lookup: pe people: la gente[Noun] pepper: pepe[Noun] peppercorn: grano di pepe[Noun] peppermint: menta peperita[Noun] peppery: pepato, acre, pungente[Adjective] pepsin: pepsina[Noun] permutation: permutazione[Noun] permutations: permutazioni[Noun] permute: permutare[Verb] perorate: perorare perpendicular: perpendicolare[Adjective] perpendicularly: perpendicolarmente[Adverb] perpendiculars: perpendicolari[Noun] perpetrate: perpetrare[Verb] perpetrated: perpetrato[Verb] perpetual: perpetuo[Adjective] petard: petardo[Noun] petroleum: petrolio[Noun] Now the source. # Each node is a tuple of (letter, node list, word list). A word # list is just a list of strings. root = ('', [], []) def insert(node, key, value): if len(key) == 0: node[2].append(value) else: first = key[0] rest = key[1:] for n in node[1]: if n[0] == first: insert(n, rest, value) return node[1].append((first, [], [])) insert(node, key, value) def lookup(node, key): if len(key) == 0: return node else: first = key[0] rest = key[1:] for v in node[1]: if v[0] == first: return lookup(v, rest) return None def word_list(node, word): for v in node[2]: print '%s: %s' % (word, v) for n in node[1]: word_list(n, word+n[0]) # Italian.txt from http://www.june29.com/IDP/ source = open('Italian.txt', 'r') # Build tree for line in source: line = line.strip() if line[0] == '#': continue key, value = line.split('\t') insert(root, key, value) # Look up a prefix x = raw_input("lookup: ") tree = lookup(root, x) if tree: word_list(tree, x) else: print "Not found." -- Neil Cerutti From tbrkic at yahoo.com Mon May 28 08:17:30 2007 From: tbrkic at yahoo.com (glomde) Date: 28 May 2007 05:17:30 -0700 Subject: Good idea to use a class as function with __new__? Message-ID: <1180354650.472117.144430@p77g2000hsh.googlegroups.com> Hi, I am implementing som code generation and want to to use some variant of the template method pattern. What I came up with is to have a class with the common part in a method and the subclasses can then override the Customize methods to do their own special part. Now to the question I use the __new__ to return the result instead of the instance. So that the class is used as an function. So insted of having. a = Template() result = a.__TemplateMethod(preifix="foo") I can write: result = Template(prefix="foo") class Template(object): def __init__(cls, *args, **kwds): pass def __new__(cls, *args, **kwds): obj = super(Template, cls).__new__(cls, *args, **kwds) return obj.__TemplateMethod(*args, **kwds) def Customize1(self, prefix="hello", *args, **kwds): return prefix+"1\n" def Customize2(self, prefix="hello", *args, **kwds): return prefix+"2\n" def __TemplateMethod(self, *args, **kwds): result = "" result += self.Customize1(*args, **kwds) result += self.Customize1(*args, **kwds) return result b = Template("foo") print b From rahulnag22 at yahoo.com Fri May 4 09:41:09 2007 From: rahulnag22 at yahoo.com (rahulnag22 at yahoo.com) Date: 4 May 2007 06:41:09 -0700 Subject: tkinter listboxes In-Reply-To: References: <1178249216.774940.141950@p77g2000hsh.googlegroups.com> Message-ID: <1178286069.736041.221420@y80g2000hsf.googlegroups.com> On May 4, 1:55 am, "Eric Brunel" wrote: > On Fri, 04 May 2007 05:26:56 +0200, wrote: > > I will give a simplified example of the problem at hand -- > > > I have a case in which I have two listboxes - listbox1 and listbox2, > > if I click on an item in listbox1 the item gets highlighted as > > expected. Now if I click on an item in listbox2 the selected item in > > listbox1 loses its highlight. My question is how do I keep the > > listbox1 item from losing its highlight if I select an item in > > listbox2 or to that matter any other widget. > > By default, the 'highlighting' is considered as a selection. Since you > can't have two items selected at the same time, the second cancels the > first. To avoid this behaviour, make each list keep its selection to > itself by using the 'exportselection=0' option when you create the Listbox > instance. This should work as you expect. > > HTH > -- > python -c "print ''.join([chr(154 - ord(c)) for c in > 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" Eric that works. Thank You. James thank you for the detailed explanation it will be useful for me. Regards Rahul From __peter__ at web.de Sat May 19 15:01:05 2007 From: __peter__ at web.de (Peter Otten) Date: Sat, 19 May 2007 21:01:05 +0200 Subject: RFC - n-puzzle.py References: <1179530104.645902.135250@p77g2000hsh.googlegroups.com> Message-ID: Phoe6 wrote: > I would like to request a code and design review of one of my program. > n-puzzle.py > I have used OO Python for the above program and would like comments on > my approach as I am just starting with OOP. [The following has nothing to do with OOP, I just read Raymond's post and got interested in the context] > class State: > def huristic_next_state(self, st): It's heuristics, not huristics. # Choose a random item from exp_sts among those with minimal # manhattan_distance() > exp_sts = self.expand(st) > mdists = [] > for st in exp_sts: > mdists.append(self.manhattan_distance(st)) > mdists.sort() > short_path = mdists[0] > if mdists.count(short_path) > 1: > least_paths = [] > for st in exp_sts: > if self.manhattan_distance(st) == short_path: > least_paths.append(st) > return random.choice(least_paths) > else: > for st in exp_sts: > if self.manhattan_distance(st) == short_path: > return st Looks like you do not need the count() method call at all as the branch for multiple nearest items works with a length-one list, too. As a consequence, there's no need to keep a list of distances, just the minimum: # all untested exp_sts = self.expand(st) short_path = min(exp_sts, key=self.manhattan_distance) least_paths = [s for s in exp_sts if self.manhattan_distance(s) == short_path] return random.choice(least_paths) Calling random.choice() on a list with only one item is predictable but will do no harm if the code is not time-critical. By the way, you could write a helper function that finds all minima according to some criterion >>> minima([1, 2, -1, 1.0, 3], key=abs) [1, -1, 1.0] With such a function the method body would become return random.choice(minima(self.expand(st), key=self.manhattan_distance)) Almost self-documenting, I'd say :-) Here's a quick and dirty implementation: def minima(values, key=lambda x: x): d = {} for v in values: d.setdefault(key(v), []).append(v) return d[min(d)] The advantage of this approach is that you - iterate over the list just once - call the key() function once per list item - can test the function independently from your State class The memory overhead for the extra lists can be avoided by a better implementation. Peter From kyosohma at gmail.com Wed May 9 15:31:01 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 9 May 2007 12:31:01 -0700 Subject: which is more pythonic/faster append or +=[] In-Reply-To: <1178726923.909537.209300@l77g2000hsb.googlegroups.com> References: <1hxtelz.7f6rvnw4cyxmN%aleax@mac.com> <1178726923.909537.209300@l77g2000hsb.googlegroups.com> Message-ID: <1178739061.919664.128260@y80g2000hsf.googlegroups.com> On May 9, 11:08 am, 7stud wrote: > On May 8, 11:05 pm, a... at mac.com (Alex Martelli) wrote: > > > > > alf wrote: > > > two ways of achieving the same effect > > > > l+=[n] > > > > or > > > > l.append(n) > > > > so which is more pythonic/faster? > > > .append - easy to measure, too: > > > brain:~ alex$ python -mtimeit 'L=range(3); n=23' 'x=L[:]; x.append(n)' > > 1000000 loops, best of 3: 1.31 usec per loop > > > brain:~ alex$ python -mtimeit 'L=range(3); n=23' 'x=L[:]; x+=[n]' > > 1000000 loops, best of 3: 1.52 usec per loop > > > Alex > > Ah, I see. The list would grow too large with all that appending, so > you begin again with the original list for every loop. > > Is there any documentation for the syntax you are used with timeit? I > checked 'man python', and I also read the example in the python docs, > but you seem to be using a hybrid syntax. > > Thanks. If you want to have multiple statements on one line, all you need to do is add the semi-colon. That is what Alex did. I think I saw that trick in the book "Programming Python" by Lutz...or some other reference text. Here's one link to the anomaly: http://safari.oreilly.com/0201748843/ch07lev1sec5 Here's another link that mentions it as well: http://www-128.ibm.com/developerworks/opensource/library/os-python5/ Mike From saif.shakeel at gmail.com Thu May 3 09:15:52 2007 From: saif.shakeel at gmail.com (saif.shakeel at gmail.com) Date: 3 May 2007 06:15:52 -0700 Subject: file Error In-Reply-To: References: <1178195977.521889.167910@p77g2000hsh.googlegroups.com> Message-ID: <1178198152.382431.306950@c35g2000hsg.googlegroups.com> On May 3, 6:09 pm, "Gabriel Genellina" wrote: > En Thu, 03 May 2007 09:39:37 -0300, escribi?: > > > Hi, > > I am parsing an xml file,and using raw_input command to ask the > > user to enter the file name.Ex > > > Enter The ODX File Path: > > > Suppose my code does not work properly,then in the python idle window > > it shows something like this: > > [...traceback...] > > I want the inputfile prompt to appear regardless of > > the error condition.I dont know where the problem lies.Can someone > > help me out. > > - IDLE is a development environment - don't use it to actually run your > program in production. > > - Instead of asking the user to type the file name, accept it as a > parameter, that's what almost everyone else does in the world... It has > many advantages: you can associate your program with the filename > extension, you can use the "Send to..." menu, you can run it inside a > batch file, you can drop a file over your program to be processed, etc. > > -- > Gabriel Genellina Thanks for the reply........How do i accept the filename is a parameter and avoid the error.Can you elaborate. From deepbroke6 at gmail.com Wed May 16 13:24:32 2007 From: deepbroke6 at gmail.com (deepbroke6 at gmail.com) Date: 16 May 2007 10:24:32 -0700 Subject: ~!~ Britneys New BOOBS Message-ID: <1179336272.349749.183150@q75g2000hsh.googlegroups.com> http://scargo.in - Download pics and videos of Britneys new Boob job see her new tits naked! From grante at visi.com Mon May 14 15:17:37 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 14 May 2007 19:17:37 -0000 Subject: Time References: <1178916216.893542.257320@y80g2000hsf.googlegroups.com> <1178916422.065108.312920@l77g2000hsb.googlegroups.com> <1178920014.621031.301860@n59g2000hsh.googlegroups.com> <1178927105.482975.174760@y5g2000hsa.googlegroups.com> <1179151205.987222.54910@k79g2000hse.googlegroups.com> <1179152573.315362.37040@u30g2000hsc.googlegroups.com> <1179152855.424498.274820@p77g2000hsh.googlegroups.com> Message-ID: <134hdehnrd73bef@corp.supernews.com> On 2007-05-14, Gabriel Genellina wrote: > En Mon, 14 May 2007 11:27:35 -0300, HMS Surprise > escribi?: > >> On May 14, 9:22 am, HMS Surprise wrote: >> >> Oops +=1, should be: >> hrMn[0] = int(hrMn[0] >> if t[2] == 'PM': >> hrMn[0] += 12 >> >> Need more starter fluid, coffee please!!! > > Still won't work for 12 AM nor 12 PM... Do you mean 12 Noon or 12 Midnight? 12AM and 12PM don't exist, do they? -- Grant Edwards grante Yow! HELLO, everybody, at I'm a HUMAN!! visi.com From dborne at gmail.com Wed May 2 11:14:28 2007 From: dborne at gmail.com (Dave Borne) Date: Wed, 2 May 2007 10:14:28 -0500 Subject: Writing a nice formatted csv file In-Reply-To: <1178115244.446071.317250@n76g2000hsh.googlegroups.com> References: <1178115244.446071.317250@n76g2000hsh.googlegroups.com> Message-ID: <6e42ec490705020814o15cf616exbbcc127a2918a461@mail.gmail.com> > Whereas what I'd like to get is: > 1, 2, 3, > 10, 20, 30 (without trying this myself first...) You might try setting up a csv dialect with a delimiter of ',\t' then using a reader that can set tab stops for display. -Dave From python-url at phaseit.net Mon May 7 09:29:44 2007 From: python-url at phaseit.net (Cameron Laird) Date: Mon, 7 May 2007 13:29:44 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (May 7) Message-ID: QOTW: "As a general rule, *ALL* multithread operations are at least that troublesome, and most are far more so." - Gary Herron "I'm a recent, belated convert from Perl. I work in a physics lab and have been using Python to automate a lot of measurement equipment lately. It works fabulously for this purpose." - Dan Lenski It *is* possible to copy a function--by replication of all its attributes. John Nagle explains why it's so difficult: http://groups.google.com/group/comp.lang.python/browse_thread/thread/2dfe7d6b150a0ec/ If you think you need a macro as C knows it in your Python code, you're almost certainly missing a far easier solution: http://groups.google.com/group/comp.lang.python/browse_thread/thread/4cda4dc6b78b94a9/ If you think you need difficult quoting to move your data from Python to a standard database, you're almost certainly missing an easier standard solution, perhaps involving parameter passing: http://groups.google.com/group/comp.lang.python/browse_thread/thread/7bf20c46b6e1f29e/ If you think you need abstruse (extended) regular expressions for your parsing ... well, maybe you're right. Informed opinion on this one is divided: http://groups.google.com/group/comp.lang.python/browse_thread/thread/a54607d8f2232a68/ Maxim Veksler exhibits more than a thousand non-blocking sockets all listening simultaneously. Jean-Paul Calderone shows how twisted does 'em better: http://groups.google.com/group/comp.lang.python/browse_thread/thread/f0d3dd52e754c1d0/ Microsoft's DLR appears to have substance: http://groups.google.com/group/comp.lang.python/browse_thread/thread/360c79cf6093d713/ bounced for a while. Resend requests that were lost, please: http://groups.google.com/group/comp.lang.python/browse_thread/thread/3be0130e02ddcca4/ This is almost Foundational: how does one receive one element from a Set? http://groups.google.com/group/comp.lang.python/browse_thread/thread/4392b09c281feca2/ Many agitate for Python to build in a different GUI toolkit. Jeremiah Foster makes clear how to work with one of the alternatives--wxPython for Mac OS X: http://groups.google.com/group/comp.lang.python/browse_thread/thread/f73834fb0238d880/ ======================================================================== 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. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, Planet Python indexes much of the universe of Pybloggers. http://www.planetpython.org/ The Python Papers aims to publish "the efforts of Python enthusiats". http://pythonpapers.org/ 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 kevin.t.ryan at gmail.com Sun May 6 21:11:07 2007 From: kevin.t.ryan at gmail.com (Kevin T. Ryan) Date: 6 May 2007 18:11:07 -0700 Subject: Plot with scipy In-Reply-To: <1178283196.755609.241790@n59g2000hsh.googlegroups.com> References: <1178283196.755609.241790@n59g2000hsh.googlegroups.com> Message-ID: <1178500267.351341.145750@p77g2000hsh.googlegroups.com> On May 4, 8:53 am, redcic wrote: > Hi all, > > I've just downloaded scipy v 0.5.2 and I would like to be able to draw > plots. I've tried: > import scipy.gplt > import scipy.plt > import scipy.xplt > > and none of them work. Are these modules still included in scipy ? If > not, where can I find them ? > > Thanks for your answers, > > C?dric As a lightweight alternative to matplotlib, you might be interested in trying out my *small* (and functionally *limited*) code at: http://code.google.com/p/graphn. I created it to be hopefully useful around web graphs, but it only does line graphs and bar charts. It requires the gd library, but nothing outside of that. I think it's pretty easy to use, but obviously you'll have to be the judge of that. From stefan.behnel-n05pAM at web.de Mon May 14 04:54:21 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 14 May 2007 10:54:21 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> Message-ID: <464823BD.9050200@web.de> Eric Brunel wrote: > Even when writing code that appears to be "private" at some > time, one *never* knows what will become of it in the future. If it ever > goes public, its chances to evolve - or just to be maintained - are far > bigger if it's written all in english. > > --python -c "print ''.join([chr(154 - ord(c)) for c in > 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" Oh well, why did *that* code ever go public? Stefan From howe.steven at gmail.com Wed May 16 18:18:38 2007 From: howe.steven at gmail.com (Steven Howe) Date: Wed, 16 May 2007 15:18:38 -0700 Subject: How do I count the number of spaces at the left end of a string? In-Reply-To: <1179351367.714864.47190@l77g2000hsb.googlegroups.com> References: <1179351367.714864.47190@l77g2000hsb.googlegroups.com> Message-ID: <464B833E.5040806@gmail.com> walterbyrd wrote: > I don't know exactly what the first non-space character is. I know the > first non-space character will be * or an alphanumeric character. > > using builtin function rindex st = 'asblde ' >>> st.rindex(' ') sph -- HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 From bignose+hates-spam at benfinney.id.au Sun May 27 04:35:44 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 27 May 2007 18:35:44 +1000 Subject: Is PEP-8 a Code or More of a Guideline? References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> Message-ID: <87myzqpstb.fsf@benfinney.id.au> Paul McGuire writes: > At this point, I realized that I was taking things too far > off-topic, so I decided to start a new thread. So, uh, what's the purpose of this thread? Did you have a specific point to start off with, or a question to ask? -- \ "It seems intuitively obvious to me, which means that it might | `\ be wrong." -- Chris Torek | _o__) | Ben Finney From jmfbahciv at aol.com Sat May 5 05:33:08 2007 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Sat, 05 May 07 09:33:08 GMT Subject: Firefighters at the site of WTC7 "Move away the building is going to blow up, get back the building is going to blow up." References: <1178161820.731367.264500@y80g2000hsf.googlegroups.com> <1hlj33p6aq838o2urk1dv6h75b5is4i2vd@4ax.com> <3TD_h.219$mR2.195@newssvr22.news.prodigy.net> <1178329932.455122.161530@u30g2000hsc.googlegroups.com> <1178346041.557106.129670@y80g2000hsf.googlegroups.com> Message-ID: In article <1178346041.557106.129670 at y80g2000hsf.googlegroups.com>, MooseFET wrote: >On May 4, 8:19 pm, James Stroud wrote: >> MooseFET wrote: >> > On May 4, 12:32 pm, James Stroud wrote: >> > [....] >> >> >>The Marxist contribution to western thought is that it put everything in >> >>terms of labor and thus allowed us to quantify the human component of >> >>economies. >> >> > No the great insight by Marx was in the selling of ducks. "Anybody >> > want to buy a duct" has done more to advance economic thinking than >> > the works of most economists. >> >> > Economists have a vested interest in preventing people from >> > understanding economics. They are well paid and know that they >> > wouldn't be for long if people really understood what was going on. >> >> You must be an economist because you provide absolutely no >> interpretation of what the hell you were saying in ghe first paragraph >> (as if you actually know what you were trying to say). Duct or duck, >> first of all. Second of all--make a point. > >Groucho Marx. Give that man a cigar. /BAH From vatamane at gmail.com Mon May 14 13:10:17 2007 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 14 May 2007 10:10:17 -0700 Subject: Sorting troubles In-Reply-To: <1179158708.433792.127150@h2g2000hsg.googlegroups.com> References: <1179158708.433792.127150@h2g2000hsg.googlegroups.com> Message-ID: <1179162617.578315.133640@h2g2000hsg.googlegroups.com> On May 14, 12:05 pm, seyens... at yahoo.com wrote: > I have the following implementations of quicksort and insertion sort: > > def qSort(List): > if List == []: return [] > return qSort([x for x in List[1:] if x< List[0]]) + List[0:1] + \ > qSort([x for x in List[1:] if x>=List[0]]) > > def insertSort(List): > for i in range(1,len(List)): > value=List[i] > j=i > while List[j-1]>value and j>0: > List[j]=List[j-1] > j-=1 > List[j]=value > > Now, the quickSort does not modify the original list, mostly because > it works on products and concatenations, rather than alterations. > The insertion sort, however, does modify the list. Now, to give > results, they should be called in such a way( A is an unsorted list) > A=qSort(A) > # the insertion sort does not require this, > insertSort(A) > > I would like to know how can I modify the qSort function such that it > affects the list directly inside > I have tried doing it like this > > def qSort(List): > if List == []: return [] > List = qSort([x for x in List[1:] if x< List[0]]) + List[0:1] + \ > qSort([x for x in List[1:] if x>=List[0]]) > return List > > while processing, the list changes, but those changes remain inside > the function, so that once it's over, if nothis catches the return, > the original List remains unchanged. > > If not a solution, I would like to at least know why it does what it > does. I so understand that List(above) is only a reference to the > actual data(a list), but I'm not passing a copy of the data to the > function, but the actual reference(hence, insertSort does > modifications). But then how can I change, inside the function, the > object List is referencing to? If I can't modify the original list, > maybe I can make the variable List point to another list? But changes > inside the function are local. Sorry if this is a bit confusing. It does what it does because in the return statement when you concatenate qsort(...x<..)+List[0:1]+qsort(...x>=..) you create a new list. In the insertion sort you modify the values of the list directly by doing List[j]=List[j-1] or List[j]=value. If you just have to have the list modified in place, create another wrapper function that calls your qsort and then will copy all data from the result into the original list and you are done. Something like: def qsort_in_place(L): sortedL=qsort(L) for (i,x) in enumerate(sortedL): L[i]=x Cheers, -Nick Vatamaniuc From antroy at gmail.com Wed May 16 11:20:16 2007 From: antroy at gmail.com (Ant) Date: 16 May 2007 08:20:16 -0700 Subject: Newbie Question: Getting a list of files In-Reply-To: <1179324440.729561.27920@w5g2000hsg.googlegroups.com> References: <1179324440.729561.27920@w5g2000hsg.googlegroups.com> Message-ID: <1179328815.567298.109920@o5g2000hsb.googlegroups.com> On May 16, 3:07 pm, Gerard Flanagan wrote: ... > import os > > def iter_dirs(root, dirs=False): ... Rather than rolling your own directory walker: The same iterator using os.walk: def iter_dirs(root, dirs=False): for root, directories, files in os.walk(root): if dirs: for dir in directories: yield os.path.join(root, dir) for file in files: yield os.path.join(root, file) os.path.walk requires a different mindset: def visitor(yield_dirs, dirname, names): for name in names: pth = os.path.join(dirname, name) if os.path.isfile(pth) or yield_dirs: print pth os.path.walk(root, visitor, False) From marcello.lussana at nekhem.com Wed May 23 04:19:36 2007 From: marcello.lussana at nekhem.com (marcello.lussana at nekhem.com) Date: Wed, 23 May 2007 10:19:36 +0200 Subject: SOAPpy - send xml data Message-ID: <20070523081936.GA20083@avalon.nekhem.com> Hi, I'm trying to send some xml data to a WSDL server. Here's my code: xmldata = " Test di messaggio 1 + 222222222 17.5.2007 12:59:53 """ SOAPpy.WSDL.Config.namespaceStyle = '2001' server = SOAPpy.WSDL.Proxy('https://www.mywdslserver.com/foo.asp?WSDL') print server.insertMessages(xmlRequest=xmldata) parsing the output I've got two problems, about the tag, that is the tag that contains my xml data: - soappy escape xmlRequest tag, in my output I've got _xFFFF_xmlRequest as xml is _xFFFF_ - I didn't find a way to specify the type of the data that I send to my WSDL server => <_xFFFF_xmlRequest xsi3:type="xsd3:string"> In other words, I'd like to include my xmldata into a simple and I don't know how to do it with SOAPpy library. thank you From ville at oikarinen.org Tue May 29 02:09:02 2007 From: ville at oikarinen.org (Ville Oikarinen) Date: Tue, 29 May 2007 06:09:02 GMT Subject: 3D libraries (was The Concepts and Confusions of Prefix, Infix, Postfix and Fully Functional Notations) In-Reply-To: <465bb872$0$8729$ed2619ec@ptn-nntp-reader02.plus.net> References: <1179936917.652372.24780@q69g2000hsb.googlegroups.com> <1oveejxwke.fsf@hod.lan.m-e-leypold.de> <465bb872$0$8729$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: On Tue, 29 May 2007, Jon Harrop wrote: > Anyway, are there any libraries to do hardware accelerated vector graphics > in Perl, Python, Lisp, Java or any functional language (except OCaml and F# > and excluding WPF and Silverlight)? I believe there are OpenGL bindings for quite many languages, here are two for java: https://jogl.dev.java.net/ http://www.lwjgl.org/ - Ville Oikarinen From igouy at yahoo.com Tue May 8 21:23:55 2007 From: igouy at yahoo.com (Isaac Gouy) Date: 8 May 2007 18:23:55 -0700 Subject: My newbie annoyances so far In-Reply-To: <6Xx%h.20332$JZ3.15645@newssvr13.news.prodigy.net> References: <1177688082.758043.133920@r30g2000prh.googlegroups.com> <_9pYh.1787$uJ6.894@newssvr17.news.prodigy.net> <1178400807.051103.95690@q75g2000hsh.googlegroups.com> <1hxp15f.1bvtgo11ydx3cvN%aleax@mac.com> <1178504008.035594.216920@o5g2000hsb.googlegroups.com> <6Xx%h.20332$JZ3.15645@newssvr13.news.prodigy.net> Message-ID: <1178673835.629205.127950@y5g2000hsa.googlegroups.com> On May 6, 9:29 pm, John Nagle wrote: > Isaac Gouy wrote: > > On May 6, 6:09 pm, John Nagle wrote: > > >>Alex Martelli wrote: > > >>>John Nagle wrote: > > >>>>igo... at yahoo.com wrote: > > >>>>>On Apr 27, 9:07 am, John Nagle wrote: > > >>>>>>The CPython implementation is unreasonably slow compared > >>>>>>to good implementations of other dynamic languages such > >>>>>>as LISP and JavaScript. > >> My point is that there are optimizing hard-code compiler implementations > >>of many dynamic languages, including LISP, Self, and Smalltalk, but not Python. > > > I guess Lisp is a safe-ish example but I don't think Self really made > > it out of the lab, and it really depends which Smalltalk > > implementation you have in mind and what you think about Pysco. > > See > > http://research.sun.com/self/papers/third-generation.html > > on a high performance Self implementation. That laid the groundwork > for Java's JIT system. I don't think Java HotSpot equates to Self getting out of the lab. (And wasn't that more directly related to Strongtalk?) > Here are some early Tamarin benchmarks. > > http://www.playercore.com/pub/Tamarin/Avmplus_vs._javascript.htm > > Tamarin doesn't do type inference, though, so they get the best > performance only with type declarations. > > John Nagle Thank you Neil Hodgson :-) I wonder where the runtime was hosted? I wonder what current measurements look like? From apatheticagnostic at gmail.com Wed May 23 02:58:13 2007 From: apatheticagnostic at gmail.com (kaens) Date: Wed, 23 May 2007 02:58:13 -0400 Subject: xml.parsers.expat loading xml into a dict and whitespace In-Reply-To: <163f0ce20705222316x7d6247a7hea019e7fd2aa2ee2@mail.gmail.com> References: <163f0ce20705222316x7d6247a7hea019e7fd2aa2ee2@mail.gmail.com> Message-ID: <163f0ce20705222358u1170486an40128b20726e50cc@mail.gmail.com> Now the code looks like this: import xml.etree.ElementTree as etree optionsXML = etree.parse("options.xml") options = {} for child in optionsXML.getiterator(): if child.tag != optionsXML.getroot().tag: options[child.tag] = child.text for key, value in options.items(): print key, ":", value freaking easy. Compare with making a generic xml parser class, and inheriting from it for doing different things with different xml files. This does exactly the right thing. I'm sure it's not perfect for all cases, and I'm sure there will be times when I want something closer to expat, but this is PERFECT for what I need to do right now. That settles it, I'm addicted to python now. I swear I had a little bit of a nerdgasm. This is orders of magnitude smaller than what I had before, way easier to read and way easier to maintain. Thanks again for the point in the right direction, Steve. On 5/23/07, kaens wrote: > > [1] ElementTree is in the 2.5 standard library, but if you're stuck with > > an earlier python, just Google for it -- there are standalone versions > > I've got 2.5, and I'm not attached to expat at all. I'll check it out, thanks. > From joshua at eeinternet.com Wed May 16 15:37:10 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Wed, 16 May 2007 11:37:10 -0800 Subject: How to do basic CRUD apps with Python References: <1179098458.333666.307750@e65g2000hsc.googlegroups.com> <464848fa$0$465$426a74cc@news.free.fr> <1179197198.513508@smirk> Message-ID: <464b5112$0$16271$88260bb3@free.teranews.com> On Monday 14 May 2007 18:46, James T. Dennis wrote: > I'm thinking of some sort of class/module that would generate > various sorts of HTML forms by default, but also allow one to > sub-class each of the form/query types to customize the contents. Turbogears has catwalk, which is already an interface to a database, but there is a CRUD template for TG: http://docs.turbogears.org/1.0/CRUDTemplate Might be what you're looking for. j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE -- Posted via a free Usenet account from http://www.teranews.com From rogerb at rogerbinns.com Wed May 23 16:22:42 2007 From: rogerb at rogerbinns.com (Roger Binns) Date: Wed, 23 May 2007 13:22:42 -0700 Subject: How to release the GIL from C? Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I am trying to release the GIL in a multi-threaded program (efforts detailed below) without any success. In the main thread during startup, I do the following: Py_InitializeEx(0); /* Python shouldn't handle signals */ PyEval_InitThreads(); /* release the GIL */ ... various pieces of code tried here ... Note that no other threads exist yet when the code above is run. After startup, there are around 30 threads and my handler routines do work in them. void handler(...) { PyGILState_STATE gilstate=PyGILState_Ensure(); ... do the interesting stuff ... PyGILState_Release(gilstate); } No matter what I try, the PyGILState_Ensure() hangs trying to acquire the GIL: #0 0x00002afd50ce243d in sem_wait () from /lib/libpthread.so.0 #1 0x00002afd5471557d in PyThread_acquire_lock () from /usr/lib/libpython2.5.so.1.0 #2 0x00002afd546e44d4 in PyEval_RestoreThread () from /usr/lib/libpython2.5.so.1.0 #3 0x00002afd5470bb8a in PyGILState_Ensure () from /usr/lib/libpython2.5.so.1.0 Here are the various things I have tried to release the GIL (the documentation says they all do, but that doesn't appear to be the case :-( Unfortunately the doc is all geared around saving the interpreter state and then later restoring it. I have nowhere to save it in the main thread nor do I know when the main thread is having handlers invoked in it again anyway in order to restore it. 1. (Based on Py_BEGIN_ALLOW_THREADS) PyThreadState_Swap(NULL); PyEval_ReleaseLock(); 2. (Based on high level Py_BEGIN_ALLOW_THREADS) PyEval_SaveThread(); 3. Random code I found on the web PyThreadState *tstate = PyThreadState_Get(); PyThreadState_Clear(tstate); PyEval_ReleaseThread(tstate); 4. Something simple PyEval_ReleaseLock(); 5. Other code I found on the web PyThreadState_Swap(NULL); Does anyone know exactly which sequence of calls I should be making? Thanks, Roger -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (GNU/Linux) iD8DBQFGVKKSmOOfHg372QQRAi4VAJ9KO8z/WnSgPOlCjEOOJgDCf20nCwCeJHUE kkhvMsy6p3qflvGKolttWTo= =4Z8h -----END PGP SIGNATURE----- From kakeez at hotmail.com Thu May 24 04:22:50 2007 From: kakeez at hotmail.com (Karim Ali) Date: Thu, 24 May 2007 08:22:50 +0000 Subject: Call script which accepts com. line par. from another scriptand error control In-Reply-To: Message-ID: Hi James, Thanks for that. That is exactly what i needed for the error control bit... What I still dont know though is how do I handle the fact that the first script is expecting command line parameters. I would like to be able to replace the command line parameters by a variable such that the second script can call: first_script.main("command line"). Is this possible? If i can simply do whatever it is that parse_args() does but on a variable of my choosing.. Karim >From: James Stroud >To: python-list at python.org >Subject: Re: Call script which accepts com. line par. from another >scriptand error control >Date: Wed, 23 May 2007 17:21:47 -0700 > >Karim Ali wrote: > > def MAIN(expression2parse) <----- add a main so can > > call from other script > >Of course you don't mean you want another python interpreter to fire up >and run the other script? > >Here is an example of the way to do what you are suggesting: > ># mod1.py > >def doit(param): > if not param % 37: > raise ValueError, 'Why u want to do dat?' > else: > print 'All right!' > return 'Value is: %s' % param > ># end of mod1.py > > ># mod2.py > >import mod1 > >print mod1.doit(20) >print >print mod1.doit(30) >print >try: > print mod1.doit(37) >except ValueError: > print 'Gracefully handling 37....' > print >print mod1.doit(37) > ># end of mod2 > > >James >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ Fight Allergies With Live Search http://search.live.com/results.aspx?q=Remedies+For+Spring+Allergies&mkt=en-ca&FORM=SERNEP From half.italian at gmail.com Thu May 10 04:55:10 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 10 May 2007 01:55:10 -0700 Subject: replacing string in xml file--revisited In-Reply-To: <1178783809.444544.79640@w5g2000hsg.googlegroups.com> References: <1178783809.444544.79640@w5g2000hsg.googlegroups.com> Message-ID: <1178787310.006875.204040@w5g2000hsg.googlegroups.com> On May 10, 12:56 am, saif.shak... at gmail.com wrote: > Hi, > I need to replace a string in xml file with something else.Ex > > - > rate > rate > > > > - > > Here i have opened an xml > file(small part is pasted here).I want to replace the word 'localId' > with 'dataPackageID' wherever it comes in xml file.I have asked this > before and got a code: > input_file = open(filename) > xmlcontents = input_file.read() > input_file.close() > xmlcontents = xmlcontents.replace("spam", "eggs") > output_file = open(filename,"w") > output_file.write(xmlcontents) > output_file.close() > > Although this works alone it is nto > working when i handle multiple file I/O.Is there a alternative to do > this.(maybe without read() operation) > Thanks After reading your post again, this might be better: #!/usr/bin/env python from elementtree import ElementTree as et tree = et.parse("testxml.xml") for t in tree.getiterator("SERVICEPARAMETER"): if t.get("Semantics") == "localId": t.set("Semantics", "dataPackageID") tree.write("output.xml") ~Sean From bbxx789_05ss at yahoo.com Wed May 23 15:29:41 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 23 May 2007 12:29:41 -0700 Subject: Namespace issue In-Reply-To: Message-ID: <1179948581.687930.34730@h2g2000hsg.googlegroups.com> On May 23, 12:20 pm, Ritesh Raj Sarraf wrote: > As per my understanding, the bad part is that on every call of the method > FetchData(), an import would be done. > > To not let that happen, I can put the import into __init__(). But when I put > in there, I get a NameError saying that my_module is not available even > though it got imported. > All I noticed is that the import has to be part of the method else I end up > getting a NameError. But always importing my_module is also not good. How about something like this: class Dog(object): myimport = None def __init__(self): if not Dog.myimport: print "importing..." import os Dog.myimport = os def test(self): print Dog.myimport.listdir("./") d = Dog() d.test() print print d2 = Dog() d2.test() From JHoover at fbi.gov Thu May 10 16:38:41 2007 From: JHoover at fbi.gov (Gordon Airporte) Date: Thu, 10 May 2007 16:38:41 -0400 Subject: searching algorithm In-Reply-To: References: Message-ID: <7dydnfjNWbo9H97bnZ2dnUVZ_oupnZ2d@comcast.com> > For the above (abrideged) dictionary, you would generate (use a > fixed-width "programmers" font so the tree looks good): > > a > | > b > | > s > / \ > i o > / / \ > n l r > / / \ \ > t u v b->(absorbirati, crpisti) > / | | > (pelin)<-h t e->(odrije?iti, osloboditi) > | | > (pelin)<-e e->(apsolutan, apsolutni kod) > > As the user enter letters, you just march down the tree, printing > all the words held in leaf nodes held in the current node. > Call me dense, but how does one do this in Python - which doesn't have pointers? Dictionaries with dictionaries within dictionaries... (with each letter as the key and the its children as values) is going to be extremely space inefficient, right? From michael at jedimindworks.com Sat May 12 01:23:41 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Sat, 12 May 2007 00:23:41 -0500 Subject: searching algorithm In-Reply-To: <31AA93DB-0432-4BDF-B913-A6AA1A40F8C3@jedimindworks.com> References: <31AA93DB-0432-4BDF-B913-A6AA1A40F8C3@jedimindworks.com> Message-ID: <2EBDB8CC-0B11-4C94-B4AE-6965BBA9FFA4@jedimindworks.com> On May 11, 2007, at 3:50 AM, Michael Bentley wrote: > > Here's an idea: use a rats' nest of dictionaries and do all the > lookup work up front when you build the rats' nest. Maybe something > like this: ... Oops! This is better :-) #! /usr/bin/env python import pprint dictionary = """absinth:pelin absinthe:pelin absolute:apsolutan absolute:apsolutni kod absolute:apsolutno absolute:čist absolute:nesumnjiv absolute:potpun absolute:savrsen absolute coordinates:apsolutne koordinate absolute frequency:apsolutna učestalost absolute gap:apsolutni jaz absolute line spacing:apsolutni međurazmak linija absolute majority:apsolutna većina absolute pointing device:apsolutni pokazivački uređaj absolute quantity:apsolutni udio absolute value:apsolutna vrijednost absolute zero:apsolutna nula absolutely:apsolutno absolutely:bezuvjetno absolutely:nezavisno absolutely:potpuno absolutely:samostalno absolutely:sasvim absolution:odrjesenje absolution:oprostaj absolutism:apsolutizam absolve:odrijesiti absolve:osloboditi absorb:absorbirati absorb:apsorbirati absorb:crpsti""" lookup = {'words':{}, 'letters':{}} for translation in dictionary.split('\n'): english, croatian = translation.split(':') if english in lookup['words']: lookup['words'][english].append(croatian) else: lookup['words'][english] = [english, croatian] for position, letter in enumerate(english): if position == 0: youAreHere = lookup['letters'] if letter not in youAreHere: youAreHere[letter] = {'words':[]} if lookup['words'][english] not in youAreHere[letter]['words']: youAreHere[letter]['words'].append(lookup['words'][english]) youAreHere = youAreHere[letter] def tryit(partial): youAreHere = lookup['letters'] for letter in partial: youAreHere = youAreHere[letter] return youAreHere['words'] if __name__ == '__main__': pprint.pprint(tryit('abs')) print '=' * 50 pprint.pprint(tryit('absorb')) From showell30 at yahoo.com Mon May 28 18:22:25 2007 From: showell30 at yahoo.com (Steve Howell) Date: Mon, 28 May 2007 15:22:25 -0700 (PDT) Subject: itertools.groupby In-Reply-To: <1hytsy4.18fwrl71gwf3cgN%aleax@mac.com> Message-ID: <93112.57558.qm@web33512.mail.mud.yahoo.com> --- Alex Martelli wrote: > Steve Howell wrote: > ... > > for has_chars, frags in itertools.groupby(lines, > > lambda x: len(x) > 0): > > Hmmm, it appears to me that itertools.groupby(lines, > bool) should do > just the same job, just a bit faster and simpler, > no? > Agreed. I updated the webpages with your change (after testing it in 2.5): http://wiki.python.org/moin/SimplePrograms ____________________________________________________________________________________Take the Internet to Go: Yahoo!Go puts the Internet in your pocket: mail, news, photos & more. http://mobile.yahoo.com/go?refer=1GNXIC From steven at REMOVE.THIS.cybersource.com.au Sun May 13 23:42:56 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 14 May 2007 03:42:56 -0000 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <20070513160046.GC29172@v.igoro.us> <7x646wa9wz.fsf@ruckus.brouhaha.com> <7xfy608bkk.fsf@ruckus.brouhaha.com> <7xejlk3xpk.fsf@ruckus.brouhaha.com> Message-ID: On Sun, 13 May 2007 20:12:23 -0700, Paul Rubin wrote: > Steven D'Aprano writes: >> If I'm mistaken, please explain why I'm mistaken, not just repeat your >> claim in different words. > > if user_entered_password != stored_password_from_database: > password_is_correct = False > ... > if password_is_correct: > log_user_in() > > Does "password_is_correct" refer to the same variable in both places? No way of telling without a detailed code inspection. Who knows what happens in the ... ? If a black hat has access to the code, he could insert anything he liked in there, ASCII or non-ASCII. How is this a problem with non-ASCII identifiers? password_is_correct is all ASCII. How can you justify saying that non-ASCII identifiers introduce a security hole that already exists in all-ASCII Python? -- Steven. From ptmcg at austin.rr.com Wed May 23 16:56:59 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 23 May 2007 13:56:59 -0700 Subject: Inverse of id()? In-Reply-To: <1179741319.122807.56960@z24g2000prd.googlegroups.com> References: <1179618173.280286.284120@n59g2000hsh.googlegroups.com> <1179741319.122807.56960@z24g2000prd.googlegroups.com> Message-ID: <1179953819.739357.139470@o5g2000hsb.googlegroups.com> On May 21, 4:55 am, Paul Boddie wrote: > On 20 May, 01:42, Paul McGuire wrote: > > > > > >>> re = Regex("(\d*)").setResultsName("x").setParseAction(lambda t:int(t[0])) > > >>> results = re.parseString("123") > > > pyparsing results have some special lookup behavior, that if the > > results name is a Python-friendly identifier, can use the name as if > > it were an object attribute: > > > >>> results.x > > 123 > > First of all, having recently looked at pyparsing again, I must say > that it's a nice framework for writing parsers quickly. Now I'm not > sure what the intention is behind this inquiry, so the following may > seem somewhat tangential, but one thing that I tend to do a lot with > pyparsing is to automatically set the results name by having a special > grammar object: > > class Grammar: > def __setattr__(self, name, value): > self.__dict__[name] = Group(value.setResultsName(name)) > > This permits stuff like the following: > > g = Grammar() > g.x = Regex("(\d*)").setParseAction(lambda t:int(t[0])) > > You'd even be able to incorporate the parse action, too, with some > extra magic. As pyparsing is a library which seems to encourage clean > grammar definitions, I think this makes quite a difference, although I > now expect to be told that there's a class in the library which > supports this. > > Anyway, back to the scheduled programme... > > Paul I'm considering adding a notational short-cut as an abbreviated version of setResultsName(), in the next pyparsing release, described here: http://pyparsing.wikispaces.com/message/view/home/606302 I propose we move the discussion of this idea to the pyparsing wiki, so as not to (further?) clutter up c.l.py with this topic. -- Paul From bytter at gmail.com Sat May 19 21:27:47 2007 From: bytter at gmail.com (Hugo Ferreira) Date: Sun, 20 May 2007 02:27:47 +0100 Subject: Typed named groups in regular expression In-Reply-To: <1179574798.034285.65120@o5g2000hsb.googlegroups.com> References: <1179552763.278347.163300@e65g2000hsc.googlegroups.com> <1179574798.034285.65120@o5g2000hsb.googlegroups.com> Message-ID: <4e8efcf50705191827n3a30f413y1824b6893811cd85@mail.gmail.com> Both Paddy (hackish) and McGuire (right tool for the job) ideas sound very interesting ;-) I'll definitely research on them further. Thanks for the support... On 19 May 2007 04:39:58 -0700, Paul McGuire wrote: > On May 19, 12:32 am, Paddy wrote: > > On May 16, 6:58 pm, "Hugo Ferreira" wrote: > > > > > Hi! > > > > > Is it possible to "automagically" coerce the named groups to python types? e.g.: > > > > > >>> type(re.match('(?P\d*)', '123').groupdict()['x']) > > > > > > > > > > But what I'm looking forward is for the type to be 'int'. > > > > > Cheers! > > > > > Hugo Ferreira > > > > If you do a ot of that sort of thing in many programs > > then it might be worth your while to set up a framework > > that does it. Something like adding an underscore > > then the name of a type conversion function to all > > group names, and creating a function to apply the > > type convertion function to all named groups of a > > match object. > > - Paddy. > > pyparsing might just be this sort of framework, in that you can attach > parse actions to elements within a grammar. At parse time, the parse > action is called with the list of tokens currently matched. > > >>> from pyparsing import Regex > >>> re = Regex( r"(\d*)" ).setResultsName("x")\ > ... .setParseAction(lambda t:int(t[0])) > >>> results = re.parseString("123") > >>> print results.x > 123 > > -- Paul > > -- > http://mail.python.org/mailman/listinfo/python-list > From deepbroke9 at gmail.com Thu May 17 18:48:39 2007 From: deepbroke9 at gmail.com (deepbroke9 at gmail.com) Date: 17 May 2007 15:48:39 -0700 Subject: ^-^*^*^ Britneys BACK AND TITS!!! GALORE! !^-^` Message-ID: <1179442118.785916.292840@y80g2000hsf.googlegroups.com> DOWNLOAD http://scargo.in/ - Videos of Britneys TITS AND PUSSY! Videos of Britneys TITS AND PUSSY! Videos of Britneys TITS AND PUSSY! Videos of Britneys TITS AND PUSSY! Videos of Britneys TITS AND PUSSY! Videos of Britneys TITS AND PUSSY! Videos of Britneys TITS AND PUSSY! Videos of Britneys TITS AND PUSSY! Videos of Britneys TITS AND PUSSY! Videos of Britneys TITS AND PUSSY! Videos of Britneys TITS AND PUSSY! Videos of Britneys TITS AND PUSSY! http://askaninja.com/ Videos of Britneys TITS AND PUSSY! Videos of Britneys TITS AND PUSSY! -!@-^-^` From claird at lairds.us Mon May 21 19:43:31 2007 From: claird at lairds.us (Cameron Laird) Date: Mon, 21 May 2007 23:43:31 +0000 Subject: python shell/Intermediate Python tools. References: <1179337107.842668.112690@k79g2000hse.googlegroups.com> <1179552984.466321.137550@u30g2000hsc.googlegroups.com> <1179659540.663784.228420@y80g2000hsf.googlegroups.com> Message-ID: <3en9i4-mhv.ln1@lairds.us> In article <1179659540.663784.228420 at y80g2000hsf.googlegroups.com>, Paddy wrote: . . . >Sometimes you have to mess with the case of letters in wiki pages >which is the case here, but I did actually cut-n-paste the address >from Wikipedia as I like to look at the page from time to time as, >like yourself, I think doctest shows the true spirit of what is >Pythonic, and created the page when I found Wikipedia did not have it. So *you* were the one! Nice work--that is, I think we agree (despite my erratic spelling) that doctest deserves plenty of attention, and a Wiki page is a nice place to collect miscellaneous details. . . . >The other Python tool I am apt to carp on about is Kodos >http://kodos.sourceforge.net/ . >Kodos is a great tool for those new to reguar expressions. It allows >you to test your regular expressions on snippets of text and gives >great visual feedback on the results. After over a decade of writing >regexps I still use Kodos occasionally, and wish I had such a tool a >decade ago. Thanks for the tip. You might have an interest in . . . . I've sent copies of this follow-up both to Paddy and, on the chance that the URL will serve others, to comp.lang.python. From steve at holdenweb.com Fri May 25 08:17:28 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 25 May 2007 08:17:28 -0400 Subject: method override inside a module In-Reply-To: <4656A86E.5040602@iriti.cnr.it> References: <4656A86E.5040602@iriti.cnr.it> Message-ID: Fabrizio Pollastri wrote: > Hello, > I am trying to override a method of a class defined into an imported > module, but keeping intact the namespace of the imported module. > > For example, let suppose > > import module_X > > and in module_X is defined something like > > class A: > > ... > > def method_1(): > ... > > ... > > I wish to override method_1 with a new function and to call the > overrided method inside my application with the same name of the > original method like > > ... > module_X.method_1() > ... > > Thanks in advance for any help. > The names of things don't count for that much in Python (though classes, methods and functions *are* associated with their names). Have you tried something like module_X.A.method_1 = method_1 module_x.py: class A: def __init__(self): print "Creating an A" def method_1(self, arg): print "Calling original method_1 with argument", arg test20.py: import module_X a1 = module_X.A() def method_1(self, arg): print "Calling substituted method_1 with", arg module_X.A.method_1 = method_1 a2 = module_X.A() a1.method_1('banana') a2.method_1('orange') Running it: sholden at bigboy ~/Projects/Python $ python test20.py Creating an A Creating an A Calling substituted method_1 with banana Calling substituted method_1 with orange As you can see, even if you created objects before you tinkered witht he class definition they still get the new method (because it's looked up and found in the class). This kind of activity is called "monkey patching", and is sometimes a useful technique to alter a module for one specific application. Try not to take it too far, though. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From s.mientki at id.umcn.nl Wed May 23 07:54:14 2007 From: s.mientki at id.umcn.nl (stef) Date: Wed, 23 May 2007 13:54:14 +0200 Subject: Can I reference 1 instance of an object by more names ? rephrase In-Reply-To: <4654289a$0$2326$426a74cc@news.free.fr> References: <4654289a$0$2326$426a74cc@news.free.fr> Message-ID: <476f5$46542b66$83aef404$11748@news2.tudelft.nl> Bruno Desthuilliers wrote: > stef a ?crit : >> thanks Guys for your information, >> >> indeed you're all quit right, >> but I think I've not correctly described my problem :-( >> >> I need to have 2 (or more) names, that references the same instance >> of an object, >> and in assigning a value to the object (or to some property in the >> object), >> I need to do extra activities (like changing some global variables). > > Then you want a property (aka computed attribute). > >> Now if I use a "container type object", without actual using the >> index of the container object, >> I get things working OK. >> But now I have to use a dummy index, if I use the object in >> assignments, see program below. >> Is there another way, without using the dummy index, to achieve the >> same results ? > >> thanks, >> Stef Mientki >> >> >> class cpu_ports(object): >> def __init__(self, value=0): >> self._d = value >> def __setitem__(self, index, value): >> print 'vv' >> self._d = value >> def __getitem__(self, index): >> return self._d >> def __repr__(self): >> return str(self._d) >> >> name1 = cpu_ports() # create an instance >> name2 = name1 # refer with a second name to the same instance >> print name1, name2 # test ok >> >> name1[0] = 25 # assign a value to the instance >> print name1, name2 # both references are OK >> >> name2[0] = 26 # assign another value through the other >> name >> print name1, name2 # both reference are OK >> >> name2[0] = name1[0] + 13 # use both names at either side of an >> assignment >> print name1, name2 # both references still OK > > You can have something working the same way using a property, but > that's how far you'll get - if you hoped to be able to automagically > rebind name2 when rebinding name1, then too bad, because python wont > let you do so. You have to understand that > name = obj > is totally different from > name.attr = obj > or > name[index] = obj > > In the first case, this is *really* a binding, and that's one of the > few things that Python won't let you mess with. In the two last cases, > it's in fact a method call - as the use of __[get|set]item__ should > make obvious. > > here's an example using a property: > > class cpu_ports(object): > def __init__(self, value=0): > self._d = value > @apply > def value(): > def fset(self, value): > print 'vv' > self._d = value > def fget(self): > return self._d > return property(**locals()) > > def __repr__(self): > return str(self._d) > > name1 = cpu_ports() # create an instance > name2 = name1 # refer with a second name to the same instance > print name1, name2 # test ok > > name1.value = 25 # assign a value to the instance > print name1, name2 # both references are OK > > name2.value = 26 # assign another value through the other name > print name1, name2 # both reference are OK > > name2.value = name1.value + 13 > print name1, name2 # both reference are OK > > And that's about as far as you can go (without rewriting Python I mean). thanks Bruno for your clear explanation, I was "afraid" that this would be the only solution, and now I'm sure, I can implement it in this way (which is not really a problem). I just found a Python compiler for PICs (Pyastra), I still have to study it, but it might be a good idea, to translate JAL to Python, using the exact syntax of Pyastra. thanks again, Stef Mientki From bradallen137 at gmail.com Tue May 1 17:25:53 2007 From: bradallen137 at gmail.com (bradallen) Date: 1 May 2007 14:25:53 -0700 Subject: Python user group in Portland, OR? Message-ID: <1178054753.732189.137230@h2g2000hsg.googlegroups.com> I've been visiting Portland, OR on a multi-week client project, and am wondering if there are any local Python or Zope programmers in the Portland area. I am only going to be here for a couple more weeks, and the client is getting nervous about whether there are any Python/Zope programmers in the local area, because they are thinking seriously of hiring internal staff to manage their app. They have a fairly large web app that uses Zope 2/FIVE and a couple of significant wxPython apps, along with a Linux server running PostgreSQL as well as a lot of other moving parts managed by Python scripts. I have enjoyed working on this project, but cannot stay indefinitely. I've tried to assure them that Python is widely used, and that they should have no difficulty finding local support in a city like Portland. Anybody out there? Even if you're not looking for work, I'd enjoy meeting local Pythonistas while I'm in Portland, since I am missing the Dallas user group meetings I normally attend. Thanks! From mccredie at gmail.com Mon May 21 19:21:20 2007 From: mccredie at gmail.com (Matimus) Date: 21 May 2007 16:21:20 -0700 Subject: A newbie question In-Reply-To: References: Message-ID: <1179789680.837603.245120@a26g2000pre.googlegroups.com> How about this: [code] def __add__(self,x): return Cc14(self.r+x.r, self.i+x.i) [/code] However... Are you aware that Python has built in support for complex numbers already? >>> x = 4+5j >>> y = 4+5j >>> x+y (8+10j) >>> From http Sat May 19 22:13:44 2007 From: http (Paul Rubin) Date: 19 May 2007 19:13:44 -0700 Subject: What is deployment? (was: A Few More Forrester Survey Questions) References: <68m4i4-9a4.ln1@lairds.us> Message-ID: <7x4pm8tf6v.fsf@ruckus.brouhaha.com> claird at lairds.us (Cameron Laird) writes: > What might C. mean? Say I install a program, but I still have to worry > about how I'm going to configure it within the cluster where I intend to > use it, AND I need to co-ordinate its configuration with the central > database on which it depends, AND I have to tie it in to our license- > management system, AND there are issues with users sharing data and also > protecting data from each other, AND ...--well, all those things that > happen after narrow-sense installation are still part of "deployment". Deployment also refers to pre-installation issues, like buying the hardware that you're going to install on. From aleax at mac.com Mon May 28 20:25:46 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 28 May 2007 17:25:46 -0700 Subject: Long double in Python References: <200705252140.34353.charles.vejnar@isb-sib.ch> Message-ID: <1hyu25e.kps4w411ueduaN%aleax@mac.com> Charles Vejnar wrote: > Hi, > > Thanks for both suggestions. > > I have indeed tried gmpy. For me, it's not very important to choose between > numpy or gmpy. > > I hope I won't be off topic. But, as I told you before, I have a C library > using "long double" numbers and I would like to be able to use it in Python. > I try to build a module with Swig but I didn't find the C function to use in > the wrapper to have a "numpy.longdouble" (or the equivalent in gmpy). Is it > something possible ? I'm not a SWIG expert, but I believe you can tell SWIG exactly what C function to use to convert a certain C type to Python; gmpy has a C API for that purpose, and so no doubt does numpy (I'm the author of gmpy, but don't know much about numpy, so I'm just guessing about it). You may have to write a little bit of custom C code for the purpose... and I'm not even sure you'll be able to do that with SWIG specifically for "long double", judging from a document at swig.org which I quote later. I realize that this answer is far from being fully satisfactory:-(. Unfortunately, neither pyrex nor ctypes, which today are probably the two best ways to interface arbitrary C code with Python, have good support for long double, and, as says, "The rarely used datatype of long double is not supported by SWIG":-(. Writing a custom C extension to wrap long double for Python would not be hard -- essentially, copy Objects/floatobject.c from the Python source distribution and edit it just a wee little bit -- but wouldn't necessarily be sufficient to let you use your desired C library, since you'd still have to somehow tell SWIG (or whatever other C/Python interfacing approach) to use it... Alex From gagsl-py2 at yahoo.com.ar Tue May 8 22:37:08 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 08 May 2007 23:37:08 -0300 Subject: String parsing References: <1178672992.522463.228620@l77g2000hsb.googlegroups.com> <1178676374.081202.74850@e51g2000hsg.googlegroups.com> Message-ID: En Tue, 08 May 2007 23:06:14 -0300, HMS Surprise escribi?: > Thanks for posting. Could you reccommend an HTML parser that can be > used with python or jython? Try BeautifoulSoup, which handles malformed pages pretty well. -- Gabriel Genellina From walterbyrd at iname.com Sun May 13 19:20:58 2007 From: walterbyrd at iname.com (walterbyrd) Date: 13 May 2007 16:20:58 -0700 Subject: How to do basic CRUD apps with Python Message-ID: <1179098458.333666.307750@e65g2000hsc.googlegroups.com> With PHP, libraries, apps, etc. to do basic CRUD are everywhere. Ajax and non-Ajax solutions abound. With Python, finding such library, or apps. seems to be much more difficult to find. I thought django might be a good way, but I can not seem to get an answer on that board. I would like to put together a CRUD grid with editable/deletable/ addable fields, click on the headers to sort. Something that would sort-of looks like an online spreadsheet. It would be nice if the fields could be edited in-line, but it's not entirely necessary. Are there any Python libraries to do that sort of thing? Can it be done with django or cherrypy? Please, don't advertise your PHP/Ajax apps. From sjdevnull at yahoo.com Tue May 15 17:19:07 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 15 May 2007 14:19:07 -0700 Subject: Trying to choose between python and java In-Reply-To: <464a190c$0$19570$426a34cc@news.free.fr> References: <1179250163.596672.321480@o5g2000hsb.googlegroups.com> <464a190c$0$19570$426a34cc@news.free.fr> Message-ID: <1179263947.704564.77650@n59g2000hsh.googlegroups.com> On May 15, 5:16 pm, Bruno Desthuilliers wrote: > Beliavsky a ?crit : > > > > > On May 15, 1:30 am, Anthony Irwin wrote: > > > > > >>#5 someone said that they used to use python but stopped because the > >>language changed or made stuff depreciated (I can fully remember > >>which) and old code stopped working. Is code written today likely to > >>still work in 5+ years or do they depreciate stuff and you have to update? > > > Because Python 3 will change the syntax of print to disallow > > > print "Hello, world." > > > a substantial fraction of Python programs in existence, including all > > of my programs, will be broken. Draw your own conclusions. > > The fact that Py3K will be a "big cleanup" release is not new - it has > been clear for some years now that this would be the first release that > would break compatibility. Eliminating core libraries breaks compatibility. Getting rid of regex was very traumatic, and I still find myself occasionally patching up code because of that change. To be fair, regex was deprecated for many versions before it was dropped (and warned loudly of the coming change), and Java's been notably worse at maintaining backward compatibility. But saying it's the first release that breaks compatibility isn't true unless you have a very limited definition of compatibility. > Still GvR and the team seem to be making > their best to not avoid as much breakage as possible, clearly document > what will break, and if possible provide tools to ease migration. Absolutely. From stefan.behnel-n05pAM at web.de Sun May 6 02:04:45 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sun, 06 May 2007 08:04:45 +0200 Subject: Python Binding In-Reply-To: References: Message-ID: <463D6FFD.2050005@web.de> Georg Grabler wrote: > There's a C library which i'd like to have python bindings for. I havn't > known anything before about how to write python bindings for a C library. > > I succeeded now by using distutils to write the first bindings for functions > and similar. > > Now, it seems as something is blocking my brain. For the library, i > need "custom" types, so types defined in this library (structures), > including pointers and similar. > > I've been thinking about what i will need to represent this lists in python. > I thought about creating an external python object, providing "information" > i get from the list in C structures which can be converted. > > Basically, it are list of packages, which have several attributes (next, > prev, etc). But i don't know how to supply a proper list from the binding / > object written in C. > > Any suggestions or hints about this? Use Pyrex. It's a Python-like language that was designed to write extension modules in C and it's great for writing wrappers. http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/ An example wrapper is described here: http://ldots.org/pyrex-guide/ Hope it helps, Stefan From mensanator at aol.com Fri May 18 20:12:05 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 18 May 2007 17:12:05 -0700 Subject: pyodbc data corruption problem In-Reply-To: References: Message-ID: <1179533525.685271.43670@n59g2000hsh.googlegroups.com> On May 18, 6:46 pm, "Joe Salmeri" wrote: > I have found a data corruption problem with pyodbc. > > OS = Windows XP SP2 > DB = Microsoft Access XP > > PROBLEM: > > When selecting columns from a table that are of type Memo the value > returned is padded with a bunch of null characters at the end. > > The problems does not seem to occur until the length of the Memo column > exceeds 2048 bytes. Interesting. MS-Access has had a bug about Memo fields ever since Version 2.0 (the last time it worked). I was trying to use a Memo field on a form and append short status messages. This mysteriously stopped working in the version following 2.0 (Access 95?) and has never worked since. Seems there is some kind of 2048 buffer involved that was created by some punk MicroSoft gave the lowly job of software revision to while those more educated did more important things. My guess is you won't find a Python solution short of accepting what Access gives you and dealing with it. > > I have attached several scripts to help demonstrate the problem. > > To recreate the problem: > > 1. Create a blank Access database named test. > 2. Create a ODBC DSN named test for that database > 3. Run the createtable.py script to create the table > and load it with the dummy data > 4. Run the broke.py script to show the problem. > > The issue is when the data value is > 2048 bytes. > > The size in the createtable.py is 2046 bytes plus 3 bytes at the end that > contain "JOE" for a total of 2049 bytes. > > If you change it from 2046 to 2045 (or less) then the problem does not > occur. > > # > # createtable.py script > # > > import pyodbc > > dbs = pyodbc.connect('dsn=test') > > c = dbs.cursor() > > try: > sql = 'drop table test_memo' > c.execute(sql) > dbs.commit() > except: > # ignore drop table failure > pass > > sql = 'create table test_memo (c1 int not null, c2 memo not null)' > > c.execute(sql) > > dbs.commit() > > sql = 'insert into test_memo values(1, ?)' > > c2_value = '1' * 2046 > > c2_value = '%sJOE' % (c2_value) > > c.execute(sql, (c2_value,)) > > dbs.commit() > > c.close() > dbs.close() > > # > # broke.py script > # > > import pyodbc > > dbs = pyodbc.connect('dsn=test') > > c = dbs.cursor() > > sql = 'select c2, len(c2) as c2_db_len from test_memo where c1 = 1' > > c.execute(sql) > > row = c.fetchone() > > ( > c2, > c2_db_len > ) = row > > print repr(c2) > > print 'c2 length :', len(c2) > print 'c2_db_length :', c2_db_len > > print 'before nul length:', len(c2[0:c2.find('\x00')]) > > c.close() > dbs.close() From sjmachin at lexicon.net Thu May 17 17:17:23 2007 From: sjmachin at lexicon.net (John Machin) Date: 17 May 2007 14:17:23 -0700 Subject: Regexes: How to handle escaped characters In-Reply-To: References: <87tzubqniq.fsf@wilson.homeunix.com> <87irarqkz7.fsf@wilson.homeunix.com> Message-ID: <1179436643.802119.226060@y80g2000hsf.googlegroups.com> On May 18, 6:50 am, James Stroud wrote: > def guarded_search(rgx, astring, escaped): > m = re.search(rgx, astring) > if m: > s = m.start() > e = m.end() > for i in escaped: > if s <= i <= e: Did you mean to write if s <= i < e: ? > m = None > break > return m > Your guarded search fails if there is a match after the rightmost bad position i.e. it gives up at the first bad position. My "guarded_search" (see separated post) needs the following done to it: 1. make a copy 2. change name of copy to "guarded_searchall" or something similar 3. change "yield" to "return" in the original Cheers, John From carsten at uniqsys.com Thu May 10 13:12:02 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 10 May 2007 13:12:02 -0400 Subject: append In-Reply-To: <1178816546.689849.255070@y5g2000hsa.googlegroups.com> References: <1178816546.689849.255070@y5g2000hsa.googlegroups.com> Message-ID: <1178817122.3367.104.camel@dot.uniqsys.com> On Thu, 2007-05-10 at 10:02 -0700, HMS Surprise wrote: > Trying not to be a whiner but I sure have trouble finding syntax in > the reference material. I want to know about list operations such as > append. Is there a pop type function? I looked in tutorial, language > reference, and lib for list, append, sequence. Have you tried Google? Searching for "python list append" brings up the following useful looking link to the tutorial at the very top: http://docs.python.org/tut/node7.html HTH, -- Carsten Haese http://informixdb.sourceforge.net From grahn+nntp at snipabacken.dyndns.org Wed May 30 16:04:01 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 30 May 2007 20:04:01 GMT Subject: speeding things up with C++ References: <1180171179.687276.77930@z28g2000prd.googlegroups.com> Message-ID: On 26 May 2007 02:19:39 -0700, bullockbefriending bard wrote: ... > Essentially, I need to pass a list of 6-tuples containing only > integers to my new sadly necessary super-fast compiled language > function which i am not looking forward to writing: > > input: [(1,2,3,4,5,6), (7,8,9,10,11,12),...] > > and after much thrashing of processor resources, return data which > looks like this to the Python calling environment: > > output: [( (1, 2), (1,), (12,), (13), (1, 7, 11), (9,) ), ( another > nested tuple like preceding one ), .... ] ... > However, I hope someone reading this will be able to tell me that I'm > being a total pessimist and that in fact it isn't very difficult to do > what I want to do using SWIG. You're talking about the actual conversion between Python data structures and C or C++ data structures? That is easy to do even manually, IMHO -- provided a decent C background. Have a look in the Python/C API Reference Manual, and the mapping becomes clear. The PyListObject stuff for example, where there's a C function for every basic operation on lists, and where the elements have the C type PyObject. And so on. Mapping to C is just a matter of walking a nested data structure, where you have a good idea what it is supposed to look like (a list of six-tuples of some kind of numbers). /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From aleax at mac.com Sat May 19 00:58:59 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 18 May 2007 21:58:59 -0700 Subject: A Few More Forrester Survey Questions References: <464DC49F.1090608@taupro.com> Message-ID: <1hybx11.1l5ts4kzs2twuN%aleax@mac.com> Terry Reedy wrote: > | 1) What -existing- examples of the use of Python to create social > | web applications are there? These include chat, collaboration, > | forum boards, and editable content pages, RSS feeds. > | > | I know I use a lot of these, but under pressure I'm not coming > | up with a lot of names. > > You should have listed them so we could try to think of others. reddit is the first one that comes to my mind, essentially because there was such a buzz when they recoded from Lisp to Python. Alex From bj_666 at gmx.net Wed May 9 13:12:08 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 09 May 2007 19:12:08 +0200 Subject: Getting some element from sets.Set References: <1178258913.095438.173020@h2g2000hsg.googlegroups.com> <1178267029.258868.219800@h2g2000hsg.googlegroups.com> <1178316417.371855.63170@p77g2000hsh.googlegroups.com> <1178725344.400736.210280@n59g2000hsh.googlegroups.com> Message-ID: In <1178725344.400736.210280 at n59g2000hsh.googlegroups.com>, tutufan at gmail.com wrote: > Since any element of the set serves as a name (and you know the sets are > all non- empty), it'd be very nice to have a .element() method, or some > such. I guess "iter(s).next()" works okay, but it's not very readable, > and I wonder if it's efficient. Give it a name and it gets more readable: def get_name(setobj): return iter(setobj).next() Ciao, Marc 'BlackJack' Rintsch From gagsl-py2 at yahoo.com.ar Thu May 10 20:11:08 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 10 May 2007 21:11:08 -0300 Subject: reading argv argument of unittest.main() References: <1178818976.822327.145380@w5g2000hsg.googlegroups.com> Message-ID: En Thu, 10 May 2007 14:42:56 -0300, escribi?: > I've read that unittest.main() can take an optional argv argument, and > that if it is None, it will be assigned sys.argv. > > Is there a way to pass command line arguments through unittest.main() > to the setUp method of a class derived from unittest.TestCase? Can't you use sys.argv[] directly inside setUp()? -- Gabriel Genellina From bscrivener42 at gmail.com Thu May 31 18:17:32 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: 31 May 2007 15:17:32 -0700 Subject: paste text with newlines into raw_input? In-Reply-To: <1180619700.613805.291110@w5g2000hsg.googlegroups.com> References: <1180559052.806975.154890@h2g2000hsg.googlegroups.com> <1180581322.594132.259100@a26g2000pre.googlegroups.com> <1180619700.613805.291110@w5g2000hsg.googlegroups.com> Message-ID: <1180649852.614065.136350@p77g2000hsh.googlegroups.com> Hi, I'm going to post this here in case somebody else searches for an example Tkinter Text Widget for entering multiline text. I don't like GUI and don't even quite understand how it works, but it seems to work. In my case it's part of a program for pasting a quote from the clipboard into a MySQL database (hence the separate paste button). I also don't know OO and Classes. If someone wants to wrap it in a class and repost it could save the free world. Or suggestions for making it better much appreciated. Thanks, Rick --------------------------------- #! /usr/bin/python import Tkinter import tkFont """ Tkinter Text Widget for entering multline text. Rick Dooling http://dooling.com Based on: Alan Gauld's "GUI Programming with Tkinter" http://www.freenetpages.co.uk/hp/alan.gauld/tutgui.htm Jeff Eppler's clp post - 3 August 2005 "cut and paste text between Tkinter widgets" http://tinyurl.com/2d97gj """ # the first two functions come from Jeff Eppler's post def make_menu(w): global the_menu the_menu = Tkinter.Menu(w, tearoff=0) the_menu.add_command(label="Cut") the_menu.add_command(label="Copy") the_menu.add_command(label="Paste") def show_menu(e): w = e.widget the_menu.entryconfigure("Cut", command=lambda: w.event_generate("<>")) the_menu.entryconfigure("Copy", command=lambda: w.event_generate("<>")) the_menu.entryconfigure("Paste", command=lambda: w.event_generate("<>")) the_menu.tk.call("tk_popup", the_menu, e.x_root, e.y_root) def evClear(): eText.delete(0.0,Tkinter.END) def assign(): # get text from the text widget and assign it to Quote Quote = eText.get(0.0, Tkinter.END) # just for testing the assignment print Quote def paste(): eText.event_generate("<>") t = Tkinter.Tk() # create the top level window/frame F = Tkinter.Frame(t) F.master.title("Enter Quote ") F.pack(expand="true") myfont = tkFont.Font(family="Courier", size=14) # frame for message to the troops fMessage = Tkinter.Frame(F, border=1) fMessage.pack(side="top", expand="true") lMessage = Tkinter.Label(fMessage, text="Paste your quote into the Text Box from the clipboard, or type it in. When you are finished, click Enter.") lMessage.pack(expand="true") # frame for text entry field fText = Tkinter.Frame(F, border=1) fText.pack(side="top", expand="true") # the text widget eText = Tkinter.Text(fText, width= 75, height=20, font=myfont, wrap=Tkinter.WORD); eText.pack(side="top") eText.bind_class("Text", "", show_menu) # frame with the buttons fButtons = Tkinter.Frame(F, relief="groove", border=3) # the buttons bPaste = Tkinter.Button(fButtons, text="Paste", command=paste) bPaste.pack(side="left", padx=15, pady=4) bEnter = Tkinter.Button(fButtons, text="Enter", command=assign) bEnter.pack(side="left", padx=15, pady=4) bClear = Tkinter.Button(fButtons, text="Clear Text", command=evClear) bClear.pack(side="left", padx=15, pady=4) bQuit = Tkinter.Button(fButtons, text="Quit", command=F.quit) bQuit.pack(side="left", padx=15, pady=4) # pack them fButtons.pack(side="bottom", expand="true") make_menu(t) t.mainloop() From duncan.booth at invalid.invalid Sun May 13 12:47:17 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 May 2007 16:47:17 GMT Subject: elementtree and entities References: Message-ID: "Daniel Nogradi" wrote: > Hi list, > > How does one prevent elementtree converting & to & (and similarly > for other entities)? > >>>> from xml.etree import ElementTree as et >>>> x = et.Element( 'test' ) >>>> x.text = '&' >>>> et.tostring( x ) > '&' > > Sometimes I would like to have the output '&' > > Daniel > elementtree is for processing xml. If you want to output something which isn't xml then you'll have to use a different library or mess about with the xml after it has been generated: et.tostring(x).replace('&', '&') does what you want, but you won't be able to parse it again with anything which expects xml. From ready.or.special5 at gmail.com Wed May 16 02:13:32 2007 From: ready.or.special5 at gmail.com (ready.or.special5 at gmail.com) Date: 15 May 2007 23:13:32 -0700 Subject: ^? Britney Gets Boob Job L@@K Message-ID: <1179296012.248775.286520@w5g2000hsg.googlegroups.com> http://scargo.in/2007/05/mortgage-defaults-increase-arkansas.html - See Videos and Pics of Brineys Failed Boob Job!!!! From srinivas.gundelli at googlemail.com Wed May 30 11:34:56 2007 From: srinivas.gundelli at googlemail.com (IT Recruiter) Date: 30 May 2007 08:34:56 -0700 Subject: Call for Ruby Champion !! Message-ID: <1180539296.378055.194680@m36g2000hse.googlegroups.com> Hello friends! I am looking for a Ruby Champion to lead the race in Website development within Java environment... Who loves programming, with new techniques as well as old..... Who also enjoys hand coding open source technologies with in-depth knowledge of statistical methods Has a practical approach when it comes to problem solving And aspires a team spirit to be agile... It's very useful to have other programming languages and paradigms About Client: Young Company, fastest growing in the web market This is a permanent role in central London, paying as per market rate for the excellent candidate About Me: I am a Resourcing Consultant specialist in recruiting for Open Source Technologies. please do not hesitate to speak to me or write me back ! Really appreciable for a word of mouth with our friends !!! Cheers, Srini From orsenthil at gmail.com Mon May 21 08:09:00 2007 From: orsenthil at gmail.com (Phoe6) Date: 21 May 2007 05:09:00 -0700 Subject: Lists vs tuples (newbie) In-Reply-To: References: Message-ID: <1179749339.954399.322320@a26g2000pre.googlegroups.com> On May 21, 4:48 pm, Szabolcs wrote: > In what circumstances is it advantageous to use tuples instead of lists? > Is there a difference in performance? > As you should not, tuples are immutable while lists are mutable. You can think of all the scenarios where immutable datatype are required. 1) Return values from a function. When you return multiple values from a function. You store them as a tuple and access them individually rather then in the list, which bear the danger of being modified. Look up the standard library itself and you will find many instances. (cin, cout, cerr) = os.popen3('man man') If you had the above as list, then you might end up spoiling things knowingly/unknowingly. 2) Programming requirements arise when you have to deal with persistent data. HTH. Senthil http://uthcode.sarovar.org From grante at visi.com Wed May 16 13:03:00 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 16 May 2007 17:03:00 -0000 Subject: Declaring variables References: <1179334649.990688.73320@o5g2000hsb.googlegroups.com> Message-ID: <134mea4o0svae73@corp.supernews.com> On 2007-05-16, HMS Surprise wrote: > I looked in the language but did not find a switch for requiring > variables to be declared before use. Still trying to write Pascal, eh? ;) > Is such an option available? No. However, there are utilities to "proofread" your code should you have a desire for that: http://www.logilab.org/pylint http://pychecker.sourceforge.net/ -- Grant Edwards grante Yow! What I need is a at MATURE RELATIONSHIP with a visi.com FLOPPY DISK ... From warren at muse.com Thu May 31 11:44:16 2007 From: warren at muse.com (Warren Stringer) Date: Thu, 31 May 2007 08:44:16 -0700 Subject: c[:]() In-Reply-To: <135tobve86qj808@corp.supernews.com> References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com><1180554872.3356.30.camel@dot.uniqsys.com><465DF3DE.40404@cc.umanitoba.ca><1180566831.239580.199300@m36g2000hse.googlegroups.com><005401c7a31a$136f7fe0$240110ac@Muse> <135tobve86qj808@corp.supernews.com> Message-ID: <002901c7a39a$8e67d910$240110ac@Muse> > > > > But that still isn't as simple or as direct as: > > > > c[:]() > > Why do you always use a _copy_ of c in your examples? As long > as you're wishing, why not just > > c() Oh hey Grant, yes, I misunderstood your question for a bit. I thought you meant the difference between List comprehension [...] and generator expressions (...) where the first returns the whole list and the second iterates the whole list. But, yes, good point if I was only using [:]. For more expressiveness, I could using the alternative, to the example in my reply to Douglas def beauty(judge): ... As an alternative to my reply to Douglas ... and is more cell phone friendly, due to lack of cumbersome [], which I just mentioned to Mikael, who came up with an really cool [] solution ... hmmm ... Translating Mikael's solution to the original c[:]() with some tweaks: class do(list): def __call__(self,*args,**kwargs): return [f(*args,**kwargs) for f in self] def a(): print 'a called' def b(): print 'b called' c = [a,b] do(c[:])() # close but with cell phone gnarly [] do(c)() # woo hoo! In recalling Marc's reply about a cool one liner, such a statement translates in English, as "do everything in c" Cheers, \~/ From steven.klass at gmail.com Tue May 1 17:42:18 2007 From: steven.klass at gmail.com (rh0dium) Date: 1 May 2007 14:42:18 -0700 Subject: Having problems accepting parameters to a function In-Reply-To: <1178039953.223506.52760@y80g2000hsf.googlegroups.com> References: <1178037488.163487.114930@l77g2000hsb.googlegroups.com> <1178039183.030942.86270@y5g2000hsa.googlegroups.com> <1178039953.223506.52760@y80g2000hsf.googlegroups.com> Message-ID: <1178055738.454313.182040@l77g2000hsb.googlegroups.com> Thanks to all who helped!! Let me expand a bit more - I am working on a threading class and I want to be able to push on the Queue a list of args. If you run the following program - I am failing to understand how to push items onto the queue in a manner so that func2 recognizes them as kwargs not as args. Can anyone help me with this. test1 works test2 fails again I can't figure out how to push onto the queue a dictionary and get it back off. I know this is a lot longer than I tend to post but I really want to solve this bugger. Any help is greatly appreciated. ---------------------------- #!/usr/bin/env python # encoding: utf-8 """ myThreading.py """ import sys import os import traceback import logging import threading import Queue LOGLEVEL=logging.DEBUG # Basic logger logging.basicConfig(level=LOGLEVEL, format="%(asctime)s %(name)s % (levelname)-8s %(message)s", datefmt='%d %b %Y %H:%M:%S', stream=sys.stderr) # Identifies (hopefully) the current module name try: module= os.path.basename(traceback.extract_stack(limit=2)[1] [0]).split(".py")[0]+"." except: module = os.path.basename(traceback.extract_stack(limit=2)[0] [0]).split(".py")[0]+"." class myThread(threading.Thread): def __init__(self, *args, **kwargs): """description""" self.id = kwargs.get('id', 0) self.requestQ = kwargs.get('requestQ', None) self.responseQ = kwargs.get('responseQ', None) self.function = kwargs.get('function', None) # Setup Logging self.log = logging.getLogger(module+self.__class__.__name__ +"."+str(self.id)) self.loglevel = kwargs.get('loglevel', logging.WARN) self.setLoglevel(self.loglevel) self.log.debug("Starting Thread %d" % self.id) threading.Thread.__init__(self, name=module +self.__class__.__name__+"."+str(self.id)) def setLoglevel(self,loglevel): """setLog log level""" if loglevel is not False: self.log.setLevel(loglevel) self.log.debug("Setting Logging level to %s" % loglevel) else: self.log.setLevel(logging.WARN) if self.loglevel == logging.DEBUG: self.debug = True else: self.debug=False def run(self): while 1: input = self.requestQ.get() if input is None: self.log.debug("Ending the thread - Recieved None") if self.responseQ is not None: self.responseQ.put(None) break self.log.info("Applying %s to function %s" % (str(input),str(self.function.__name__))) result = self.function(input) if self.responseQ is not None: self.log.debug("Response recieved = %s" % result) self.responseQ.put(result) def func(input): import time time.sleep(input) return 2*input def test1(loglevel=False): log = logging.getLogger(module+sys._getframe().f_code.co_name ) if loglevel is not False: log.setLevel(loglevel) else:log.setLevel(logging.WARN) maxThreads=5 # Set up two queues one for sending request data (req) one for getting response to the request (res) reqQ = Queue.Queue() resQ = Queue.Queue() # Push some data onto the reqestQ end it with None import random for x in range(200): reqQ.put(random.random()) for n in range(maxThreads): reqQ.put(None) # Start Up some threads to do some work for n in range(maxThreads): t = myThread(id=n,loglevel=logging.INFO, function=func, requestQ=reqQ, responseQ=resQ).start() # Collect the results results = 0 while 1: try: data = resQ.get() if data is None: break else: results += data except: break print results def func2( input, loglevel=False ): import time #print "args", args #print "kwargs", kwargs log = logging.getLogger(module+sys._getframe().f_code.co_name ) #loglevel = kwargs.get('loglevel', logging.WARN) log.setLevel(loglevel) # input = kwargs.get('input', 0.0) log.debug("Using input %s" % str(input)) time.sleep(input) return 3*input def test2(loglevel=False): log = logging.getLogger(module+sys._getframe().f_code.co_name ) if loglevel is not False: log.setLevel(loglevel) else:log.setLevel(logging.WARN) maxThreads=5 # Set up two queues one for sending request data (req) one for getting response to the request (res) reqQ = Queue.Queue() resQ = Queue.Queue() # Push some data onto the reqestQ end it with None import random for x in range(5): reqQ.put({'input':random.random(), 'loglevel':loglevel}) for n in range(maxThreads): reqQ.put(None) # Start Up some threads to do some work for n in range(maxThreads): t = myThread(id=n,loglevel=logging.INFO, function=func2, requestQ=reqQ, responseQ=resQ).start() # Collect the results results = 0 while 1: try: data = resQ.get() if data is None: break else: results += data except: break print results def main(loglevel=False): """ """ # Setup Logging log = logging.getLogger(module+sys._getframe().f_code.co_name ) if loglevel is not False: log.setLevel(loglevel) else:log.setLevel(logging.WARN) # test1(loglevel) test2(loglevel) if __name__ == '__main__': sys.exit(main(loglevel=LOGLEVEL)) From bob at snee.com Tue May 22 13:22:25 2007 From: bob at snee.com (bob at snee.com) Date: 22 May 2007 10:22:25 -0700 Subject: trying to gzip uncompress a StringIO Message-ID: <1179854545.199999.247590@k79g2000hse.googlegroups.com> I'm using the code below to read the zipped, base64 encoded WMF file saved in an XML file with "Save as XML" from MS Word. As the "At this point" comment shows, I know that the base64 decoding is going fine, but unzipping from the decodedVersion StringIO object isn't getting me anything, because the len(fileContent) call is returning 0. Any suggestions? thanks, Bob ########################################### import sys, base64, gzip, StringIO infile = sys.argv[1] outfile = sys.argv[2] # When unencoding base64 file, write to a string that acts like a file decodedVersion = StringIO.StringIO() base64.decode(open(infile, 'r'),decodedVersion) # At this point, if we write out decodedVersion.getvalue() to a file, # gzip -d makes a proper wmf file from it, so we know everything's OK so far. # following based on # http://www.diveintopython.org/http_web_services/gzip_compression.html fileObj = gzip.GzipFile(fileobj=decodedVersion); fileContent = fileObj.read() print len(fileContent) From stefan.behnel-n05pAM at web.de Tue May 15 07:35:50 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 15 May 2007 13:35:50 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46499a54$0$10199$9b4e6d93@newsspool4.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <4648252D.5020704@web.de> <46483740.4050406@web.de> <46498cb1$0$6411$9b4e6d93@newsspool2.arcor-online.net> <46499273.6050806@web.de> <46499a54$0$10199$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <46499B16.2070901@web.de> Ren? Fleschenberg wrote: > Stefan Behnel schrieb: >> Ren? Fleschenberg wrote: >>> you have failed to do that, in my opinion. All you have presented are >>> vague notions of rare and isolated use-cases. >> I don't think software development at one of the biggest banks in Germany can >> be considered a "rare and isolated use case". > > And that software development at that bank is not done in Python because > Python does not support non-ASCII identifiers? Can you provide a source > for that? > >> Admittedly, it's done in Java, but why should Python fail to support unicode >> identifiers in the way Java does? > > Your example does not prove much. The fact that some people use > non-ASCII identifiers when they can does not at all prove that it would > be a serious problem for them if they could not. Are we trying to prove that? And, would we have serious problems and people running from Python if Python 2.5 did not integrate the "with" statement? Stefan From stefan.behnel-n05pAM at web.de Mon May 14 08:33:31 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 14 May 2007 14:33:31 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <7x4pmg716p.fsf@ruckus.brouhaha.com> Message-ID: <4648571B.9050102@web.de> Duncan Booth wrote: > Alexander Schmolck wrote: > >> scheme (major implementations such as PLT and the upcoming standard), >> the most popular common lisp implementations, haskell[1], fortress[2], >> perl 6 and I should imagine (but haven't checked) all new java or .NET >> based languages (F#, IronPython, JavaFX, Groovy, etc.) as well -- the >> same goes for XML-based languages. >> > > Just to confirm that: IronPython does accept non-ascii identifiers. From > "Differences between IronPython and CPython": > >> IronPython will compile files whose identifiers use non-ASCII >> characters if the file has an encoding comment such as "# -*- coding: >> utf-8 -*-". CPython will not compile such a file in any case. Sounds like CPython would better follow IronPython here. Stefan From stefan.behnel-n05pAM at web.de Wed May 16 04:02:33 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 16 May 2007 10:02:33 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464ab2f9$0$23146$9b4e6d93@newsspool1.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <464ab2f9$0$23146$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <464ABA99.8080208@web.de> Ren? Fleschenberg wrote: > Gregor Horvath schrieb: >> If comments are allowed to be none English, then why are identifier not? > > I don't need to be able to type in the exact characters of a comment in > order to properly change the code, and if a comment does not display on > my screen correctly, I am not as fscked as badly as when an identifier > does not display (e.g. in a traceback). Then get tools that match your working environment. Stefan From joshbloom at gmail.com Fri May 4 15:41:21 2007 From: joshbloom at gmail.com (Josh Bloom) Date: Fri, 4 May 2007 12:41:21 -0700 Subject: how to find a lable quickly? In-Reply-To: References: Message-ID: I haven't used it myself, but I'm pretty sure you're going to get a lot of pointers to http://pyparsing.wikispaces.com/ Also you may want to start naming your variables something more descriptive. IE testResultsFile = open('test.txt','r') testLines=testResultsFile.readlines() for line in testLines: label = line.split( ) etc.. Another option is to use a Regular Expression which may speed this up for you. http://docs.python.org/lib/module-re.html -Josh On 5/4/07, wang frank wrote: > > Hi, > > I am a new user on Python and I really love it. > > I have a big text file with each line like: > > label 3 > teststart 5 > endtest 100 > newrun 2345 > > I opened the file by uu=open('test.txt','r') and then read the data as > xx=uu.readlines() > > In xx, it contains the list of each line. I want to find a spcefic labels > and read the data. Currently, I > do this by > for ss in xx: > zz=ss.split( ) > if zz[0] = endtest: > index=zz[1] > > Since the file is big and I need find more lables, this code runs slowly. > Are there anyway to speed up the process? I thought to convert the data xx > from list to a dictionay, so I can get the index quickly based on the > label. Can I do that effeciently? > > Thanks > > Frank > > _________________________________________________________________ > ??????????????????2???????????????? > http://campaign.live.jp/dizon/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jzgoda at o2.usun.pl Tue May 15 09:01:02 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Tue, 15 May 2007 15:01:02 +0200 Subject: Iron Python In-Reply-To: <1179231778.899533.78590@u30g2000hsc.googlegroups.com> References: <464981fa$0$8759$ed2619ec@ptn-nntp-reader02.plus.net> <1179224521.550517.271820@e51g2000hsg.googlegroups.com> <1179231778.899533.78590@u30g2000hsc.googlegroups.com> Message-ID: BartlebyScrivener napisa?(a): >>>> Anybody tried it? >>> Me. >> Me too. > > Anybody like it? Tried id, did not found any use, put on shelf. Don't know if this case fits "likes" or "doesn't like". ;) -- Jarek Zgoda "We read Knuth so you don't have to." From python at rcn.com Sun May 27 20:50:41 2007 From: python at rcn.com (Raymond Hettinger) Date: 27 May 2007 17:50:41 -0700 Subject: itertools.groupby In-Reply-To: References: <1180295221.3163.9.camel@localhost.localdomain> Message-ID: <1180313441.598026.198230@d30g2000prg.googlegroups.com> On May 27, 2:59 pm, Steve Howell wrote: > These docs need work. Please do not defend them; > please suggest improvements. FWIW, I wrote those docs. Suggested improvements are welcome; however, I think they already meet a somewhat high standard of quality: - there is an accurate, succinct one-paragraph description of what the itertool does. - there is advice to pre-sort the data using the same key function. - it also advises when to list-out the group iterator and gives an example with working code. - it includes a pure python equivalent which shows precisely how the function operates. - there are two more examples on the next page. those two examples also give sample inputs and outputs. This is most complex itertool in the module. I believe the docs for it can be usable, complete, and precise, but not idiot-proof. The groupby itertool came-out in Py2.4 and has had remarkable success (people seem to get what it does and like using it, and there have been no bug reports or reports of usability problems). All in all, that ain't bad (for what 7stud calls a poster child). Raymond From irmen.NOSPAM at xs4all.nl Mon May 7 19:15:17 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Tue, 08 May 2007 01:15:17 +0200 Subject: getmtime differs between Py2.5 and Py2.4 In-Reply-To: <463FA51D.1060600@v.loewis.de> References: <463FA51D.1060600@v.loewis.de> Message-ID: <463fb305$0$326$e4fe514c@news.xs4all.nl> Martin v. L?wis wrote: >> Is this a bug? > > Why don't you read the responses posted earlier? John Machin > replied (in <1178232636.415630.106320 at l77g2000hsb.googlegroups.com>) > that you are mistaken: There is NO difference between the outcome > of os.path.getmtime between Py2.5 and Py2.4. It always did return > UTC, and always will. > > Regards, > Martin Err.....: [E:\Projects]dir *.py Volume in drive E is Data Serial number is 2C4F:9C2D Directory of E:\Projects\*.py 31-03-2007 20:46 511 log.py 25-11-2006 16:59 390 p64.py 7-03-2007 23:07 207 sock.py 3-02-2007 16:15 436 threads.py 1.544 bytes in 4 files and 0 dirs 16.384 bytes allocated 287.555.584 bytes free [E:\Projects]c:\Python24\python.exe -c "import os; print os.path.getmtime('p64.py')" 1164470381 [E:\Projects]c:\Python25\python.exe -c "import os; print os.path.getmtime('p64.py')" 1164466781.28 This is python 2.4.4 and Python 2.5.1 on windows XP. The reported time clearly differs. --Irmen From tjreedy at udel.edu Sun May 6 15:53:37 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 6 May 2007 15:53:37 -0400 Subject: howto make Python list from numpy.array? References: <1178480447.245977.293010@n59g2000hsh.googlegroups.com> Message-ID: "dmitrey" wrote in message news:1178480447.245977.293010 at n59g2000hsh.googlegroups.com... | howto make Python list from numpy.array? I Googled 'numpy array Python list' and looked at the third hit (PythonBasics) and at the bottom found your answer. About 30 seconds or less. tjr From bj_666 at gmx.net Thu May 24 12:20:36 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 24 May 2007 18:20:36 +0200 Subject: of destructors, open files and garbage collection References: <1180021256.619953.80500@q66g2000hsg.googlegroups.com> Message-ID: In <1180021256.619953.80500 at q66g2000hsg.googlegroups.com>, massimo s. wrote: > I have a for loop that looks like the following : > > for item in long_list: > foo(item) > > def foo(item): > item.create_blah() #<--this creates item.blah; by doing that it > opens a file and leaves it open until blah.__del__() is called > > Now, what I thought is that if I call > > del(item) > > it will delete item and also all objects created inside item. It will delete the *name* `item`. It does nothing to the object that was bound to that name. If the name was the only reference to that object, it may be garbage collected sooner or later. Read the documentation for the `__del__()` method for more details and why implementing such a method increases the chance that the object *won't* be garbage collected! Relying on the `__del__()` method isn't a good idea because there are no really hard guaranties by the language if and when it will be called. Ciao, Marc 'BlackJack' Rintsch From claird at lairds.us Thu May 17 20:10:46 2007 From: claird at lairds.us (Cameron Laird) Date: Fri, 18 May 2007 00:10:46 +0000 Subject: Python-URL! - weekly Python news and links (May 16) References: <1179427472.766442.252900@w5g2000hsg.googlegroups.com> Message-ID: <6h7vh4-d67.ln1@lairds.us> In article <1179427472.766442.252900 at w5g2000hsg.googlegroups.com>, wrote: >> PythonWare complements the digest you're reading with the >> marvelous daily python url >> http://www.pythonware.com/daily > >Ha, ha, ha... > >That is a good joke! > > > 'Wasn't meant that way. While he doesn't make it explicit, I assume memracom is reacting to the over-two-week hiatus in updates to The Daily Python-URL. I confess I don't know what the prospects are for resumption of the service; perhaps someone more knowledgeable will follow-up here. From paul at boddie.org.uk Tue May 15 10:20:47 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 15 May 2007 07:20:47 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <4649BC4C.10200@web.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649BC4C.10200@web.de> Message-ID: <1179238847.407605.4620@w5g2000hsg.googlegroups.com> On 15 May, 15:57, Stefan Behnel wrote: > > But the positions are clear, I think. Amongst the small group of people responsible for pumping out almost 200 messages on the subject. > Open-Source people are against it, as they expect hassle with people sending > in code or code being lost as it can't go public as-is. Amongst the small sample here, perhaps that's true. I'm more a Free Software person than an open source person and I can perfectly well see the benefits in having identifiers in a broader range of characters than just the subset of ASCII currently permitted. That's because I can separate the issues of being able to express concepts in one's own writing system and being able to share work with other people, familiar or otherwise with that writing system. > Teachers are for it as they see the advantage of having children express > concepts in their native language. Yes, because it allows them to concentrate on fewer "new things" simultaneously. > In-house developers are rather for this PEP as they see the advantage of > expressing concepts in the way the "non-techies" talk about it. Yes, but this point can be stretched too far. I've worked in environments with English plus another language in use, as well as just a non-English language in use, and in all of them there's been a tendency to introduce English or English-like terms into systems, often to the detriment of dedicated, officially recommended non- English terms. But I can see the potential benefit of just letting people get on with it - again, it's possible to separate the social issues from the technical ones. > That's about all I could extract as arguments. >From a relatively small group of people where an even smaller group of participants seem intent on amplifying their arguments on the subject. > To me, this sounds pretty much like something people and projects could handle > on their own once the PEP is accepted. Yes, of course. But what I'd like to see, for a change, is some kind of analysis of the prior art in connection with this matter. Java has had extensive UTF-8 support all over the place for ages, but either no- one here has any direct experience with the consequences of this support, or they are more interested in arguing about it as if it were a hypothetical situation when it is, in fact, a real-life situation that can presumably be observed and measured. Paul From jzgoda at o2.usun.pl Thu May 17 10:21:29 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Thu, 17 May 2007 16:21:29 +0200 Subject: Python Web Programming - looking for examples of solid high-traffic sites In-Reply-To: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> Message-ID: Victor Kryukov napisa?(a): > Our main requirement for tools we're going to use is rock-solid > stability. As one of our team-members puts it, "We want to use tools > that are stable, has many developer-years and thousands of user-years > behind them, and that we shouldn't worry about their _versions_." The > main reason for that is that we want to debug our own bugs, but not > the bugs in our tools. I don't think you find anything even remotely resembling that idea here. Moreover, I don't think you find it elsewhere. Maybe even such tools do not exist in nature? -- Jarek Zgoda "We read Knuth so you don't have to." From martin at v.loewis.de Tue May 8 02:57:48 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 08 May 2007 08:57:48 +0200 Subject: getmtime differs between Py2.5 and Py2.4 In-Reply-To: <1178601073.116993.8030@u30g2000hsc.googlegroups.com> References: <463FA51D.1060600@v.loewis.de> <1178601073.116993.8030@u30g2000hsc.googlegroups.com> Message-ID: <46401F6C.1080708@v.loewis.de> >> that you are mistaken: There is NO difference between the outcome >> of os.path.getmtime between Py2.5 and Py2.4. It always did return >> UTC, and always will. > > Different results are indeed obtained, as others have demonstrated > (other than the irrelevant float/int distinction). The following C > sample program illustrates: Right. However, contrary to what the OP claimed, 2.4 does *not* return local time - it still returns UTC. It may just return "a different" UTC. > A key fact here, I believe, is that in February (when temp.txt was > last modified), my local time was UTC-11. I expect this is the > suffering that your comment in posixmodule.c refers to (it looks to me > like Python 2.5 is correct). In case there was any doubt: your tests show that 2.4 does not return local time. The output of dir matches the results of the time.ctime output, that must meant that the ctime input was UTC. Now, that there is a one-hour difference is an inherent problem with the FAT file system (so I assume you use FAT on your disk drive). FAT has an inherent problem with UTC file stamps, as the time stamps are stored in local time. So if you have an old time, you can only interpret it in a meaningful way by assuming that the machine was in the same time zone when the file was created as it is now. The the DST issue come in: should one assume that the DST switched since when the time stamp was created; depending on what you assume here, a one-hour difference will occur. IIRC (and I clearly didn't at the beginning of the thread): The MS CRT tries to adjust time stamps because of these problems, but does so incorrectly. In particular, it adjusts time stamps on NTFS volumes as well, which *are* in UTC. So even though the system reports the correct time stamp, the CRT will return the wrong one. Python 2.5 fixes this, bypassing the CRT. So yes: the time stamps returned in 2.4 and 2.5 may differ. But still: they were always UTC, and always will be. It's just that 2.4 had a bug which 2.5 has fixed. Regards, Martin From gandalf at shopzeus.com Fri May 25 09:50:57 2007 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Fri, 25 May 2007 15:50:57 +0200 Subject: Reading a file and resuming reading. In-Reply-To: References: Message-ID: <4656E9C1.1080500@shopzeus.com> Karim Ali wrote: > Hi, > > Simple question. Is it possible in python to write code of the type: > > ----------------------------- > while not eof <- really want the EOF and not just an empty line! > readline by line > end while; > ----------------------------- > > What I am using now is the implicit for loop after a readlines(). I don't > like this at all as a matter of opinion (my background is C++). > > But also, in case for one reason or another the program crashes, I want to > be able to rexecute it and for it to resume reading from the same position > as it left. If a while loop like the one above can be implemented I can do > this simply by counting the lines! > > I appreciate any help. > What about this: fin = file('test.txt','r') for line in fin: process_line(line) By the way, readline returns an empty line only at the end of the file. In all other cases, it will return a string that ends with a newline. E.g. you can detect if you are at the end of the file or not. But using the above snippet is usually better. Text files are iterable, line by line. Best, Laszlo From jjreavis at gmail.com Sat May 26 18:34:36 2007 From: jjreavis at gmail.com (Jeff Reavis) Date: 26 May 2007 15:34:36 -0700 Subject: Tix and OS X Message-ID: <1180218876.623283.174680@p77g2000hsh.googlegroups.com> Does python not ship with Tix for OS X? I know there was an issue with 2.5.0 and Tix on Windows, and upgrading to 2.5.1 fixed it. Unfortunately, I seem to have the same issue with OS X and 2.5.1. The error I get is: self.tk.eval('package require Tix') _tkinter.TclError: can't find package Tix I did find tkinter.so (Tkinter seems to work), but nothing matching tix.so. Is this a known issue? I haven't found any information about it on the web or in this group. Thanks in advance. This is an Intel Mac, btw. -jjr From thorsten at thorstenkampe.de Tue May 15 09:10:54 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 15 May 2007 14:10:54 +0100 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476081.7080609@web.de> <46498514$0$6402$9b4e6d93@newsspool2.arcor-online.net> <4649882E.3060005@web.de> <46499940$0$10199$9b4e6d93@newsspool4.arcor-online.net> <46499BF9.30209@web.de> <4649a2c1$0$10193$9b4e6d93@newsspool4.arcor-online.net> <4649A429.3010406@web.de> <4649ae4a$0$20289$9b4e6d93@newsspool3.arcor-online.net> Message-ID: * Ren? Fleschenberg (Tue, 15 May 2007 14:57:45 +0200) > Stefan Behnel schrieb: > > You're not trying to suggest that writing code in a closed area project is a > > bad habit, are you? > > I think that the idea that you know today, with 100% certainty, that all > parts of your closed area project will stay closed forever is an > illusion and thus a bad idea, yes. > > > What would be bad about allowing a project to decide about the best and > > clearest way to name identifiers? > > That very same argument could be used to allow all sorts of "strange > stuff" in Python like gotos and worse. What would be bad about allowing > a project to decide about how to do flow control, especially if you > never get in touch with it? GOTOs are not understable. Identifiers in foreign languages are perfectly understable. Just not to you. For coding problems better solutions (approaches) exist than using GOTOs (procedural programming, modules). For identifier naming problems it's not a better approach to stick to English or ASCII. It's just a different approach. From alessiogiovanni.baroni at gmail.com Tue May 1 06:03:52 2007 From: alessiogiovanni.baroni at gmail.com (alessiogiovanni.baroni at gmail.com) Date: 1 May 2007 03:03:52 -0700 Subject: Error in python.org homepage. Message-ID: <1178013832.880214.134660@l77g2000hsb.googlegroups.com> Hi to all!!! I sended an email to webmaster at python dot org, but was blocked... why?.... In the homepage of python.org there is an error: the link that point to source distribution is not updated to Python 2.5.1. From deets at nospam.web.de Wed May 23 10:29:00 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 23 May 2007 16:29:00 +0200 Subject: Properties/Decorators [WAS: Can I reference 1 instance of an object by more names ? rephrase] References: <4654289a$0$2326$426a74cc@news.free.fr> Message-ID: <5bj1ddF2sd0aoU1@mid.uni-berlin.de> Wildemar Wildenburger wrote: > Bruno Desthuilliers wrote: >> here's an example using a property: >> >> class cpu_ports(object): >> def __init__(self, value=0): >> self._d = value >> @apply >> def value(): >> def fset(self, value): >> print 'vv' >> self._d = value >> def fget(self): >> return self._d >> return property(**locals()) >> > Wow! I've never seen properties written that way. Kind of takes all the > mess out of what it usually is. Nice. BUT! I don't quite get the > @apply-decorator here. The rest I get and so I gather what it is sort of > kind of supposed to do. I have only found the depricated apply() > function in the docs (which I also don't quite get just by scanning it). > Is it that? If yes: How does it work? If not: What's going on there? It is that very apply. And apply takes a function as argument + additional arguments, and executes that function, returning the result of that function-call. It was used before the f(*args, **kwargs) notation was introduced. Now what we have here is "value" as function, passed as single argument to apply (because decorators are just callables), which will invoke "value" with no arguments. The result of that operation is the property-object, that thus is returned by apply. And in the end gets assigned to the name value in the cpu_ports-class. diez From deets at nospam.web.de Wed May 2 04:04:32 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 02 May 2007 10:04:32 +0200 Subject: Killing Threads In-Reply-To: References: <000d01c78c60$8c0056d0$a4010470$@rawlins@thinkbluemedia.co.uk> Message-ID: <59qv0hF2lsq6uU1@mid.uni-berlin.de> > You probably need to setDaemon (True) on your threads > after you've created them and before they run. That > tells the OS: don't bother waiting for these ones to > finish if the program exits. (At least I think that's > what it does; I don't use threads all that much) Actually all it does is to tell the at_exit-handler that it's ok to terminate even though there are still some threads. The OS isn't concerned with this. Diez From __peter__ at web.de Mon May 21 13:53:03 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 21 May 2007 19:53:03 +0200 Subject: doctest environment question References: <1179762737.153434.143030@b40g2000prd.googlegroups.com> Message-ID: thomas.guest at gmail.com wrote: > I'm not making progress with the following and would appreciate any > help. > > Here's an interpreted Python session. > >>>> import sys >>>> def f(): pass > ... >>>> this_module = sys.modules[__name__] >>>> delattr(this_module, 'f') >>>> f() > Traceback (most recent call last): > File "", line 1, in > NameError: name 'f' is not defined > > Suppose I want to doctest this behaviour. I cut and paste the above > into a file "test.txt" then run: > > python -c "import doctest; doctest.testfile('test.txt')" > > This gives me unexpected test failures: > > python -c "import doctest; doctest.testfile('test.txt')" > ********************************************************************** > File "test.txt", line 5, in test.txt > Failed example: > delattr(this_module, 'f') > Exception raised: > Traceback (most recent call last): > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/doctest.py", line 1212, in __run > compileflags, 1) in test.globs > File "", line 1, in > delattr(this_module, 'f') > AttributeError: f > ********************************************************************** > File "test.txt", line 6, in test.txt > Failed example: > f() > Expected: > Traceback (most recent call last): > File "", line 1, in > NameError: name 'f' is not defined > Got nothing > ********************************************************************** > 1 items had failures: > 2 of 5 in test.txt > ***Test Failed*** 2 failures. The doctest code is executed in a module without a __name__, it seems. Unfortunately (in this case) the builtin module serves as a fallback helping out with its own name: >>> __name__ '__main__' >>> del __name__ >>> __name__ '__builtin__' What to do about it? doctest could be changed to execute code snippets in a module with a name and a sys.modules entry though I don't see much benefit here. Peter From openopt at ukr.net Mon May 21 09:14:47 2007 From: openopt at ukr.net (dmitrey) Date: 21 May 2007 06:14:47 -0700 Subject: howto get function from module, known by string names? In-Reply-To: References: <1179228596.349933.168610@l77g2000hsb.googlegroups.com> Message-ID: <1179753287.816169.311950@x35g2000prf.googlegroups.com> And howto check does module 'asdf' exist (is available for import) or no? (without try/cache of course) Thx, D. Carsten Haese wrote: > On 15 May 2007 04:29:56 -0700, dmitrey wrote > > hi all, > > can anyone explain howto get function from module, known by string > > names? > > I.e. something like > > > > def myfunc(module_string1, func_string2, *args): > > eval('from ' + module_string1 + 'import ' + func_string2') > > return func_string2(*args) > > To find a module by its name in a string, use __import__. To find an object's > attribute by its name in a string, use getattr. > > Together, that becomes something like this: > > >>> def myfunc(module_string1, func_string2, *args): > ... func = getattr(__import__(module_string1), func_string2) > ... return func(*args) > ... > >>> myfunc("math", "sin", 0) > 0.0 > >>> myfunc("operator", "add", 2, 3) > 5 > > Hope this helps, > > -- > Carsten Haese > http://informixdb.sourceforge.net From vatamane at gmail.com Mon May 7 23:19:01 2007 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 7 May 2007 20:19:01 -0700 Subject: How to make Python poll a PYTHON METHOD In-Reply-To: <1178592128.327658.212000@p77g2000hsh.googlegroups.com> References: <1178590029.225298.195430@y80g2000hsf.googlegroups.com> <1178592128.327658.212000@p77g2000hsh.googlegroups.com> Message-ID: <1178594341.680457.192440@q75g2000hsh.googlegroups.com> On May 7, 10:42 pm, Nick Vatamaniuc wrote: > On May 7, 10:07 pm, johnny wrote: > > > Is there a way to call a function on a specified interval(seconds, > > milliseconds) every time, like polling user defined method? > > > Thanks. > > Sure, > > >>> def baz(): > > ...: print "Baz!" > ...: > > >>> from threading import Timer > >>> timer=Timer(5.0,baz) > >>> timer.start() > >>> Baz! > > Cheers, > -Nick Vatamaniuc By the way, here is another way to do it. This way it will repeat, the other one executed once. Of course, if it executed once, you can make it do it again, but there is some trickery involved. Here is a way to do it using threads. Hope it helps, -Nick Vatamaniuc from threading import Thread from time import sleep class Repeater(Thread): def __init__(self,interval,fun,*args,**kw): Thread.__init__(self) self.interval=interval self.fun=fun self.args=args self.kw=kw self.keep_going=True def run(self): while(self.keep_going): sleep(self.interval) self.fun(*self.args,**self.kw) def stop_repeating(self): self.keep_going=False def eat(*a): print "eating: " , ','.join([stuff for stuff in a]) r=Repeater(1.0, eat, 'eggs','spam','kelp') r.start() sleep(6.0) r.stop_repeating() From mail at timgolden.me.uk Wed May 2 14:57:48 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 02 May 2007 19:57:48 +0100 Subject: how to use Dispatch to open an application in win32com.client In-Reply-To: <545586.61889.qm@web63405.mail.re1.yahoo.com> References: <545586.61889.qm@web63405.mail.re1.yahoo.com> Message-ID: <4638DF2C.4090203@timgolden.me.uk> Peter Fischer wrote: > Hello, > > I also use the COM API via python to dispatch an application. My > problem now is that I want to dispatch a second instance of this > application (Google Earth by the way). But when I invoke dispatch > the second time, nothing happens although using another variable to > store the returned value: > > GE_1 = win32com.client.Dispatch("GoogleEarth.ApplicationGE") > > GE_2 = win32com.client.Dispatch("GoogleEarth.ApplicationGE") > > (import and while not .IsInitialized() statements omitted for brevity) > > Does anyone know how to start a second, third, and so on, instance of > the application? Suspect you want win32com.client.DispatchEx which, among other things, starts a separate instance of the app. (Or whatever they call the things in COMspeak). GE_n = win32com.client.DispatchEx ("GoogleEarth.ApplicationGE") TJG From bbrown at speakeasy.net Sun May 13 17:56:39 2007 From: bbrown at speakeasy.net (Robert Brown) Date: Sun, 13 May 2007 17:56:39 -0400 Subject: Towards faster Python implementations - theory References: <1210i.7468$2v1.2505@newssvr14.news.prodigy.net> <1178804728.527486.196400@y80g2000hsf.googlegroups.com> <1178895954.457221.277820@p77g2000hsh.googlegroups.com> Message-ID: sturlamolden writes: > On May 10, 7:18 pm, "Terry Reedy" wrote: > > CMUCL and SBCL depends on the dominance of the x86 architecture. CMUCL and SBCL run on a variety of architectures, including x86, 64-bit x86, PowerPC, Sparc, Alpha, and Mips. See http://www.sbcl.org/platform-table.html for platform support information. > Or one could translate between Python and Lisp on the fly, and use a > compiled Lisp (CMUCL, SBCL, Franz, GCL) as runtime backend. This has been done by Willem Broekema. PLPython is a Python implementation that translates Python source into Common Lisp at read time. Under the covers, the Lisp is compiled into machine code and then run. See http://trac.common-lisp.net/clpython/ Currently, CLPython uses some non-standard Allegro Common Lisp features, so it does not run on all the free implementations of ANSI Common Lisp. The implementation is interesting, in part because it shows how expensive and complex some Python primitives are. From mg.mailing-list at laposte.net Tue May 15 05:26:12 2007 From: mg.mailing-list at laposte.net (Mathieu Gontier) Date: Tue, 15 May 2007 11:26:12 +0200 Subject: distutil & visual-studio-2005 Message-ID: <46497CB4.5000900@laposte.net> Hello, Few month ago, I try to build/install additional python packages like Numarray, Numpy, etc on Windows with Visual Studio 2005. I realized that distutil does not support Visual Studio 2005 and it was not planned to be included in the Python release at this moment. Now, does someone has any news about the integration of Visual Studio 2005 in distutil? Many thanks, -- Mathieu Gontier Product Development Engineer Free Field Technologies S.A. Skype Name: mathieu_gontier Read the attached v-card for telephone, fax, adress Look at our web-site http://www.fft.be From basilisk96 at gmail.com Mon May 21 21:53:23 2007 From: basilisk96 at gmail.com (Basilisk96) Date: 21 May 2007 18:53:23 -0700 Subject: A few questions In-Reply-To: References: Message-ID: <1179798803.682192.309290@w5g2000hsg.googlegroups.com> > 2. Is there a good book to start with while learning Python? I'm > currently reading 'Python Essential Reference' by David M. Beazley. > So far it looks like a pretty good book, but would like more > tutorials to work with (I've also been reading through the tutorials > at 'python.org' which has some excellent stuff!). Take a walk through the text "How to Think Like a Computer Scientist": http://www.ibiblio.org/obp/thinkCSpy/ It's medium-paced, well-organized, and - quite importantly IMHO - builds well on knowledge acquired in the previous chapters as it progresses. There are plenty of hands-on examples; and really, the text was written by a high school teacher for a CS curriculum, so it's structured more like a tutorial. I found it to be priceless when I first got interested in Python, and I would highly recommend it to any newbie, whether with previous programming experience or not, but who has never laid eyes on Python before. As I think back on it, the book gives you just enough information to make you hungry for more - and indeed, after reading it I had enough insight to explore Python on my own and started writing useful programs by myself. > > 3. Currently, I write most of my code with Xcode (on the Mac > platform) using Applescript. This gives me GUI capabilities. Is > there anything you'd recommend that I could use for Python that would > give me a GUI interface? I'd like this to be able to work for both > the Mac and Windows platforms. I've been reading a little about > 'Claro Graphics Toolkit' and 'PyGUI'... would you recommend either of > those? I'll be writing code on a Mac so I need something that will > run on that system. > Try wxPython. I've seen it run on a Mac with OS X and Windows simultaneously, where the operating systems were switched from one to the other at the touch of a button, and the GUI had a very native look in either platform (mind you, the app was running exactly the same code in both cases!). I write my code on a win32 box, so I have no further pointers for you regarding a Mac. -Basilisk96 From sable at users.sourceforge.net Thu May 3 09:46:38 2007 From: sable at users.sourceforge.net (=?ISO-8859-1?Q?S=E9bastien_Sabl=E9?=) Date: Thu, 03 May 2007 15:46:38 +0200 Subject: Sybase module 0.38 released Message-ID: <4639E7BE.8050804@users.sourceforge.net> WHAT IS IT: The Sybase module provides a Python interface to the Sybase relational database system. It supports all of the Python Database API, version 2.0 with extensions. The module is available here: http://downloads.sourceforge.net/python-sybase/python-sybase-0.38.tar.gz The module home page is here: http://python-sybase.sourceforge.net/ CHANGES SINCE 0.38pre2: * Corrected bug in databuf_alloc: Sybase reports the wrong maxlength for numeric type - verified with Sybase 12.5 - thanks to patch provided by Phil Porter MAJOR CHANGES SINCE 0.37: * This release works with python 2.5 * It also works with sybase 15 * It works with 64bits clients * It can be configured to return native python datetime objects * The bug "This routine cannot be called because another command structure has results pending." which appears in various cases has been corrected * It includes a unitary test suite based on the dbapi2.0 compliance test suite From michele.simionato at gmail.com Wed May 2 01:28:08 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 1 May 2007 22:28:08 -0700 Subject: pre-PEP: Standard Microthreading Pattern In-Reply-To: References: Message-ID: <1178083688.414491.317340@o5g2000hsb.googlegroups.com> On May 1, 10:58 pm, dus... at v.igoro.us wrote: > def fibonacci(n): > latest, i = (1, 1), 2 > if n < 1: > raise ValueError # raise exception > while i < n: > latest = (latest[1], latest[0] + latest[1]) > yield # cooperative yield > raise StopIteration(latest[1]) # return value There is an infinite loop here! > def fibsquared(n): > try: > fibn = (yield fibonacci(n)) ** 2 # function call > except ValueError: # catch exception > print "Sorry, cannot calculate fibsquared of", n > else: > print "fibsquared of", n, "is", fibn It is not clear to me if you mean here F(yield ) as a a shortcut for for el in : yield F(el) In other words, is ``fibsquared(n).next()`` should return a value or a generator object?? BTW, in spite of having a great tradition, the Fibonacci example sucks as a motivation for microthreading programming. You could show a simple state machine instead. Michele Simionato From elventear at gmail.com Mon May 14 15:07:06 2007 From: elventear at gmail.com (elventear) Date: 14 May 2007 12:07:06 -0700 Subject: Recursion limit problems In-Reply-To: References: <1178921877.442519.165740@u30g2000hsc.googlegroups.com> <1179156916.706892.144770@y80g2000hsf.googlegroups.com> Message-ID: <1179169626.079123.115780@p77g2000hsh.googlegroups.com> On May 14, 2:03 pm, "Gabriel Genellina" wrote: > > Dicts and sets use the key's hash value to determine the "bucket" where > the key will be placed, and == to distingish between different objects > with the same hash value. > That is, you should define __hash__ and one of (__cmp__ or __eq__). > __neq__ (inequality) isn't required nor used by dict/set implementation. > (Anyway, Python will transform a!=b into not(a==b), if __neq__ isn't > defined). Neither <, <=, >, >= are used. > The important thing is that, if two objects compare equal, they must have > the same hash value. That is: (a==b) => (hash(a)==hash(b)) (the reciprocal > is not true). Cool! I think this answers my last question. Thanks! From tjreedy at udel.edu Fri May 4 23:49:59 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 4 May 2007 23:49:59 -0400 Subject: My Python annoyances References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> Message-ID: "Ben Collver" wrote in message news:OvadnZpRt8hbq6bbnZ2dnUVZ_ternZ2d at scnresearch.com... | Hi Terry, | | I understand and agree that the number was the same bit pattern. OK | I don't remember being asked to challenge this. You don't need an invitation to disagree with another person's tracker comment. I assumed you knew this and took non-response as acquiesence. That (closing no response by item submitter) is a fairly typical pattern , by the way. I wish it were otherwise. | I must have missed the status change notification. The SF item-change emails indicate the changes, but you have to look. | I do wonder whether the diagnosis is accurate: is the sparc64 port | actually using an unsigned int where the i386 port is using a signed int? I have no idea. I was essentially acting on GG's behalf since I know him to be techically competent and stronly suspected (correctly, it turns out) that could not put the close button himself. | Either way, I don't see how it reflects on the validity of the report. A bug is a discrepancy between promise and performance | I reported that the resulting numbers were different. I understand CRC checks to produce bit patterns rather than 'numbers'. | To me that seems a trap for the unwary. That is a different issue. If, for instance, you think the docs could and should be improved to make people more wary, reopen the item, change the appropriate field to 'documentation' and please give a suggested addition or change. | All I saw was a comment on what might cause my problem, I understood (correctly, as it turns out) GG as saying 'invalid'. | and then I saw that the problem report was closed. Think of GG and I as a team acting as one. I had nothing to add and other bug reports to attend to. | Now I am told that I didn't even file a real bug report. Invalid reports are more common than I wish. We try to be polite and accurate in rejecting them. Once a seemingly competant judgement is made in this direction, the ball is in the submitter's court, so to speak. | don't know whether to take that as "this is a | trivial problem not worth reporting" or "this is a poorly filed bug report". Your choice. See above. | I am an honest person, honestly! I can see that there was some non-understanding both ways, which is why I have tried to clarify things. Terry Jan Reedy From aleax at mac.com Sat May 5 10:58:13 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 5 May 2007 07:58:13 -0700 Subject: Looping over lists References: <1hxlsky.tgi88sj7tfrN%aleax@mac.com> <1178363220.575060.219310@y5g2000hsa.googlegroups.com> Message-ID: <1hxmqpe.19wlfrk17zgjvxN%aleax@mac.com> Dustan wrote: > On May 5, 3:15 am, kaens wrote: > > I think the for i in range() is more readable (Maybe because I'm > > coming from a c-style syntax language background) - but what would > > the benefits of using enumerate be (other that being more . . . > > pythonesque?) > > It doesn't create a whole new list just for iterating. As the example list was of length 5, that's not all that important in this case. In cases where it _is_ crucial, you can use xrange. The performance of the various ways of looping is substantially the same: $ python -mtimeit -s'n=5; a=n*[23]' 'for i in range(n): x=a[i]' 1000000 loops, best of 3: 1.4 usec per loop $ python -mtimeit -s'n=5; a=n*[23]' 'for i in xrange(n): x=a[i]' 1000000 loops, best of 3: 1.18 usec per loop $ python -mtimeit -s'n=5; a=n*[23]' 'for i,v in enumerate(a): x=v' 1000000 loops, best of 3: 1.49 usec per loop $ Here, xrange is minutely faster and enumerate slower, but each speed difference "in the noise". Focusing on clarity is thus well warranted. > > > > for i in range(n): > > > > for j in range(i+1, n): > > > > print a[i], a[j] > > > > > Ah, but wouldn't the cleaner Python be something like > > > > > >>> a = [1, 2, 3, 4, 5, 3, 6] #just to confuse matters > > > >>> for pos, val in enumerate(a): > > > ... for v2 in a[pos+1:]: > > > ... print val, v2 This "breaks symmetry", by using enumerate in the outer loop and a slice in the inner loop; the symmetrical construction of using range in both loops is a big conceptual/clarity win -- the reader of the code needs to "grasp" one fewer concept (locally). Using xrange in both loops would be just as good from this POV. Alex From whamil1 at entergy.com Tue May 15 13:37:16 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Tue, 15 May 2007 12:37:16 -0500 Subject: Trying to choose between python and java Message-ID: <588D53831C701746A2DF46E365C018CE01D2CA9A@LITEXETSP001.etrsouth.corp.entergy.com> > From: Beliavsky On May 15, 1:30 am, Anthony Irwin wrote: > > > > > #5 someone said that they used to use python but stopped because the > > language changed or made stuff depreciated (I can fully remember > > which) and old code stopped working. Is code written today likely to > > still work in 5+ years or do they depreciate stuff and you have to > update? > > Because Python 3 will change the syntax of print to disallow > > print "Hello, world." > > a substantial fraction of Python programs in existence, including all > of my programs, will be broken. Draw your own conclusions. > No, they'll work just fine. They just won't work with Python 3. It's not like the Python Liberation Front is going to hack into your computer in the middle of the night and delete you 2.x installation. --- -Bill Hamilton From rschroev_nospam_ml at fastmail.fm Fri May 4 07:38:08 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 04 May 2007 11:38:08 GMT Subject: 4 quadrant atan In-Reply-To: <463a94cc$0$14025$c30e37c6@lon-reader.news.telstra.net> References: <1178120019.271716.299590@e65g2000hsc.googlegroups.com> <1178203772.243333.24990@p77g2000hsh.googlegroups.com> <463a94cc$0$14025$c30e37c6@lon-reader.news.telstra.net> Message-ID: Charles Sanders schreef: > Roel Schroeven wrote: >> I might be wrong of course, but can't you just use atan2? Only problem >> is that it returns negative angles for quadrants 3 and 4, but that is >> easily solved. In Python: >> >> from math import atan2, pi, fmod >> def vectorAngle(x, y): >> return fmod(atan2(y, x) + 2*pi, 2*pi) >> >> No conditionals in sight. >> > > Yes, but there will be some conditionals for special > cases in the implementation of atan2(). That's true, but the user of the atan2() doesn't need to concern himself with it; that's what I meant with 'in sight'. > > I am pretty sure that in Python (and Perl) atan2() is > the C atan2() from the C math library, also often used by > Fortran. I'm pretty sure too: the Python 2.4 documentation says "The math module consists mostly of thin wrappers around the platform C math library functions." > This is normally written in assembler for the individual > architecture by the hardware vendor or compiler writer, is usually > heavily optimized, carefully handles all the corner cases, and > often carries extra precision to ensure accuracy. Yep, and that's why I prefer using that instead of trying to roll my own. And because it leverages the speed of the FPU on platforms where it is implemented in hardware. I believe the FPU's of the i386 family have it in their instruction set. I even believe there are no instructions for asin, atan and acos; they are all calculated using FPATAN which calculates atan2. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From vasudevram at gmail.com Wed May 30 08:24:23 2007 From: vasudevram at gmail.com (vasudevram) Date: 30 May 2007 05:24:23 -0700 Subject: Periodic tasks. In-Reply-To: <465d22b8$0$325$e4fe514c@news.xs4all.nl> References: <1180420430.610215.96330@a26g2000pre.googlegroups.com> <465d22b8$0$325$e4fe514c@news.xs4all.nl> Message-ID: <1180527863.388484.100260@r19g2000prf.googlegroups.com> Steve Howell wrote: >Thanks. Here are two links, not sure those are >exactly what are being referenced here, but look in >the ballpark: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413137 > http://docs.python.org/lib/module-sched.html You're welcome. The ActiveState recipe you mention above is not the one I meant, although it uses sched. I saw the recipe that I mentioned, in the print version of the Python Cookbook, when reading it a few days ago. The second link above you mention is right, its about the sched library. Also just found these other recipes in the online Python Cookbook, may or may not be of help to you: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496800 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/114644 Vasudev Ram www.dancingbison.com From steve at holdenweb.com Thu May 17 17:29:56 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 17 May 2007 17:29:56 -0400 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179423799.254286.294930@w5g2000hsg.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <464C5382.6080403@v.loewis.de> <1179423799.254286.294930@w5g2000hsg.googlegroups.com> Message-ID: Istvan Albert wrote: > On May 17, 9:07 am, "Martin v. L?wis" wrote: > >> up. I interviewed about 20 programmers (none of them Python users), and >> most took the position "I might not use it myself, but it surely >> can't hurt having it, and there surely are people who would use it". > > Typically when you ask people about esoteric features that seemingly > don't affect them but might be useful to someone, the majority will > say yes. Its simply common courtesy, its is not like they have to do > anything. > > At the same time it takes some mental effort to analyze and understand > all the implications of a feature, and without taking that effort > "something" will always beat "nothing". > Indeed. For example, getattr() and friends now have to accept Unicode arguments, and presumably to canonicalize correctly to avoid errors, and treat equivalent Unicode and ASCII names as the same (question: if two strings compare equal, do they refer to the same name in a namespace?). > After the first time that your programmer friends need fix a trivial > bug in a piece of code that does not display correctly in the terminal > I can assure you that their mellow acceptance will turn to something > entirely different. > And pretty quickly, too. If anyone but Martin were the author of the PEP I'd have serious doubts, but if he thinks it's worth proposing there's at least a chance that it will eventually be implemented. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From gagsl-py2 at yahoo.com.ar Tue May 8 00:41:11 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 08 May 2007 01:41:11 -0300 Subject: interesting exercise References: <1178595952.641173.76540@y80g2000hsf.googlegroups.com> Message-ID: En Tue, 08 May 2007 01:33:51 -0300, Steven D'Aprano escribi?: > On Tue, 08 May 2007 01:21:37 -0300, Gabriel Genellina wrote: > >> if not sorted(values): raise ValueError("unsorted values") > > sorted() doesn't return a flag telling if the values are sorted, it > returns a new list containing values sorted. So this line will raise an > exception only on an empty sequence. Ouch! -- Gabriel Genellina From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun May 20 06:39:43 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 20 May 2007 12:39:43 +0200 Subject: questions about programming styles References: Message-ID: <5bamrfF2rj5dkU1@mid.individual.net> fdu.xiaojf at gmail.com wrote: > Hi all, I'm not skilled at programming, so sorry for my ignorance. ?! Seems you met many not-so-nice programmers. > (1) > which is the better way to calculate the value of attributes of a > class ? for example: > > (A) > def cal_attr(self, args): > #do some calculations > self.attr = calculated_value > and then if the vlue of attribute is needed, > self.cal_attr(args) > some_var = self.attr > or I can define cal_attr() as follows: > (B) > def cal_attr(self, args): > #do some calculations > return calculated_value > and then, if the value of attribute is needed, > self.attr = self.cal_attr(args) > some_var = self.attr Do you mean when to save a class attribute to an instance or how to calculate and save something _inside_ an instance? No matter what, it depends largely on your design. If some value is a permanent "feature" of an instance, it makes sense to save it as a member. If the value must always be calculated on the fly, it makes sense to use a function that returns it. Also check the docs on Python's "property" feature. > (2) > when to use class methods and when to use functions ? Functions are best used if you just "do" something that isn't focused on a specific class or object type. Class methods are best used if there is something to "do" that always needs the class object. > In my opinion, both of class methods and functions have advantages > and disadvantages. I have to pass many arguments to a function, > which is annoying. Yep. But there are also recipes to let functions store and reuse parameters, I think. > When using class methods, the arguments can be stored as > attributes of the class, which is convenient for later use. But I > have to create an object in advance. But only a class object, which exists when you have defined a class. Class methods don't operate on instances. All you asked depends much on specific design. So if you provide some details, I'm sure at least one here will have a hint. Regards, Bj?rn -- BOFH excuse #208: Your mail is being routed through Germany ... and they're censoring us. From whamil1 at entergy.com Thu May 10 11:25:37 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Thu, 10 May 2007 10:25:37 -0500 Subject: keyword checker - keyword.kwlist Message-ID: <588D53831C701746A2DF46E365C018CE01D2CA96@LITEXETSP001.etrsouth.corp.entergy.com> > From: tom at finland.com > > Hi > > I try to check whether a given input is keyword or not. However this > script won't identify keyword input as a keyword. How should I modify it > to make it work? > > #!usr/bin/env python > import keyword > > input = raw_input('Enter identifier to check >> ') > if input in keyword.kwlist: > print input + "is keyword" > > else: > print input + "is not keyword" It works fine for me. Well, it did once I realized that 'keyword.py' was not a good name to save the file under. --- -Bill Hamilton From stefan.sonnenberg at pythonmeister.com Sun May 6 23:32:21 2007 From: stefan.sonnenberg at pythonmeister.com (Stefan Sonnenberg-Carstens) Date: Mon, 07 May 2007 05:32:21 +0200 Subject: import conflict In-Reply-To: <1178504177.697440.23740@p77g2000hsh.googlegroups.com> References: <1178504177.697440.23740@p77g2000hsh.googlegroups.com> Message-ID: <463E9DC5.70501@pythonmeister.com> rplzqx402 at sneakemail.com schrieb: > Hello, > > I have a problem where I need to set up two separate Python projects > that each live under the same package. Once they are distributed, > they will live under the same filesystem path, but during development, > they are separated. > > For example: > proj1/lib/pkg/foo/mod1.py > proj2/lib/pkg/bar/mod2.py > > Furthermore, proj1 is dependent on proj2, so I want to be able to say > things like this, from within proj1: > > import pkg.foo.mod1 > import pkg.bar.mod2 > > Of course this doesn't work, even with a PYTHONPATH configured to see > both projects, because it will find 'pkg' in proj1/lib and so pkg.bar > will be hidden from view. > > Any suggestions? > > Thanks! > > Hi, my only suggestion would be to overthink your project organization. You can surely solve that problem with symlinks, but if they depend on another, perhaps the structure is not optimal. If you use python 2.5 you can try absolute imports (which I personally find not so well): from __future__ import absolute_import See here: http://python.mirrors-r-us.net/dev/peps/pep-0328/ Cheers, Stefan From kay.schluehr at gmx.net Wed May 9 21:16:32 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 9 May 2007 18:16:32 -0700 Subject: Erlang style processes for Python Message-ID: <1178759792.268979.206630@p77g2000hsh.googlegroups.com> Every once in a while Erlang style [1] message passing concurrency [2] is discussed for Python which does not only imply Stackless tasklets [3] but also some process isolation semantics that lets the runtime easily distribute tasklets ( or logical 'processes' ) across physical processes. Syntactically a tasklet might grow out of a generator by reusing the yield keyword for sending messages: yield_expr : 'yield' ([testlist] | testlist 'to' testlist) where the second form is specific for tasklets ( one could also use a new keyword like "emit" if this becomes confusing - the semantics is quite different ) and the addition of a new keyword for assigning the "mailbox" e.g: required_stmt: 'required' ':' suite So tasklets could be identified on a lexical level ( just like generators today ) and compiled accordingly. I just wonder about sharing semantics. Would copy-on-read / copy-on-write and new opcodes be needed? What would happen when sharing isn't dropped at all but when the runtime moves a tasklet around into another OS level thread / process it will be pickled and just separated on need? I think it would be cleaner to separate it completely but what are the costs? What do you think? [1] http://en.wikipedia.org/wiki/Erlang_programming_language [2] http://en.wikipedia.org/wiki/Actor_model [3] http://www.stackless.com/ From mail at microcorp.co.za Fri May 4 01:31:29 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 4 May 2007 07:31:29 +0200 Subject: 32 OS on 64-bit machine References: <1178183424.548438.303170@y80g2000hsf.googlegroups.com> Message-ID: <025d01c78e1a$9dd00ca0$03000080@hendrik> "SamG" wrote: > If anyone has a x86_64 machine and is running a 32bit OS on top of > that.... could you tell me what output would you get for the following > program > > #====================== > import platform > print platform.processor() > print platform.architecture() > #====================== > not copy pasted - the new machine is not on the network yet the answers look like: i686 and ('32bit','') Suse 10 gave me a warning during installation last night... the machine is an HP Compaq Celeron D - Hendrik From ptmcg at austin.rr.com Thu May 3 11:08:36 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 3 May 2007 08:08:36 -0700 Subject: problem with meteo datas In-Reply-To: References: Message-ID: <1178204916.426232.115500@e65g2000hsc.googlegroups.com> On May 3, 4:08 am, "napol... at tin.it" wrote: > ----Messaggio originale---- > Da: napol... at tin.it > Data: 3-mag-2007 > 10.02 > A: > Ogg: problem with meteo datas > > Hello, > I'm Peter and I'm new in python codying and I'm using parsying > to > extract data from one meteo Arpege file. > This file is long file and > it's composed by word and number arguments like this: > > GRILLE EURAT5 > Coin Nord-Ouest : 46.50/ 0.50 Coin Sud-Est : 44.50/ 2.50 > MODELE PA > PARAMETRE P > NIVEAU MER 0 ECHEANCE 0.0 DATE 20020304000000 NB_POINTS > 25 > 1020.91 1020.87 1020.91 1021.05 1021.13 > > 1020.07 1020.27 1020.49 1020.91 1021.15 > 1019.37 > 1019.65 1019.79 1020.53 1020.77 > 1018.73 1018.89 > 1019.19 1019.83 1020.81 > 1018.05 1018.19 1018.75 > 1019.55 1020.27 > NIVEAU MER 0 ECHEANCE 3.0 DATE 20020304000000 > NB_POINTS 25 > 1019.80 1019.78 1019.92 1020.18 1020.34 > 1018.94 1019.24 1019.54 1020.08 1020.32 > 1018.24 > 1018.64 1018.94 1019.84 1019.98 > 1017.48 1017.88 > 1018.28 1018.98 1019.98 > 1016.62 1017.08 1017.66 > 1018.26 1018.34 > NIVEAU MER 0 ECHEANCE 6.0 DATE 20020304000000 > NB_POINTS 25 > 1019.37 1019.39 1019.57 ........ > ........ Peter - Your first attempt at pyparsing is a good step - just get something working! You've got a first pattern working that detects and extracts all decimal numbers. (I think you are the first one to model a decimal number as a delimited list of integers with "." as the delimiter.) The next step is to start looking for some higher-level text groups or patterns. Your data is well structured as an n-level hierarchy, that looks to me like: - model+parameter - level - nb_points - level - nb_points - level - nb_points - model+parameter - level - nb_points - level - nb_points ... You can build your pyparsing grammar from the ground up, first to parse individual terminal expressions (such as decimal numbers which you already have), and then buld up to more and more complex structures within your data. The first thing to change about your approach is to start looking at this data as a whole, instead of line by line. Instead of extracting this first line of 5 point values: 1020.91 1020.87 1020.91 1021.05 1021.13 look at this as one piece of a larger structure, a data set for a given niveau: NIVEAU MER 0 ECHEANCE 0.0 DATE 20020304000000 NB_POINTS 25 1020.91 1020.87 1020.91 1021.05 1021.13 1020.07 1020.27 1020.49 1020.91 1021.15 1019.37 1019.65 1019.79 1020.53 1020.77 1018.73 1018.89 1019.19 1019.83 1020.81 1018.05 1018.19 1018.75 1019.55 1020.27 So let's create a parser for this structure that is the next step up in the data hierarchy. NIVEAU, ECHEANCE, DATE, and NB_POINTS are helpful labels for marking the data, but not really important to return in the parsed results. So I will start by creating definitions for these labels which will parse them, but leave out (suppress) them from the returned data: NIVEAU, ECHEANCE, DATE, NB_POINTS = \ map(Suppress,"NIVEAU ECHEANCE DATE NB_POINTS" .split()) You stated that there are several options for what a niveau identifier can look like, so this should be its own expression: niveau_ref = Literal("MER 0") | Literal("SOL 0") | \ Combine(Literal("HAUTEUR ") + eurodec) (I defined eurodec as you defined dec, but with a comma delimiter.) I'll also define a dateString as a Word(nums) of exactly 14 digits, but you can come back to this later and refine this as you like (build in parse-time conversion for example). dateString = Word(nums,exact=14) And then you can create an expression for a full niveau's-worth of data: niveau = NIVEAU + niveau_ref + ECHEANCE + dec + DATE + dateString + NB_POINTS + countedArray(dec) Notice that we can use the pyparsing built-in countedArray to capture all of the data point values, since NB_POINTS gives the number of points to follow, and these are followed immediately by the points themselves. Pyparsing will convert all of these into a nice n-element list for us. You astutely requested that these values should be accessible like values in a dict, so we do this in pyparsing by adding results names: niveau = NIVEAU + niveau_ref.setResultsName("niveau") + \ ECHEANCE + dec.setResultsName("echeance") + \ DATE + dateString.setResultsName("date") + \ NB_POINTS + countedArray(dec).setResultsName("nb_points") Now you should be able to search through your data file, extracting all of the niveaux (?) and their related data: f=file("arqal-Arpege.00", "r") fdata = f.read() # read the entire file, instead of going line-by- line for n in niveau.searchString(fdata): print n.niveau print n.dump() pointValues = map(float,n.nb_points[0]) print "- NB_POINTS mean:", sum(pointValues) / len(pointValues) print (I also added some examples of extracting data using the results names. You can also use dict-style notation, n["niveau"], if you prefer.) Gives this output (I've truncated with '...' for the sake of Usenet posting, but the actual program gives the full lists of values): MER 0 ['MER 0', '0.0', '20020304000000', ['1020.91', '1020.87', ... - date: 20020304000000 - echeance: 0.0 - nb_points: [['1020.91', '1020.87', '1020.91', '1021.05', ... - niveau: MER 0 - NB_POINTS mean: 1020.0052 MER 0 ['MER 0', '3.0', '20020304000000', ['1019.80', '1019.78', ... - date: 20020304000000 - echeance: 3.0 - nb_points: [['1019.80', '1019.78', '1019.92', '1020.18', ... - niveau: MER 0 - NB_POINTS mean: 1018.9736 MER 0 ['MER 0', '48.0', '20020304000000', ['1017.84', '1017.46', ... - date: 20020304000000 - echeance: 48.0 - nb_points: [['1017.84', '1017.46', '1017.14', '1016.86', ... - niveau: MER 0 - NB_POINTS mean: 1015.9168 HAUTEUR 2 ['HAUTEUR 2', '0.0', '20020304000000', ['1.34', '1.51', '1.40', ... - date: 20020304000000 - echeance: 0.0 - nb_points: [['1.34', '1.51', '1.40', '0.56', '-0.36', '1.73', ... - niveau: HAUTEUR 2 - NB_POINTS mean: 0.9028 HAUTEUR 2,4 ['HAUTEUR 2,4', '3.0', '20020304000000', ['1.34', '1.51', '1.40', ... - date: 20020304000000 - echeance: 3.0 - nb_points: [['1.34', '1.51', '1.40', '0.56', '-0.36', '1.73', ... - niveau: HAUTEUR 2,4 - NB_POINTS mean: 0.9028 Now I'll let you take this the next step: compose the expression for the model+parameter hierarchy level (hint: the body of each model +parameter value will be an expression of OneOrMore( Group( niveau ) ) - be sure to give this a results name, too). -- Paul From see.signature at no.spam Wed May 16 11:04:19 2007 From: see.signature at no.spam (Eric Brunel) Date: Wed, 16 May 2007 17:04:19 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <7x4pmg716p.fsf@ruckus.brouhaha.com> <4648EC26.8020907@v.loewis.de> Message-ID: On Wed, 16 May 2007 16:29:27 +0200, Neil Hodgson wrote: > Eric Brunel: > >> Have you ever tried to enter anything more than 2 or 3 characters like >> that? > > No, only for examples. Lengthy texts are either already available > digitally or are entered by someone skilled in the language. > > > I did. It just takes ages. Come on: are you really serious about >> entering *identifiers* in a *program* this way? > > Are you really serious about entry of identifiers in another > language being a problem? Yes. > Most of the time your identifiers will be available by selection > from an autocompletion list or through cut and paste. Auto-completion lists have always caused me more disturbance than help. Since - AFAIK - you have to type some characters before they can be of any help, I don't think they can help much here. I also did have to copy/paste identifiers to program (because of a broken keyboard, IIRC), and found it extremely difficult to handle. Constant movements to get every identifier - either by keyboard or with the mouse - are not only unnecessary, but also completely breaks my concentration. Programming this way takes me 4 or 5 times longer than being able to type characters directly. > Less commonly, you'll know what they sound like. Highly improbable in the general context. If I stumble on a source code in Chinese, Russian or Hebrew, I wouldn't be able to figure out a single sound. > Even more rarely you'll only have a printed document. I wonder how that could be of any help. > Each of these can be handled reasonably considering their frequency of > occurrence. I have never learned Japanese but have had to deal with > Japanese text at a couple of jobs and it isn't that big of a problem. > Its certainly not "virtually impossible" nor is there "absolutely no way > of entering the word" (???). I think you should moderate your > exaggerations. I do admit it was a bit exaggerated: there actually are ways. You know it, and I know it. But what about the average guy, not knowing anything about Japanese, kanji, radicals and stroke counts? How will he manage to enter these funny-looking characters, perhaps not even knowing it's Japanese? And does he have to learn a new input method each time he stumbles across identifiers written in a character set he doesn't know? And even if he finds a way, the chances are that it will be terribly inefficient. Having to pay attention on how you can type the things you want is a really big problem when it comes to programming: you have a lot of other things to think about. -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From mangabasi at gmail.com Wed May 23 15:29:05 2007 From: mangabasi at gmail.com (Mangabasi) Date: 23 May 2007 12:29:05 -0700 Subject: Inheriting from Python list object(type?) In-Reply-To: <1179947949.769537.91920@r3g2000prh.googlegroups.com> Message-ID: <1179948545.205715.306090@g4g2000hsf.googlegroups.com> On May 23, 2:19 pm, Lyosha wrote: > On May 23, 12:07 pm, Mangabasi wrote: > > > On May 23, 1:43 pm, "Jerry Hill" wrote: > > > > On 23 May 2007 11:31:56 -0700, Mangabasi wrote: > > > > > When I modified this to: > > > > > class Point(list): > > > > def __init__(self,x,y): > > > > super(Point, self).__init__([x, y]) > > > > self.x = x > > > > self.y = y > > > > > It worked. > > > > Are you sure? > > > > >>> p = Point(10, 20) > > > >>> p > > > [10, 20] > > > >>> p.x > > > 10 > > > >>> p.x = 15 > > > >>> p > > > [10, 20] > > > >>> p[0] > > > 10 > > > >>> p.x > > > 15 > > > > That doesn't look like what you were asking for in the original post. > > > I'm afraid I don't know anything about numpy arrays or what special > > > attributes an object may need to be put into a numpy array though. > > > > -- > > > Jerry > > > This is the winner: > > > class Point(list): > > def __init__(self, x, y, z = 1): > > super(Point, self).__init__([x, y, z]) > > self.x = x > > self.y = y > > self.z = z > > [...] > > http://docs.python.org/dev/whatsnew/node3.htmlannounces named tuples > in python2.6. This is not what you want since tuples are immutable, > but you might get some inspiration from their implementation. Or > maybe not. This looks very interesting. Currently I am using ver. 2.4. In the future I will consider this. Tuples may be better when I have to deal with a lot of points. For my test cases lists vs. tuples are not making a big difference yet. I have a hunch that I will end up with tuples though. From anil_jacob at comcast.net Tue May 8 19:07:31 2007 From: anil_jacob at comcast.net (anil_jacob at comcast.net) Date: Tue, 08 May 2007 23:07:31 +0000 Subject: e-mailing multiple values Message-ID: <050820072307.24482.464102B3000B7E4300005FA222135753330D010C0E06A10407020E@comcast.net> I have a script which has a method which returns multiple strings at once using the yield. I would like to send an e-mail of these values in a single e-mail instead of a mail for each string. How would I be able to do that? Thanks AJ From irmen.NOSPAM at xs4all.nl Fri May 25 13:06:18 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Fri, 25 May 2007 19:06:18 +0200 Subject: Shared Memory Space - Accross Apps & Network In-Reply-To: References: <1179913683.260600.283420@q69g2000hsb.googlegroups.com> Message-ID: <46571794$0$320$e4fe514c@news.xs4all.nl> Hendrik van Rooyen wrote: >>> Just to get the ball rolling, I'd suggest two things: >>> >>> Pyro -http://pyro.sf.net > > This is good advice, if you have the power to run it. What do you mean exactly by "the power to run it"? --Irmen From rene at korteklippe.de Tue May 15 07:17:13 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 15 May 2007 13:17:13 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <464996b9$0$10193$9b4e6d93@newsspool4.arcor-online.net> Steven D'Aprano schrieb: > >> A Python >> project that uses Urdu identifiers throughout is just as useless >> to me, from a code-exchange point of view, as one written in Perl. > > That's because you can't read it, not because it uses Unicode. It could > be written entirely in ASCII, and still be unreadable and impossible to > understand. That is a reason to actively encourage people to write their code in English whereever possible, not one to allow non-ASCII identifiers, which might even do the opposite. >> - Unicode is harder to work with than ASCII in ways that are more >> important >> in code than in human-language text. Humans eyes don't care if two >> visually indistinguishable characters are used interchangeably. >> Interpreters do. There is no doubt that people will accidentally >> introduce mistakes into their code because of this. > > That's no different from typos in ASCII. There's no doubt that we'll give > the same answer we've always given for this problem: unit tests, pylint > and pychecker. Maybe it is no different (actually, I think it is: With ASCII, at least my terminal font can display all the identifiers in a traceback), but why do you want to create *more* possibilities to do mistakes? -- Ren? From joshua at eeinternet.com Wed May 2 17:45:48 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Wed, 02 May 2007 13:45:48 -0800 Subject: I wish that [].append(x) returned [x] References: <46379a41$0$25252$88260bb3@free.teranews.com> <1178053211.209905.154030@h2g2000hsg.googlegroups.com> <4638e263$0$16368$88260bb3@free.teranews.com> Message-ID: <4638fa2e$0$16322$88260bb3@free.teranews.com> On Wednesday 02 May 2007 12:05, Tobiah wrote: > >> In addition to the above good advice, in case you are submitting a query >> to a DB-API compliant SQL database, you should use query parameters >> instead of building the query with string substitution. > > I tried that a long time ago, but I guess I found it to be > more awkward. I imagine that it is quite a bit faster that way? > I'm using MySQLdb. The issue is not speed, it's security. Query parameters are automatically escaped to prevent SQL injection attacks. j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE -- Posted via a free Usenet account from http://www.teranews.com From hpj at urpla.net Thu May 10 14:08:06 2007 From: hpj at urpla.net (Hans-Peter Jansen) Date: Thu, 10 May 2007 20:08:06 +0200 Subject: trouble with generators References: <5agru2F2ovai8U1@mid.uni-berlin.de> Message-ID: Hi Diez, first, thanks for your comprehensive answer. Diez B. Roggisch wrote: > Hans-Peter Jansen schrieb: >> >> I'm trying to generate a bunch of similar classes, where some are >> contained in list attributes of others, e.g.: > > All your code below shows that you don't create classes, but _instances_ > of classes. So - is that what you mean to do? Yes, exactly. Sorry for the confusion.. > > In a nutshell, you do this: > > b = B() > res = [] > for i in xrange(3): > b.id = i > res.append(b) > > Always the same b. > > What you seem to want is this > > >>> class B(object): > ... pass > ... > >>> res = [] > >>> for i in xrange(3): > ... class BSubClass(B): > ... pass > ... BSubClass.id = i > ... res.append(BSubClass) > ... > >>> print [c.id for c in res] > [0, 1, 2] > > I'm still not sure what you want - do you want instances created, or > classes? For the former, you need constructor calls on your classes, and > pass the class instead of an instance. Like this: > > > class B(object): > pass > > > def g(cls): > for i in xrange(3): > o = cls() > o.id = i > yield o > > list(g(B)) Yes, that did the trick. Silly me. Rookie error. Here's what I was after: #!/usr/bin/env python # -*- coding: utf8 -*- class A(object): "A" def __init__(self): self.id = None self.b = [] class B(object): "B" def __init__(self): self.id = None class Gen(object): "Gen" def records(self, cls): for n in range(3): i = cls() i.id = "%s%s" % (i.__doc__, n) yield i class GenA(Gen): def __init__(self): self.genB = GenB() def records(self): for a in Gen.records(self, A): for b in self.genB.records(): a.b.append(b) yield a class GenB(Gen): def records(self): return Gen.records(self, B) aRecs = [] bRecs = [] for i, r in enumerate(GenB().records()): bRecs.append(r) print i, r.id, r for i, r in enumerate(GenA().records()): aRecs.append(r) print i, r.id, r for b in r.b: print b.id, b created pretty nice different _instances_ of what I wanted: 0 B0 <__main__.B object at 0xb7cacfec> 1 B1 <__main__.B object at 0xb7cae04c> 2 B2 <__main__.B object at 0xb7cae08c> 0 A0 <__main__.A object at 0xb7cae12c> B0 <__main__.B object at 0xb7cae1ac> B1 <__main__.B object at 0xb7cae1ec> B2 <__main__.B object at 0xb7cae22c> 1 A1 <__main__.A object at 0xb7cae16c> B0 <__main__.B object at 0xb7cae2ac> B1 <__main__.B object at 0xb7cae2ec> B2 <__main__.B object at 0xb7cae32c> 2 A2 <__main__.A object at 0xb7cae26c> B0 <__main__.B object at 0xb7cae3ac> B1 <__main__.B object at 0xb7cae3ec> B2 <__main__.B object at 0xb7cae42c> Didn't found the forest because all the trees. Thanks again. Greetings to Berlin, Pete From gagsl-py2 at yahoo.com.ar Tue May 22 17:39:38 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 22 May 2007 18:39:38 -0300 Subject: The use of universal_newlines in subprocess References: <465305A0.5010201@gmail.com> Message-ID: En Tue, 22 May 2007 12:00:48 -0300, Joel Andres Granados escribi?: > I have been working with the universal_newlines option that can be > specified while using the subprocess module. I'm calling an app that > uses sys.stdout.write('\r'+' '*80) to manage its stdout. The situation > that I encountered was that when I wanted to log this output into a file > it looked rather freaky, so I needed to change the way the output was > logged. I found the answer in the universal_newlines option (it > basically changed all the \r for \n, which is a good idea in my case). > When I read the documentation for the universal_newline it stated that > "Also, the newlines attribute of the file objects stdout, stdin and > stderr are not updated by the communicate() method.". So I did not use > the communicate method thinking that it could not be used for my > purpose. After some hours of trying to make it work without the > communicate method I decide to use it and to my surprise it worked. So > my question is what does " are not updated by the communicate() method " > mean in the documentation. "Universal" newlines means that any of "\r\n", "\r", "\n" is interpreted as a line separator (and translated into a single "\n" on input). File objects have an attribute "newlines", which is a tuple (or a single string, or None) containing all newline variants seen till now in that file. The docs are simply saying that communicate() does not update said attribute, that is, after a call to communicate() you can't inspect the "newlines" attribute to see which newline variants have been received. -- Gabriel Genellina From gherron at islandtraining.com Fri May 11 12:21:59 2007 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 11 May 2007 09:21:59 -0700 Subject: Simple Python REGEX Question In-Reply-To: <1178898871.781501.135170@p77g2000hsh.googlegroups.com> References: <1178898871.781501.135170@p77g2000hsh.googlegroups.com> Message-ID: <46449827.1000208@islandtraining.com> johnny wrote: > I need to get the content inside the bracket. > > eg. some characters before bracket (3.12345). > > I need to get whatever inside the (), in this case 3.12345. > > How do you do this with python regular expression? > >>> import re >>> x = re.search("[0-9.]+", "(3.12345)") >>> print x.group(0) 3.12345 There's a lot more to the re module, of course. I'd suggest reading the manual, but this should get you started. Gary Herron From newsgroups at nospam.demon.co.uk Sun May 20 03:48:31 2007 From: newsgroups at nospam.demon.co.uk (Douglas Woodrow) Date: Sun, 20 May 2007 08:48:31 +0100 Subject: python shell References: <1179337107.842668.112690@k79g2000hse.googlegroups.com> <1179552984.466321.137550@u30g2000hsc.googlegroups.com> Message-ID: <7HNE7MEP1$TGFwtY@woodrowhorsfall.plus.com> On Sat, 19 May 2007 21:42:27, Steve Holden wrote > http://en.wikipedia.org/wiki/Doctest >Since you claim to be exercising your pedantry, I wonder why I get the >results I do. Since we *are* being pedantic, by the way, surely the >name is actually "doctest", not "Doctest". Yes, as the page you are referring to mentions right at the top: ,---------------- | Doctest | From Wikipedia, the free encyclopedia | | The correct title of this article is doctest. The initial letter is shown | capitalized due to technical restrictions. `---------------- -- Doug Woodrow From mccredie at gmail.com Thu May 17 11:53:10 2007 From: mccredie at gmail.com (Matimus) Date: 17 May 2007 08:53:10 -0700 Subject: Newbie: Joining Lists In-Reply-To: <1179395397.157566.209330@l77g2000hsb.googlegroups.com> References: <1179395397.157566.209330@l77g2000hsb.googlegroups.com> Message-ID: <1179417190.465570.18440@q23g2000hsg.googlegroups.com> One: Not that I know of Two: You could use list comprehension... ----------------------- CODE ---------------------- import os import glob patterns = ('.\\t*.py', '.\\*.c??', '.\\*.txt') filenames = [glob.glob(pat) for pat in patterns] # Or as a one liner... filenames = [glob.glob(pat) for pat in ('.\\t*.py', '.\\*.c??', '.\ \*.txt')] # Also, I don't think specifying the current directory is necessary. So this should also work: filenames = [glob.glob(pat) for pat in ('t*.py', '*.c??', '*.txt')] From mensanator at aol.com Fri May 4 20:03:49 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 4 May 2007 17:03:49 -0700 Subject: How to check if a string is empty in python? In-Reply-To: References: <1178302751.544971.281270@y5g2000hsa.googlegroups.com> Message-ID: <1178323429.322071.282990@h2g2000hsg.googlegroups.com> On May 4, 1:31 pm, "Hamilton, William " wrote: > > -----Original Message----- > > From: mensana... at aol.com > > > On May 4, 5:02 am, Jaswant wrote: > > > This is a simple way to do it i think > > > > s=hello > > > > >>> if(len(s)==0): > > > > ... print "Empty" > > > ... else: > > > ... print s > > > ... > > > hello > > > But you are still making the assumption that s is a string. > > (BTW, you need quotes around your example.) > > > For example: > > > >>> print a,b > > 11 11 > > > Can you tell which one is the string? I.e., which one had quotes > > around it? > > > If you correctly assume that it was b, then yes, your example works. > > > >>> print len(b) > > 2 > > > If you incorrectly assume it was a, then the example doesn't work. > > > >>> print len(a) > > Traceback (most recent call last): > > File "", line 1, in > > print len(a) > > TypeError: object of type 'int' has no len() > > > You have to know that a variable is a string before you try to do a > > len(). > > > Dynamic typing is a feature, but that doesn't relieve you of the > > necessary tests. > > Your point would be important if the question were "How can I tell if x > is an empty string?" On the other hand, "How to check if a string is > empty?" implies that the OP already knows it is a string. Maybe he's > been using string methods on it, maybe he got it from a function that he > knows provides a string. Maybe he's checked its type. It doesn't really > matter, if he's aware it is a string he doesn't have to test it for > stringness. OTOH, some don't know enough to quote their string literals, so I think my point is well justified. > > --- > -Bill Hamilton From ptmcg at austin.rr.com Mon May 14 09:17:58 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 14 May 2007 06:17:58 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <1179148678.765153.93290@n59g2000hsh.googlegroups.com> On May 14, 4:30?am, Nick Craig-Wood wrote: > > A variable called OHM etc! > -- > Nick Craig-Wood --http://www.craig-wood.com/nick Then can 'lambda' -> '?' be far behind? (I know this is a keyword issue, not covered by this PEP, but I also sense that the 'lambda' keyword has always been ranklesome.) In my own personal English-only experience, I've thought that it would be helpful to the adoption of pyparsing if I could distribute class name translations, since so much of my design goal of pyparsing is that it be somewhat readable as in: integer = Word(nums) is 'an integer is a word composed of numeric digits'. By distributing a translation file, such as: Palabra = Word Grupo = Group etc. a Spanish-speaker could write their own parser using: numero = Palabra(nums) and this would still pass the "fairly easy-to-read" test, for that user. While my examples don't use any non-ASCII characters, I'm sure the issue would come up fairly quickly. As to the responder who suggested not mixing ASCII/Latin with, say, Hebrew in any given identifier, this is not always possible. On a business trip to Israel, I learned that there are many terms that do not have Hebrew correspondents, and so Hebrew technical literature is sprinkled with English terms in Latin characters. This is especially interesting to watch being typed on a terminal, as the Hebrew characters are written on the screen right-to-left, and then an English word is typed by switching the editor to left-to-right mode. The cursor remains in the same position and the typed Latin characters push out to the left as they are typed. Then typing in right-to-left mode is resumed, just to the left of the Latin characters just entered. -- Paul From tinaweb at bestemselv.com Wed May 16 01:44:48 2007 From: tinaweb at bestemselv.com (Tina I) Date: Wed, 16 May 2007 07:44:48 +0200 Subject: Distributing programs depending on third party modules. In-Reply-To: <53357$4649c4a6$4275d90a$20775@FUSE.NET> References: <53357$4649c4a6$4275d90a$20775@FUSE.NET> Message-ID: <-J6dnUQxANzMB9fbRVnzvAA@telenor.com> Kevin Walzer wrote: > > What platform are you doing this on? On the Linux platform, "dependency > hell" of this sort is pretty much unavoidable, because there are so many > different packaging systems (apt, rpm, and so on): it's standard to let > the package manager handle these dependencies. And yes, it is > frustrating for end users. I mainly write apps for Linux although some are in theory cross platform (but I don't have Windows to test on so I don't really care about that part). Of course catering to every concievable package management system is impossible so I'm looking for something to make it easy for people to use the app as it is. > > There are other methods for distributing "frozen binaries," including > the freeze module that ships with Python itself, cx_freeze, and > PyInstaller: these three may work on Linux/Unix as well as Windows (they > are not supported on the Mac). But the methods above are generally the > ones most widely used. > A binary would be ideal. I'll look into the freeze modules and Pyinstaller. Even if they don't handle huge things like Qt it would be a step in the right direction if it handles smaller third part modules. And maybe the smartest thing to do would be to dump PyQt and just go for tkinter, however ugly it is :/ Anyways, thanks for the help people Tina From gagsl-py2 at yahoo.com.ar Mon May 14 15:03:56 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 14 May 2007 16:03:56 -0300 Subject: Recursion limit problems References: <1178921877.442519.165740@u30g2000hsc.googlegroups.com> <1179156916.706892.144770@y80g2000hsf.googlegroups.com> Message-ID: En Mon, 14 May 2007 12:35:16 -0300, elventear escribi?: > Since I am defining a hash for my object, it makes sense that I should > be able to define equality. But I am not sure about inequality, in my > specific case. The paragraph above mentions that __cmp__ should be > defined if I define a __hash__, but in the default behaviour of > __cmp__ inequality is included. So what should I do? Also why is > equality necessary to be defined? Do dicts only use __hash__ or do > they use equality as well? Dicts and sets use the key's hash value to determine the "bucket" where the key will be placed, and == to distingish between different objects with the same hash value. That is, you should define __hash__ and one of (__cmp__ or __eq__). __neq__ (inequality) isn't required nor used by dict/set implementation. (Anyway, Python will transform a!=b into not(a==b), if __neq__ isn't defined). Neither <, <=, >, >= are used. The important thing is that, if two objects compare equal, they must have the same hash value. That is: (a==b) => (hash(a)==hash(b)) (the reciprocal is not true). -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Sun May 27 11:34:44 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 27 May 2007 12:34:44 -0300 Subject: PyPI bdist_wininst upload failing References: <1180249872.007145.48030@a26g2000pre.googlegroups.com> Message-ID: En Sun, 27 May 2007 12:19:03 -0300, Steven Bethard escribi?: > Also, I couldn't get the StringIO code from there to work: > > >>> import StringIO > >>> content = open('argparse-0.8.0.win32.exe').read() Use open("...","rb").read() - the "b" is important on Windows. -- Gabriel Genellina From pahprints at comcast.net Mon May 21 11:26:53 2007 From: pahprints at comcast.net (Van & Phyllis) Date: Mon, 21 May 2007 08:26:53 -0700 Subject: Want to touch Lisa Simpson's pussy?!!?!!! Message-ID: <4651BA3D.5080909@comcast.net> From stargaming at gmail.com Wed May 2 15:46:59 2007 From: stargaming at gmail.com (Stargaming) Date: Wed, 02 May 2007 21:46:59 +0200 Subject: Lazy evaluation: overloading the assignment operator? In-Reply-To: <1178133344.415521.118710@n76g2000hsh.googlegroups.com> References: <1178133344.415521.118710@n76g2000hsh.googlegroups.com> Message-ID: sturlamolden wrote: > Python allows the binding behaviour to be defined for descriptors, > using the __set__ and __get__ methods. AFAIK, __getattribute__ calls them *explicitly*. > I think it would be a major > advantage if this could be generalized to any object, by allowing the > assignment operator (=) to be overloaded. > > One particular use for this would be to implement "lazy evaluation". > For example it would allow us to get rid of all the temporary arrays > produced by NumPy. > > For example, consider the expression: > [snip] > > y = a * b + c * d > > would then result in something like this: > > tmp1 = LazyExpr('__mul__',a,b) # symbolic representation of "a * b" > tmp2 = LazyExpr('__mul__',c,d) # symbolic representation of "c * d" > tmp3 = LazyExpr('__add__',tmp1,tmp1) # symbolic "a * b + c * d" > del tmp1 > del tmp2 > y = tmp3 # tmp3 gets evaluated as assignment is overloaded > To allow lazy evaluation, you need overloading of the assignment operator? Where should you overload it? y is less than None when you do that assignment. I don't really see the need for overloading here. Following the binding rules, __mul__ would (even without any hackery) be evaluated before __add__. > > Should there be a PEP to overload the assignment operator? If -- after this discussion -- community seems to like this feature, you could try to come up with some patch and a PEP. But not yet. > In terms of > syntax, it would not be any worse than the current descriptor objects > - but it would make lazy evaluation idioms a lot easier to implement. -- Stargaming From aleax at mac.com Fri May 18 10:12:06 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 18 May 2007 07:12:06 -0700 Subject: Python Web Programming - looking for examples of solid high-traffic sites References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> <1hy9yf9.1nnsttj139za6bN%aleax@mac.com> Message-ID: <1hyarxo.iqtdo1v9qpivN%aleax@mac.com> Jarek Zgoda wrote: > Daniel Nogradi napisa?(a): > > >> For example, it HAS been published elsewhere that YouTube uses lighttpd, > >> not Apache: . > > > > How do you explain these, then: > > > > http://www.youtube.com/results.xxx > > http://www.youtube.com/results.php > > http://www.youtube.com/results.py > > Server signature is usually configurable. Yeah, but I don't know why it's configured it that way. A good example of a question that looks perfectly appropriate for YouTube's OSCON session. Alex From ajayre at gmail.com Thu May 17 15:10:54 2007 From: ajayre at gmail.com (ajayre at gmail.com) Date: 17 May 2007 12:10:54 -0700 Subject: Creating a Python Type in C - tp_init and tp_new Message-ID: <1179429054.518950.240520@y80g2000hsf.googlegroups.com> I'm creating a type in a C function as follows: static PyObject *Receive(PyObject *self, PyObject *args) { pyMessageObject *msgobj = PyObject_New(pyMessageObject, &pyMessageType); return (PyObject *)msgobj; } I have (some lines omitted): static PyTypeObject pyMessageType = { PyObject_HEAD_INIT(NULL) ... pyMessage_Init, /*tp_init*/ 0, /*tp_alloc*/ pyMessage_New, /*tp_new*/ }; I have noticed that pyMessage_New and pyMessage_Init are not called. However if the type is created in Python then they are called. Why is this and how can I solve it? Thanks, Andy (please reply to the newsgroup only - thanks) From george.sakkis at gmail.com Sun May 20 22:22:21 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 20 May 2007 19:22:21 -0700 Subject: converting strings to most their efficient types '1' --> 1, 'A' ---> 'A', '1.2'---> 1.2 In-Reply-To: <1179529661.555196.13070@k79g2000hse.googlegroups.com> References: <1179529661.555196.13070@k79g2000hse.googlegroups.com> Message-ID: <1179714141.595881.186240@z24g2000prd.googlegroups.com> On May 18, 7:07 pm, py_genetic wrote: > Hello, > > I'm importing large text files of data using csv. I would like to add > some more auto sensing abilities. I'm considing sampling the data > file and doing some fuzzy logic scoring on the attributes (colls in a > data base/ csv file, eg. height weight income etc.) to determine the > most efficient 'type' to convert the attribute coll into for further > processing and efficient storage... > > Example row from sampled file data: [ ['8','2.33', 'A', 'BB', 'hello > there' '100,000,000,000'], [next row...] ....] > > Aside from a missing attribute designator, we can assume that the same > type of data continues through a coll. For example, a string, int8, > int16, float etc. > > 1. What is the most efficient way in python to test weather a string > can be converted into a given numeric type, or left alone if its > really a string like 'A' or 'hello'? Speed is key? Any thoughts? > > 2. Is there anything out there already which deals with this issue? There are several replies to your immediate column type-guessing problem, so I'm not going to address that. Once you decide the converters for each column, you have to pass the dataset through them (and optionally rearrange or omit some of them). That's easy to hardcode for a few datasets with the same or similar structure but it soon gets tiring. I had a similar task recently so I wrote a general and efficient (at least as far as pure python goes) row transformer that does the repetitive work. Below are some examples from an Ipython session; let me know if this might be useful and I'll post it here or at the Cookbook. George #======= RowTransformer examples ============================ In [1]: from transrow import RowTransformer In [2]: rows = [row.split(',') for row in "1,3.34,4-3.2j,John", "4,4,4,4", "0,-1.1,3.4,None"] In [3]: rows Out[3]: [['1', '3.34', '4-3.2j', 'John'], ['4', '4', '4', '4'], ['0', '-1.1', '3.4', 'None']] # adapt the first three columns; the rest are omitted In [4]: for row in RowTransformer([int,float,complex])(rows): ...: print row ...: [1, 3.3399999999999999, (4-3.2000000000000002j)] [4, 4.0, (4+0j)] [0, -1.1000000000000001, (3.3999999999999999+0j)] # return the 2nd column as float, followed by the 4th column as is In [5]: for row in RowTransformer({1:float, 3:None})(rows): ....: print row ....: [3.3399999999999999, 'John'] [4.0, '4'] [-1.1000000000000001, 'None'] # return the 3rd column as complex, followed by the 1st column as int In [6]: for row in RowTransformer([(2,complex),(0,int)])(rows): ....: print row ....: [(4-3.2000000000000002j), 1] [(4+0j), 4] [(3.3999999999999999+0j), 0] # return the first three columns, adapted by eval() # XXX: use eval() only for trusted data In [7]: for row in RowTransformer(include=range(3), default_adaptor=eval)(rows): ....: print row ....: [1, 3.3399999999999999, (4-3.2000000000000002j)] [4, 4, 4] [0, -1.1000000000000001, 3.3999999999999999] # equivalent to the previous In [8]: for row in RowTransformer(default_adaptor=eval, exclude=[3]) (rows): ....: print row ....: [1, 3.3399999999999999, (4-3.2000000000000002j)] [4, 4, 4] [0, -1.1000000000000001, 3.3999999999999999] From bbxx789_05ss at yahoo.com Tue May 15 21:56:56 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 15 May 2007 18:56:56 -0700 Subject: inherit from file and create stdout instance? In-Reply-To: References: <1179267498.154549.58370@h2g2000hsg.googlegroups.com> <1179270178.281061.34860@k79g2000hse.googlegroups.com> <1179272294.058634.140760@k79g2000hse.googlegroups.com> Message-ID: <1179280616.341224.171590@h2g2000hsg.googlegroups.com> On May 15, 7:43 pm, "Gabriel Genellina" wrote: >>... def __getattr__(self, name): >>... return getattr(self.file, name) Nice. From malaclypse2 at gmail.com Mon May 7 16:20:53 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 7 May 2007 16:20:53 -0400 Subject: is for reliable? In-Reply-To: References: Message-ID: <16651e80705071320n2cff715dgb965f5b8bc4c1304@mail.gmail.com> On 5/7/07, pabloski at giochinternet.com wrote: > for fn in cachefilesSet: ... > this code stops at the 473th file instead of reaching 1398 This is often caused by mutating the object you are iterating over inside the for loop. I didn't see anything in the code you posted that would do that, but you also didn't show us all of your code. Are you doing anything that would change cachefilesSet inside your for loop? If so, try looping over a copy of your set instead: from copy import copy for fn in copy(cachefilesSet): ... -- Jerry From admin at loial.co.uk Tue May 1 07:13:28 2007 From: admin at loial.co.uk (loial) Date: 1 May 2007 04:13:28 -0700 Subject: Problems with time Message-ID: <1178018008.341271.300880@n59g2000hsh.googlegroups.com> I am running on an AIX system with time zone set to BST If I run the following, I get the GMT time, i.e an hour less than the correct time. How can I get the correct time now = time() timeProcessed = strftime("%H:%M",gmtime(now)) From mr.williamchang at gmail.com Fri May 25 20:44:10 2007 From: mr.williamchang at gmail.com (William Chang) Date: 25 May 2007 17:44:10 -0700 Subject: printing list, is this a bug? In-Reply-To: References: <1180126524.884163.234040@k79g2000hse.googlegroups.com> Message-ID: <1180140250.230991.245260@k79g2000hse.googlegroups.com> oh okay. thanks. From laurent.pointal at limsi.fr Wed May 2 10:01:41 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Wed, 02 May 2007 16:01:41 +0200 Subject: pack/unpack zero terminated string In-Reply-To: <1178114191.580368.59520@c35g2000hsg.googlegroups.com> References: <1178114191.580368.59520@c35g2000hsg.googlegroups.com> Message-ID: tmp123 a ?crit : > Hello, > > Thanks for your time. > > After review the "struct" documentation, it seems there are no option > to pack/unpack zero terminated strings. > > By example, if the packed data contains: byte + zero terminated string > + zero terminated string + byte, it seems no possible to unpack it > using "struct". > > Please, has someone any hint or pointer to another librarian to be > used? May look at xstruct too http://www.sis.nl/python/xstruct/xstruct.shtml From katiemeery at yahoo.com Thu May 17 06:38:11 2007 From: katiemeery at yahoo.com (katiemeery at yahoo.com) Date: 17 May 2007 03:38:11 -0700 Subject: Personal Computers (PC's) contains a lot of info Message-ID: <1179398291.279599.110930@q75g2000hsh.googlegroups.com> Personal Computers (PC's) contains a lot of info that the average user doesn't usually know. At http://PCTermDefinitions.com there is extensive infomation related to this topic (all free). Along with a link portal to other PC computer related sites. From whamil1 at entergy.com Tue May 22 11:35:07 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Tue, 22 May 2007 10:35:07 -0500 Subject: 'int' object is not callable in an threaded app Message-ID: <588D53831C701746A2DF46E365C018CE01D2CAA7@LITEXETSP001.etrsouth.corp.entergy.com> > From: king kikapu > > Hi, > > i have a problem with the following piece of code that id just drive > me nuts (from the morning...) > I think is more Python specific than Qt, folks from Qt forum have > already give me directions of how to do it but that Python error > message is just impossible for me to figure out. And i am sure that it > something just under my nose... > > So, i have a form with 2 spin boxes, a button and a progress bar. When > i hit the button i expect to see the progressbar filled with the > values of spFrom and spTo (the 2 spinboxes) > > I was given help if how to setup correctly the Signals and Slots > mechanism but i am stuck at this Python error at the "worker.start()" > command: > > TypeError: 'int' object is not callable > > > Before i go and suicide, has anybody an idea what is going on > here ??... > > > > import sys > from PyQt4 import QtCore, QtGui > from calculatorform_ui import Ui_CalculatorForm > from ui_countNumbers import Ui_MainWindow > from time import sleep > > class WorkerThread(QtCore.QThread): > def __init__(self, start, end): > QtCore.QThread.__init__(self) > self.start = start > self.end = end > > def run(self): > for x in range(start, end): > self.emit(QtCore.SIGNAL("updateProgress"), x) > > > class CountNumbersForm(QtGui.QMainWindow): > def __init__(self, parent=None): > QtGui.QMainWindow.__init__(self, parent) > self.ui = Ui_MainWindow() > self.ui.setupUi(self) > > @QtCore.pyqtSignature("") > def on_start_clicked(self): > worker.start() > > def updateProgress(self, val): > self.ui.progres.setValue(val) > > > if __name__ == "__main__": > app = QtGui.QApplication(sys.argv) > count = CountNumbersForm(); > worker = WorkerThread(count.ui.spFrom.value(), > count.ui.spTo.value() + 1); > QtCore.QObject.connect(worker, QtCore.SIGNAL("updateProgress"), > count.updateProgress, QtCore.Qt.QueuedConnection) > count.show() > sys.exit(app.exec_()) It appears that worker.start gets set to the result of count.ui.spFrom.value(). If that result is an int, then worker.start() is going to generate the TypeError you received. Did you actually mean to call worker.run() instead? --- -Bill Hamilton From rene at korteklippe.de Tue May 15 10:33:44 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 15 May 2007 16:33:44 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <464996b9$0$10193$9b4e6d93@newsspool4.arcor-online.net> <4649a72d$0$10186$9b4e6d93@newsspool4.arcor-online.net> <4649aca1$0$23148$9b4e6d93@newsspool1.arcor-online.net> <4649b6e0$0$23143$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <4649c4c6$0$10189$9b4e6d93@newsspool4.arcor-online.net> Thorsten Kampe schrieb: > You could actually try by giving some arguments for your opinion. Your > rationale was "English only, please" because of "code sharing". I thought this was pretty clear. The more people can easily read code, the higher the probability that it will be useful for them and that they can make it more useful for others. >> That completely depends on how you look at code-sharing. My impression >> always was that the Python community in general does regard code-sharing >> as A Good Thing. > > I don't think the "Python community" does that because for something > to be considered good it should actually be clear what it means. So > what actually is "Code sharing"?! Wikipedia seems to know this term > but in a slightly different meaning: > > http://en.wikipedia.org/wiki/Code_sharing I think we all know what "code" in the context of Python means. As for "to share", I think that is pretty clear, also. It means that people other than the original authors use, study and modify the code. FWIW, a Google search for 'Python code-sharing' yields almost 30k results. > If the "Python community" would think that "code sharing" (whatever > that means) is per se a good thing it would switch to spaces only > allowed (instead of tabs and spaces allowed). There is PEP 8 that encourages the use of spaces only. Personally, I would not have much of a problem with tabs being banned for indentation. Maybe the main reason why that is not actually done is compatibility with legacy code -- I don't know. > Actually it would > refrain from giving indentation and white space a syntactical meaning > because this undoubtedly makes "code sharing" (on web pages or through > news readers for instance) /a lot/ more difficult. Where did anyone say that code-sharing is the only concern? I just think that it is undoubtedly one among others. So for something that harms this concern to be done, there should be substantial benefits in it. I fail to see them with non-ASCII identifiers so far. -- Ren? From tjreedy at udel.edu Thu May 10 15:33:31 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 10 May 2007 15:33:31 -0400 Subject: Towards faster Python implementations - theory References: <1210i.7468$2v1.2505@newssvr14.news.prodigy.net><1178705421.711371.182770@e65g2000hsc.googlegroups.com> <1178821414.998672.247260@w5g2000hsg.googlegroups.com> Message-ID: wrote in message news:1178821414.998672.247260 at w5g2000hsg.googlegroups.com... | The idea is to create a special dictionary for python internals that | contains a pointer-to-a-pointer for the value side of the dictionary, | instead of just the standard PyObject*. Then when you start to eval a | code block, you could do a one-time lookup of the pointer-to-the- | pointer for each method, attribute, etc; and store them in pre- | allocated slots. The calls in the block to various GET_ and SET_ | functions can then just deal with pointer derefencing instead of a | dictionary lookup, and the dictionary can still get changed while this | is going on without things blowing up. | | I think you'd get a big speed up by changing all those dictionary | function calls to inlined pointer deref code. | | Anyone else buy this approach? Or see any fatal flaws? Within CPython functions, local variables are usually implemented as numbered slots in a C array (of PyObject pointers). There is why a) the compiler makes a first pass thru a function body (to determine what is local and what is not) and b) LOAD_FAST is faster than LOAD_GLOBAL. Terry Jan Reedy From sjmachin at lexicon.net Fri May 11 19:45:05 2007 From: sjmachin at lexicon.net (John Machin) Date: 11 May 2007 16:45:05 -0700 Subject: Time In-Reply-To: <1178920014.621031.301860@n59g2000hsh.googlegroups.com> References: <1178916216.893542.257320@y80g2000hsf.googlegroups.com> <1178916422.065108.312920@l77g2000hsb.googlegroups.com> <1178920014.621031.301860@n59g2000hsh.googlegroups.com> Message-ID: <1178927105.482975.174760@y5g2000hsa.googlegroups.com> On May 12, 7:46 am, HMS Surprise wrote: [first message] HS ==> I need to convert the string below into epoch seconds so that I can perform substractions and additions. JM ==> I presume you mean "seconds since the epoch". You don't need to do that. HS ==> I assume I will need to break it up into a time_t struct and use mktime. JM ==> You assume wrongly. The time module exists (IMVHO) solely as a crutch for people who are converting C etc code that uses the time.h functions from the C standard library. If you are starting off from scratch, use the Python datetime module -- especially if you need to store and manipulate pre-1970 dates; e.g. the date of birth of anyone aged more than about 37.5 years :-) HS ==> Two questions if you will please: Is there a way to use multiple separator characters for split similar to awk's [|] style? JM ==> Only if you can find such a way in the manual. HS ==> Could you point to an example of a python time_t struct? JM ==> Python doesn't have that; it's a C concept HS ==> 05/11/2007 15:30 [second message] HS==> > Could you point to an example of a python time_t struct? Or maybe that should be a tm struct??? JM ==> See previous answer. [third message] HS ==> Sorry, reading a little closer I see that the time tuple is apparently an ordinary list. JM ==> Huh? A tuple is a tuple. A tuple is not a list, not even a very extraordinary one. If you are desperate to use the time module, try this: >>> import time >>> s = "05/11/2007 15:30" >>> fmt = "%m/%d/%Y %H:%M" # Given the current date, I'm presuming that your example indicates that you adhere to the "month-first-contrary-to-common-sense" religion :-) >>> time.strptime(s, fmt) (2007, 5, 11, 15, 30, 0, 4, 131, -1) otherwise: >>> import datetime >>> d1 = datetime.datetime.strptime(s, fmt) >>> d1 datetime.datetime(2007, 5, 11, 15, 30) >>> d2 = datetime.datetime(2007, 5, 1) >>> d2 datetime.datetime(2007, 5, 1, 0, 0) >>> delta = d1 - d2 >>> delta datetime.timedelta(10, 55800) >>> days_diff = delta.days + delta.seconds / 60. / 60. / 24. >>> days_diff 10.645833333333334 Do read the datetime module documentation for more info ... in particular the timedelta object has a microseconds attribute; in general there is a whole heap of functionality in there. HTH, John From dsampson at NRCan.gc.ca Thu May 10 12:57:57 2007 From: dsampson at NRCan.gc.ca (Sampson, David) Date: Thu, 10 May 2007 12:57:57 -0400 Subject: Python and Decimal integers from DB Message-ID: <2FAA57395C1F914DB27CAA4C376058F2025F7B74@S0-OTT-X2.nrn.nrcan.gc.ca> Hey folks Freshie looking for help.... This is what I am trying to do. Use PYODBC to hit an oracle DB that has a ODBC connection.\ \The code bellow works when I replace '*' with a specific collumn name that does not have commas in the number. It also works for alphanumberic values. It fails when I try '*' or any collumn that has a comman in the number. The numbers are Latitude longitude readings. I get back "Select Success" but not "fetch success" so I feel as thopugh something is missing on the fetchall() function So how do I get the numbers to be recognized by python? I did lots of searches on python, ODBC, PYODBC, Decimal us and commas as decimals and various combinations. Lots of mailing lists a few tutorials and lots of misses. I came across: Import decimal Decimal.Decimal() This works a bit. It took a coma separated number string and kept the first part. But that works only when I put in a raw value, it doesn't work on the Fetchall function. HELP PLEASE... Cheers ===============PYHTON CODE======================== import pyodbc conn = pyodbc.connect("DSN=NAPL;UID=NAPL_VIEW;PWD=NAPVIEW") curs = conn.cursor() roll_num = 'A27255' Cols = '*' Table = 'photos' Select = 'Select ' + Cols + ' from ' + Table + ' where roll_number = ' +"'" + roll_num + "'" curs.execute(Select) print "select sucess" rows= curs.fetchall() print "fetch success" for row in rows: print row.PHOTO_NUMBER print "done" ==================================== =================Standard Output ======================== Traceback (most recent call last): File "C:\Python25\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py" , line 310, in RunScript exec codeObject in __main__.__dict__ File "U:\My Documents\py_projects\georef\NAPL_DB.py", line 12, in rows= curs.fetchall() File "C:\Python25\lib\decimal.py", line 614, in __new__ self._sign, self._int, self._exp = context._raise_error(ConversionSyntax) File "C:\Python25\lib\decimal.py", line 2325, in _raise_error raise error, explanation InvalidOperation ==================================== -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed May 9 03:29:34 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 09 May 2007 09:29:34 +0200 Subject: change of random state when pyc created?? References: Message-ID: Alan Isaac wrote: > This may seem very strange, but it is true. > If I delete a .pyc file, my program executes with a different state! > Can someone explain this to me? There is nothing wrong with the random module -- you get the same numbers on every run. When there is no pyc-file Python uses some RAM to create it and therefore your GridPlayer instances are located in different memory locations and get different hash values. This in turn affects the order in which they occur when you iterate over the GridPlayer.players_played set. Here is a minimal example: import test # sic class T: def __init__(self, name): self.name = name def __repr__(self): return "T(name=%r)" % self.name if __name__ == "__main__": print set(T(i) for i in range(4)) $ python2.5 test.py set([T(name=2), T(name=1), T(name=0), T(name=3)]) $ python2.5 test.py set([T(name=3), T(name=1), T(name=0), T(name=2)]) $ python2.5 test.py set([T(name=3), T(name=1), T(name=0), T(name=2)]) $ rm test.pyc $ python2.5 test.py set([T(name=2), T(name=1), T(name=0), T(name=3)]) Peter From nospam at invalid.com Sat May 26 21:24:02 2007 From: nospam at invalid.com (Jack) Date: Sat, 26 May 2007 18:24:02 -0700 Subject: Large Amount of Data References: <1180228756.574525.16110@q19g2000prn.googlegroups.com> Message-ID: I'll save them in a file for further processing. "John Machin" wrote in message news:1180228756.574525.16110 at q19g2000prn.googlegroups.com... > On May 26, 6:17 pm, "Jack" wrote: >> I have tens of millions (could be more) of document in files. Each of >> them >> has other >> properties in separate files. I need to check if they exist, update and >> merge properties, etc. > > And then save the results where? > Option (0) retain it in memory > Option (1) a file > Option (2) a database > > And why are you doing this agglomeration of information? Presumably so > that it can be queried. Do you plan to load the whole file into memory > in order to satisfy a simple query? From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed May 30 10:20:42 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 30 May 2007 16:20:42 +0200 Subject: Key Listeners In-Reply-To: References: <1180491273.446164.281990@q75g2000hsh.googlegroups.com> <1180510259.914953.225420@h2g2000hsg.googlegroups.com> <465d64c4$0$7452$426a74cc@news.free.fr> Message-ID: <465d8831$0$17081$426a74cc@news.free.fr> kaens a ?crit : > On 5/30/07, Bruno Desthuilliers > wrote: >> Benedict Verheyen a ?crit : >> > bruno.desthuilliers at gmail.com schreef: >> >> On 30 mai, 04:14, Mike wrote: >> >>> Are there key listeners for Python? Either built in or third party? >> >> >> >> What is a "key listener" ? >> >> >> (snip) >> > In google, the first link is a link to the java sun home page. >> > The first sentence on that page: "Key events indicate when the user is >> > typing at the keyboard." >> >> I do know what's a "key listener" in Java, thanks !-) >> >> My question was supposed to have side effects - like the OP asking >> himself if he was really asking the right question. >> >> Regards too. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > What, he wants to know if there's a way in python to capture > keystrokes, and do something with them depending on what they are. Which would have been a much better way to express the question. > I mean, it's very unlikely that you would ask for something called a > "key listener" if you didn't want to do something like: > > if keypress == 'a': > do somem > > right? Wrong. *You* can deduce this from the OP question because you know Java (and more exactly : GUI programming in Java). As far as I'm concerned, a 'key listener' could be something observing adding/deletion of key/value couples in a dict !-) > Not to mention asking the OP "what's a key listener" isn't going to > make them think about the question they asked - it makes it seem like > you don't know what a key listener is Exactly. Which may lead the OP to the conclusion that not everybody knows Java GUI programming, and that it may be better to ask in more general terms... Also, and FWIW, there are words that name very different concepts in different languages. And I don't know each and every concept of each and every language in the world (perhaps you do ?). So, just because I know what name X means in langage Y doesn't necessarily imply the OP isn't thinking of what it means in langage ZZ... From hardcoded.software at gmail.com Thu May 3 22:03:57 2007 From: hardcoded.software at gmail.com (Virgil Dupras) Date: 3 May 2007 19:03:57 -0700 Subject: Decorating class member functions In-Reply-To: <1178241696.641350.292210@n59g2000hsh.googlegroups.com> References: <1178241696.641350.292210@n59g2000hsh.googlegroups.com> Message-ID: <1178244237.702552.201410@l77g2000hsb.googlegroups.com> On May 3, 9:21 pm, Andy Terrel wrote: > Okay does anyone know how to decorate class member functions? > > The following code gives me an error: > > Traceback (most recent call last): > File "decorators2.py", line 33, in > s.update() > File "decorators2.py", line 13, in __call__ > retval = self.fn.__call__(*args,**kws) > TypeError: update() takes exactly 1 argument (0 given) > > ------------------ > > #! /usr/bin/env python > > class Bugger (object): > def __init__ (self, module, fn): > self.module = module > self.fn = fn > > def __call__ (self,*args, **kws): > ret_val = self.fn(*args,**kws) > return ret_val > > def instrument (module_name): > ret_val = lambda x: Bugger(module_name, x) > return ret_val > > class Stupid: > def __init__(self): > self.val = 1 > > @instrument("xpd.spam") > def update(self): > self.val += 1 > > s = Stupid() > s.update() Second attempt. After some fuss around, I think it's just not possible to have a class instance as a decorator. the self gets lost in translation. #! /usr/bin/env python class Caller(object): def __init__ (self, fn): self.fn = fn def __call__(self, *args, **kwargs): print 'Caller calling!', repr(args) return self.fn(*args, **kwargs) def mydecorator(f): return Caller(f) class Stupid: def __init__(self): self.val = 1 @mydecorator def update(self): self.val += 1 s = Stupid() s.update() Caller calling! () Traceback (most recent call last): File "/Users/hsoft/Desktop/foo.py", line 22, in ? s.update() File "/Users/hsoft/Desktop/foo.py", line 8, in __call__ return self.fn(*args, **kwargs) TypeError: update() takes exactly 1 argument (0 given) But why do you want to use a class? If you want to have a decorator with argument, you only need to have something like: def instrument(module): def decorator(f): def wrapper(*args, **kwargs): print module return f(*args, **kwargs) return wrapper return decorator From S.Mientki-nospam at mailbox.kun.nl Wed May 9 14:43:21 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Wed, 09 May 2007 20:43:21 +0200 Subject: preferred windows text editor? In-Reply-To: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> References: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> Message-ID: PyScripter or JALcc Stef T. Crane wrote: > Right now I'm using Notepad++. What are other people using? > > trevis > > From gherzig at fmed.uba.ar Tue May 22 14:34:08 2007 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Tue, 22 May 2007 15:34:08 -0300 Subject: using google search api for python Message-ID: <465337A0.5080808@fmed.uba.ar> Hi all. Im looking for the pyGoogle for making google searchs y a python script. The thing is, all im founding is an AJAX api, but the application ill use is NOT a web app. So, someone know if there is a pure python api that i can download and use? Thanks! Gerardo From rzantow at gmail.com Tue May 22 21:36:11 2007 From: rzantow at gmail.com (rzed) Date: Wed, 23 May 2007 01:36:11 +0000 Subject: Printing dots in sequence ('...') References: Message-ID: "Tim Williams" wrote in news:mailman.8029.1179845747.32031.python-list at python.org: [...] > maybe this: (on Win32, don't know about *nix) > > for x in range(10): > print '.\b', better: print '\b.', -- rzed From joshbloom at gmail.com Thu May 31 11:29:04 2007 From: joshbloom at gmail.com (Josh Bloom) Date: Thu, 31 May 2007 08:29:04 -0700 Subject: Python memory handling In-Reply-To: <1180611604.247696.149060@h2g2000hsg.googlegroups.com> References: <1180611604.247696.149060@h2g2000hsg.googlegroups.com> Message-ID: If the memory usage is that important to you, you could break this out into 2 programs, one that starts the jobs when needed, the other that does the processing and then quits. As long as the python startup time isn't an issue for you. On 31 May 2007 04:40:04 -0700, frederic.pica at gmail.com wrote: > Greets, > > I've some troubles getting my memory freed by python, how can I force > it to release the memory ? > I've tried del and gc.collect() with no success. > Here is a code sample, parsing an XML file under linux python 2.4 > (same problem with windows 2.5, tried with the first example) : > #Python interpreter memory usage : 1.1 Mb private, 1.4 Mb shared > #Using http://www.pixelbeat.org/scripts/ps_mem.py to get memory > information > import cElementTree as ElementTree #meminfo: 2.3 Mb private, 1.6 Mb > shared > import gc #no memory change > > et=ElementTree.parse('primary.xml') #meminfo: 34.6 Mb private, 1.6 Mb > shared > del et #no memory change > gc.collect() #no memory change > > So how can I free the 32.3 Mb taken by ElementTree ?? > > The same problem here with a simple file.readlines() > #Python interpreter memory usage : 1.1 Mb private, 1.4 Mb shared > import gc #no memory change > f=open('primary.xml') #no memory change > data=f.readlines() #meminfo: 12 Mb private, 1.4 Mb shared > del data #meminfo: 11.5 Mb private, 1.4 Mb shared > gc.collect() # no memory change > > But works great with file.read() : > #Python interpreter memory usage : 1.1 Mb private, 1.4 Mb shared > import gc #no memory change > f=open('primary.xml') #no memory change > data=f.read() #meminfo: 7.3Mb private, 1.4 Mb shared > del data #meminfo: 1.1 Mb private, 1.4 Mb shared > gc.collect() # no memory change > > So as I can see, python maintain a memory pool for lists. > In my first example, if I reparse the xml file, the memory doesn't > grow very much (0.1 Mb precisely) > So I think I'm right with the memory pool. > > But is there a way to force python to release this memory ?! > > Regards, > FP > > -- > http://mail.python.org/mailman/listinfo/python-list > From carsten at uniqsys.com Mon May 28 09:17:55 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 28 May 2007 09:17:55 -0400 Subject: itertools.groupby In-Reply-To: <702263.11522.qm@web33504.mail.mud.yahoo.com> References: <702263.11522.qm@web33504.mail.mud.yahoo.com> Message-ID: <1180358275.3152.17.camel@localhost.localdomain> On Sun, 2007-05-27 at 18:12 -0700, Steve Howell wrote: > [...] there is no way > that "uniquekeys" is a sensible variable [...] That's because the OP didn't heed the advice from the docs that "Generally, the iterable needs to already be sorted on the same key function." > http://informixdb.blogspot.com/2007/04/power-of-generators-part-two.html > > > > Do we now, or could we, link to this example from the > docs? Do we? No. Could we? Technically we could, but I'm not sure we should. The article is about more than just groupby. I just brought it up as one readily available instance of an independent source of examples. > To repeat myself, I think a concrete example is > beneficial even on the main page: I disagree. Examples add clutter to the page of synopses. Somebody looking for examples should look on the page that's conveniently called Examples. Suppose hypothetically you wanted to show off a really neat example that involves chain, izip, and groupby. If the examples were forced into the page of function synopses, you'd have to duplicate it in all three functions, or randomly pick one function for which your example is an example. Having a separate examples page that is not arbitrarily sectioned by function name makes more sense. Best regards, -- Carsten Haese http://informixdb.sourceforge.net From godzillaismad at gmail.com Thu May 10 21:51:19 2007 From: godzillaismad at gmail.com (Godzilla) Date: 10 May 2007 18:51:19 -0700 Subject: how to use cx_Oracle callfunc Message-ID: <1178848279.652462.291690@e51g2000hsg.googlegroups.com> Hi all, I need to know how to use the method callfunc in cx_Oracle. I am trying to get a primary key after an insert via a function call, but I do not know how to pass the return value from the function via the callfunc method. Can anyone help? I also tried the execute(), and callproc(), but to no avail. My function is as below: create or replace function addRow(desc table1.col1%type) return number is id number; begin insert into table1 (description) values (desc) returning table1ID into id; return(id); exception when others then return(-1) end; The code in the callfunc: cur.callfunc("addRow", returnType, param) Question is: - What is returnType and how to I declare that before passing into the function? - How do I define the parameters? I tried the setinputsizes and setoutputsize, but I keep getting errors saying the parameter is incorrectly defined. Please help. Thank. From carsten at uniqsys.com Sun May 27 09:20:49 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sun, 27 May 2007 09:20:49 -0400 Subject: Is PEP-8 a Code or More of a Guideline? In-Reply-To: References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> Message-ID: <1180272049.3157.2.camel@localhost.localdomain> On Sun, 2007-05-27 at 07:30 +0000, OKB (not okblacke) wrote: > Underscores are harder to type than any alphanumeric character. This is a discussion about underscores versus capital letters denoting the word boundaries in identifiers. How is an underscore harder to type than a capital letter? -- Carsten Haese http://informixdb.sourceforge.net From steve at holdenweb.com Fri May 25 00:24:27 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 25 May 2007 00:24:27 -0400 Subject: sockets, gethostname() changing In-Reply-To: <1180062244.266857.300830@m36g2000hse.googlegroups.com> References: <1180062244.266857.300830@m36g2000hse.googlegroups.com> Message-ID: 7stud wrote: > Hi, > > I'm experimenting with a basic socket program(from a book), and both > the client and server programs are on my computer. In both programs, > I call socket.gethostname(), but I discovered that when I am connected > to the internet, both the client and server hang and nothing happens. > I discovered that the hostname of my computer automatically changes to > that of my isp when I'm connected to the internet, and presumably the > server program on my computer cannot listen on my isp's address(host, > port). Is there a way to make the hostname of my computer static, so > that it doesn't change to my isp's hostname when I connect to the > internet. I'm using mac os 10.4.7. Why does my computer's hostname > dynamically change in the first place? > > server program: > ------------------- > import socket > > s = socket.socket() > > host = socket.gethostname() > print host > port = 1274 > s.bind((host, port)) > > s.listen(5) > while("Ctrl-C hasn't been entered"): > c, addr = s.accept() #blocks and waits for client connection > print "Got socket connection from", addr > c.send("Thank you for connecting. Now get lost.") > c.close() > > > client program: > ------------------- > import socket > > s = socket.socket() > > host = socket.gethostname() > port = 1274 > > s.connect((host, port)) > print s.recv(1024) > s.close() > For local testing it is *much* easier to have your client and server use IP address 127.0.0.1 - this is the usual address on the "loopback" network, which doesn't require any physical network hardware to operate. Just as a matter of interest, what is socket.gethostname() returning? I suspect it will depend on whether you have established an interface specific domain suffix - I haven't, and I have no trouble with your 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From fsckedagain at gmail.com Thu May 3 12:18:10 2007 From: fsckedagain at gmail.com (fscked) Date: 3 May 2007 09:18:10 -0700 Subject: _csv.Error: string with NUL bytes In-Reply-To: References: <1178204593.280648.208040@c35g2000hsg.googlegroups.com> Message-ID: <1178209090.674787.202970@o5g2000hsb.googlegroups.com> On May 3, 9:11 am, Larry Bates wrote: > fscked wrote: > > Anyone have an idea of what I might do to fix this? I have googled adn > > can only find some random conversations about it that doesn't make > > sense to me. > > > I am basically reading in a csv file to create an xml and get this > > error. > > > I don't see any empty values in any fields or anything... > > You really should post some code and the actual traceback error your > get for us to help. I suspect that you have an ill-formed record in > your CSV file. If you can't control that, you may have to write your > own CSV dialect parser. > > -Larry Certainly, here is the code: import os,sys import csv from elementtree.ElementTree import Element, SubElement, ElementTree def indent(elem, level=0): i = "\n" + level*" " if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + " " for elem in elem: indent(elem, level+1) if not elem.tail or not elem.tail.strip(): elem.tail = i else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = i root = Element("{Boxes}boxes") myfile = open('test.csv', 'rb') csvreader = csv.reader(myfile) for boxid, mac, activated, hw_ver, sw_ver, heartbeat, name, address, phone, country, city, in csvreader: mainbox = SubElement(root, "{Boxes}box") mainbox.attrib["city"] = city mainbox.attrib["country"] = country mainbox.attrib["phone"] = phone mainbox.attrib["address"] = address mainbox.attrib["name"] = name mainbox.attrib["pl_heartbeat"] = heartbeat mainbox.attrib["sw_ver"] = sw_ver mainbox.attrib["hw_ver"] = hw_ver mainbox.attrib["date_activated"] = activated mainbox.attrib["mac_address"] = mac mainbox.attrib["boxid"] = boxid indent(root) ElementTree(root).write('test.xml', encoding='UTF-8') The traceback is as follows: Traceback (most recent call last): File "createXMLPackage.py", line 35, in ? for boxid, mac, activated, hw_ver, sw_ver, heartbeat, name, address, phone, country, city, in csvreader: _csv.Error: string with NUL bytes Exit code: 1 , 0001h From claird at lairds.us Mon May 7 08:49:25 2007 From: claird at lairds.us (Cameron Laird) Date: Mon, 7 May 2007 12:49:25 +0000 Subject: c macros in python. References: <1178485280.394666.51970@n76g2000hsh.googlegroups.com> Message-ID: In article , Amaury Forgeot d'Arc wrote: >noagbodjivictor at gmail.com a ?crit : >> Hey, >> >> I'm writing a script to generate code. I'm a bit tired of typing >> outfile.write(....). Does python have a way to c-like macros? Every >> instance of o(...) in the code will be replaced by outfile.write(...)? > >First: Python has no macro facility. . . . For the sake of completeness, I want to note that the standard distribution includes Tools/Scripts/ifdef.py, and pyparsing now has an example macro preprocessor. Neither of these would be the correct response to the original question, of course, but they might interest other readers who believe they need "c-like macros". From horpner at yahoo.com Thu May 24 08:49:07 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 24 May 2007 12:49:07 GMT Subject: converting text and spans to an ElementTree References: Message-ID: On 2007-05-23, Steven Bethard wrote: > Neil Cerutti wrote: >> On 2007-05-22, Steven Bethard wrote: >>> Thanks a lot! This put me on the right track (though the >>> devil's definitely in the details). It's working now:: >>> >>> >>>>>> tree = xmltools.text_and_spans_to_etree('aaa aaa aaaccc cccaaa', [ >>> ... (etree.Element('a'), 0, 21), >>> ... (etree.Element('b'), 11, 11), >>> ... (etree.Element('c'), 11, 18), >>> ... ]) >>>>>> etree.tostring(tree) >>> 'aaa aaa aaaccc cccaaa' >>>>>> tree = xmltools.text_and_spans_to_etree('bbb\naaaccc\ncccaaa', [ >>> ... (etree.Element('a'), 0, 17), >>> ... (etree.Element('b'), 0, 4), >>> ... (etree.Element('c'), 7, 14), >>> ... (etree.Element('b'), 14, 14), >>> ... ]) >>>>>> etree.tostring(tree) >>> 'bbb\naaaccc\ncccaaa' >>>>>> tree = xmltools.text_and_spans_to_etree('abc', [ >>> ... (etree.Element('a'), 0, 3), >>> ... (etree.Element('b'), 0, 3), >>> ... (etree.Element('c'), 0, 3), >>> ... ]) >>>>>> etree.tostring(tree) >>> 'abc' >>> >>> >>> And for the sake of any poor soul who runs into a similar >>> problem, here's the code I wrote using Gabriel's hints above:: >> >> When I saw you manually keeping a stack, I called Captain >> Recursion on my Red-Alert Recursion Phone. >> >> (I'm sorry he left out the Element stuff, which he doesn't know >> or use yet. The Captain's get_tree just returns the string) > > Heh heh. > > I actually thought about writing it recursively, but note that > you need both recursive and non-recursive parts of this > algorithm to do the ElementTree part right: You mean... I left out the hard part? Shucks. I had really hoped it didn't matter. > * the recursive (or stack) part assigns children to parents > * the non-recursive part assigns text or tail to the previous element > (note that's previous in a sequential sense, not a recursive sense) > > I'm sure I could implement this recursively, passing around > annother appropriate argument, but it wasn't obvious to me that > the code would be any cleaner. Moreover, it looks like you have experience in writing that sort of code. I'd have never even attempted it without recursion, but that's merely exposing one of my limitations. ;) -- Neil Cerutti From bbxx789_05ss at yahoo.com Fri May 4 18:39:01 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 4 May 2007 15:39:01 -0700 Subject: behavior difference for mutable and immutable variable in function definition In-Reply-To: <1178314206.701824.291560@n59g2000hsh.googlegroups.com> References: <1178314206.701824.291560@n59g2000hsh.googlegroups.com> Message-ID: <1178318341.669871.294390@n76g2000hsh.googlegroups.com> On May 4, 3:30 pm, jianbing.c... at gmail.com wrote: > Hi, > > Can anyone explain the following: > > Python 2.5 (r25:51908, Apr 9 2007, 11:27:23) > [GCC 4.1.1 20060525 (Red Hat 4.1.1-1)] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> def foo(): > > ... x = 2 > ...>>> foo() > >>> def bar(): > > ... x[2] = 2 > ... > > >>> bar() > > Traceback (most recent call last): > File "", line 1, in > File "", line 2, in bar > NameError: global name 'x' is not defined > > Thanks, > Jianbing The first function is completely irrelevant unless you expect this to work: x = 2 x[2] = 2 Traceback (most recent call last): File "test1.py", line 2, in ? x[2] = 2 TypeError: object does not support item assignment So that leaves you with: > >>> def bar(): > > ... x[2] = 2 > ... > > >>> bar() Would you expect this to work: x[2] = 2 print x From showell30 at yahoo.com Sat May 26 22:58:10 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sat, 26 May 2007 19:58:10 -0700 (PDT) Subject: ten small Python programs In-Reply-To: <1180232026.357074.186770@o5g2000hsb.googlegroups.com> Message-ID: <50977.22668.qm@web33501.mail.mud.yahoo.com> --- Paul McGuire wrote: > On May 26, 8:48 pm, Steve Howell > wrote: > > > > I'm thinking you could actually have a progression > > from a 1 line program up to a 50-line program. > The > > number 50 is kind of arbitrary, but my gut says > that > > by a 50-line program, you will have demonstrated > > almost every useful concept. > > > > If there is anything arbitrary here, I'd say it is > your "increment > each example by one source line" constraint. This > can force you to > use some bad coding practices to meet your target > line count for a > given example. > I understand your point, but I'm sticking to the concept for now. My intent with the progression isn't so much for each example to thoroughly teach a concept (although I could certainly hyperlink to a more in-depth treatment), but really more to give a bird's eye view of the language very quickly. I recently helped teach a Java programmer to program in Python, and he learned a lot just by seeing simple examples. So I guess my target audience isn't so much people learning how to program; it's more for programmers getting their first exposure to Python. On the other side of the fence, I recently tried to relearn a bit of Ruby, and I remember being frustrated by their tutorials, as really, I just wanted to see a bunch of simple programs, and I can figure out mostly what they're doing. Instead, I had to wade through verbose descriptions of what a variable is, rules for how you construct identifiers, etc. > Maybe try this approach: pick your top 10/20/50 > language features and > develop concise examples. Then order the examples by > length as a first > cut (longer examples probably *are* more complex), > and then reorder a > bit to handle pre-requisites (introduce a minimum of > new features, > preferably 1, per example). Overall, I'd have a > tough time picking > just 10 language features to illustrate, but there > are probably 10-20 > basic features that will get new people onto fairly > productive > ground. Pick 20 as your example count (50 sounds a > bit long), and > stick to it, and then later add "20 More Little > Programs" for the next > wave of examples in increasing complexity. > My only reluctance with that approach is that it sounds like a little more work than I'm ready to take on right away. But it's on the Wiki now, so maybe other folks can help me grow it. > One other nit to pick: have your example classes > inherit from object, > to get new people using new-style classes from the > get-go. > My only fear here is that when old classes go away (Py3K? I don't know), that practice may become obsolete. But on a more general note, I welcome folks to just clean up my examples on the Wiki if I accidentally introduce some bad practices...but preserving line counts. :) ____________________________________________________________________________________ Never miss an email again! Yahoo! Toolbar alerts you the instant new Mail arrives. http://tools.search.yahoo.com/toolbar/features/mail/ From SuperM at ssiveBlackHoleAtTheCenterOfTheMilkyWayGalaxy.org Sun May 6 09:40:04 2007 From: SuperM at ssiveBlackHoleAtTheCenterOfTheMilkyWayGalaxy.org (The Great Attractor) Date: Sun, 06 May 2007 06:40:04 -0700 Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> <08qk33t594ih0ulmjmev90d22lkfnotgoe@4ax.com> <463C2A3A.8332D211@hotmail.com> <0k8p33h90bp5tfajedb4bmd2eik8gfi2ho@4ax.com> Message-ID: <9lmr335jde9aiugs2dvcjh7eufgk0at3nr@4ax.com> On Sat, 05 May 2007 10:34:06 -0500, quasi wrote: >On Sat, 05 May 2007 07:54:50 +0100, Eeyore > wrote: > >> >> >>quasi wrote: >> >>> Gib Bogle wrote: >>> >>> >Ah, so the firefighters were in on the conspiracy! >>> >>> No, but the firefighters are very much aware that there is more to >>> 9/11 than has been officially revealed. >>> >>> This is even more true at Pentagon. The firefighters there brought >>> dogs trained to search for survivors and/or remains >> >>Sounds like good practice. >> >> >>> and found nothing. >> >>And the significance of this is ? > >The plane was supposed to have passengers. > You're a goddamned retard. From jjl at pobox.com Thu May 24 14:59:18 2007 From: jjl at pobox.com (John J. Lee) Date: Thu, 24 May 2007 18:59:18 GMT Subject: ClientForm .click() oddity References: Message-ID: <87bqgaqc87.fsf@pobox.com> Gordon Airporte writes: [...] > Simply .click()ing on the form does not properly fill in > submit_button=Forward&action=apply, however. The arguments are there > but with no values. > Is this because ClientForm doesn't run javascript, Yes. > or is there a way > to determine and fix these values without manually editing the .data > string of the Request with values I have to find on my own? No. (Strictly, it shouldn't be necessary to actually edit the data string -- you should be able to use the API to do it -- but I'm not sure that's fully documented and tested, so that may not work correctly. Either way, you have to do it manually.) John From darrinth at gmail.com Mon May 28 13:06:28 2007 From: darrinth at gmail.com (Darrin Thompson) Date: Mon, 28 May 2007 13:06:28 -0400 Subject: Build problems with sqlite on OSX Message-ID: I'm attempting to build python 2.5.1 fat binaries on OSX and statically link to a newer sqlite than what ships with OSX. (3.3.17). I'm getting "Bus Error" early when I run my app. If I turn on a lot of malloc debugging options and run under gdb I get this trace: (gdb) info threads * 1 process 18968 local thread 0x1003 0x900e41d1 in strtol_l () (gdb) bt #0 0x900e41d1 in strtol_l () #1 0x900160a5 in atoi () #2 0x9406fd80 in sqlite3InitCallback () #3 0x0381faf2 in sqlite3_exec (db=0x338d080, zSql=0x331f1e0 "SELECT name, rootpage, sql FROM 'main'.sqlite_master WHERE tbl_name='sqlite_sequence'", xCallback=0x9406fd00 , pArg=0xbfffde14, pzErrMsg=0x0) at ./src/legacy.c:93 #4 0x0384c769 in sqlite3VdbeExec (p=0x1945200) at ./src/vdbe.c:4090 #5 0x03816686 in sqlite3Step (p=0x1945200) at ./src/vdbeapi.c:236 #6 0x03816817 in sqlite3_step (pStmt=0x1945200) at ./src/vdbeapi.c:289 #7 0x0380b9aa in _sqlite_step_with_busyhandler (statement=0x1945200, connection=0x32a77a0) at /Users/pandora/build-toolchain/build/Python-2.5.1/Modules/_sqlite/util.c:33 #8 0x0380850d in cursor_executescript (self=0x32bd4d0, args=0x32a2d10) at /Users/pandora/build-toolchain/build/Python-2.5.1/Modules/_sqlite/cursor.c:788 #9 0x0020e6fc in PyObject_Call (func=0x329ecd8, arg=0x32a2d10, kw=0x0) at Objects/abstract.c:1860 #10 0x00292a36 in PyEval_CallObjectWithKeywords (func=0x329ecd8, arg=0x32a2d10, kw=0x0) at Python/ceval.c:3433 #11 0x0020e6cd in PyObject_CallObject (o=0x329ecd8, a=0x32a2d10) at Objects/abstract.c:1851 #12 0x03806e1c in connection_executescript (self=0x32a77a0, args=0x32a2d10, kwargs=0x0) at /Users/pandora/build-toolchain/build/Python-2.5.1/Modules/_sqlite/connection.c:1001 #13 0x002998ae in PyEval_EvalFrameEx (f=0x338c250, throwflag=0) at Python/ceval.c:3564 Can someone advise as to the correct configure arguments for sqlite or something else I might be missing? Thanks in advance. -- Darrin From ai.nature at gmail.com Thu May 31 22:22:59 2007 From: ai.nature at gmail.com (ai) Date: Thu, 31 May 2007 19:22:59 -0700 Subject: How to clean a module? In-Reply-To: <5c87f5F2mg4c1U1@mid.uni-berlin.de> References: <1180622824.836459.222090@q19g2000prn.googlegroups.com> <5c87f5F2mg4c1U1@mid.uni-berlin.de> Message-ID: <1180664579.182455.26170@g37g2000prf.googlegroups.com> Yes, you are right. But from this problem, could I infer that the statement "del xxx" doesn't release the memory which xxx used? On May 31, 11:21 pm, "Diez B. Roggisch" wrote: > ai schrieb: > > > It assumes that there is a module A which have two global variables X > > and Y. If I run "import A" in the IDLE shell, then I can use A.X and > > A.Y correctly. But if I want to change the module A and then delete > > the variable Y, I find I can use A.Y just the same as before! > > In fact, I have tried all the following methods but can't remove the > > A.Y: > > execute "import A" again > > "reload(A)" > > "del A; import A" > > Yes, if you use "del A.Y", it works. But it is stupid since there are > > probably many names. In my thought, if no one references objects in A, > > "del A" will release all memory about A. But it seems that the fact is > > not. So I can not refresh the namespace to follow changes of a module > > easily and I will worry about the memory if I del a module. > > I want to know if there is a way to clear a module entirely. > > There might be other answers - but the easiest and IMHO best is to > simply restart the interpreter. Because whatever you type in there, you > could or should even (if it reaches some complexity) put in a small test > script - and execute that from the interpreter at a shell prompt. The > advantage is that you don't suffer from any side-effects e.g. IDLE has > (no Tk mainloop for example) and avoid the problems you describe > entirely. Together with a bunch of others. > > If you want/have to, you can drop into interpreter mode after script > execution with > > python -i myscript.py > > Diez From saif.shakeel at gmail.com Wed May 9 07:39:20 2007 From: saif.shakeel at gmail.com (saif.shakeel at gmail.com) Date: 9 May 2007 04:39:20 -0700 Subject: replacing string in xml file In-Reply-To: <1178624770.794888.198450@e65g2000hsc.googlegroups.com> References: <1178623414.092046.91120@y5g2000hsa.googlegroups.com> <46405F73.3080501@web.de> <1178624770.794888.198450@e65g2000hsc.googlegroups.com> Message-ID: <1178710760.558710.262680@w5g2000hsg.googlegroups.com> On May 8, 4:46 pm, saif.shak... at gmail.com wrote: > On May 8, 4:30 pm, Stefan Behnel wrote: > > > > > > > saif.shak... at gmail.com schrieb: > > > > Hi, > > > I need to replace a string in xml file with something else.Ex > > > > - > > > rate > > > rate > > > > > > > > > > > > - > > > > Here i have opened an xml > > > file(small part is pasted here).I want to replace the word 'localId' > > > with 'dataPackageID' wherever it comes in xml file.I tried this but > > > didnt work: > > > > import sys > > > > file_input = raw_input("Enter The ODX File Path:") > > > input_xml = open(file_input,'r') > > > This should say > > > input_xml = open(file_input,'r').read() > > > > input_xml.replace('localId','dataPackageId') > > > This gives error ---> AttributeError: 'file' > > > object has no attribute 'replace' > > > Can someone help me . > > > Thanks > > > Stefan- Hide quoted text - > > > - Show quoted text - > > There is no error now,but the string is not being replaced,It remains > the same,should we save the opened file or something- Hide quoted text - > > - Show quoted text - HI, Thanks for the reply.that seems to work,but i was doing this so as to attach it to a bigger code where it will be utilised before a parsing. #Input file and Output file path from user file_input = raw_input("Enter The ODX File Path:") (shortname,ext)=os.path.splitext(file_input) f_open_out=shortname+".ini" log=shortname+".xls" test_file=shortname+"testxml.xml" saveout = sys.stdout input_xml = open(file_input,'r') xmlcont=input_xml.read() xmlcont=xmlcont.replace('localId','dataPackageId') output_file = open(test_file,"w") output_file.write(xmlcont) output_file.close() f_open=open(f_open_out, 'w') logfile=open(log,"w") sys.stdout = f_open #Parse the input file,and check for correct ODX version xmldoc = minidom.parse(input_xml) I am opening 2 more files in addition to the file where the new xml goes.One file is written using the sys.stdout command as most of the output has to go there printing takes place in many places (so cant use f_open.write) each time. When i attach the part of replacing the string 'localid' in xml file with something else as given above with xmlcont=xmlcont.replace('localId','dataPackageId') the code does not run and hangs.Can more than 3 files be opened at a time .I dotn know what the problem is here. Thanks From svenrech at gmx.de Fri May 11 18:57:05 2007 From: svenrech at gmx.de (Sven Rech) Date: Sat, 12 May 2007 00:57:05 +0200 Subject: find out all threads? Message-ID: <1178924225.6165.3.camel@sven-laptop> Hi, I have a written a C program which makes use of python embedding. I want to find out all threads that a loaded module has started. But I can't find anything about this in the docs. Is it possible? From gagsl-py2 at yahoo.com.ar Mon May 14 17:35:15 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 14 May 2007 18:35:15 -0300 Subject: os.listdir() doesn't work ?? References: <1179173881.163830.54930@n59g2000hsh.googlegroups.com> <91a85$4648d2cd$d443bb3a$3987@news.speedlinq.nl> Message-ID: En Mon, 14 May 2007 18:24:23 -0300, Stef Mientki escribi?: >>> files = os.listdir('D:\\akto_yk\\yk_controle\\*.txt') >>> >>> I get an error message >>> >>> WindowsError: [Errno 123] The filename, directory name, or volume >>> label syntax is incorrect: >>> 'D:\\akto_yk\\yk_controle\\*.txt/*.*' > Still don't know why it's not allowed through listdir ;-) Because listir expects a single directory as parameter, not a wildcard specification. That is, you could do: files = os.listdir("D:\\akto_yk\\yk_controle") to get ALL the filenames in that directory, and then filter them using fnmatch. But that's exactly what the glob module does internally. -- Gabriel Genellina From nagle at animats.com Thu May 24 00:46:01 2007 From: nagle at animats.com (John Nagle) Date: Thu, 24 May 2007 04:46:01 GMT Subject: using google search api for python In-Reply-To: References: <465337A0.5080808@fmed.uba.ar> Message-ID: Vyacheslav Maslov wrote: > Gerardo Herzig wrote: > >> Hi all. Im looking for the pyGoogle for making google searchs y a >> python script. The thing is, all im founding is an AJAX api, but the >> application ill use is NOT a web app. So, someone know if there is a >> pure python api that i can download and use? >> >> Thanks! >> Gerardo > > http://www.ibm.com/developerworks/webservices/library/ws-pyth14/ Can't use that any more. Google dropped their SOAP API a few months back. All they offer now is their AJAX API, which comes with restrictive contract terms. You have to display their data on screen in their format, although you can annotate it with info of your own, as long as that info isn't an ad. However, Yahoo offers a true search API: put in a URL, get XML back. Yahoo limits you to 5000 calls per day unless you talk to them about getting more requests. We use both of these, and our site is written in Python. Javascript in the browser is handling the interaction with the search engine, requesting ratings on the sites mentioned in the search results from our server, and displaying those ratings. http://www.sitetruth.com/yhoo.html for Yahoo http://www.sitetruth.com/goog.html for Google Ask (formerly Ask Jeeves) used to have the Teoma API, but they dropped that a few months back, and "xml.teoma.com" is now dead. Microsoft has a search API which is SOAP-based, but Microsoft wants you to access it via C# and .NET, and it's documented accordingly. There are "meta-search" engines that just screen scrape user-type results from other search engines, but for the major search engines, this violates the terms of service. John Nagle From gagsl-py2 at yahoo.com.ar Sat May 19 16:28:01 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 19 May 2007 17:28:01 -0300 Subject: Can't embed python in C++(Mingw[3.*] compiler) References: <1179591280.469302.289010@p77g2000hsh.googlegroups.com> Message-ID: En Sat, 19 May 2007 13:14:40 -0300, Arjun Narayanan escribi?: > For thr program, > #include "E:\Python25\include\Python.h" > #include Configure your environment so using: #include works (you may need to add E:\Python25\include to some list of searched directories, maybe an INCLUDE environment variable). -- Gabriel Genellina From steve at holdenweb.com Tue May 8 21:41:40 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 08 May 2007 21:41:40 -0400 Subject: SEO - Search Engine Optimization - Seo Consulting In-Reply-To: References: <1177808356.681710.42980@n76g2000hsh.googlegroups.com> <#O8fXGAjHHA.3700@TK2MSFTNGP06.phx.gbl> <1178160448.699851.227600@p77g2000hsh.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Wed, 02 May 2007 19:47:28 -0700, Huck Phin wrote: [a request for peace, love and understanding, concluding with] >> We all should be a little more considerate of each other. > > And if the hippy hug fest fails to stop spamming, perhaps we'll be allowed > to hunt them down like rabid dogs and stick their heads up on pikes as a > warning to others. > > Hey, a man can dream can't he??? *wink* > > Yeah, just ONE day a year when we could roast them on spits over open fires ... just to discourage the survivors, you understand. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From rw at smsnet.pl Fri May 18 15:15:10 2007 From: rw at smsnet.pl (Rob Wolfe) Date: Fri, 18 May 2007 21:15:10 +0200 Subject: emacs python debugging: pydb or pdb fringe interaction References: <87k5v61qpc.fsf@rudin.co.uk> <87veeqnf5q.fsf@merkury.smsnet.pl> <87sl9u9ceo.fsf@rudin.co.uk> Message-ID: <87r6pendtt.fsf@merkury.smsnet.pl> Paul Rudin writes: > Unfortunately this doesn't make any difference for me, with either > emacs 22 or 21. I guess I'll just have to dig deeper into the code. So what happens after M-x pdb? From nogradi at gmail.com Sun May 13 12:27:17 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Sun, 13 May 2007 18:27:17 +0200 Subject: elementtree and entities Message-ID: <5f56302b0705130927s26be7b14t519a0269a350e90a@mail.gmail.com> Hi list, How does one prevent elementtree converting & to & (and similarly for other entities)? >>> from xml.etree import ElementTree as et >>> x = et.Element( 'test' ) >>> x.text = '&' >>> et.tostring( x ) '&' Sometimes I would like to have the output '&' Daniel From steve at holdenweb.com Fri May 25 07:27:37 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 25 May 2007 07:27:37 -0400 Subject: stdlib doc for logger.findCaller() needs update. In-Reply-To: <1180080963.742418.170360@q75g2000hsh.googlegroups.com> References: <1179918325.803451.76820@o5g2000hsb.googlegroups.com> <1180080963.742418.170360@q75g2000hsh.googlegroups.com> Message-ID: <4656C829.1000001@holdenweb.com> Vinay Sajip wrote: > On May 23, 12:05 pm, jitu... at hotmail.com wrote: >> The logger objects findCaller() method is returning a "3" element >> tuple instead of "2" two as >> documented in the 2.4.4 Python Library Reference .DocString is showing >> it correctly. > > I've updated the docs - the next 2.4.x release should have them. > Thanks for the report. > Is a further 2.4 release planned? I'd have thought that unless a security issue appears the answer is likely to be "no". 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From wildemar at freakmail.de Fri May 25 20:46:33 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Sat, 26 May 2007 02:46:33 +0200 Subject: Module listing in order. In-Reply-To: References: <1179905562.541601.264400@m36g2000hse.googlegroups.com> <1180120016.349259.9540@x18g2000prd.googlegroups.com> Message-ID: <46578369.5050408@freakmail.de> Peter Otten wrote: > Ramashish Baranwal wrote: > > >>>> I want a way to get the contents in the order of their declaration, >>>> i.e. [B, A, D]. Does anyone know a way to get it? >>>> >>> My suggestion would be to actually parse the text of the module. "Brute >>> force" is what it's called ;). But doing so with, say, pyparsing >>> shouldn't be *very* difficult. >>> > > >> Nevertheless, it would be interesting to see how it can be done.:) >> > > >>>> import pyclbr >>>> classes = pyclbr.readmodule("mymodule") >>>> sorted(classes, key=lambda name: classes[name].lineno) >>>> > ['B', 'A', 'D'] > > Good God! Is there *anything* that python does not already do? I hardly feel the need to write programs anymore ... Its really 80% like of the questions that are asked here get answered along the lines of: import some_fancy_module solution = some_fancy_module.exactly_the_right_function_to_solve(problem) Kinda scary ... :) W From gagsl-py2 at yahoo.com.ar Mon May 28 06:45:51 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 28 May 2007 07:45:51 -0300 Subject: Issue of redirecting the stdout to both file and screen References: <1180343858.903251.182490@x35g2000prf.googlegroups.com> Message-ID: En Mon, 28 May 2007 06:17:39 -0300, ??????????????? escribi?: > I wanna print the log to both the screen and file, so I simulatered a > 'tee' > > class Tee(file): > > def __init__(self, name, mode): > file.__init__(self, name, mode) > self.stdout = sys.stdout > sys.stdout = self > > def __del__(self): > sys.stdout = self.stdout > self.close() > > def write(self, data): > file.write(self, data) > self.stdout.write(data) > > Tee('logfile', 'w') > print >>sys.stdout, 'abcdefg' > > I found that it only output to the file, nothing to screen. Why? > It seems the 'write' function was not called when I *print* something. You create a Tee instance and it is immediately garbage collected. I'd restore sys.stdout on Tee.close, not __del__ (you forgot to call the inherited __del__ method, btw). Mmm, doesn't work. I think there is an optimization somewhere: if it looks like a real file object, it uses the original file write method, not yours. The trick would be to use an object that does NOT inherit from file: import sys class TeeNoFile(object): def __init__(self, name, mode): self.file = open(name, mode) self.stdout = sys.stdout sys.stdout = self def close(self): if self.stdout is not None: sys.stdout = self.stdout self.stdout = None if self.file is not None: self.file.close() self.file = None def write(self, data): self.file.write(data) self.stdout.write(data) def flush(self): self.file.flush() self.stdout.flush() def __del__(self): self.close() tee=TeeNoFile('logfile', 'w') print 'abcdefg' print 'another line' tee.close() print 'screen only' del tee # should do nothing -- Gabriel Genellina From learned at gmail.com Thu May 24 00:23:56 2007 From: learned at gmail.com (Denrael) Date: 23 May 2007 21:23:56 -0700 Subject: Accessing iTunes with Python via the Windows SDK Message-ID: <1179980636.045976.145070@q75g2000hsh.googlegroups.com> I've been playing with the iTunes sdk on windows, and have come across a strange problem. With the following code: import win32com.client iTunes = win32com.client.gencache.EnsureDispatch("iTunes.Application") curr = iTunes.CurrentTrack name = curr.Name skipped = curr.SkippedCount skipdate = curr.SkippedDate print name print skipped print skipdate I get an error indicating that SkippedCount isn't a valid attribute: File "C:\bin\skiptest.py", line 5, in skipped = curr.SkippedCount File "C:\Python25\Lib\site-packages\win32com\client\__init__.py", line 454, in __getattr__ raise AttributeError, "'%s' object has no attribute '%s'" % (repr(self), att r) AttributeError: ' x14463944>' object has no attribute 'SkippedCount' If I comment out the lines referring to SkippedCount and SkippedDate, it works just fine. As far as I can tell from testing the same code in VBS, there should be no difference in how SkippedCount is accessed vs. how Name is accessed. I'm new to Python. Is anyone out there using iTunes that may have an idea? Thanks Den From blsecres at gmail.com Tue May 1 08:09:38 2007 From: blsecres at gmail.com (Ben Secrest) Date: Tue, 1 May 2007 12:09:38 +0000 (UTC) Subject: sqlite for mac? References: <1177993261.572563.70370@n76g2000hsh.googlegroups.com> <5f56302b0705010308h5c3f64a8ka05cd92de879f6bd@mail.gmail.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 2007-05-01, Daniel Nogradi wrote: >> Does sqlite come in a mac version? >> > > The interface (pysqlite) is part of the python 2.5 standard library > but you need to install sqlite itself separately (as far as I > remember) from www.sqlite.org http://developer.apple.com/documentation/MacOSX/Conceptual/OSX_Technology_Overview/AppTechnology/chapter_5_section_20.html - -- Ben Secrest -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (NetBSD) iD8DBQFGNy4DeLi5NDZQ3o0RAtVOAJ9AglHEPH/9HUKIsLLWIkaNwoZC8QCaAy7T MC8VhXY2MyOyp2DaJAPOb0I= =UGAL -----END PGP SIGNATURE----- From jx.ygressier at lapostex.net Wed May 30 07:48:33 2007 From: jx.ygressier at lapostex.net (Jgressier) Date: Wed, 30 May 2007 13:48:33 +0200 Subject: Python + Prolog Message-ID: <465d649f$0$5075$ba4acef3@news.orange.fr> For those who may also work with Prolog : http://code.google.com/p/pyswip/ From gagsl-py2 at yahoo.com.ar Tue May 22 05:11:36 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 22 May 2007 06:11:36 -0300 Subject: doctest environment question References: <1179762737.153434.143030@b40g2000prd.googlegroups.com> <1179775483.685881.236940@x18g2000prd.googlegroups.com> <1179818466.394663.222390@k79g2000hse.googlegroups.com> Message-ID: En Tue, 22 May 2007 04:21:06 -0300, tag escribi?: > Here's a function which rebinds a function at the top level of a > module (it won't work for nested functions). > >>>> def announce_function(f): > ... " Rebind f within a module so that calls to f are announced. " > ... import inspect > ... setattr(inspect.getmodule(f), f.__name__, announce(f)) > > Let's give it a try. This next works fine in an interactive Python > session but fails when doctested. The version given by Peter Otten may do what you want, but I'd consider if you really need an announce_function in the first place, given all the other ways you already have to do the same thing. Implicitely rebinding globals does not look good. -- Gabriel Genellina From JoeSalmeri at hotmail.com Fri May 18 20:02:31 2007 From: JoeSalmeri at hotmail.com (Joe Salmeri) Date: Fri, 18 May 2007 20:02:31 -0400 Subject: cgi.py bug submitted to source_forge - Martin v. Löwis Message-ID: I submitted a patch quite a while back for a bug in cgi.py (see source forge 1159139) Martin, I posted this here, hoping you would see the message. Back in March 2007 you were looking at this bug and updated the item on source forge looking for more details. I have documented the bug further for you and have also included a test script which demonstrates the problem and also demonstrates how the patch fixes the bug in cgi.py Please take a look at the additiona information and test script (at source forge bug 1159139) and let me know if you have further questions. Thanks for taking time to look at the patch. Joe From n-ko at nyc.rr.com Thu May 31 23:41:28 2007 From: n-ko at nyc.rr.com (ibrahima) Date: Fri, 1 Jun 2007 02:41:28 -0100 Subject: yes I would like register References: Message-ID: <004401c7a3fe$bc9b8d40$6401a8c0@nanahome> ----- Original Message ----- From: To: Sent: Thursday, May 31, 2007 11:46 PM Subject: Python-list Digest, Vol 45, Issue 2 > 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..." > ---------------------------------------------------------------------------- ---- > Today's Topics: > > 1. M2Crypto-0.17 blocks python threads? (reizes at gmail.com) > 2. Re: call function in console without paranthesis (Robert Kern) > 3. Re: Using PIL to find separator pages (half.italian at gmail.com) > 4. Re: implementing callback function (Steve Holden) > 5. Re: Python 2.5.1 broken os.stat module (Joe Salmeri) > 6. Re: getmtime differs between Py2.5 and Py2.4 (Joe Salmeri) > 7. Re: file reading by record separator (not line by line) > (Steve Howell) > ---------------------------------------------------------------------------- ---- > -- > http://mail.python.org/mailman/listinfo/python-list > From paul at boddie.org.uk Wed May 9 06:10:21 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 9 May 2007 03:10:21 -0700 Subject: Towards faster Python implementations - theory In-Reply-To: References: <1210i.7468$2v1.2505@newssvr14.news.prodigy.net> Message-ID: <1178705421.711371.182770@e65g2000hsc.googlegroups.com> On 9 May, 08:09, "Hendrik van Rooyen" wrote: > > I am relatively new on this turf, and from what I have seen so far, it > would not bother me at all to tie a name's type to its first use, so that > the name can only be bound to objects of the same type as the type > of the object that it was originally bound to. But it's interesting to consider the kinds of names you could restrict in this manner and what the effects would be. In Python, the only kind of name that can be considered difficult to arbitrarily modify "at a distance" - in other words, from outside the same scope - are locals, and even then there are things like closures and perverse implementation-dependent stack hacks which can expose local namespaces to modification, although any reasonable "conservative Python" implementation would disallow the latter. In a local namespace you could restrict names in this way, although I'd argue that with the limitations on locals, you don't gain as much as you would by restricting other names similarly. However, by restricting other kinds of names (eg. instance attributes) you have to start thinking about polymorphism: what if attribute x on instances of class C can have different types? If you aren't careful, you've introduced interfaces as the primary mechanism permitting some kind of polymorphism. Paul From castironpi at gmail.com Tue May 8 18:04:11 2007 From: castironpi at gmail.com (castironpi at gmail.com) Date: 8 May 2007 15:04:11 -0700 Subject: interesting exercise In-Reply-To: <1178661305.063868.130730@e65g2000hsc.googlegroups.com> References: <1178595952.641173.76540@y80g2000hsf.googlegroups.com> <1178601624.812907.23550@u30g2000hsc.googlegroups.com> <1178661305.063868.130730@e65g2000hsc.googlegroups.com> Message-ID: <1178661851.606885.104330@p77g2000hsh.googlegroups.com> On May 8, 4:55 pm, castiro... at gmail.com wrote: > On May 8, 3:55 pm, James Stroud wrote: > > > > > Steven D'Aprano wrote: > > > On Tue, 08 May 2007 10:22:05 +0000, James Stroud wrote: > > > >>This takes annoying past annoying to some new level of hell to which > > >>even satan himself wouldn't venture. > > > > And thank you for sharing that piece of spam with us again. It was so much > > > less enjoyable to see it the second time. > > > > Seriously James, with more and more people using automated spam filters, > > > it might not be such a wise idea to keep having your name associated with > > > spam content. > > > Thank you for the tip. > > > James > > We also have: > > p=lambda a,n: [ ''.join( y ) for y in eval('[%%s %s]'%' '.join(['for x > %i in a'%i for i in range(n)]) %'(%s)'%','.join(['x%i'%i for i in > range(n)]) ) ] > p('abc',2) > #fb: ['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc'] > len(p('13579',3)) > #fb: 125 > edit() > > File under obscurities. acb Slightly clearer: p=lambda a,n:[ ''.join( y ) for y in eval('[(%s) %s]'%(','.join(['x %i'%i for i in range(n)]),' '.join(['for x%i in a'%i for i in range(n)])))] p('abc',2) #fb: ['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc'] len(p('13579',3)) #fb: 125 edit() where for n=4: ('[(%s) %s]'%(','.join(['x%i'%i for i in range(n)]),' '.join(['for x%i in a'%i for i in range(n)]))) #fb: '[(x0,x1,x2,x3) for x0 in a for x1 in a for x2 in a for x3 in a]' From duncan.booth at invalid.invalid Tue May 15 15:04:56 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 15 May 2007 19:04:56 GMT Subject: Splitting a string References: <1179253692.110024.96330@w5g2000hsg.googlegroups.com> Message-ID: HMS Surprise wrote: > The string s below has single and double qoutes in it. For testing I > surrounded it with triple single quotes. I want to split off the > portion before the first \, but my split that works with shorter > strings does not seem to work with this one. > > Ideas? > > Thanks, > jvh > > s = ''''D132258\',\'\', > \'status=no,location=no,width=630,height=550,left=200,top=100\')" > target="_blank" class="dvLink" title="Send an Email to selected > employee">''' > > t = s.split('\\') > > Remember that the the backslash used as an escape character is purely part of the syntax, it doesn't put a backslash into the string. You used triple quotes around the string so you didn't need to quote the other single quotes as \' in that case the escaping backslash is simply ignored. So your string doesn't have any backslash characters in it and splitting on a backslash won't do anything useful. If you want to split it before the first single quote then use: t = s.split("'") From nospam at invalid.com Fri May 25 14:11:28 2007 From: nospam at invalid.com (Jack) Date: Fri, 25 May 2007 11:11:28 -0700 Subject: Large Amount of Data References: Message-ID: Thanks for the replies! Database will be too slow for what I want to do. "Marc 'BlackJack' Rintsch" wrote in message news:pan.2007.05.25.18.03.09.688008 at gmx.net... > In , Jack wrote: > >> I need to process large amount of data. The data structure fits well >> in a dictionary but the amount is large - close to or more than the size >> of physical memory. I wonder what will happen if I try to load the data >> into a dictionary. Will Python use swap memory or will it fail? > > What about putting the data into a database? If the keys are strings the > `shelve` module might be a solution. > > Ciao, > Marc 'BlackJack' Rintsch From carsten at uniqsys.com Tue May 1 21:32:55 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 01 May 2007 21:32:55 -0400 Subject: Why are functions atomic? In-Reply-To: <1178065685.161372.81790@y80g2000hsf.googlegroups.com> References: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> <1178044821.864741.235260@o5g2000hsb.googlegroups.com> <1178063341.779617.289690@o5g2000hsb.googlegroups.com> <1178065685.161372.81790@y80g2000hsf.googlegroups.com> Message-ID: <1178069575.3407.22.camel@localhost.localdomain> On Tue, 2007-05-01 at 17:28 -0700, Michael wrote: > A bit more info, but still no clear picture about why functions are > mutable but have immutable copy symantics. There are arguments why > functions should be immutable, but the decision was to make user- > defined functions mutable. My question is still: why the present > ummutable copy symantics? One could make a case that this is a bug, a leftover from when functions were mostly immutable. However, one can also make a case that correcting this bug is not worth the effort. Your use case appears to be that you want to make multiple copies of the same function, and those copies should be almost, but not quite, the same. The Pythonic solution is to produce the copies by a factory function along these lines: >>> def powerfactory(exponent): ... def inner(x): ... return x**exponent ... return inner ... >>> square = powerfactory(2) >>> cube = powerfactory(3) >>> square(2) 4 >>> square(3) 9 >>> cube(2) 8 >>> cube(3) 27 This approach makes copying functions unnecessary, and as you have pointed out yourself, if you find yourself needing to make a copy of an existing function you can work around the unexpected copy semantics with new.function. -Carsten From saif.shakeel at gmail.com Thu May 10 03:56:49 2007 From: saif.shakeel at gmail.com (saif.shakeel at gmail.com) Date: 10 May 2007 00:56:49 -0700 Subject: replacing string in xml file--revisited Message-ID: <1178783809.444544.79640@w5g2000hsg.googlegroups.com> Hi, I need to replace a string in xml file with something else.Ex - rate rate - Here i have opened an xml file(small part is pasted here).I want to replace the word 'localId' with 'dataPackageID' wherever it comes in xml file.I have asked this before and got a code: input_file = open(filename) xmlcontents = input_file.read() input_file.close() xmlcontents = xmlcontents.replace("spam", "eggs") output_file = open(filename,"w") output_file.write(xmlcontents) output_file.close() Although this works alone it is nto working when i handle multiple file I/O.Is there a alternative to do this.(maybe without read() operation) Thanks From deets at nospam.web.de Tue May 8 09:34:28 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 08 May 2007 15:34:28 +0200 Subject: changing a var by reference of a list References: Message-ID: <5abcj4F2nv0p0U1@mid.uni-berlin.de> Jorgen Bodde wrote: > Hi, > > I am trying to simplify my code, and want to automate the assigning of > variables I get back from a set. I was thinking of putting the > variables I want changed in a list: > > L = [self._varA, self._varB ] > > self._varA is a variable I want to change when I pass L to a function. > I know doing this; > > L[0] = 12 > > Will replace the entry self._varA with 12, but is there a way to > indirectly change the value of self._varA, through the list, something > like a by-reference in C++ or a pointer-pointer? No, there isn't. But you could do L = ['_varA'] for v in L: setattr(self, v, value) Diez From steve at REMOVE.THIS.cybersource.com.au Fri May 11 23:56:35 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 12 May 2007 13:56:35 +1000 Subject: Newbie look at Python and OO References: <1178812734.860473.236370@y80g2000hsf.googlegroups.com> <1346hrvgve90nea@corp.supernews.com> <1178939255.996029.263520@p77g2000hsh.googlegroups.com> Message-ID: On Fri, 11 May 2007 20:07:36 -0700, walterbyrd wrote: >> He's thinking in Pascal, not C. >> > > Actually, I have programmed in many languages. I just first learned in > Pascal. > > For me, going from Pascal, to basic,c,cobol,fortran . . was not that > difficult. Python, however, feels strange. Sounds to me like it is the object-oriented stuff that causes the confusion, not Python per se. > As crazy as this may sound: Python, in some ways, reminds me of > assembly language. I haven' t programmed in assembly in a *long* time. > But I vaugly remember doing a lot of stuff where I used memory > addresses as pointers to data, and also as pointers to pointers. > Although, when I first started assembly language, I think it took me a > week to write a program to print "hello world." You shouldn't need to think about memory addresses in Python. The only exceptions are that the id() function returns the memory address (although that's just an implementation detail, it could be any old number for all the difference it makes), and that some objects expose the memory address as part of their default string representation: >>> print object() I too learnt to program in Pascal, and I also found the OO side of things confusing at first. With the exception of a few "gotchas" like string.join() which feels like it is written backwards, it is usually quite natural. You started this thread with a list of conceptual problems you were having. Are they now cleared up? -- Steven. From mailmaverick666 at gmail.com Fri May 18 01:32:33 2007 From: mailmaverick666 at gmail.com (rishi pathak) Date: Fri, 18 May 2007 11:02:33 +0530 Subject: Lindsay Lohans TITS OOPSIE!!! In-Reply-To: <1179465924.977288.65570@n59g2000hsh.googlegroups.com> References: <1179465924.977288.65570@n59g2000hsh.googlegroups.com> Message-ID: <180b672e0705172232m1cc5abd8rb4ecadd47da38e13@mail.gmail.com> Is there not a way to block these kind of mails Their quantity is increasing day by day On 17 May 2007 22:25:25 -0700, Goofy.throat2 at gmail.com < Goofy.throat2 at gmail.com> wrote: > > Download http://scargo.in Lindsay Lohans Tits free tits and videos! > MUST CLICK! I mean see... . > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Regards-- Rishi Pathak National PARAM Supercomputing Facility Center for Development of Advanced Computing(C-DAC) Pune University Campus,Ganesh Khind Road Pune-Maharastra -------------- next part -------------- An HTML attachment was scrubbed... URL: From quasi at null.set Sat May 5 11:34:06 2007 From: quasi at null.set (quasi) Date: Sat, 05 May 2007 10:34:06 -0500 Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> <08qk33t594ih0ulmjmev90d22lkfnotgoe@4ax.com> <463C2A3A.8332D211@hotmail.com> Message-ID: <0k8p33h90bp5tfajedb4bmd2eik8gfi2ho@4ax.com> On Sat, 05 May 2007 07:54:50 +0100, Eeyore wrote: > > >quasi wrote: > >> Gib Bogle wrote: >> >> >Ah, so the firefighters were in on the conspiracy! >> >> No, but the firefighters are very much aware that there is more to >> 9/11 than has been officially revealed. >> >> This is even more true at Pentagon. The firefighters there brought >> dogs trained to search for survivors and/or remains > >Sounds like good practice. > > >> and found nothing. > >And the significance of this is ? The plane was supposed to have passengers. quasi From carsten at uniqsys.com Thu May 10 12:25:47 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 10 May 2007 12:25:47 -0400 Subject: Newbie look at Python and OO In-Reply-To: <1178812734.860473.236370@y80g2000hsf.googlegroups.com> References: <1178812734.860473.236370@y80g2000hsf.googlegroups.com> Message-ID: <1178814347.3367.89.camel@dot.uniqsys.com> On Thu, 2007-05-10 at 08:58 -0700, walterbyrd wrote: > I learned to program with Pascal, way back when. Went into software > development for a while, then went into systems admin. Have programmed > in several languages, just learning Python. > > Some things I find odd: > > 1) 5/-2 == -3? Division of integers performs a "floor division" that rounds the result down to a whole number. If you want a floating point result, you'll need to specify that you're working with floats: 5.0/-2 or float(5)/-2 > 2) list assignment handling, pointing two vars to the same list: See http://effbot.org/zone/python-objects.htm . > 3) ambiguous use of the form: this.that() The form "this.that" *always* means the same: It refers to the attribute called "that" of the object called "this". This may yield seemingly different meanings depending on what type of object "this" is, but the basic mechanism is always the same. The main source of your confusion seems to stem from the fact that join() was decided somewhat non-intuitively to be a method of string instances. By the way, the next time you have a number of unrelated questions, please consider posting them in separate messages. That allows you to pick a more descriptive subject line for each message, and it makes the ensuing conversations easier to follow. Best regards, -- Carsten Haese http://informixdb.sourceforge.net From steve at REMOVE.THIS.cybersource.com.au Fri May 11 23:41:57 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 12 May 2007 13:41:57 +1000 Subject: Simple Python REGEX Question References: <1178898871.781501.135170@p77g2000hsh.googlegroups.com> Message-ID: On Fri, 11 May 2007 08:54:31 -0700, johnny wrote: > I need to get the content inside the bracket. > > eg. some characters before bracket (3.12345). > > I need to get whatever inside the (), in this case 3.12345. > > How do you do this with python regular expression? Why would you bother? If you know your string is a bracketed expression, all you need is: s = "(3.12345)" contents = s[1:-1] # ignore the first and last characters If your string is more complex: s = "lots of things here (3.12345) and some more things here" then the task is harder. In general, you can't use regular expressions for that, you need a proper parser, because brackets can be nested. But if you don't care about nested brackets, then something like this is easy: def get_bracket(s): p, q = s.find('('), s.find(')') if p == -1 or q == -1: raise ValueError("Missing bracket") if p > q: raise ValueError("Close bracket before open bracket") return s[p+1:q-1] Or as a one liner with no error checking: s[s.find('(')+1:s.find(')'-1] -- Steven. From SuperM at ssiveBlackHoleAtTheCenterOfTheMilkyWayGalaxy.org Thu May 3 21:35:53 2007 From: SuperM at ssiveBlackHoleAtTheCenterOfTheMilkyWayGalaxy.org (The Great Attractor) Date: Thu, 03 May 2007 18:35:53 -0700 Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> <08qk33t594ih0ulmjmev90d22lkfnotgoe@4ax.com> Message-ID: On Thu, 03 May 2007 18:08:31 -0500, quasi wrote: >On Fri, 04 May 2007 09:37:37 +1200, Gib Bogle > wrote: > >>Ah, so the firefighters were in on the conspiracy! > >No, but the firefighters are very much aware that there is more to >9/11 than has been officially revealed. > >This is even more true at Pentagon. The firefighters there brought >dogs trained to search for survivors and/or remains and found nothing. > >quasi You're a goddamned idiot. From yavannadil at yahoo.com Fri May 4 08:59:48 2007 From: yavannadil at yahoo.com (yavannadil at yahoo.com) Date: 4 May 2007 05:59:48 -0700 Subject: How do I get type methods? In-Reply-To: References: <1178220806.664557.245780@c35g2000hsg.googlegroups.com> <1178253260.075515.43810@q75g2000hsh.googlegroups.com> Message-ID: <1178283588.694886.204250@c35g2000hsg.googlegroups.com> On 4 ???, 09:08, "Gabriel Genellina" wrote: > En Fri, 04 May 2007 01:34:20 -0300, escribio: > > I'm not against 'dir(MyClass)'; the question is, what should I 'dir()' > > to get methods of 'pyuno' type instance? > Usually instances don't have its own methods, they get them from the > class. So you actually need dir(MyClass). > Note that dir() might not show all available methods. Let me retype my question: what I 'dir()' in case of 'pyuno' type instance? Or in case of 'dict' type instance? Or in case of any other new python type? From DirkHagemann at gmail.com Wed May 2 11:24:25 2007 From: DirkHagemann at gmail.com (Dirk Hagemann) Date: 2 May 2007 08:24:25 -0700 Subject: Active Directory: how to delete a user from a group? Message-ID: <1178119465.469546.275440@e65g2000hsc.googlegroups.com> Hi! Does anyone has experience with manipulating MS Active Directory objects? I'd like to delete some users from a group, but so far I couldn't find anything about this. There is some good stuff about retrieving data out of the AD (thanks to Tim Golden!), but how can I manipulate or change AD objects like users, computers and groups with Python? Is there somewhere a documentation or some code? Dirk From Goofy.throat2 at gmail.com Fri May 18 01:25:25 2007 From: Goofy.throat2 at gmail.com (Goofy.throat2 at gmail.com) Date: 17 May 2007 22:25:25 -0700 Subject: Lindsay Lohans TITS OOPSIE!!! Message-ID: <1179465924.977288.65570@n59g2000hsh.googlegroups.com> Download http://scargo.in Lindsay Lohans Tits free tits and videos! MUST CLICK! I mean see... . From steve at holdenweb.com Sun May 20 16:30:50 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 20 May 2007 16:30:50 -0400 Subject: List Moderator In-Reply-To: <880dece00705201305q6944986fj8f77c4b5cac09456@mail.gmail.com> References: <880dece00705172218n71123b55q531ec0c5e500f208@mail.gmail.com> <880dece00705190012g4f3d3ef6v4e6c87a156708bb0@mail.gmail.com> <880dece00705191305m203bc8ep804d647c17438581@mail.gmail.com> <464F5E42.6090607@holdenweb.com> <880dece00705201305q6944986fj8f77c4b5cac09456@mail.gmail.com> Message-ID: <4650AFFA.2080800@holdenweb.com> Dotan Cohen wrote: > On 19/05/07, Steve Holden wrote: [...] >> The Python list managers know what they are doing, and they *do* keep a >> huge amount of spam off the list. The occasional piece gets through, but >> this is Usenet. It will, from time to time. >> > > Again, I appreciate the efforts made to reduce spam on the list of > course. It's obvious that much effort is being put into it. The > procmail filters that I'm referring to would be right before the mail > gets handed to sendmail. I read this list as a mailing list, and I'm > unfamiliar with the different interfaces. But it all goes through a > central point from which is it diseminated. Right before that point is > where I'd imagine the filters are. They do exist, no? > It doesn't all go through a central point - users like me who use a news server to access the list submit articles through a local news server using NNTP. While there *is* a single point of access for articles pulled from python.org's news server and gatewayed out as email (and for which the filters you mention probably ought to help), articles I see have never been processed by this interface. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From bj_666 at gmx.net Sat May 12 13:28:28 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 12 May 2007 19:28:28 +0200 Subject: Finally started on python.. References: Message-ID: In , Roger Gammans wrote: > I found myself using this sort of code a bit in one of my recent > scripts > class Something: > def Entries(self): > sort=self._data.keys() > sort.sort() > for i in sort: > yield i > > IS this preferable to just returning the sort array from the function > or not? Which is more runtime efficent. I see no benefit for a generator here as the whole list mus be build for sorting anyway. If you still want return an iterable here it could be written this way: class Something(object): def iter_entries(self): return iter(sorted(self._data.keys())) Just leave out the `iter()` call to return a sorted list. If you want to make `Something` objects iterable over the sorted keys, change the method name to `__iter__()`. Then you can use `Something` objects like this: something = Something() # Puts some entries into `something`. for entry in something: print entry Ciao, Marc 'BlackJack' Rintsch From flyzone at technologist.com Wed May 2 04:17:00 2007 From: flyzone at technologist.com (Flyzone) Date: 2 May 2007 01:17:00 -0700 Subject: regexp match string with word1 and not word2 In-Reply-To: References: <1177920984.247487.54620@c35g2000hsg.googlegroups.com> <9rGdnQGHaNy1mqvbnZ2dnUVZ_v_inZ2d@comcast.com> <1177946577.080567.73400@u30g2000hsc.googlegroups.com> Message-ID: <1178093820.914883.113760@n76g2000hsh.googlegroups.com> On 30 Apr, 20:00, Steven Bethard wrote: > Well then it seems like you might want to rethink this rule-file > approach since your problem is clearly not amenable to regular expressions. [cut] > That said, here's a regexp that might work:: > ((?!two:).)*one((?!two:).)* > That makes a negative lookahead assertion at each character in the string. But match again something so don't work like i wanted. Maybe a right approach will be another if after the first one? Like: for y in range(0, len(skip_lst) ): if (re.search(skip_lst[y], line)): if (re.search(skip_lst_negative[y], line)): skip=1 break and in the rule-file, i could add a new column and check to do the if just if the second column is not empty. From larry.bates at websafe.com Tue May 22 10:07:29 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 22 May 2007 09:07:29 -0500 Subject: [Fwd: Re: managed lists?] In-Reply-To: References: <4651fe96$0$24671$426a34cc@news.free.fr> <11e49df10705220013q11c35e6axba72cc4227401ac2@mail.gmail.com> Message-ID: <6LOdnaLGvua9ZM_bnZ2dnUVZ_oCmnZ2d@comcast.com> Jorgen Bodde wrote: > Hi Gabriel, > > Yep that basically covered my implementation as well. It was rather > trivial to make it, and even for a python newbie it was simple which > says enough about the language itself. ;-) > > Although I understand the opinions that you should not care about > types, I do believe putting a constraint on the list by either class > type or interface spec, is no bad thing. The interface specification > is hard to realise as this list now functions as some kind of template > class (hence the parameter that specifies which type is allowed). > > I also added callback arguments that are called opon when there are > items added to the list, deleted or when it is cleared so that the > main object gets notified when another object changes it. > > Here is my implementation (I bet it can be done better, but I am only > playing with python since about 3 months now): > > -------------------------- > > class ObjListException(Exception): > pass > > class ObjListIterator(object): > def __init__(self, objlist): > self.__objlist = objlist > self.__idx = 0 > > > #--------------------------------------------------------------------------- > > def __iter__(self): > return self > > > #--------------------------------------------------------------------------- > > def next(self): > result = None > if self.__idx >= len(self.__objlist): > raise StopIteration() > else: > result = self.__objlist[self.__idx] > self.__idx += 1 > return result > > #=============================================================================== > > > """ ObjList - A managed somewhat strong typed list for Python. > Expects {object}._id to be a property """ > > class ObjList(object): > def __init__(self, class_name, add_callback = None, > remove_callback = None, clear_callback = None): > self.__list = [] > self.__cname = class_name > self.__add_cb = add_callback > self.__remove_cb = remove_callback > self.__clear_cb = clear_callback > > > #--------------------------------------------------------------------------- > > def __iter__(self): > return ObjListIterator(self.unmanaged_list()) > > > #--------------------------------------------------------------------------- > > def __getitem__( self, key): > if key < len(self.__list) and key >= 0: > return self.__list[key] > return None > > > #--------------------------------------------------------------------------- > > def clear(self): > self.__list = [] > > > #--------------------------------------------------------------------------- > > def append(self, obj): > if isinstance(obj, self.__cname): > if obj not in self.__list: > self.__list.append(obj) > if self.__add_cb: > self.__add_cb(self, obj) > else: > raise ObjListException() > > > #--------------------------------------------------------------------------- > > def remove(self, obj): > if obj in self.__list: > self.__list.remove(obj) > if self.__remove_cb: > self.__remove_cb(self, obj) > > > #--------------------------------------------------------------------------- > > def count(self): > return len(self.__list) > > > #--------------------------------------------------------------------------- > > def unmanaged_list(self): > return self.__list[:] > > > #--------------------------------------------------------------------------- > > def find_id(self, id): > for i in self.__list: > if i._id == id: > return i > return None > > > #--------------------------------------------------------------------------- > > def has_item(self, obj): > if obj in self.__list: > return True > return False > > > #--------------------------------------------------------------------------- > > def append_many(self, lst): > for l in lst: > self.append(l) > > Regards, > - Jorgen IMHO you are trying to write C in Python. In another 3 months I'll bet you will look back on this and say "Why did I bother?". I would suggest that the time to do such "restrictions" would better be spent writing good unit tests for your application. They are what really will assist you in finding those problems way down deep in your code and will be useful for the entire life of the project. You may also want to consider checking to see if the object that is passed in implements the interface that you want instead of requiring that it be a a specific class instance. Something like (not tested): class ObjListIterator(object) # # class variable # __required_methods=['methodname1','methodname2','methodname3'] def chkObjInterface(self, obj): for method in self.__required_methods: if not hasattr(obj, 'methodname1': raise ObjListException("obj must implement '%s' method") else: raise ObjListException("obj must implement 'methodname'" \ "method") return True def append(self, obj): if chkObjInterface(obj): if obj not in self.__list: self.__list.append(obj) if self.__add_cb: self.__add_cb(self, obj) else: raise ObjListException("append.obj must implement 'methodname'" \ method") I would also write append_many as: def extend(self, lst): map(self.append, lst) return I would find it easier to remember extend (since that is very pythonic). If your collection of objects is large, I would also consider putting them in a dictionary instead of a list and indexing them on ID. Hope this helps in some way. -Larry From irmen.NOSPAM at xs4all.nl Mon May 14 20:48:47 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Tue, 15 May 2007 02:48:47 +0200 Subject: Python Power Point Slides In-Reply-To: <1179183962.824333.31730@q75g2000hsh.googlegroups.com> References: <1179183962.824333.31730@q75g2000hsh.googlegroups.com> Message-ID: <46490372$0$334$e4fe514c@news.xs4all.nl> Krypto wrote: > Hi, > > I want to give a short presentation in my group about benefits of > python, why should one use python and some basic starting information > about python, about its data type, etc. > > Can somebody point me to the right references on the web. I have > searched a lot and I do get quite a few but I thought to check on > newsgroup for a better presentation, or if you have prepared any, can > you please share it. > > Thanks > Ahem, if you can't create one yourself, how could you ever give a convincing presentation about these subjects? You'll have to tell your own story... You know the benefits of Python etc. yourself, don't you? --Irmen From jgodoy at gmail.com Mon May 7 18:29:33 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Mon, 07 May 2007 19:29:33 -0300 Subject: No module named urllib References: <1178575589.059564.226060@q75g2000hsh.googlegroups.com> Message-ID: <87tzuop8s2.fsf@gmail.com> HMS Surprise writes: > I edited environment varialbes and have added C:\Python25\Lib to > PYTHONPATH but get the no module message when the statement > > import urllib > > is executed. > > Even tried copying the urllib file to my working directory. > > Any suggestions? No messages is good! :-) If you got any error messages then you'd have a problem. -- Jorge Godoy From aleax at mac.com Fri May 11 10:26:47 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 11 May 2007 07:26:47 -0700 Subject: searching algorithm References: <7dydnfjNWbo9H97bnZ2dnUVZ_oupnZ2d@comcast.com> Message-ID: <1hxxtyc.ge0tgk9kqbjdN%aleax@mac.com> Michael Bentley wrote: > > > > Call me dense, but how does one do this in Python - which doesn't have > > pointers? Dictionaries with dictionaries within dictionaries... (with > > each letter as the key and the its children as values) is going to be > > extremely space inefficient, right? > > Isn't *everything* in python essentially a pointer? Dictionaries > with dictionaries within dictionaries... My gut feeling (which means > I have not measured it, so I don't actually know) is that it would > not be space inefficient. Perhaps someone who knows more about this > will speak up? Dicts are hash tables, and therefore, for performance, always keep some "extra" space (so that the table won't be too full). Alex From aleax at mac.com Mon May 14 02:00:16 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 13 May 2007 23:00:16 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <20070513160046.GC29172@v.igoro.us> <7x646wa9wz.fsf@ruckus.brouhaha.com> Message-ID: <1hy2q4c.x5ih391i7k1hyN%aleax@mac.com> Steven D'Aprano wrote: > automated -- if the patch uses an unexpected "#-*- coding: blah" line, or No need -- a separate PEP (also by Martin) makes UTF-8 the default encoding, and UTF-8 can encode any Unicode character you like. Alex From steve at holdenweb.com Sun May 27 23:06:54 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 27 May 2007 23:06:54 -0400 Subject: Why isn't this query working in python? In-Reply-To: References: <1180103946.552760.239200@p47g2000hsd.googlegroups.com> <6e42ec490705250751i89d3cf3v3a3062690d0284aa@mail.gmail.com> <1180207521.072958.322770@p47g2000hsd.googlegroups.com> <1180225290.235515.274000@q19g2000prn.googlegroups.com> <1180279833.131269.136770@w5g2000hsg.googlegroups.com> Message-ID: <465A474E.1000502@holdenweb.com> davelist at mac.com wrote: > > On May 27, 2007, at 4:01 PM, Steve Holden wrote: > >> erikcw wrote: >>> On May 26, 8:21 pm, John Machin wrote: >>>> On May 27, 5:25 am, erikcw wrote: >>>> >>>> >>>> >>>>> On May 25, 11:28 am, Carsten Haese wrote: >>>>>> On Fri, 2007-05-25 at 09:51 -0500, Dave Borne wrote: >>>>>>>> I'm trying to run the following query: >>>>>>> ... >>>>>>>> member_id=%s AND expire_date > NOW() AND completed=1 AND >>>>>>>> (product_id >>>>>>> Shouldn't you be using the bind variable '?' instead of '%s' ? >>>>>> The parameter placeholder for MySQLdb is, indeed and >>>>>> unfortunately, %s. >>>>>> The OP is using parameter substitution correctly, though in an >>>>>> obfuscated fashion. 'sql' is a misnamed tuple containing both the >>>>>> query >>>>>> string *and* the parameters, which is being unpacked with '*' into >>>>>> two >>>>>> arguments to the execute call. >>>>>> The only problem I see is that the parameters should be a >>>>>> sequence, i.e. >>>>>> (self.uid,) instead of just (self.uid). >>>>>> HTH, >>>>>> -- >>>>>> Carsten Haesehttp://informixdb.sourceforge.net >>>>> I tried adding the comma to make it a sequence - but now change. >>>>> ('SELECT payment_id FROM amember_payments WHERE member_id=%s AND >>>>> expire_date > NOW() AND completed=1 AND (product_id >11 AND product_id >>>>> <21)', (1608L,)) >>>>> () >>>>> What else could it be? >>>> Possibly a type mismatch. How is member_id declared in the CREATE >>>> TABLE? For diagnostic purposes, try passing in (1608,) and ('1608',). >>> >>> Here is a copy of the table schema and the first 2 rows. >>> >>> -- phpMyAdmin SQL Dump >>> -- version 2.9.0.2 >>> -- http://www.phpmyadmin.net >>> -- >>> -- Host: localhost >>> -- Generation Time: May 27, 2007 at 11:29 AM >>> -- Server version: 5.0.27 >>> -- PHP Version: 4.4.2 >>> -- >>> -- Database: `lybp_lybp` >>> -- >>> >>> -- -------------------------------------------------------- >>> >>> -- >>> -- Table structure for table `amember_payments` >>> -- >>> >>> CREATE TABLE `amember_payments` ( >>> `payment_id` int(11) NOT NULL auto_increment, >>> `member_id` int(11) NOT NULL default '0', >>> `product_id` int(11) NOT NULL default '0', >>> `begin_date` date NOT NULL default '0000-00-00', >>> `expire_date` date NOT NULL default '0000-00-00', >>> `paysys_id` varchar(32) NOT NULL default '', >>> `receipt_id` varchar(32) NOT NULL default '', >>> `amount` decimal(12,2) NOT NULL default '0.00', >>> `completed` smallint(6) default '0', >>> `remote_addr` varchar(15) NOT NULL default '', >>> `data` text, >>> `time` timestamp NOT NULL default CURRENT_TIMESTAMP on update >>> CURRENT_TIMESTAMP, >>> `aff_id` int(11) NOT NULL default '0', >>> `payer_id` varchar(255) NOT NULL default '', >>> `coupon_id` int(11) NOT NULL default '0', >>> `tm_added` datetime NOT NULL default '0000-00-00 00:00:00', >>> `tm_completed` datetime default NULL, >>> `tax_amount` decimal(12,2) NOT NULL default '0.00', >>> PRIMARY KEY (`payment_id`), >>> KEY `member_id` (`member_id`), >>> KEY `payer_id` (`payer_id`), >>> KEY `coupon_id` (`coupon_id`), >>> KEY `tm_added` (`tm_added`,`product_id`), >>> KEY `tm_completed` (`tm_completed`,`product_id`) >>> ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=11020 ; >>> >>> -- >>> -- Dumping data for table `amember_payments` >>> -- >>> >>> INSERT INTO `amember_payments` VALUES (423, 107, 1, '2004-10-01', >>> '2004-10-21', 'authorize_aim', '5687944', 3.95, 1, '', NULL, >>> '2004-11-30 19:21:43', 0, '', 0, '2004-11-30 19:21:43', '2004-11-30 >>> 19:21:43', 0.00); >>> INSERT INTO `amember_payments` VALUES (422, 107, 1, '2004-10-22', >>> '2004-11-21', 'authorize_aim', '5873225', 9.95, 1, '', NULL, >>> '2004-11-30 19:22:18', 0, '', 0, '2004-11-30 19:20:13', '2004-11-30 >>> 19:20:13', 0.00); >>> >>> Thanks for your help! >>> Erik >>> >> I feel obliged to point out that there ARE no rows meeting the criteria >> you query specified! >> >> mysql> SELECT expire_date, NOW() FROM amember_payments; >> +-------------+---------------------+ >> | expire_date | NOW() | >> +-------------+---------------------+ >> | 2004-10-21 | 2007-05-27 15:59:21 | >> | 2004-11-21 | 2007-05-27 15:59:21 | >> +-------------+---------------------+ >> 2 rows in set (0.02 sec) >> >> mysql> >> >> So I am not sure how you managed to get a manual query to work, but do >> be sure that the Python query you mentioned at the start of the thread >> >> sql = """SELECT payment_id FROM amember_payments WHERE >> member_id=%s AND expire_date > NOW() AND completed=1 AND (product_id >>>> 11 AND product_id <21)""", (self.uid) >> > > > And doesn't the above comma, need to be a percent symbol? > Nope. > Dave > > >> doesn't stand a chance of returning any results unless you use a time >> machine to go back almost three years! >> >> 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From machicoane at gmail.com Tue May 15 09:32:54 2007 From: machicoane at gmail.com (Thierry) Date: 15 May 2007 06:32:54 -0700 Subject: Yet Another Software Challenge In-Reply-To: <1179150005.400863.256700@e51g2000hsg.googlegroups.com> References: <1179148471.466017.156290@q75g2000hsh.googlegroups.com> <1179150005.400863.256700@e51g2000hsg.googlegroups.com> Message-ID: <1179235974.448243.262260@w5g2000hsg.googlegroups.com> On May 14, 3:40 pm, Paul McGuire wrote: > > In Riddle 2, the "global" declarations are unnecessary, as you are > only referencing the globally-defined vars for read. > > Also in Riddle 2, I would replace > for s in alphabet: indices[s] = alphabet.index(s) > with > indices = dict( (s,i) for i,s in enumerate(alphabet) ) > > (I see part of your Python Challenge as giving new Pythoners something > to cut their teeth on, and so this is an opportunity for giving > examples of good style.) > > I do enjoy these challenges, they are quite addicting. :) > > -- Paul Hi Paul, Many thanks for your feedback and your example of good Python style. Even though the challenge is opened to any language practitioner, I must confess that I personally prefer Python and that languages like Python and Ruby are likely to be the most effective to solve the riddles. Don't hesitate to report any issue you could find. Enjoy. Cheers. Thierry From jstroud at mbi.ucla.edu Fri May 4 15:32:13 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 04 May 2007 12:32:13 -0700 Subject: Firefighters at the site of WTC7 "Move away the building is going to blow up, get back the building is going to blow up." In-Reply-To: References: <1178161820.731367.264500@y80g2000hsf.googlegroups.com> <1hlj33p6aq838o2urk1dv6h75b5is4i2vd@4ax.com> <3TD_h.219$mR2.195@newssvr22.news.prodigy.net> Message-ID: default wrote: > On Fri, 04 May 2007 03:26:17 -0700, James Stroud > wrote: > >> default wrote: >>> On 2 May 2007 20:10:20 -0700, Midex wrote: >>> >>>> LIES LIES LIES LIES LIES >>> Trying to understand the World Trade Center events is like waking up >>> to act fifteen of a long Greek Tragedy. It needs a complex fabric of >>> description to give a full picture. In explaining this crisis, we will >>> be showing how the situation rests on layers of historical >>> developments, layers of crises and solutions. >>> >>> shamelessly taken from: >>> http://www.againstsleepandnightmare.com/ASAN/ASAN7/ASAN7.html >>> >>> The World After September 11th, 2001 >>> >>> Damn good read. > >> Marxist trash. > > We've been conditioned to think in those terms and the web site is > communist. The philosophy of communism isn't so bad, it is the people > and application that are the problem. > > Capitalism works right out of the box then begins to fray and > deteriorate - again due to people and application. Either system > creates an elite class and poor class with little or no middle ground. > Each system is, ultimately, a failure. > > I'm not advocating either system, both are flawed as long as people > can gain and hold power. Somewhere in there is a solution to the > problems - I wouldn't presume to know the right course. The Marxist contribution to western thought is that it put everything in terms of labor and thus allowed us to quantify the human component of economies. Though insightful, these insights were made 100 years ago and are really only helpful in a sociological context. To attempt to turn Marxist philosophy and insight into an economic policy is flawed because economies are driven by greed. No policy will eliminate the greed, so it is better to make policies that allow competition for resources (even labor) fair. Marxism consolidates economic power into the hands of government officials, who are the most greedy, and thus it ends up siphoning wealth from the laborers who produce it in total contradiction to its goals. That has been shown to be the reality despite the ideology. Yes, the current global economic model is based on fascism, which is unfortunate, but Marxism and the communism that arises from it are not better alternatives--so it is better to identify Marxist economics as the trash it is than to allow the unwitting to get confused about how the greedy would end up applying it. James From grante at visi.com Thu May 31 12:47:39 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 31 May 2007 16:47:39 -0000 Subject: c[:]() References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> <135tobve86qj808@corp.supernews.com> <135tru124pie2b3@corp.supernews.com> Message-ID: <135tv1bjqgbmsc9@corp.supernews.com> On 2007-05-31, Warren Stringer wrote: >> How is it more expressive? In the context you're concerned >> with, c[:] is the exactly same thing as c. You seem to be >> worried about saving keystrokes, yet you use c[:] instead of c. >> >> It's like having an integer variable i and using ((i+0)*1) >> instead of i. > > Nope, different. > > c[:] holds many behaviors that change dynamically. I've absolutely no clue what that sentence means. If c[:] does behave differently than c, then somebody's done something seriously weird and probably needs to be slapped around for felonious overriding. > So c[:]() -- or the more recent go(c)() -- executes all those > behaviors. Still no clue. > This is very useful for many performers. What are "performers"? > The real world example that I'm working one is a collaborative > visual music performance. So c can contain wrapped MIDI events > or sequencer behaviors. c may get passed to a scheduler to > execute those events, or c may get passed to a pickler to > persist the performance. I still don't see how c[:] is any different from c. -- Grant Edwards grante Yow! TONY RANDALL! Is YOUR at life a PATIO of FUN?? visi.com From carsten at uniqsys.com Wed May 30 15:54:32 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 30 May 2007 15:54:32 -0400 Subject: c[:]() In-Reply-To: <002801c7a2eb$288a8750$240110ac@Muse> References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180504773.374529.161740@q66g2000hsg.googlegroups.com> <002801c7a2eb$288a8750$240110ac@Muse> Message-ID: <1180554872.3356.30.camel@dot.uniqsys.com> On Wed, 2007-05-30 at 11:48 -0700, Warren Stringer wrote: > I want to call every object in a tupple, like so: > > #------------------------------------------ > def a: print 'a' > def b: print 'b' > c = (a,b) > > >>>c[:]() # i wanna > [...] > Is there something obvious that I'm missing? Yes: Python is not Perl. Python is based on the principle that programmers don't write computer code for the benefit of the computer, but for the benefit of any programmer who has to read their code in the future. Terseness is not a virtue. To call every function in a tuple, do the obvious: for func in funcs: func() HTH, -- Carsten Haese http://informixdb.sourceforge.net From usenet at solar-empire.de Thu May 10 04:59:02 2007 From: usenet at solar-empire.de (Marc Christiansen) Date: 10 May 2007 08:59:02 GMT Subject: Minor bug in tempfile module (possibly __doc__ error) References: <1178693438.689184@smirk> Message-ID: <4642ded5$0$20290$9b4e6d93@newsspool3.arcor-online.net> James T. Dennis scribis: > In fact I realized, after reading through tempfile.py in /usr/lib/... > that the following also doesn't "work" like I'd expect: > > # foo.py > tst = "foo" > def getTst(arg): If I change this line: > return "foo-%s" % arg to: return "%s-%s" % (tst, arg) > # bar.py > import foo > foo.tst = "bar" > print foo.getTst("testing") > > foo-testing <<<----- NOT "bar-testing" Then "python bar.py" prints "bar-testing". 0:tolot at jupiter:/tmp> cat foo.py tst = "foo" def getTst(arg): return "%s-%s" % (tst,arg) 0:tolot at jupiter:/tmp> cat bar.py import foo foo.tst = "bar" print foo.getTst("testing") 0:tolot at jupiter:/tmp> python bar.py bar-testing And regarding the tempfile.template problem, this looks like a bug. Because all functions in tempfile taking a prefix argument use "def function(... , prefix=template, ...)", only the value of template at import time matters. Adia?, Marc From steve at holdenweb.com Mon May 7 07:52:03 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 07 May 2007 07:52:03 -0400 Subject: Bastion/rexec use cases? In-Reply-To: <1178534949.324994.60870@l77g2000hsb.googlegroups.com> References: <1178534949.324994.60870@l77g2000hsb.googlegroups.com> Message-ID: Paul Miller wrote: > Bastion and rexec have been deprecated since Python 2.2, so it seems > we (the Python community) have gotten along well enough without them. > Have these modules not been reimplemented because: > > a) There are no valid use cases for them. > b) Doing so would be difficult and prone to breakage as new features > are introduced into the language. > c) Nobody has any idea how to do it. > d) Nobody cares. > e) Guido thinks it's a bad idea. > > or, some combination of these? > All of the above except c) and d), I think. You might like to Google for something like Brett Cannon secure Python to get up to speed on some work that may eventually result in Python acquiring a more security-minded framework. Bastion and rexec were so full of holes you could drive a London double-decker bus through them, so their deprecation and eventual exclusion was felt to be safer than leaving them in to be mistaken for secure 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From jmcmonagle at velseis.com.au Tue May 15 19:25:19 2007 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Wed, 16 May 2007 09:25:19 +1000 Subject: {Possible_Spam} tkFileDialog.askopenfilename() In-Reply-To: <1179270010.433011.23580@y80g2000hsf.googlegroups.com> References: <1179270010.433011.23580@y80g2000hsf.googlegroups.com> Message-ID: <464A415F.4090101@velseis.com.au> rahulnag22 at yahoo.com wrote: > Hi, > When I call tkFileDialog.askopenfilename() , the dialog box opens with > the current directory as the default directory. Is it possible to open > the dialog box with a directory other than the current directory. Can > we pass in a user defined starting directory. > Thanks > Rahul > tkFileDialog.askopenfilename() uses the tk command tk_getOpenFile, the documentation for which is at: http://www.tcl.tk/man/tcl8.4/TkCmd/getOpenFile.htm Regards, John From ludovic.danigo at gmail.com Thu May 10 05:25:27 2007 From: ludovic.danigo at gmail.com (ldng) Date: 10 May 2007 02:25:27 -0700 Subject: How to convert Unicode string to raw string escaped with HTML Entities In-Reply-To: References: <1178787272.922167.79480@q75g2000hsh.googlegroups.com> Message-ID: <1178789127.182810.153040@o5g2000hsb.googlegroups.com> On 10 mai, 11:03, Tim Golden wrote: > > Probably worth having a look at this: > > http://effbot.org/zone/unicode-convert.htm Great ! You made my day :-) Thanks. From deets at nospam.web.de Mon May 21 07:24:43 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 21 May 2007 13:24:43 +0200 Subject: Translating some Java to Python References: <1179692679.422164.27700@r3g2000prh.googlegroups.com> <1179738814.282655.192700@r3g2000prh.googlegroups.com> <465176ce$0$323$e4fe514c@news.xs4all.nl> Message-ID: <5bddrrF2r1nupU1@mid.uni-berlin.de> > > Hmm, > > As an experienced developer I'm rather new to Python, so please forgive me > any non-Pythonic babbling. > From a language point you're probably right, but from a design point I'd > like to have methods that are clearly associated with a class as methods > of that class, even if they don't use any class or instance related data. Why so? If they _don't_ use that class, whatfor? I use classmethods for factory-methods. But that at least needs the _class_ as argument somehow, and grouping it namespace-wise below the class makes sense. Otherwise, all they do is allowing for java-programming in python - and that simply because java lacks module level functions. Diez From rahulnag22 at yahoo.com Tue May 8 17:29:17 2007 From: rahulnag22 at yahoo.com (rahulnag22 at yahoo.com) Date: 8 May 2007 14:29:17 -0700 Subject: tkinter get widget option value In-Reply-To: References: <1178649638.119603.265380@y5g2000hsa.googlegroups.com> Message-ID: <1178659757.617633.140350@y80g2000hsf.googlegroups.com> On May 8, 2:15 pm, Rob Williscroft wrote: > wrote innews:1178649638.119603.265380 at y5g2000hsa.googlegroups.comin > comp.lang.python: > > > If I have a button widget > > > w = Button(root, text = "Button", state = 'disabled') > > > How can I get the value of option 'state' from the widget 'w'. > > I want something like -- > > > print w.state >> to print out >> 'disabled' > > print w.cget( "state" ) > > Rob. > --http://www.victim-prime.dsl.pipex.com/ Thanks Rob, that does it. From deets at nospam.web.de Tue May 8 06:38:16 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 08 May 2007 12:38:16 +0200 Subject: File Name Format References: Message-ID: <5ab28oF2n4947U1@mid.uni-berlin.de> Anand wrote: > Greetings, > > How do I convert programmatically the file names from WIN32 to UNIX > format? > > A code snippet would be of great help. > We are new to python! :) unix_name = win_name.replace("\\", "/") But this of course won't work for anything that starts with a drive letter for example. Diez From steve at holdenweb.com Sat May 19 13:34:56 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 19 May 2007 13:34:56 -0400 Subject: RFC - n-puzzle.py In-Reply-To: References: <1179530104.645902.135250@p77g2000hsh.googlegroups.com> <1179566627.583978.304810@n59g2000hsh.googlegroups.com> <1179578316.956894.164140@y80g2000hsf.googlegroups.com> Message-ID: Peter Otten wrote: > Steve Holden wrote: > >> Phoe6 wrote: >>> On May 19, 2:23 pm, Raymond Hettinger wrote: >>>> Instead of: >>>> short_path = mdists[0] >>>> if mdists.count(short_path) > 1: >>>> write: >>>> short_path = mdists[0] >>>> if short_path in mdists[1:]: >>> I would like to understand the difference between the two if >>> statements. >>> I had used count method, to signify the meaning that, if the least >>> distance occurs more then proceed with block. >>> How is 'in' with list[1:] an advantage? If it is. >> Because it can stop as soon as short_path is found, whereas the count >> method must examine all elements to determine whether they should >> increment the count beyond one. > > It's a trade-off. You check only half (on average) of the items in the > original list, but in exchange copy all but one into a new list. > The idiom Raymond recommended only makes sense because comparison is "slow" > and slicing is "fast" in Python. > That's true. > If the original list were large in comparison to the available RAM the > following idiom might be preferrable: > > it = iter(mdists) > short_path = it.next() > if short_path in it: > # ... Yes, that would nail it. Though of course it loses the obviousness which both original solutions have. I suppose that's often the nature of optimizations, though. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From ckraft at SPAMTRAP.west.net Fri May 4 23:46:17 2007 From: ckraft at SPAMTRAP.west.net (Charles) Date: Sat, 05 May 2007 03:46:17 GMT Subject: Firefighters at the site of WTC7 "Move away the building is going to blow up, get back the building is going to blow up." References: <1178161820.731367.264500@y80g2000hsf.googlegroups.com> <1hlj33p6aq838o2urk1dv6h75b5is4i2vd@4ax.com> <3TD_h.219$mR2.195@newssvr22.news.prodigy.net> <1178329932.455122.161530@u30g2000hsc.googlegroups.com> Message-ID: <7hvn3358vhfo3k4iqp44167tbq6b0fnl0t@4ax.com> On Fri, 04 May 2007 20:19:33 -0700, James Stroud wrote: >MooseFET wrote: >> On May 4, 12:32 pm, James Stroud wrote: >> [....] >> >>>The Marxist contribution to western thought is that it put everything in >>>terms of labor and thus allowed us to quantify the human component of >>>economies. >> >> >> No the great insight by Marx was in the selling of ducks. "Anybody >> want to buy a duct" has done more to advance economic thinking than >> the works of most economists. >> >> Economists have a vested interest in preventing people from >> understanding economics. They are well paid and know that they >> wouldn't be for long if people really understood what was going on. >> > >You must be an economist because you provide absolutely no >interpretation of what the hell you were saying in ghe first paragraph >(as if you actually know what you were trying to say). Duct or duck, >first of all. Second of all--make a point. > >James Different Marx? From msurel at comcast.net Mon May 7 09:24:15 2007 From: msurel at comcast.net (Mike) Date: 7 May 2007 06:24:15 -0700 Subject: adding methods at runtime and lambda In-Reply-To: References: <1178221975.149008.192410@y5g2000hsa.googlegroups.com> <1178300759.455134.60560@n59g2000hsh.googlegroups.com> <1178311451.947716.231640@q75g2000hsh.googlegroups.com> Message-ID: <1178544254.978312.114990@h2g2000hsg.googlegroups.com> On May 4, 5:46 pm, Peter Otten <__pete... at web.de> wrote: > Mike wrote: > > I just realized in working with this more that the issues I was having > > with instancemethod and other things seems to be tied solely to > > What you describe below is a function that happens to be an attribute of an > instance. There are also "real" instance methods that know about "their" > instance: > > >>> import new > >>> class A(object): > > ... def __init__(self, name): > ... self.name = name > ...>>> def method(self): # a function... > > ... print self.name > ...>>> a = A("alpha") > >>> b = A("beta") > >>> a.method = new.instancemethod(method, a) # ...turned into a method... > >>> a.method() > alpha > >>> b.method() # ... but only known to a specific instance of A > > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'A' object has no attribute 'method' > > > builtins like dict or object. I remember at some point just doing > > something like: > > > x.fn = myfnFunction > > > and having it just work. > > With the caveat that x.fn is now an alias for myfnFunction, but doesn't get > x passed as its first argument (conventionally named 'self') and therefore > has no knowledge of the instance x. > > > > > If I do that with an instance of generic > > object however, I get an AttributeError. So: > > > x = object() > > x.fn = myFn > > > blows up. However, if I do > > > class nc(object):pass > > x = nc() > > x.fn = myFn > > > Then all is well. > > > checking for an ability on somebody is as simple as > > > 'fn' in dir(x) > > > or > > > hasattr(x, 'fn') > > > I had thought this was a lot easier than I was making it out to be. > > What I don't know is why using an object derived from object allows > > you to dynamically add methods like this but the base object does not. > > At this point it is more of a curiosity than anything, but if somebody > > knows the answer off the top of their head, that would be great. > > Arbitrary instance attributes are implemented via a dictionary (called > __dict__), and that incurs a certain overhead which is sometimes better to > avoid (think gazillion instances of some tiny class). For example, tuples > are derived from object but don't have a __dict__. > As a special case, what would happen if dict were to allow attributes? It > would need a __dict__ which would have a __dict__ which would have... > As a consequence object could no longer be the base class of all (newstyle) > classes. > > Peter Thanks. From john at datavoiceint.com Tue May 29 12:22:49 2007 From: john at datavoiceint.com (HMS Surprise) Date: 29 May 2007 09:22:49 -0700 Subject: Scope - import and globals Message-ID: <1180455769.891470.116360@p47g2000hsd.googlegroups.com> In the file snippet below the value for the global hostName is determined at runtime. Functions imported from the parent baseClass file such as logon also need access to this variable but cannot see it the with the implementation I have attempted here. Also, functions in this file and in the imported parent class need PyHttpTestCase. Does there need to be an import statement in both files? Thanks, jh #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ from PyHttpTestCase import PyHttpTestCase from baseClass import baseClass # definition of test class class temp(baseClass): def runTest(self): global hostName hostName = getHostNameFromUser() self.logon() From sjdevnull at yahoo.com Wed May 16 05:24:48 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 16 May 2007 02:24:48 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179305839.190121.177990@e65g2000hsc.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649dd55$0$23144$9b4e6d93@newsspool1.arcor-online.net> <464a25e9$0$10188$9b4e6d93@newsspool4.arcor-online.net> <464A3354.4060205@web.de> <1179305839.190121.177990@e65g2000hsc.googlegroups.com> Message-ID: <1179307488.083859.93410@p77g2000hsh.googlegroups.com> Ben wrote: > On May 15, 11:25 pm, Stefan Behnel > wrote: > > Rene Fleschenberg wrote: > > > Javier Bezos schrieb: > > >>> But having, for example, things like open() from the stdlib in your code > > >>> and then o:ffnen() as a name for functions/methods written by yourself is > > >>> just plain silly. It makes the code inconsistent and ugly without > > >>> significantly improving the readability for someone who speaks German > > >>> but not English. > > >> Agreed. I always use English names (more or > > >> less :-)), but this is not the PEP is about. > > > > > We all know what the PEP is about (we can read). The point is: If we do > > > not *need* non-English/ASCII identifiers, we do not need the PEP. If the > > > PEP does not solve an actual *problem* and still introduces some > > > potential for *new* problems, it should be rejected. So far, the > > > "problem" seems to just not exist. The burden of proof is on those who > > > support the PEP. > > > > The main problem here seems to be proving the need of something to people who > > do not need it themselves. So, if a simple "but I need it because a, b, c" is > > not enough, what good is any further prove? > > > > Stefan > > For what it's worth, I can only speak English (bad English schooling!) > and I'm definitely +1 on the PEP. Anyone using tools from the last 5 > years can handle UTF-8 The falsehood of the last sentence is why I'm moderately against this PEP. Even examples within this thread don't display correctly on several of the machines I have access too (all of which are less than 5 year old OS/browser environments). It strikes me a similar to the arguments for quoted-printable in the early 1990s, claiming that everyone can view it or will be able to soon--and even a decade _after_ "everyone can deal with latin1 just fine" it was still causing massive headaches. From bruno.desthuilliers at gmail.com Mon May 28 06:02:02 2007 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: 28 May 2007 03:02:02 -0700 Subject: conditionally creating functions within a class? In-Reply-To: References: <163f0ce20705251744j5c728e9fn53585fe0c9250827@mail.gmail.com> Message-ID: <1180346522.922275.222870@w5g2000hsg.googlegroups.com> On 26 mai, 04:14, Steve Holden wrote: (snip) > one of the primary ideas behind object > orientation is that the class defines the same methods for all instances. > While this is effectively the standard behaviour in class-based OOPLs, I would definitively not present this as "one of the primary ideas behind" OO, since nothing in OO "primary ideas" mandate the explicit of classes. From dhwild at talktalk.net Wed May 30 05:01:52 2007 From: dhwild at talktalk.net (David H Wild) Date: Wed, 30 May 2007 10:01:52 +0100 Subject: Speex bindings for python 2.5 References: <1180466922.114571.46410@d30g2000prg.googlegroups.com> <1180467121.238065.111720@r19g2000prf.googlegroups.com> <1180485052.149837.105080@a26g2000pre.googlegroups.com> Message-ID: <465d45ab$0$1341$834e42db@reader.greatnowhere.com> In article <1180485052.149837.105080 at a26g2000pre.googlegroups.com>, momobear wrote: > > I forgot to give the url :http://www.freenet.org.nz/python/pySpeex/ > I Couldn't Open the website. It works if you knock the colon off the front of the URL as given. -- David Wild using RISC OS on broadband www.davidhwild.me.uk From noagbodjivictor at gmail.com Tue May 1 17:43:57 2007 From: noagbodjivictor at gmail.com (noagbodjivictor at gmail.com) Date: 1 May 2007 14:43:57 -0700 Subject: Python for Windows other way to getting it? In-Reply-To: <59pp42F2jtk6gU2@mid.uni-berlin.de> References: <1178051916.033367.205320@h2g2000hsg.googlegroups.com> <59pp42F2jtk6gU2@mid.uni-berlin.de> Message-ID: <1178055837.723546.228980@n59g2000hsh.googlegroups.com> On May 1, 5:17 pm, "Diez B. Roggisch" wrote: > noagbodjivic... at gmail.com schrieb: > > > Hello > > I don't have permission to install new application on the PC I'm > > using, I need a zipped version of python that I can copy on my > > external drive. Where can I get a zip version? > > http://www.voidspace.org.uk/python/movpy/ > > Diez Thank you Diez, as a student I was hoping for an open source version. There are none [good project for an experienced programmer]. But I have however found an old stand alone version here : http://arctrix.com/nas/python/standalone.html From jadestar at idiom.com Wed May 30 23:29:42 2007 From: jadestar at idiom.com (James T. Dennis) Date: Thu, 31 May 2007 03:29:42 -0000 Subject: Newbie question about string(passing by ref) References: <1178833397.076720.279940@l77g2000hsb.googlegroups.com> Message-ID: <1180582181.742975@smirk> Duncan Booth wrote: > lazy wrote: >> I want to pass a string by reference. I understand that strings are >> immutable, but Im not >> going to change the string in the function, just to aviod the overhead >> of copying(when pass-by-value) because the >> strings are long and this function will be called over and over >> again. > You'll find it is pretty hard to get Python to copy a string even if you > wanted it to. About the only way is to break it apart and then construct a > new string with the same value from it. This, of course, is an implementation detail. There are other programming languages which use "interned" objects and, as far as I know, they are considered implementation details with undefined semantics. (In other words you are supposed to ignore this detail and not rely on the identity of any particular objects except those which are defined as such by the language). (An example, in Python, of an object with a defined identity would be "None" --- all references to "None" are intentionally references to a single object and it is the most notable case where the "is" operator is preferred). That said it seems to be trivially easy to "copy" a short string in the version of Python I'm using here: Python 2.4.4 (#2, Oct 20 2006, 00:23:25) [GCC 4.1.2 20061015 (prerelease) (Debian 4.1.1-16.1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> foo = "foo" >>> bar = "".join(list(foo)) >>> id(foo); id(bar); foo is bar -1211235616 -1211235296 False >>> -- Jim Dennis, Starshine: Signed, Sealed, Delivered From roy at panix.com Mon May 28 10:50:54 2007 From: roy at panix.com (Roy Smith) Date: Mon, 28 May 2007 10:50:54 -0400 Subject: Is PEP-8 a Code or More of a Guideline? References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> Message-ID: In article , Steven Bethard wrote: > Stefan Sonnenberg-Carstens wrote: > > Paul McGuire schrieb: > >> I'm starting a new thread for this topic, so as not to hijack the one > >> started by Steve Howell's excellent post titled "ten small Python > >> programs". > >> > >> In that thread, there was a suggestion that these examples should > >> conform to PEP-8's style recommendations, including use of > >> lower_case_with_underscores style for function names. I raised some > >> questions about this suggestion, since I liked the names the way they > >> were, but as a result, part of the discussion has drifted into a > >> separate track about PEP-8, and naming styles. > > > > I prefer mixedCaseStyle, and I think that should be "standard", as this > > style is commonly > > used in all "major" languages , for example Java,C++,C#. > > It shortens the identifiers but leaves the meaning intact. > > The argument for under_score_names is usually that non-native speakers > can more easily find the word boundaries. Not being a non-native speaker > ;-) I can't verify that one, but it's pretty plausible given the current > amount of money spent on research on automatic word-segmentation for > languages like Chinese. =) > > STeVe I've gone through a few different flavors of composite name schemes over the years (starting with FORTRAN's 6 upper case character limit). When first exposed to camelCase, I thought it was horrible. Eventually, I came to like it. On the other hand, I'm convinced that words_with_underscores, is easier to read. This is especially true when abbreviations creep into variable names. It's certainly easier to parse ip_address as compared to IPAddress. Same with snmp_manager vs SNMPManager. I really like lisp's convention of using dashes instead of underscores, i.e. ip-address and snmp-manager. I think the only reason most languages don't use that is the parsing ambiguity, but if you required white space around all operators, then "ip-address" would unambiguously be a variable name and "ip - address" would be a subtraction expression. From john at datavoiceint.com Mon May 7 19:41:49 2007 From: john at datavoiceint.com (HMS Surprise) Date: 7 May 2007 16:41:49 -0700 Subject: No module named urllib In-Reply-To: <87hcqop5w1.fsf@gmail.com> References: <1178575589.059564.226060@q75g2000hsh.googlegroups.com> <87tzuop8s2.fsf@gmail.com> <1178577562.498615.222340@e51g2000hsg.googlegroups.com> <87ps5cp816.fsf@gmail.com> <1178578923.067315.14440@q75g2000hsh.googlegroups.com> <1178580280.902179.248000@w5g2000hsg.googlegroups.com> <87hcqop5w1.fsf@gmail.com> Message-ID: <1178581309.003967.214380@o5g2000hsb.googlegroups.com> On May 7, 6:31 pm, Jorge Godoy wrote: > HMS Surprise writes: > > Since sys.path = ['.', 'C:\\maxq\\lib\\Lib', 'C:\\maxq\\jython'] I > > copied urllib to c:\maxq\lib\Lib. > > > Now I get the error - > > > Traceback (innermost last): > > File "", line 5, in ? > > File "C:\maxq\lib\Lib\urllib.py", line 1148 > > _hextochr = dict(('%02x' % i, chr(i)) for i in range(256)) > > ^ > > SyntaxError: invalid syntax > >>> dict(1, 1) > > Traceback (most recent call last): > File "", line 1, in > TypeError: dict expected at most 1 arguments, got 2 > > >>> dict(a=1) > {'a': 1} > > -- > Jorge Godoy Using the 18.5.2 Examples and a few lines added in from CompactTest import CompactTest import sys print sys.path import urllib class login(CompactTest): # Recorded test actions. def runTest(self): self.msg('Test started') opener = urllib.FancyURLopener({}) f = opener.open("http://www.python.org/") f.read() # Code to load and run the test if __name__ == 'main': login('login').Run() From sjmachin at lexicon.net Sat May 12 19:12:29 2007 From: sjmachin at lexicon.net (John Machin) Date: 12 May 2007 16:12:29 -0700 Subject: Bug? import cp1252 In-Reply-To: <46462b1a$0$25919$ba4acef3@news.orange.fr> References: <46462b1a$0$25919$ba4acef3@news.orange.fr> Message-ID: <1179011549.196725.300860@y80g2000hsf.googlegroups.com> On May 13, 3:33 am, "M?ta-MCI" wrote: > Hi! > > I've a problem with these 2 scripts: > > file aaa.py (write in ANSI/cp1252): What is "ANSI/cp1252"??? > > # -*- coding: cp1252 -*- > > compo={} > > compo['pxrtf']= { > 'fichier': "pxrtf.py", > 'description': "G?n?ration de fichiers RTF" > } > > file bbb.py (write in ANSI/cp1252): > > # -*- coding: cp1252 -*- > > import aaa > > With run bbb.py, I see: > > Traceback (most recent call last): > File "D:\dev\python\bbb.py", line 3, in > import aaa > File "D:\dev\python\aaa.py", line 3 > > ^ > SyntaxError: invalid syntax > > (run directly aaa.py give no problem) > > (Python 2.5.1 + win_XP-SP2_french) > > BUT, if I write the file aaa.py in UTF-8, with 1st line: # -*- coding: > utf-8 -*- > the problem is removed (file bbb.py stay in ANSI/cp1252) > > Bug? or am I wrong? > > @-salutations > Michel, I can't reproduce this -- Python 2.5.1, Windows XP Pro SP2 Given that the syntax error seems to be pointing to a blank empty line, I suspect that's there's some invisible character in the file. This would be likely not to show up when we view your file through a web browser or news client. I suggest that you show us *exactly* what you've got: print open('aaa.py', 'rb').read() HTH, John From tijs_news at bluescraper.com Thu May 31 09:15:02 2007 From: tijs_news at bluescraper.com (Tijs) Date: Thu, 31 May 2007 15:15:02 +0200 Subject: file reading by record separator (not line by line) References: <1180614374.027569.235540@g4g2000hsf.googlegroups.com> <1180615143.228557.258760@g4g2000hsf.googlegroups.com> <1180616302.063134.108170@p77g2000hsh.googlegroups.com> Message-ID: <465eca56$0$327$e4fe514c@news.xs4all.nl> aspineux wrote: > > something like > > name=None > lines=[] > for line in open('yourfilename.txt'): > if line.startwith('>'): > if name!=None: > print 'Here is the record', name > print lines > print > name=line.stripr('\r') > lines=[] > else: > lines.append(line.stripr('\n')) > That would miss the last chunk. -- Regards, Tijs From broek at cc.umanitoba.ca Fri May 25 13:04:07 2007 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Fri, 25 May 2007 13:04:07 -0400 Subject: webbrowser module bug? In-Reply-To: References: <1180106384.198363.14120@p47g2000hsd.googlegroups.com> Message-ID: <46571707.8020702@cc.umanitoba.ca> Ron Adam said unto the world upon 05/25/2007 12:28 PM: > kyosohma at gmail.com wrote: >> On May 24, 5:03 pm, Ron Adam wrote: >>> Is anyone else having problems with the webbrowser module? >>> >>> Python 2.5.1c1 (release25-maint, Apr 12 2007, 21:00:25) >>> [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 >>> Type "help", "copyright", "credits" or "license" for more information. >>> >>> import webbrowser >>> >>> webbrowser.open('http://www.python.org') >>> True >>> >>> >>> >>> It opens firefox as expected, but the url is ... >>> >>> file:///home/ron/%22http://www.python.org%22 >>> >>> Which of course doesn't do what is expected. >>> >>> Any ideas? > > It works for me on python 2.4 also, but not on later versions. > > Looks like I'll need to try to test the url at the point where it calls the > browser from webbrowser.py. > > Can someone else test this on python 2.5? > > Ron Works fine for me on ubuntu 7.04 (fiesty) with Python 2.5.1c1, which appear to be your set-up, too. Python 2.5.1c1 (release25-maint, Apr 12 2007, 21:00:25) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import webbrowser >>> webbrowser.open('http://www.python.org') True >>> Best, Brian vdB From attn.steven.kuo at gmail.com Tue May 22 11:27:39 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 22 May 2007 08:27:39 -0700 Subject: converting text and spans to an ElementTree In-Reply-To: References: Message-ID: <1179847659.770231.115490@r3g2000prh.googlegroups.com> On May 21, 11:02 pm, Steven Bethard wrote: > I have some text and a list of Element objects and their offsets, e.g.:: > > >>> text = 'aaa aaa aaabbb bbbaaa' > >>> spans = [ > ... (etree.Element('a'), 0, 21), > ... (etree.Element('b'), 11, 18), > ... (etree.Element('c'), 18, 18), > ... ] > > I'd like to produce the corresponding ElementTree. So I want to write a > get_tree() function that works like:: > > >>> tree = get_tree(text, spans) > >>> etree.tostring(tree) > 'aaa aaa aaabbb bbbaaa' > > Perhaps I just need some more sleep, but I can't see an obvious way to > do this. Any suggestions? > It seems you're looking to construct an Interval Tree: http://en.wikipedia.org/wiki/Interval_tree -- Hope this helps, Steven From castironpi at gmail.com Fri May 11 02:47:06 2007 From: castironpi at gmail.com (castironpi at gmail.com) Date: 10 May 2007 23:47:06 -0700 Subject: How to find C source In-Reply-To: References: <1178844459.271906.92560@o5g2000hsb.googlegroups.com> Message-ID: <1178866025.795419.63450@q75g2000hsh.googlegroups.com> On May 10, 8:36 pm, "Gabriel Genellina" wrote: > En Thu, 10 May 2007 21:47:39 -0300, escribi?: > > > How do I get to the source for parser.suite()? > > Are you looking for function parser_suite in parsermodule.c? > > -- > Gabriel Genellina Looks like -it-. Thank you for your time. From tjreedy at udel.edu Sun May 13 22:12:30 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 13 May 2007 22:12:30 -0400 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <1u9kz7l2gcz1p.1e0kxqeikfp97.dlg@40tude.net> Message-ID: "Alan Franzoni" wrote in message news:1u9kz7l2gcz1p.1e0kxqeikfp97.dlg at 40tude.net... Il Sun, 13 May 2007 17:44:39 +0200, "Martin v. L?wis" ha scritto: |Also, there should be a way to convert source files in any 'exotic' encoding to a pseudo-intellegibile encoding for any reader, a kind of translittering (is that a proper english word) system out-of-the-box, not requiring any other tool that's not included in the Python distro. This will let people to retain their usual working environments even though they're dealing with source code with identifiers in a really different charset. ============================= When I proposed that PEP3131 include transliteration support, Martin rejected the idea. tjr From attn.steven.kuo at gmail.com Thu May 31 01:55:44 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 30 May 2007 22:55:44 -0700 Subject: Usage of the __and__ method In-Reply-To: <1180588305.004419.127680@d30g2000prg.googlegroups.com> References: <1180588305.004419.127680@d30g2000prg.googlegroups.com> Message-ID: <1180590944.469615.49150@p47g2000hsd.googlegroups.com> On May 30, 10:11 pm, theju wrote: > Hello all, > I've two objects (both instances of a class called Person) and I want > to use the __and__ method and print the combined attributes of the two > instances. > > To be precise, here is my code.... > > class Person: > def __init__(self,name): > self.name = name > def print_name(self): > print self.name > def __and__(self,other): > self.name = '%s AND %s' %(self.name,other.name) > return self.name > > p = Person("John") > q = Person("George") > > r = p and q > print r.print_name() Try: class Person(object): def __init__(self, name): self.name = name def __and__(self, other): return '%s AND %s' % (self.name, other.name) p = Person("John") q = Person("George") r = p & q print r (1) A "getter" method (like your print_name method) is usually not needed, just access the attribute of the instance. Like, print p.name (2) I doubt that you want the __and__ special method to alter the name attribute of an instance. (3) You want to use the '&' operator to dispatch to the __and__ method; __and__ is typically used for Numeric objects. (4) You misunderstood how the 'and' operator is used. The expression 'p and q' causes p to be evaluated; if p is false, its value is returned; otherwise q is evaluated and its value is returned. -- Hope this helps, Steven From aisaac at american.edu Wed May 9 11:47:04 2007 From: aisaac at american.edu (Alan G Isaac) Date: Wed, 09 May 2007 10:47:04 -0500 Subject: change of random state when pyc created?? In-Reply-To: <5ae25fF2oggbqU1@mid.uni-berlin.de> References: <5ae25fF2oggbqU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Not really, but that depends on what you know about the concept of sets and > maps as collections of course. > > The contract for sets and dicts doesn't imply any order whatsoever. Which is > essentially the reason why > > set(xrange(10))[0] > > doesn't exist, and quite a few times cries for an ordered dictionary as part > of the standard libraries was made. It seems to me that you are missing the point, but maybe I am missing your point. The question of whether a set or dict guarantees some order seems quite different from the question of whether rerunning an **unchanged program** yields the **unchanged results**. The latter question is the question of replicability. Again I point out that some sophisticated users (among which I am not numbering myself) did not see into the source of this "anomaly". This suggests that an explicit warning is warranted. Cheers, Alan Isaac PS I know ordered dicts are under discussion; what about ordered sets? From resmith5 at yahoo.com Tue May 29 14:40:14 2007 From: resmith5 at yahoo.com (Simon) Date: 29 May 2007 11:40:14 -0700 Subject: python unix install, sqlite3 In-Reply-To: <1180447556.474075.12800@q19g2000prn.googlegroups.com> References: <1180443141.119281.304880@q66g2000hsg.googlegroups.com> <1180447556.474075.12800@q19g2000prn.googlegroups.com> Message-ID: <1180464013.989484.165910@q69g2000hsb.googlegroups.com> On May 29, 7:05 am, vasudevram wrote: > On May 29, 5:52 pm, Simon wrote: > > > > > > > I installed the source code on unix for python 2.5.1. The install went > > mainly okay, except for some failures regarding: > > _ssl, _hashlib, _curses, _curses_panel. > > > No errors regarding sqlite3. > > However, when I start python and do an import sqlite3 I get: > > > /ptmp/bin/> python > > Python 2.5.1 (r251:54863, May 29 2007, 05:19:30) > > [GCC 3.3.2] on sunos5 > > Type "help", "copyright", "credits" or "license" for more information.>>> import sqlite3 > > > Traceback (most recent call last): > > File "", line 1, in > > File "/ptmp/Python-2.5.1/lib/python2.5/sqlite3/__init__.py", line > > 24, in > > from dbapi2 import * > > File "/ptmp/Python-2.5.1/lib/python2.5/sqlite3/dbapi2.py", line 27, > > in > > from _sqlite3 import * > > ImportError: No module named _sqlite3 > > Some ideas: > > I don't know if sqlite3 comes bundled with the standard Python source > bundle. My guess is not. If not, that's the cause of the error - you > need to install sqlite3 (and probably pysqlite3 (not sure of the name > (whether it has a trailing 3) which, if I remember, is the Python > binding/wrapper for sqlite3 (which is a C library, I think). Other > possible cause of the error (if sqlite3 _is_ bundled with Python and > no Python binding/wrapper is needed, is that sqlite3 depends on one of > those other libraries you mention (such as _hashlib) for which you got > errors while installing Python from source. > > HTH > Vasudev Ram > Dancing Bison Enterpriseswww.dancingbison.com- Hide quoted text - > > - Show quoted text - Vasudev, Thanks so much for the reply. I went to their website and your guess was correct. Python 2.5 has included support for sqlite but it only includes the PySqlite interface module (now called sqlite3). It does not include sqlite3 with the source distribution. Simon From Marie at christalarico.com Thu May 3 17:20:48 2007 From: Marie at christalarico.com (Marie) Date: Thu, 3 May 2007 17:20:48 -0400 Subject: PHP or Python Developer needed Message-ID: <52451FA9C52ABE4A84734D856AACF281911784@NTSERVER> I represent Chris TALARICO & Associates, Inc., an award winning personnel placement service. Our client seeks a PHP or Python developer for a 2-6 month assignment in Reading, PA. Please contact me if you would be interested in learning more about this opportunity or if you know of someone who would be interested. Thank you. Sincerely, Marie Fretz Vice President Chris TALARICO & Associates, Inc. Historic Centre Park District 401 Oley Street Reading, PA 19601 (610) 478-1151 Fax (610) 478-1162 (T, F) (610) 689-0827 Fax (610) 689-0828 (M, W, TH) Toll Free 1-877-CTA-0115 -------------- next part -------------- An HTML attachment was scrubbed... URL: From mcl.office at googlemail.com Mon May 21 10:21:18 2007 From: mcl.office at googlemail.com (mosscliffe) Date: 21 May 2007 07:21:18 -0700 Subject: NEWBIE: Extending a For Statement. In-Reply-To: <1179756164.506426.116210@x18g2000prd.googlegroups.com> References: <1179749446.179064.222990@z28g2000prd.googlegroups.com> <1179756164.506426.116210@x18g2000prd.googlegroups.com> Message-ID: <1179757278.283371.263860@y2g2000prf.googlegroups.com> On 21 May, 15:02, bearophileH... at lycos.com wrote: > mosscliffe: > > > if key in xrange (60,69) or key == 3: > > I keep seeing again and again code like this, mostly from people not > much expert of Python, but the PEP 260 shows the fast in was removed, > so it's O(n). Maybe removing the fast __contains__ was bad for > necomers (or just the casual Python users, that I belive is really > large). > > Bye, > bearophile Being a non-expert in python in fact just a beginner / casual user, can you expand on how 0(n) relates to if key in xrange (60,69) or key == 3: My mind tends to go blank at the mention of __xxx__. R From half.italian at gmail.com Sat May 12 00:33:54 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 11 May 2007 21:33:54 -0700 Subject: os.popen on windows: loosing stdout of child process In-Reply-To: References: Message-ID: <1178944434.301781.201630@w5g2000hsg.googlegroups.com> On May 11, 8:46 pm, Greg Ercolano wrote: > When I use os.popen(cmd,'w'), I find that under windows, the stdout > of the child process disappears, instead of appearing in the DOS window > the script is invoked from. eg: > > C:\> type foo.py > import os > import sys > file = os.popen("nslookup", 'w') > file.write("google.com\n") > file.close() > > C:\> python foo.py > <-- nothing is printed > C:\> > > This just seems wrong. The following DOS equivalent works fine: > > C:\> echo google.com | nslookup > Default Server: dns.erco.x > Address: 192.168.1.14 > [..expected output..] > > When I run the same python program on a unix box, the output > from 'nslookup' appears in the terminal, as I'd expect. > > Shouldn't popen() be consistent in its handling of the child's > stdout and stderr across platforms? > > Maybe I'm missing something, being somewhat new to python, but > an old hand at unix and win32 and functions like popen(). Didn't > see anything in the docs for popen(), and I googled around quite > a bit on the web and groups for eg. 'python windows popen stdout lost' > and found nothing useful. > > FWIW, I'm using the windows version of python 2.5 from activestate. Glad to see you're finally coming into the light Greg! I've used Rush in a few different studios over the past couple of years. We even had sushi once. :) I'm no expert like you, but I think I can point you in the right direction. You need os.popen2 which returns a tuple of file-like objects. The first pointing to stdin, and the second pointing to stdout. Write to stdin, and read from stdout. import os import sys stdin, stdout = os.popen2("nslookup") stdin.write("google.com\n") stdin.close() print stdout.read() stdout.close() I don't use windows much, but I believe the os.popen functionality is being replaced by subprocess.Popen: from subprocess import * import sys p = Popen("nslookup", shell=True, bufsize=1024, stdin=PIPE, stdout=PIPE, close_fds=True) p.stdin.write("google.com\n") p.stdin.close() print p.stdout.read() p.stdout.close() I found these: http://pydoc.org/2.4.1/subprocess.html http://docs.python.org/lib/module-subprocess.html ~Sean DiZazzo Curious George From stefan.behnel-n05pAM at web.de Wed May 16 04:45:06 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 16 May 2007 10:45:06 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464ac189$0$20297$9b4e6d93@newsspool3.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649dd55$0$23144$9b4e6d93@newsspool1.arcor-online.net> <464a25e9$0$10188$9b4e6d93@newsspool4.arcor-online.net> <1179291296.561359.286230@h2g2000hsg.googlegroups.com> <464ab64f$0$10185$9b4e6d93@newsspool4.arcor-online.net> <464AB9F2.60906@web.de> <464ac189$0$20297$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <464ac493$0$6394$9b4e6d93@newsspool2.arcor-online.net> Ren? Fleschenberg wrote: > Stefan Behnel schrieb: >>>> - Non-english speakers can not create or understand >>>> english identifiers hence can't create good code nor >>>> easily grok existing code. >>> I agree that this is a problem, but please understand that is problem is >>> _not_ solved by allowing non-ASCII identifiers! >> Well, as I said before, there are three major differences between the stdlib >> and keywords on one hand and identifiers on the other hand. Ignoring arguments >> does not make them any less true. > > I agree that keywords are a different matter in many respects, but the > only difference between stdlib interfaces and other intefaces is that > the stdlib interfaces are part of the stdlib. That's it. You are still > ignoring the fact that, contrary to what has been suggested in this > thread, it is _not_ possible to write "German" or "Chinese" Python > without cluttering it up with many many English terms. It's not only the > stdlib, but also many many third party libraries. Show me one real > Python program that is feasibly written without throwing in tons of > English terms. > > Now, very special environments (what I called "rare and isolated" > earlier) like special learning environments for children are a different > matter. It should be ok if you have to use a specially patched Python > branch there, or have to use an interpreter option that enables the > suggested behaviour. For general programming, it IMO is a bad idea. Ok, let me put it differently. You *do not* design Python's keywords. You *do not* design the stdlib. You *do not* design the concepts behind all that. You *use* them as they are. So you can simply take the identifiers they define and use them the way the docs say. You do not have to understand these names, they don't have to be words, they don't have to mean anything to you. They are just tools. Even if you do not understand English, they will not get in your way. You just learn them. But you *do* design your own software. You *do* design its concepts. You *do* design its APIs. You *do* choose its identifiers. And you want them to be clear and telling. You want them to match your (or your clients) view of the application. You do not care about the naming of the tools you use inside. But you do care about clarity and readability in *your own software*. See the little difference here? Stefan From john at datavoiceint.com Tue May 15 15:12:49 2007 From: john at datavoiceint.com (HMS Surprise) Date: 15 May 2007 12:12:49 -0700 Subject: Splitting a string In-Reply-To: <1179255862.021110.248520@o5g2000hsb.googlegroups.com> References: <1179253692.110024.96330@w5g2000hsg.googlegroups.com> <1179255862.021110.248520@o5g2000hsb.googlegroups.com> Message-ID: <1179256369.723452.122640@q75g2000hsh.googlegroups.com> On May 15, 2:04 pm, Nick Vatamaniuc wrote: > On May 15, 2:28 pm, HMS Surprise wrote: > > > > > The string s below has single and double qoutes in it. For testing I > > surrounded it with triple single quotes. I want to split off the > > portion before the first \, but my split that works with shorter > > strings does not seem to work with this one. > > > Ideas? > > > Thanks, > > jvh > > > s = ''''D132258\',\'\', > > \'status=no,location=no,width=630,height=550,left=200,top=100\')" > > target="_blank" class="dvLink" title="Send an Email to selected > > employee">''' > > > t = s.split('\\') > > jvh, > For your split operation to work you would need your string to be in > raw format (add an 'r' in front of it). That way all your back slashes > won't be interpreted. Or you'll just have to split on ',' instead of > '\'. The first '\' is not there technically because it just escapes > the ( ' ). So when your actual string just has a quote ( ' ) an not > '\'. If it were a raw string, then all your backslashes would have > been there. (just print s and see what you get!). > > >>> s=r''''D132258\',\'\', > > ....: > \'status=no,location=no,width=630,height=550,left=200,top=100\')" > ....: target="_blank" class="dvLink" title="Send an Email to > selected > ....: employee">'''>>> s > > '\'D132258\\\',\\\'\\\',\n\\ > \'status=no,location=no,width=630,height=550,left=200,top=100\\ > \')"\ntarget="_blank" class="dvLink" title="Send an Email to selected > \nemployee">'>>> print s > > 'D132258\',\'\', > \'status=no,location=no,width=630,height=550,left=200,top=100\')" > target="_blank" class="dvLink" title="Send an Email to selected > employee"> > > >>> s.split('\\') > > ["'D132258", > "',", > "'", > "',\n", > "'status=no,location=no,width=630,height=550,left=200,top=100", > '\')"\ntarget="_blank" class="dvLink" title="Send an Email to selected > \nemployee">'] > > -Nick Vatamaniuc Thanks Nick. However I do not have the option of putting the r in front of the source string as it comes the function as a variable from another source. Unless it would be permissible to evaluate the concantenation some way. But what you have written is instructive and I appreciate your time. jh From JoeSalmeri at hotmail.com Fri May 18 20:50:25 2007 From: JoeSalmeri at hotmail.com (Joe Salmeri) Date: Fri, 18 May 2007 20:50:25 -0400 Subject: pyodbc data corruption problem References: <1179533525.685271.43670@n59g2000hsh.googlegroups.com> Message-ID: Thank you for your response but this is not an Access problem. The exact same code using mx.ODBC or using the old odbc.py that comes with the win32 files works fine. It only fails with pyodbc. wrote in message news:1179533525.685271.43670 at n59g2000hsh.googlegroups.com... > On May 18, 6:46 pm, "Joe Salmeri" wrote: >> I have found a data corruption problem with pyodbc. >> >> OS = Windows XP SP2 >> DB = Microsoft Access XP >> >> PROBLEM: >> >> When selecting columns from a table that are of type Memo the value >> returned is padded with a bunch of null characters at the end. >> >> The problems does not seem to occur until the length of the Memo column >> exceeds 2048 bytes. > > Interesting. MS-Access has had a bug about Memo fields > ever since Version 2.0 (the last time it worked). I was trying > to use a Memo field on a form and append short status messages. > This mysteriously stopped working in the version following 2.0 > (Access 95?) and has never worked since. Seems there is some > kind of 2048 buffer involved that was created by some punk > MicroSoft gave the lowly job of software revision to while > those more educated did more important things. > > My guess is you won't find a Python solution short of > accepting what Access gives you and dealing with it. > >> >> I have attached several scripts to help demonstrate the problem. >> >> To recreate the problem: >> >> 1. Create a blank Access database named test. >> 2. Create a ODBC DSN named test for that database >> 3. Run the createtable.py script to create the table >> and load it with the dummy data >> 4. Run the broke.py script to show the problem. >> >> The issue is when the data value is > 2048 bytes. >> >> The size in the createtable.py is 2046 bytes plus 3 bytes at the end that >> contain "JOE" for a total of 2049 bytes. >> >> If you change it from 2046 to 2045 (or less) then the problem does not >> occur. >> >> # >> # createtable.py script >> # >> >> import pyodbc >> >> dbs = pyodbc.connect('dsn=test') >> >> c = dbs.cursor() >> >> try: >> sql = 'drop table test_memo' >> c.execute(sql) >> dbs.commit() >> except: >> # ignore drop table failure >> pass >> >> sql = 'create table test_memo (c1 int not null, c2 memo not null)' >> >> c.execute(sql) >> >> dbs.commit() >> >> sql = 'insert into test_memo values(1, ?)' >> >> c2_value = '1' * 2046 >> >> c2_value = '%sJOE' % (c2_value) >> >> c.execute(sql, (c2_value,)) >> >> dbs.commit() >> >> c.close() >> dbs.close() >> >> # >> # broke.py script >> # >> >> import pyodbc >> >> dbs = pyodbc.connect('dsn=test') >> >> c = dbs.cursor() >> >> sql = 'select c2, len(c2) as c2_db_len from test_memo where c1 = 1' >> >> c.execute(sql) >> >> row = c.fetchone() >> >> ( >> c2, >> c2_db_len >> ) = row >> >> print repr(c2) >> >> print 'c2 length :', len(c2) >> print 'c2_db_length :', c2_db_len >> >> print 'before nul length:', len(c2[0:c2.find('\x00')]) >> >> c.close() >> dbs.close() > > From sjdevnull at yahoo.com Thu May 17 18:30:50 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 17 May 2007 15:30:50 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <464C5382.6080403@v.loewis.de> <1179423799.254286.294930@w5g2000hsg.googlegroups.com> Message-ID: <1179441050.656539.277900@o5g2000hsb.googlegroups.com> On May 17, 2:30 pm, Gregor Horvath wrote: > Istvan Albert schrieb: > > > > > After the first time that your programmer friends need fix a trivial > > bug in a piece of code that does not display correctly in the terminal > > I can assure you that their mellow acceptance will turn to something > > entirely different. > > Is there any difference for you in debugging this code snippets? > > class T?rstock(object): [snip] > class Tuerstock(object): After finding a platform where those are different, I have to say yes. Absolutely. In my normal setup they both display as "class Tuerstock" (three letters 'T' 'u' 'e' starting the class name). If, say, an exception was raised, it'd be fruitless for me to grep or search for "Tuerstock" in the first one, and I might wind up wasting a fair amount of time if a user emailed that to me before realizing that the stack trace was just wrong. Even if I had extended character support, there's no guarantee that all the users I'm supporting do. If they do, there's no guarantee that some intervening email system (or whatever) won't munge things. With the second one, all my standard tools would work fine. My user's setups will work with it. And there's a much higher chance that all the intervening systems will work with it. From newsgroups at nospam.demon.co.uk Fri May 18 03:15:09 2007 From: newsgroups at nospam.demon.co.uk (Douglas Woodrow) Date: Fri, 18 May 2007 08:15:09 +0100 Subject: Execute commands from file References: <1179320782.594398.67980@u30g2000hsc.googlegroups.com> <464b370c$0$3808$5402220f@news.sunrise.ch> <1179387023.005808.60670@o5g2000hsb.googlegroups.com> <1179432730.143022.66340@y80g2000hsf.googlegroups.com> Message-ID: On Fri, 18 May 2007 04:45:30, Dennis Lee Bieber wrote >On 17 May 2007 13:12:10 -0700, i3dmaster declaimed >the following in comp.lang.python: > >> 'b' is generally useful on systems that don't treat binary and text >> files differently. It will improve portability. > > "b" is needed for binary files on systems that /do/ treat binary >differently from text. And it does add to portability only in that it >has no effect on those that treat all files the same. > > However, as I recall the thread, the intent is to process text lines >from a file -- and using "b" is going to affect how the line endings are >being treated. Yes that was my understanding too, Dennis, and the reason I queried it in the first place. I had to remove the "b" option in order to get the sample code to work under Windows, because the standard line termination under Windows is carriage return + linefeed (\r\n). Of course if I manually edit the command file so that it only has a linefeed character at the end of each line, the binary mode works. So I think i3dmaster's method is only portable as long as the command file is created with unix-style line termination. -- Doug Woodrow From steve at holdenweb.com Sat May 19 09:32:00 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 19 May 2007 09:32:00 -0400 Subject: Execute commands from file In-Reply-To: <464ee1b6$0$3812$5402220f@news.sunrise.ch> References: <1179320782.594398.67980@u30g2000hsc.googlegroups.com> <464b370c$0$3808$5402220f@news.sunrise.ch> <1179387023.005808.60670@o5g2000hsb.googlegroups.com> <464c7e99$0$3814$5402220f@news.sunrise.ch> <464ee1b6$0$3812$5402220f@news.sunrise.ch> Message-ID: Martin Blume wrote: > "Steve Holden" schrieb >>> [ difference between exec open(fname).read() >>> and for line in open(fname): exec line ] >>> >>> So it seems to depend on the way the file is read. >>> >> It depends on the way the lines of the file are executed, >> not how they are read. >> > Could you elaborate a little bit more on the difference? > I assumed that because read() reads the whole file, the > body of my function sowhat() is present, so that it can > be parsed while the invocation of exec is still running. > If it is read and exec'd line by line, the definition of > the function is still left open at the moment exec() ends, > causing the "EOF" error. Hence my statement, "it depends > on the way the file is read". > I simply meant that the whole source has to be presented to the exec statement and not chunked into lines. Clearly I could read all the source in with lines = open(cmd_file).readlines() but if you then proceed to try and execute the source line by line as in for l in lines: exec l you will hit problems because of the disjoint nature of the execution which will breal up indented suites and so on. I was probably just a little over-zealous in pursuing correct English usage, in which case please accept my apology. > >> And you may remember the original poster was >> proposing this: >> >> inp = open(cmd_file) >> for line in inp: >> exec line >> >> As for your first example, why not just use execfile() ? >> > I assume that > execfile(fname) > is equivalent to > exec open(fname).read() ? > Pretty much. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From steven at REMOVE.THIS.cybersource.com.au Tue May 15 21:38:22 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 16 May 2007 01:38:22 GMT Subject: PEP 3131: Supporting Non-ASCII Identifiers - ambiguity issues References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649BC4C.10200@web.de> <1179238847.407605.4620@w5g2000hsg.googlegroups.com> <4649C63C.1030508@web.de> <1179242328.800088.246620@h2g2000hsg.googlegroups.com> <4649D4A5.5060102@web.de> <1179247724.234869.47310@l77g2000hsb.googlegroups.com> <4649E730.9000609@web.de> Message-ID: On Tue, 15 May 2007 10:44:37 -0700, John Nagle wrote: > We have to have visually unique identifiers. Well, Python has existed for years without such a requirement, so I think "have to" is too strong a term. Compare: thisisareallylongbutcompletelylegalidentiferandnotvisuallyuniqueataglance with thisisareallylongbutcompletelylegalidentiferadnnotvisuallyuniqueataglance I imagine, decades ago, people arguing against the introduction of long identifiers because of the risk that their projects will be flooded with Black Hats trying to slip one over them by using the vulnerability cause by really long identifiers. I can just see people banging away on their keyboard, swearing black and blue that identifiers of more than four characters are completely unnecessary (who needs more than 450,000 variables in a program?) and will just cause the End Of Programming As We Know It. rn = m = None IIl0 = IlIO = None I'm sure that the Python community has zero sympathy for anyone suggesting that Python should _enforce_ rules like "don't use a single l as an identifier", even if they have complete sympathy with anybody who has such a rule in their own projects. -- Steven. From aisaac at american.edu Mon May 7 22:12:27 2007 From: aisaac at american.edu (Alan Isaac) Date: Tue, 08 May 2007 02:12:27 GMT Subject: change of random state when pyc created?? References: <1178408359.113807.181570@l77g2000hsb.googlegroups.com> Message-ID: "Steven D'Aprano" wrote in message news:pan.2007.05.06.06.00.17.629591 at REMOVE.THIS.cybersource.com.au... > If you want to send me the modules, I will have a look at them as well. > Many eyes make for shallow bugs... Dustan and John Machin have confirmed the apparent bug, and I have sent you the files. Explanation welcome!! Cheers, Alan Isaac From gagsl-py2 at yahoo.com.ar Thu May 24 17:09:04 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 24 May 2007 18:09:04 -0300 Subject: problems to write a wav file References: Message-ID: En Thu, 24 May 2007 10:55:42 -0300, Gautier Krings escribi?: > I have a small problem for writing a .wav file. I can't find in which > format > I have to pass my data in the writeframes function of the wave module. > > here's my code, I am just trying to open a wav file, extracting the data > from it, and writing it in another wav file. You are also reducing each frame to a single number, its rms. > The problem is that the sound I get in the second wav file isn't the > same as > from the firs file (in fact it is horrible). (I bet it is!) Even if you manage to write the file correctly, replacing each frame with its rms value won't give an "audible" wav - by example, a constant volume section would give a flat wave. > new_signal = wave.open('C:\demo2.wav', 'wb') Please use either r'C:\demo2.wav' or 'C:\\demo2.wav' > new_signal.setsampwidth(width) This is the sample width in bytes - you must write an integer of this size, for each sample. > new_signal.setframerate(frameRate) > new_signal.setnchannels(signal.getnchannels()) As you only have a single value (rms), this should be always 1. > for j in range(len(power)): > data = hex(power[j]) ---> I guess that my problem is located at > this > line One of the problems, yes. For a 16bit sample, you could use: data=struct.pack("h",power[j]) > new_signal.writeframes(data) > new_signal.close() Another option would be to use the array module: http://docs.python.org/lib/module-array.html -- Gabriel Genellina From mensanator at aol.com Fri May 4 14:19:11 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 4 May 2007 11:19:11 -0700 Subject: How to check if a string is empty in python? In-Reply-To: <1178272957.427279.89350@n76g2000hsh.googlegroups.com> References: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> <1178138964.503290.254060@o5g2000hsb.googlegroups.com> <1178139155.260722.153750@n59g2000hsh.googlegroups.com> <463a31c0$0$6845$c3e8da3@news.astraweb.com> <1178224237.326531.254130@o5g2000hsb.googlegroups.com> <1178272957.427279.89350@n76g2000hsh.googlegroups.com> Message-ID: <1178302751.544971.281270@y5g2000hsa.googlegroups.com> On May 4, 5:02 am, Jaswant wrote: > This is a simple way to do it i think > > s=hello > > >>> if(len(s)==0): > > ... print "Empty" > ... else: > ... print s > ... > hello But you are still making the assumption that s is a string. (BTW, you need quotes around your example.) For example: >>> print a,b 11 11 Can you tell which one is the string? I.e., which one had quotes around it? If you correctly assume that it was b, then yes, your example works. >>> print len(b) 2 If you incorrectly assume it was a, then the example doesn't work. >>> print len(a) Traceback (most recent call last): File "", line 1, in print len(a) TypeError: object of type 'int' has no len() You have to know that a variable is a string before you try to do a len(). Dynamic typing is a feature, but that doesn't relieve you of the necessary tests. From http Fri May 18 02:58:36 2007 From: http (Paul Rubin) Date: 17 May 2007 23:58:36 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <46478694$0$1412$426a34cc@news.free.fr> <1hy252p.1anf7sr1p4yp12N%aleax@mac.com> <464988a4$0$20289$9b4e6d93@newsspool3.arcor-online.net> <464aaee8$0$10188$9b4e6d93@newsspool4.arcor-online.net> <464afa8d$0$10200$9b4e6d93@newsspool4.arcor-online.net> <1179330761.676441.302650@p77g2000hsh.googlegroups.com> <464c438e$0$14102$9b622d9e@news.freenet.de> Message-ID: <7x1whe39er.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > Now I understand it is meaning 12 in Merriam-Webster's dictionary, > a) "to decline to bid, double, or redouble in a card game", or b) > "to let something go by without accepting or taking > advantage of it". I never thought of it as having that meaning. I thought of it in the sense of going by something without stopping, like "I passed a post office on my way to work today". From andy.rockford at gmail.com Mon May 7 01:30:47 2007 From: andy.rockford at gmail.com (Andy) Date: 6 May 2007 22:30:47 -0700 Subject: Examples / Links needed Message-ID: <1178515847.621303.270280@o5g2000hsb.googlegroups.com> Gurus, I'm looking for definite examples (pardon me if I'm not clear here) on Stack class...Somewhat like this : class Stack(object): def __init__(self__) self.__contents = [] and ad hoc implementation of a class based on number system like for example somewhat like this def __imult__(self, other): self.__numerator *= other.__numerator self.__denominator *= other.__denominator . . return self I'm not satisfied with Python Docs. Thanks in advance. From anamax at earthlink.net Tue May 1 17:52:07 2007 From: anamax at earthlink.net (Andy Freeman) Date: 1 May 2007 14:52:07 -0700 Subject: Lisp-like macros in Python? In-Reply-To: <1178035825.193334.184250@o5g2000hsb.googlegroups.com> References: <1178035825.193334.184250@o5g2000hsb.googlegroups.com> Message-ID: <1178056327.451360.324060@e65g2000hsc.googlegroups.com> On May 1, 9:10 am, sturlamolden wrote: > I was > wondering if it is possible to emulate some of the functionality in > Python using a function decorator that evals Python code in the stack > frame of the caller. The macro would then return a Python expression > as a string. Granted, I know more Python than Lisp, so it may not work > exactly as you expect. How about something that can't be done with a function, such as the functionality of the "with" statement that was added to python 2.5? Yes, it has to handle a suite of statements. It would be nice if it handled both the "{as target}" and no target forms. Also, it shouldn't rely on magic names - if it needs a variable for its purposes, it should guarantee that said variable and/or use can not be one that affects how the rest of the user's program behaves. There's a fair amount of relevant discussion in http://www.python.org/dev/peps/pep-0343/ . From gagsl-py2 at yahoo.com.ar Wed May 9 19:40:22 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 09 May 2007 20:40:22 -0300 Subject: CPU usage. References: <840961.69835.qm@web54514.mail.yahoo.com> Message-ID: En Wed, 09 May 2007 02:58:45 -0300, Navid Parvini escribi?: > I want to get the CPU usage in my code. > Is there any module in Python to get it? > Also I want to get in on Windows and Linux. On Windows you can use WMI; Tim Golden made an excellent library that let's you query WMI using Python: http://tgolden.sc.sabren.com/python/wmi.html Then you need to know *what* to query; google for "WMI CPU usage". Since WMI is just Microsoft's own implementation of WBEM, you could find a Linux version, I don't know. -- Gabriel Genellina From showell30 at yahoo.com Mon May 28 09:45:05 2007 From: showell30 at yahoo.com (Steve Howell) Date: Mon, 28 May 2007 06:45:05 -0700 (PDT) Subject: Newbie question - better way to do this? In-Reply-To: <465a8fd2$0$90269$14726298@news.sunsite.dk> Message-ID: <144856.37508.qm@web33515.mail.mud.yahoo.com> --- Nis J?rgensen wrote: > Steve Howell skrev: > > > def firstIsCapitalized(word): > > return 'A' <= word[0] <= 'Z' > > For someone who is worried about the impact of > non-ascii identifiers, > you are making surprising assumptions about the > contents of data. > The function there, which I don't even remotely defend, had nothing to with the main point of the thread. Others pointed out that correct idiom here is word.istitle(), but the main point of the thread was how to prevent the newbie from essentially reinventing itertools.groupby. If you want to point out holes in my logic about the impact of non-ascii identifiers (the above code, though bad, does not suggest a hole in my logic; it perhaps even adds to my case), can you kindly do it in a thread where that's the main point of the discussion? ____________________________________________________________________________________Sick sense of humor? Visit Yahoo! TV's Comedy with an Edge to see what's on, when. http://tv.yahoo.com/collections/222 From nagle at animats.com Sun May 6 15:50:35 2007 From: nagle at animats.com (John Nagle) Date: Sun, 06 May 2007 19:50:35 GMT Subject: howto make Python list from numpy.array? In-Reply-To: <1178480447.245977.293010@n59g2000hsh.googlegroups.com> References: <1178480447.245977.293010@n59g2000hsh.googlegroups.com> Message-ID: dmitrey wrote: > howto make Python list from numpy.array? > Thx, D. > lst = map(None, arr) // for 1D arrays. John Nagle From manatlan at gmail.com Sun May 13 04:02:54 2007 From: manatlan at gmail.com (manatlan) Date: 13 May 2007 01:02:54 -0700 Subject: Dynamic subclassing ? In-Reply-To: <1hy0dfh.1d8mafv1fwburaN%aleax@mac.com> References: <1178976888.443891.116090@y80g2000hsf.googlegroups.com> <1hy0dfh.1d8mafv1fwburaN%aleax@mac.com> Message-ID: <1179043374.090262.50880@h2g2000hsg.googlegroups.com> On 13 mai, 01:24, a... at mac.com (Alex Martelli) wrote: > manatlan wrote: > > I've got an instance of a class, ex : > > > b=gtk.Button() > > > I'd like to add methods and attributes to my instance "b". > > I know it's possible by hacking "b" with setattr() methods. But i'd > > like to do it with inheritance, a kind of "dynamic subclassing", > > without subclassing the class, only this instance "b" ! > > > In fact, i've got my instance "b", and another class "MoreMethods" > > > class MoreMethods: > > def sayHello(self): > > print "hello" > > > How could i write ... > > > "b = b + MoreMethods" > > > so "b" will continue to be a gtk.Button, + methods/attributs of > > MoreMethods (it's what i call "dynamic inheritance") ...so, things > > like this should work : > > > - b.set_label("k") > > - b.sayHello() > > > I can't find the trick, but i'm pretty sure it's possible in an easy > > way. > > I think what you're asking for is totally weird, and with just about > zero advantages compared with several saner alternatives that have > already been proposed in this thread and that you have rejects, but > sure, it's possible: > > def addaclass(aninst, onemoreclass): > aninst.__class__ = type(aninst.__aclass__.__name__, > (aninst.__aclass__, onemoreclass), {}) > > Alex I know it's weird ... and solutions given here are a lot saner. But i can't do that at the creation of the instance, because it's not me who has the creation process ... the only things i've got, it's the instance i tried : class MoreMethods: def sayHello(self): print "hello" def addaclass(aninst, onemoreclass): aninst.__class__ = type(aninst.__class__.__name__, (aninst.__class__, onemoreclass), {}) b=gtk.Button("the_label") addaclass(b,MoreMethods) print b.get_label() print b.hello() but got : "TypeError: __class__ assignment: only for heap types" on the last line ... I begin to think that the only solution is to use the module new like Karlo said ... From martin.laloux at gmail.com Wed May 16 03:57:15 2007 From: martin.laloux at gmail.com (martin.laloux at gmail.com) Date: 16 May 2007 00:57:15 -0700 Subject: tkFileDialog.askopenfilename() In-Reply-To: <32eeb$464a4466$4275d90a$23243@FUSE.NET> References: <1179270010.433011.23580@y80g2000hsf.googlegroups.com> <32eeb$464a4466$4275d90a$23243@FUSE.NET> Message-ID: <1179302235.274356.204100@p77g2000hsh.googlegroups.com> look at "Basic Tkinter dialogs" from python cookbook at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/438123 From tedpottel at gmail.com Tue May 1 17:06:21 2007 From: tedpottel at gmail.com (tedpottel at gmail.com) Date: 1 May 2007 14:06:21 -0700 Subject: How can I get the ascii code of a charter in python? Message-ID: <1178053581.390873.65850@n76g2000hsh.googlegroups.com> Hi, a python newbe needs some help, I read the python doc at http://docs.python.org/lib/module-curses.ascii.html I tried Import curses.asciicurses.ascii Print ascii('a') I get an error saying module curses.ascii8 does not exsist. How can I get the ascii code of a charter in python? -Ted From ptmcg at austin.rr.com Mon May 21 09:51:11 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 21 May 2007 06:51:11 -0700 Subject: Inverse of id()? In-Reply-To: <1179741319.122807.56960@z24g2000prd.googlegroups.com> References: <1179618173.280286.284120@n59g2000hsh.googlegroups.com> <1179741319.122807.56960@z24g2000prd.googlegroups.com> Message-ID: <1179755471.432160.84850@x18g2000prd.googlegroups.com> On May 21, 4:55 am, Paul Boddie wrote: > > < some very kind comments re: pyparsing :) > > > You'd even be able to incorporate the parse action, too, with some > extra magic. As pyparsing is a library which seems to encourage clean > grammar definitions, I think this makes quite a difference, although I > now expect to be told that there's a class in the library which > supports this. > > Anyway, back to the scheduled programme... > > Paul Paul - I'm glad pyparsing is working well for you. I've struggled with the unwieldiness of setName and setResultsName since version 0.6 or so, and yours is an interesting solution. This is definitely a case of Python's __setAttr__ to the rescue. And, no there is nothing in pyparsing that does anything like this, I think most people write their own workarounds to this issue. For instance, Seo Sanghyeon (I believe the same one now working on IronPython) uses the following technique in the EBNF parser/"compiler" that he contributed to the pyparsing examples directory: # list of all the grammar variable names all_names = ''' integer meta_identifier terminal_string ... '''.split() # parse actions follow def do_integer(str, loc, toks): return int(toks[0]) ... # now attach names and parse actions (and optionally set debugging) for name in all_names: expr = vars()[name] action = vars()['do_' + name] expr.setName(name) expr.setParseAction(action) #~ expr.setDebug() This requires that you maintain the list of all_names, and it self- imposes a naming standard for parse actions (which I am loath to impose on others, in general). Philosophically, though, there is a distinction between an expression's name and its results name. I might define an integer and use it many times within a grammar. All are named "integer" (as done with setName), but I may wish to name the returned results with different names (such as "age", "numberOfChildren", "birthYear", etc.), and setResultsName performs this function. I suppose I could add another operator, such as '/', so that something like: re = Regex("(\d*)").setParseAction(lambda t:int(t[0]))/"x" would be equivalent to: re = Regex("(\d*)").setParseAction(lambda t:int(t[0])).setResultsName("x") But this may be bordering on Perlishness, and it certainly is not as explicit as "setResultsName" (there are also operator precedence issues - note that I would need parens to use the '/' operator ahead of '.setParseAction'). Now if the "as" keyword were opened up as a customizable operator (__as__), *that* would fill the bill nicely, I should think. And finally, no, there is no hidden agenda at incorporating some form of reverse id() lookup into pyparsing - I simply had an interpreter open with some leftover pyparsing work in it, so it was a good source of a non-trivial object that I could try to find, given its id. -- Paul From toby at tobiah.org Wed May 2 18:03:24 2007 From: toby at tobiah.org (Tobiah) Date: Wed, 02 May 2007 15:03:24 -0700 Subject: Slicing Arrays in this way Message-ID: <4638fe20$0$16403$88260bb3@free.teranews.com> >>> elegant_solution([1,2,3,4,5,6,7,8,9,10]) [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] -- Posted via a free Usenet account from http://www.teranews.com From facundo at taniquetil.com.ar Fri May 11 15:43:17 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Fri, 11 May 2007 19:43:17 +0000 (UTC) Subject: File writing success References: <1178907719.896993.299910@h2g2000hsg.googlegroups.com> Message-ID: HMS Surprise wrote: > If file writing has no return value (http://docs.python.org/lib/bltin- > file-objects.html), how do you know if the write was successful? If not, you'll get an error raised. Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From sjmachin at lexicon.net Sun May 6 17:09:49 2007 From: sjmachin at lexicon.net (John Machin) Date: 6 May 2007 14:09:49 -0700 Subject: c macros in python. In-Reply-To: <1178485280.394666.51970@n76g2000hsh.googlegroups.com> References: <1178485280.394666.51970@n76g2000hsh.googlegroups.com> Message-ID: <1178485789.001461.204710@y80g2000hsf.googlegroups.com> On May 7, 7:01 am, noagbodjivic... at gmail.com wrote: > Hey, > > I'm writing a script to generate code. I'm a bit tired of typing > outfile.write(....). Does python have a way to c-like macros? Every > instance of o(...) in the code will be replaced by outfile.write(...)? Functions and methods are first-class citizens in Python; all you have to do is: o = outfile.write o('blah blah\n') o('etc\n') Bonus: your code will run (measurably but almost imperceptibly) faster, because you save a method lookup every time you use it.This would not happen with a text-substituting macro approach. HTH, John From aisaac at american.edu Tue May 1 16:25:39 2007 From: aisaac at american.edu (Alan Isaac) Date: Tue, 01 May 2007 20:25:39 GMT Subject: relative import broken? References: <1hxa9x3.c0unyd1jw7vu9N%aleax@mac.com> <1hxcdkq.47p2r6beuctcN%aleax@mac.com> <1hxeg2v.1ct59rv3oyq87N%aleax@mac.com> Message-ID: <7nNZh.4420$st3.1414@trnddc06> "Alex Martelli" wrote in message news:1hxeg2v.1ct59rv3oyq87N%aleax at mac.com... > I don't know of any "pretty" way -- I'd do it by path manipulation > (finding mypackage from os.path.abspath(__file__) and inserting its > _parent_ directory in sys.path). Yes, that seems to be the standard solution. I find it ugly. Anyway, I suppose my question remains: why are we constrained from solving this with a relative import? (And I suppose your answer will be: well then, relative to *what*? I am having trouble seeing why that answer cannot be given a clear riposte.) Thanks, Alan From joshusdog at gmail.com Mon May 14 17:50:35 2007 From: joshusdog at gmail.com (joshusdog at gmail.com) Date: 14 May 2007 14:50:35 -0700 Subject: multi-line input? Message-ID: <1179179435.410251.303530@u30g2000hsc.googlegroups.com> I'm writing a C++ application with an embedded Python interpreter. Command text is captured and passed to the interpreter a single line at a time. My question is this: is there a simple way of determining whether a given input line of text will cause the prompt to change from the regular ">>>" to the multi-line "..." before sending the text to the interpreter? I suppose the completely correct solution would be tokenize and parse the entire string and then examine all the constituent parts, but that seems like a lot more work than I really want to do. As far as I can tell, there are only a few ways to trigger the multi- line input prompt: - if-statement, for-loop, function or class definition - line continuation (\) - block quote (""" or ''') Any help would be greatly appreciated. From __peter__ at web.de Fri May 4 00:34:06 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 04 May 2007 06:34:06 +0200 Subject: Decorating class member functions References: <1178241696.641350.292210@n59g2000hsh.googlegroups.com> Message-ID: Andy Terrel wrote: > Okay does anyone know how to decorate class member functions? > > The following code gives me an error: > > Traceback (most recent call last): > File "decorators2.py", line 33, in > s.update() > File "decorators2.py", line 13, in __call__ > retval = self.fn.__call__(*args,**kws) > TypeError: update() takes exactly 1 argument (0 given) > > ------------------ > > > #! /usr/bin/env python > > class Bugger (object): > def __init__ (self, module, fn): > self.module = module > self.fn = fn > > def __call__ (self,*args, **kws): > ret_val = self.fn(*args,**kws) > return ret_val > > def instrument (module_name): > ret_val = lambda x: Bugger(module_name, x) > return ret_val > > class Stupid: > def __init__(self): > self.val = 1 > > @instrument("xpd.spam") > def update(self): > self.val += 1 > > > s = Stupid() > s.update() The problem is not that you are decorating a method but that you are trying to use a callable class instance as a method. For that to work the class has to implement the descriptor protocol, see http://users.rcn.com/python/download/Descriptor.htm class Bugger (object): def __init__ (self, module, fn, instance=None): self.module = module self.fn = fn self.instance = instance def __call__ (self, *args, **kws): print "calling %s.%s()" % (self.module, self.fn.__name__) if self.instance is not None: args = (self.instance,) + args ret_val = self.fn(*args, **kws) return ret_val def __get__(self, instance, class_): if instance is None: return self return Bugger(self.module, self.fn, instance) def instrument (module_name): ret_val = lambda x: Bugger(module_name, x) return ret_val class Stupid(object): @instrument("xpd.spam") def update(self): print "update()" s = Stupid() s.update() Stupid.update(s) Peter From daniele.varrazzo at gmail.com Mon May 7 04:30:55 2007 From: daniele.varrazzo at gmail.com (Daniele Varrazzo) Date: 7 May 2007 01:30:55 -0700 Subject: problem with quoted strings while inserting into varchar field of database. In-Reply-To: References: <1178475772.423687.118800@e65g2000hsc.googlegroups.com> Message-ID: <1178526655.933789.294700@h2g2000hsg.googlegroups.com> On 7 Mag, 08:55, "krishnakant Mane" wrote: > On 6 May 2007 11:22:52 -0700, Daniele Varrazzo >> Every serious database driver has a complete and solid SQL escaping > > mechanism. This mechanism tipically involves putting placeholders in > > your SQL strings and passing python data in a separate tuple or > > dictionary. Kinda > > > cur.execute("INSERT INTO datatable (data) VALUES (%s);", > > (pickled_data,)) > > I will try doing that once I get back to the lab. > mean while I forgot to mention in my previous email that I use MySQLdb > for python-mysql connection. OK: MySQLdb implements the escaping mechanism i described. You can find the documentation if you look for it harder. > I did not find any such reference to storing pickled objects in the API. Storing pickled object is not different from storing anything else into BLOB. You would have faced the same problem if you had to write "O'Reilly" in a VARCHAR field. -- Daniele From half.italian at gmail.com Wed May 23 15:58:06 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 23 May 2007 12:58:06 -0700 Subject: Parallel/distributed generator In-Reply-To: <1179943256.575473.62610@q66g2000hsg.googlegroups.com> Message-ID: <1179950286.087794.5430@x18g2000prd.googlegroups.com> On May 23, 11:00 am, George Sakkis wrote: > I'm looking for any existing packages or ideas on how to implement the > equivalent of a generator (in the Python sense, i.e.http://www.python.org/dev/peps/pep-0255/) in a parallel/distributed > way. As a use case, imagine a function that generates a range of > primes. I'd like to be able to do something along the following lines: > > def iterprimes(start=1, end=None): > # ... > yield prime > > # rpc-related initialization > ... > rpc_proxy = some_rpc_lib(iterprimes, start=1e6, end=1e12) > for prime in proxy: > print prime > > Is there any module out there that does anything close to this ? > > George DOLT! From john at datavoiceint.com Wed May 16 15:16:01 2007 From: john at datavoiceint.com (HMS Surprise) Date: 16 May 2007 12:16:01 -0700 Subject: Declaring variables In-Reply-To: <134mea4o0svae73@corp.supernews.com> References: <1179334649.990688.73320@o5g2000hsb.googlegroups.com> <134mea4o0svae73@corp.supernews.com> Message-ID: <1179342961.494519.103620@u30g2000hsc.googlegroups.com> No haven't had to endure Pascal. Mostly C/C++, Tcl, and assembler. Oh yeah, and a (thankfully) short stint of Ada. But I glad to hear of the proofing tools. Working a lot of data parsed from web pages and the developer there a different naming convention from what I am accustomed so sometimes I introduce a new variable unintentionally. Thanks, jvh From adam at atlas.st Sat May 12 21:02:29 2007 From: adam at atlas.st (Adam Atlas) Date: 12 May 2007 18:02:29 -0700 Subject: How to cleanly pause/stop a long running function? In-Reply-To: <1179003065.771223.25600@e65g2000hsc.googlegroups.com> References: <1179003065.771223.25600@e65g2000hsc.googlegroups.com> Message-ID: <1179018149.214867.126330@h2g2000hsg.googlegroups.com> On May 12, 4:51 pm, Basilisk96 wrote: > Suppose I have a function that may run for a long time - perhaps from > several minutes to several hours. An example would be this file > processing function: > > import os > def processFiles(startDir): > for root, dirs, files in os.walk(startDir): > for fname in files: > if fname.lower().endswith(".zip"): > # ... do interesting stuff with the file here ... > > Imagine that there are thousands of files to process. This could take > a while. How can I implement this so that the caller can pause or > interrupt this function, and resume its program flow? Doing a Ctrl+C > interrupt would be a not-so-clean-way of performing such a thing, and > it would quit the application altogether. I'd rather have the function > return a status object of what it has accomplished thus far. > > I have heard about threads, queues, and asynchronous programming, but > am not sure which is appropriate for this and how to apply it. Perhaps > the above function should be a method of a class that inherits from > the appropriate handler class? Any help will be appreciated. > > -Basilisk96 Consider using generators. http://docs.python.org/tut/node11.html#SECTION00111000000000000000000 This way, whatever part of your program calls this function can completely control the iteration. Maybe you can have it yield status information each time. From rurpy at yahoo.com Wed May 16 14:32:40 2007 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 16 May 2007 11:32:40 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <7x4pmg716p.fsf@ruckus.brouhaha.com> <4648EC26.8020907@v.loewis.de> Message-ID: <1179340360.421462.321380@o5g2000hsb.googlegroups.com> On May 16, 9:04?am, "Eric Brunel" wrote: > On Wed, 16 May 2007 16:29:27 +0200, Neil Hodgson ? > > wrote: ...snip... > > Each of these can be handled reasonably considering their frequency of ? > > occurrence. I have never learned Japanese but have had to deal with ? > > Japanese text at a couple of jobs and it isn't that big of a problem. ? > > Its certainly not "virtually impossible" nor is there "absolutely no way ? > > of entering the word" (???). I think you should moderate your ? > > exaggerations. > > I do admit it was a bit exaggerated: there actually are ways. You know it, ? > and I know it. But what about the average guy, not knowing anything about ? > Japanese, kanji, radicals and stroke counts? How will he manage to enter ? > these funny-looking characters, perhaps not even knowing it's Japanese? ? > And does he have to learn a new input method each time he stumbles across ? > identifiers written in a character set he doesn't know? And even if he ? > finds a way, the chances are that it will be terribly inefficient. Having ? > to pay attention on how you can type the things you want is a really big ? > problem when it comes to programming: you have a lot of other things to ? > think about. What does this have to do with the adoption of PEP-3131? Are you saying that if non-english speakers are allowed to use non-english identifiers in their code, that you will have to *write* code in a language you don't know using a script you don't know? If you, for some extremely improbable reason *have* to modify the code, then you will be cutting and pasting the existing variables. If you are creating new variables, then given that you don't know the language and have no idea what to name the variable, the mechanics of entering it are the least of your problems. Name the new variable in ascii and leave it to a native speaker to fix later. If the aswer to that is, "see, non-english Python is bad", then arguments against *enforcing* english-only python are elsewhere in the thread so I won't repeat here. From malaclypse2 at gmail.com Thu May 3 10:57:41 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Thu, 3 May 2007 10:57:41 -0400 Subject: newbie: copy base class fields In-Reply-To: <1178201644.920048.205400@y5g2000hsa.googlegroups.com> References: <1178201644.920048.205400@y5g2000hsa.googlegroups.com> Message-ID: <16651e80705030757v7694f399t3a2989373220ec77@mail.gmail.com> On 3 May 2007 07:14:04 -0700, tmp123 wrote: > Of course, it is not an option to copy one by one all the fields of > class A inside the __init__ of B. Is it okay to copy them all at once? Like this: class B(A): def __init__(self, a): self.__dict__.update(a.__dict__) self.v2 = 2 That will copy all of the attributes of instance a into the new instance. -- Jerry From stefan.sonnenberg at pythonmeister.com Sun May 27 17:05:29 2007 From: stefan.sonnenberg at pythonmeister.com (Stefan Sonnenberg-Carstens) Date: Sun, 27 May 2007 23:05:29 +0200 Subject: Can python create a dictionary from a list comprehension? In-Reply-To: <1180299312.207986.4340@k79g2000hse.googlegroups.com> References: <1180299312.207986.4340@k79g2000hse.googlegroups.com> Message-ID: <4659F299.7000309@pythonmeister.com> erikcw schrieb: > Hi, > > I'm trying to turn o list of objects into a dictionary using a list > comprehension. > > Something like > > entries = {} > [entries[int(d.date.strftime('%m'))] = d.id] for d in links] > > I keep getting errors when I try to do it. Is it possible? Do > dictionary objects have a method equivalent to [].append? Maybe a > lambda? > > Thanks for your help! > Erik > > normally a dict(whatEver) will do ;-) Example: a = [1,2,3,4,5,6,7,8,9,10] aDict = dict([(x,x+1) for x in a if x%2==0]) print aDict From martin at v.loewis.de Sat May 19 03:34:09 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 19 May 2007 09:34:09 +0200 Subject: Uninstall speed with Python 2.4 MSI In-Reply-To: References: Message-ID: <464ea871$0$32050$9b622d9e@news.freenet.de> David Bolen wrote: > I'm in the process of uninstalling 2.4a2 to install 2.4a3 and the > uninstall is running absolutely dog slow and burning 100% cpu while > doing it (all going to mshta.exe). Watching the progress bar it > almost seems to be doing a whole bunch of operations per file or > something. Indeed it does. MSI is transactional, meaning that everything is reverted if the operation fails (e.g. through user cancel). When overwriting or deleting files, this means installer needs to move the old file out of the way. Then, when the action is committed, the file can be deleted. Therefore, during uninstall, you see two actions: first, it says that it removes files, then, it says that it removes backup files. Regards, Martin From grante at visi.com Wed May 23 11:03:29 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 23 May 2007 15:03:29 -0000 Subject: Slightly OT: Why all the spam? References: <3bb44c6e0705220008y10f5deb7v86ed82d3f8241761@mail.gmail.com> Message-ID: <1358lu17h16a96e@corp.supernews.com> On 2007-05-23, Joel Hedlund wrote: >> Thus you may want to consider reading c.l.p via nntp when at work. > > I'm doing that using Thunderbird 1.5.0, and I still get the > spam. Googling for a bit shows me that people have been > having issues with Thunderbird not removing expired articles > all the way since 2003. > > Does anyone have a suggestion on how I can make thunderbird remove > expired articles? I don't understand. Expired articles are removed on the server by the server. > Or should I perhaps use another news reader? I don't see how it will make any difference, but maybe Thunderbird is doing something weird (caching headers?). -- Grant Edwards grante Yow! My mind is a potato at field ... visi.com From duncan.booth at invalid.invalid Mon May 14 08:24:49 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 14 May 2007 12:24:49 GMT Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <7x4pmg716p.fsf@ruckus.brouhaha.com> Message-ID: Alexander Schmolck wrote: > scheme (major implementations such as PLT and the upcoming standard), > the most popular common lisp implementations, haskell[1], fortress[2], > perl 6 and I should imagine (but haven't checked) all new java or .NET > based languages (F#, IronPython, JavaFX, Groovy, etc.) as well -- the > same goes for XML-based languages. > Just to confirm that: IronPython does accept non-ascii identifiers. From "Differences between IronPython and CPython": > IronPython will compile files whose identifiers use non-ASCII > characters if the file has an encoding comment such as "# -*- coding: > utf-8 -*-". CPython will not compile such a file in any case. From C.delete_this.Sanders at BoM.GOv.AU Thu May 3 22:04:58 2007 From: C.delete_this.Sanders at BoM.GOv.AU (Charles Sanders) Date: Fri, 04 May 2007 12:04:58 +1000 Subject: 4 quadrant atan In-Reply-To: References: <1178120019.271716.299590@e65g2000hsc.googlegroups.com> <1178203772.243333.24990@p77g2000hsh.googlegroups.com> Message-ID: <463a94cc$0$14025$c30e37c6@lon-reader.news.telstra.net> Roel Schroeven wrote: > > I might be wrong of course, but can't you just use atan2? Only problem > is that it returns negative angles for quadrants 3 and 4, but that is > easily solved. In Python: > > from math import atan2, pi, fmod > def vectorAngle(x, y): > return fmod(atan2(y, x) + 2*pi, 2*pi) > > No conditionals in sight. > Yes, but there will be some conditionals for special cases in the implementation of atan2(). I am pretty sure that in Python (and Perl) atan2() is the C atan2() from the C math library, also often used by Fortran. This is normally written in assembler for the individual architecture by the hardware vendor or compiler writer, is usually heavily optimized, carefully handles all the corner cases, and often carries extra precision to ensure accuracy. If I recall correctly P. J. Plauger's book on the C standard library ("The Standard C Library") includes a C version of atan2(), which is probably pretty typical of the algorithms used when there is no hardware support for trigonometric functions. As I remember it, atan2 (and atan) in Plauger's book use a ratio of polynomials to approximate atan(x) over a limited range, (such as -1.0 ... +1.0 or 0.0 ... sqrt(2)-1) and formulae (assuming I have remembered high school trigonometry correctly) such as atan(x) = pi/2 - atan(1/x) and atan(x) = pi/4 - atan((1-x)/(1+x)) [derived from tan(pi/4-x) = (1-x)/(1+x)] to extend the range. There is an obvious trade off between the complexity of the approximating polynomials (and the range they cover with acceptable accuracy), and the number of cases needed to extend the range to all valid inputs. For example, if the polynomials cover -1.0 ... +1.0 (atan() values of -pi/4 to +pi/4) then there are at least 5 cases to consider (atan() ranges -pi ... -3pi/4, -3pi/4 ... -pi/4, -pi/4 ... +pi4, +pi/4 ... +3pi/4, +3pi/4 ... +pi), while if the approximations only cover 0.0 ... sqrt(2)-1 (atan() values from 0.0 to pi/8) then there are at least 16 cases. NaNs and infinities would add additional cases, as may the need to preserve accuracy near zero. Charles From ian.team.python at saltmob.com Thu May 10 01:51:12 2007 From: ian.team.python at saltmob.com (ian.team.python at saltmob.com) Date: 9 May 2007 22:51:12 -0700 Subject: elegant python style for loops Message-ID: <1178776272.535735.166540@h2g2000hsg.googlegroups.com> To step through a list, the python style is avoid an explicit index. But what if the same hidden index is to be used for more than one list for example:- for key,value in listKeys,listValues : newdict[key]=value won't work as it is a tuple of lists, as opposed to a list of tuples. Is there an elegant solution to this? Is there a way to merge lists into a list of tuples to allow moving through multiple lists, or is the for i in range(len(listkeys)): the only solution? Any suggestions? From steve at holdenweb.com Thu May 17 17:48:21 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 17 May 2007 17:48:21 -0400 Subject: FreeType In-Reply-To: <397DF4A1-A882-4B90-ADE1-8D3F3BC408F6@jedimindworks.com> References: <1179422948.600593.117310@p77g2000hsh.googlegroups.com> <1179431247.954420.219690@q75g2000hsh.googlegroups.com> <397DF4A1-A882-4B90-ADE1-8D3F3BC408F6@jedimindworks.com> Message-ID: <464CCDA5.4030505@holdenweb.com> Michael Bentley wrote: > On May 17, 2007, at 2:47 PM, Glich wrote: > >> I've been there. All the code is in C/C++, don't I need it in python? >> I will explore the software. I dismissed this because there was no >> python. I am knew to all of this. Thanks for your reply. > > The c stuff (freetype) is what you need (it gets installed as a > library that can be used by python or any other software entity that > needs its functionality). It may seem a little weird, but lots of > the stuff you call from python is written in c. More than likely, > your python interpreter is also written in c :-) > > Alternatively use the Python Imaging Library (PIL), which I believe includes freetype support. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From carsten at uniqsys.com Thu May 10 09:29:20 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 10 May 2007 09:29:20 -0400 Subject: change of random state when pyc created?? In-Reply-To: <588D53831C701746A2DF46E365C018CE01D2CA93@LITEXETSP001.etrsouth.corp.entergy.com> References: <588D53831C701746A2DF46E365C018CE01D2CA93@LITEXETSP001.etrsouth.corp.entergy.com> Message-ID: <1178803760.3367.37.camel@dot.uniqsys.com> On Thu, 2007-05-10 at 08:01 -0500, Hamilton, William wrote: > It's possible there are other factors that can affect this as well. A more > general statement is probably more appropriate: > > "Keys and values are listed in an arbitrary order. This order is > non-random, varies across Python implementations, and depends on the > dictionary's history of insertions and deletions as well as factors outside > the scope of the containing program." I think we should remove any implied reliability and slash it down to this: "Keys and values are listed in an arbitrary order that is random except that if items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond." > "Iteration over a set returns elements in an arbitrary order, which may > depend on factors outside the scope of the containing program." And this: "Iteration over a set returns elements in random order." Regards, -- Carsten Haese http://informixdb.sourceforge.net From irstas at gmail.com Thu May 31 12:09:28 2007 From: irstas at gmail.com (irstas at gmail.com) Date: 31 May 2007 09:09:28 -0700 Subject: c[:]() In-Reply-To: References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> Message-ID: <1180627768.286698.21840@q69g2000hsb.googlegroups.com> On May 31, 5:59 pm, "Warren Stringer" wrote: > Still I prefer > > funcs[:]() > > Because, I can describe it in English as "call everything that funcs has" Wouldn't funcs() be even better? It's shorter, and it seems like that's the only thing you're striving for. Why do you want to put the [:] in there all the time? From www.ieshoes.com118 at gmail.com Mon May 28 22:26:11 2007 From: www.ieshoes.com118 at gmail.com (www_ieshoes_com) Date: 28 May 2007 19:26:11 -0700 Subject: Air Jordan Shoes on Sale - $75 Message-ID: <1180405571.835947.109730@r19g2000prf.googlegroups.com> ieshoes.com shop Jordan 1-21's Bape shoes On Sale Now $75 http://www.ieshoes.com msn:ieshoes at hotmail.com From robert.rawlins at thinkbluemedia.co.uk Wed May 2 04:28:57 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Wed, 2 May 2007 09:28:57 +0100 Subject: Killing Threads In-Reply-To: <59qv0hF2lsq6uU1@mid.uni-berlin.de> References: <000d01c78c60$8c0056d0$a4010470$@rawlins@thinkbluemedia.co.uk> <59qv0hF2lsq6uU1@mid.uni-berlin.de> Message-ID: <000001c78c93$eda4a520$c8edef60$@rawlins@thinkbluemedia.co.uk> Thanks for this Diez and Tim, I'll take a look into this today, sorry for not posting any code fragments, its not so much a fragment as it is a bloody great big monster :-D Rob -----Original Message----- 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 Diez B. Roggisch Sent: 02 May 2007 09:05 To: python-list at python.org Subject: Re: Killing Threads > You probably need to setDaemon (True) on your threads > after you've created them and before they run. That > tells the OS: don't bother waiting for these ones to > finish if the program exits. (At least I think that's > what it does; I don't use threads all that much) Actually all it does is to tell the at_exit-handler that it's ok to terminate even though there are still some threads. The OS isn't concerned with this. Diez -- http://mail.python.org/mailman/listinfo/python-list From apatheticagnostic at gmail.com Tue May 22 23:10:21 2007 From: apatheticagnostic at gmail.com (kaens) Date: Tue, 22 May 2007 23:10:21 -0400 Subject: howto check does module 'asdf' exist? (is available for import) In-Reply-To: <7xsl9ox2ld.fsf@ruckus.brouhaha.com> References: <1179753436.736228.321400@x35g2000prf.googlegroups.com> <1179818823.916836.226090@r3g2000prh.googlegroups.com> <7xsl9ox2ld.fsf@ruckus.brouhaha.com> Message-ID: <163f0ce20705222010o4726c905qaddfad7f982a1ede@mail.gmail.com> I think that's there because you just wanted to check if it was available for import, implying that you didn't actually want to import it right then. On 22 May 2007 09:09:02 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > Asun Friere writes: > > > howto check does module 'asdf' exist (is available for import) or no? > > try : > > import asdf > > del asdf > > except ImportError : > > print "module asdf not available" > > else : > > print "module asdf available for loading" > > But this has a side effect: if asdf is already loaded, it deletes it. > -- > http://mail.python.org/mailman/listinfo/python-list > From andrew-news at andros.org.uk Mon May 7 09:49:03 2007 From: andrew-news at andros.org.uk (Andrew McLean) Date: Mon, 07 May 2007 14:49:03 +0100 Subject: Getting some element from sets.Set In-Reply-To: <1178267029.258868.219800@h2g2000hsg.googlegroups.com> References: <1178258913.095438.173020@h2g2000hsg.googlegroups.com> <1178267029.258868.219800@h2g2000hsg.googlegroups.com> Message-ID: jm.suresh at no.spam.gmail.com wrote: > In the particular case, I have to read an attribute from any one of > the elements, which one doesn't matter because this attribute value is > same across all elements in the set. Someone else pointed out that there might be better data structures. If performance was not an issue one approach would be illustrated by the following: >>> Q=set(['A','a']) >>> list(set(x.upper() for x in Q)) ['A'] This has the benefit that it does not assume all the elements of the set have the same value of the given attribute. Again not very efficient: >>> list(Q)[0] 'A' I'm guessing this would be quicker >>> iter(Q).next() 'A' From gagsl-py2 at yahoo.com.ar Tue May 1 19:07:05 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 01 May 2007 20:07:05 -0300 Subject: scaling References: <1178029348.453693.33510@u30g2000hsc.googlegroups.com> Message-ID: En Tue, 01 May 2007 11:22:28 -0300, Ashok escribi?: > IDL language contains a function called BYTSCL to scale all values of > Array that lie in the range (Min ? x ? Max) into the range (0 ? x ? > Top). Is there a similar function available in python? > > I need this to scale the pixel values of an image using PIL. Maybe PIL contains something built in, but if all else fails, you could write it in Python: def bytsclGen(data, minvalue=None, maxvalue=None, top=255): if minvalue is None: minvalue = min(data) if maxvalue is None: maxvalue = max(data) for x in data: if xmaxvalue: yield top else: yield (x-minvalue)*top/(maxvalue-minvalue) def bytscl(data, minvalue=None, maxvalue=None, top=255): return list(bytsclGen(data, minvalue, maxvalue, top)) -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Sun May 13 19:41:26 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 13 May 2007 20:41:26 -0300 Subject: file uploader References: <2adc542f0705091849t6c092ba0mf1cedd080da36960@mail.gmail.com> <2adc542f0705131441h1aabda6cl8c30589fc2f5d9a2@mail.gmail.com> Message-ID: En Sun, 13 May 2007 18:41:16 -0300, Sick Monkey escribi?: > If anyone has a simpler way of checking to see if > a file already exists (prior to uploading to a server) and renaming it, > please let me know. I will ignore the "server" part... > Here is the code that I am using (it runs exactly the same as the linux > app > 'arcgen'). > [...] > t = i-1 > filename=string.replace(filename,".-%s" % (t),".-%s" % (i)) If the original filename contained .-1 somewhere, you're modifying it. This is safer and shorter: import os,string filename = "whoa.mp3" dir_path = "/u01/" ofilename = filename i = 0 while os.path.exists(dir_path+filename): filename = "%s.-%s" % (ofilename,i) i += 1 req.write(filename) -- Gabriel Genellina From half.italian at gmail.com Thu May 10 12:44:01 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 10 May 2007 09:44:01 -0700 Subject: replacing string in xml file--revisited In-Reply-To: <1178796095.060439.40240@y5g2000hsa.googlegroups.com> References: <1178783809.444544.79640@w5g2000hsg.googlegroups.com> <1178787310.006875.204040@w5g2000hsg.googlegroups.com> <1178796095.060439.40240@y5g2000hsa.googlegroups.com> Message-ID: <1178815441.381038.315120@w5g2000hsg.googlegroups.com> On May 10, 4:21 am, saif.shak... at gmail.com wrote: > On May 10, 1:55 pm, half.ital... at gmail.com wrote: > > > > > On May 10, 12:56 am, saif.shak... at gmail.com wrote: > > > > Hi, > > > I need to replace a string in xml file with something else.Ex > > > > - > > > rate > > > rate > > > > > > > > > > > > - > > > > Here i have opened an xml > > > file(small part is pasted here).I want to replace the word 'localId' > > > with 'dataPackageID' wherever it comes in xml file.I have asked this > > > before and got a code: > > > input_file = open(filename) > > > xmlcontents = input_file.read() > > > input_file.close() > > > xmlcontents = xmlcontents.replace("spam", "eggs") > > > output_file = open(filename,"w") > > > output_file.write(xmlcontents) > > > output_file.close() > > > > Although this works alone it is nto > > > working when i handle multiple file I/O.Is there a alternative to do > > > this.(maybe without read() operation) > > > Thanks > > > After reading your post again, this might be better: > > > #!/usr/bin/env python > > > from elementtree import ElementTree as et > > tree = et.parse("testxml.xml") > > > for t in tree.getiterator("SERVICEPARAMETER"): > > if t.get("Semantics") == "localId": > > t.set("Semantics", "dataPackageID") > > > tree.write("output.xml") > > > ~Sean- Hide quoted text - > > > - Show quoted text - > > which module should be imported for above to work,it says > ImportError: No module named elementtree > Thanks You can either 1) upgrade to python 2.5 which includes the elementtree module or 2) download and add the module to your current installation http://effbot.org/zone/element-index.htm ~Sean From mccredie at gmail.com Thu May 3 17:46:19 2007 From: mccredie at gmail.com (Matimus) Date: 3 May 2007 14:46:19 -0700 Subject: cannot import name ..... In-Reply-To: <1178215347.492858.217280@y5g2000hsa.googlegroups.com> References: <1178209261.189586.95540@p77g2000hsh.googlegroups.com> <1178215347.492858.217280@y5g2000hsa.googlegroups.com> Message-ID: <1178228779.784163.85480@h2g2000hsg.googlegroups.com> I do see one problem there... if __name__ == 'main': t = nBaseTest('nBaseTest') t.logon() That should be: if __name__ == "__main__": t = nBaseTest('nBaseTest') t.logon() It should be like that in both files. From steven.bethard at gmail.com Sun May 27 14:39:27 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 27 May 2007 12:39:27 -0600 Subject: ten small Python programs In-Reply-To: References: Message-ID: Steve Howell wrote: > --- Steven Bethard wrote: >> I think I would rewrite the current unit-testing >> example to use the >> standard library unittest module:: >> >> # Let's write reusable code, and unit test it. >> def add_money(amounts): >> # do arithmetic in pennies so as not to >> accumulate float errors >> pennies = sum([round(int(amount * 100)) for >> amount in amounts]) >> return float(pennies / 100.0) >> import unittest >> class TestAddMoney(unittest.TestCase): >> def test_float_errors(self): >> self.failUnlessEqual(add_money([0.13, >> 0.02]), 0.15) >> self.failUnlessEqual(add_money([100.01, >> 99.99]), 200) >> self.failUnlessEqual(add_money([0, >> -13.00, 13.00]), 0) >> if __name__ == '__main__': >> unittest.main() >> > > Just a minor quibble, but wouldn't you want the import > and test class to only get executed in the ___main__ > context? That would be fine too. In the real world, I'd put the tests in a different module. STeVe From martin at v.loewis.de Thu May 17 08:20:54 2007 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Thu, 17 May 2007 14:20:54 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> <4648294F.2000704@web.de> <46487a6c$0$2400$426a74cc@news.free.fr> Message-ID: <464C48A6.1010805@v.loewis.de> > You could say the same about Python standard library and keywords then. > Shouldn't these also have to be translated? One can even push things a > little further: I don't know about the languages used in the countries > you mention, but for example, a simple construction like 'if > ' will look weird to a Japanese (the Japanese language has > a "post-fix" feel: the equivalent of the 'if' is put after the > condition). So why enforce an English-like sentence structure? The Python syntax does not use an English-like sentence structure. In English, a statement follows the pretty strict sequence of subject, predicate, object (SPO). In Python, statements don't have a subject; some don't even have a verb (e.g. assignments). Regardless, this PEP does not propose to change the syntax of the language, because doing so would cause technical problems - unlike the proposed PEP, which does not cause any technical problems to the language implementation whatsoever (and only slight technical problems to editors, which aren't worse than the ones cause by PEP 263). > You have a point here. When learning to program, or when programming for > fun without any intention to do something serious, it may be better to > have a language supporting "native" characters in identifiers. My > problem is: if you allow these, how can you prevent them from going > public someday? You can't, and you shouldn't. What you can prevent is that the code enters *your* project. I cannot see why you want to censor what code other people publish. Regards, Martin From iltchevi at gmail.com Thu May 3 18:24:10 2007 From: iltchevi at gmail.com (ici) Date: 3 May 2007 15:24:10 -0700 Subject: adding methods at runtime and lambda In-Reply-To: <1178221975.149008.192410@y5g2000hsa.googlegroups.com> References: <1178221975.149008.192410@y5g2000hsa.googlegroups.com> Message-ID: <1178231050.351250.39720@l77g2000hsb.googlegroups.com> On May 3, 10:52 pm, Mike wrote: > I was messing around with adding methods to a class instance at > runtime and saw the usual code one finds online for this. All the > examples I saw say, of course, to make sure that for your method that > you have 'self' as the first parameter. I got to thinking and thought > "I have a lot of arbitrary methods in several utility files that I > might like to add to things. How would I do that?" And this is what I > came up with: > > def AddMethod(currObject, method, name = None): > if name is None: name = method.func_name > class newclass(currObject.__class__):pass > setattr(newclass, name, method) > return newclass() > > And lets say I have a utility function that can check if a drive > exists on my windows box called HasDrive. I can add that like this: > > superdict = addm(dict(), lambda self, d: myUtils.HasDrive(d), > "hasdrive") > > and then I can call > > superdict.HasDrive('c') > > lambda makes it possible to add any random function because you can > use it to set self as the first parameter. I've found several real > uses for this already. My big question is, will something like this be > possible in python 3000 if lambda really does go away? I've not heard > much about lambda, reduce, etc. lately but I know Guido wanted them > out of the language. > > Is there a better way to do this today than to use lambda? It seemed > the simplest way to do this that I could find. from win32com.client import Dispatch as CreateObject class HDDs(list): def __init__(self): fso = CreateObject('Scripting.FileSystemObject') for d in fso.Drives: if d.DriveType == 2: # Fixed list.append(self, d.DriveLetter) if __name__ == "__main__": drv_list = HDDs() for d in drv_list: print d try: # Found print drv_list.index('P') except ValueError: # Not Found print "P: Not Exists!" From aboudouvas at panafonet.gr Thu May 3 06:25:47 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 3 May 2007 03:25:47 -0700 Subject: 32 OS on 64-bit machine In-Reply-To: <1178187568.032961.172620@c35g2000hsg.googlegroups.com> References: <1178183424.548438.303170@y80g2000hsf.googlegroups.com> <1178186326.789203@nntpcache01.si.eunet.at> <1178187568.032961.172620@c35g2000hsg.googlegroups.com> Message-ID: <1178187947.221872.275540@q75g2000hsh.googlegroups.com> I have at home an AMD Turion 64 and using Ubuntu. You may be interested on this, i will post here the results when i get back home! From john.clark at cabbage-rose.com Thu May 3 11:11:26 2007 From: john.clark at cabbage-rose.com (John Clark) Date: Thu, 3 May 2007 11:11:26 -0400 Subject: New York City Python Users Group Meeting - Tuesday May 8th Message-ID: <00b101c78d95$53be1c40$fefea8c0@haengma> Greetings! The next New York City Python Users Group meeting is this Tuesday, May 8th, 6:30pm at at the Millennium Partners office at 666 Fifth Avenue (53rd St. and 5th Ave.) on the 8th Floor. We welcome all those in the NYC area who are interested in Python to attend. However, we need a list of first and last names to give to building security to make sure you can gain access to the building. RSVP to clajo04 at mac.com to add your name to the list. More information can be found on the yahoo group page: http://tech.groups.yahoo.com/group/nycpython/ Hope to see you there! -John -------------- next part -------------- An HTML attachment was scrubbed... URL: From gerrit.muller at embeddedsystems.nl Fri May 4 03:08:29 2007 From: gerrit.muller at embeddedsystems.nl (Gerrit Muller) Date: Fri, 04 May 2007 09:08:29 +0200 Subject: Replacement for HTMLGen? In-Reply-To: <463a70b1$0$16345$88260bb3@free.teranews.com> References: <463a70b1$0$16345$88260bb3@free.teranews.com> Message-ID: > > That said, can someone recommend a good replacement for > HTMLGen? <...snip...> > Granted, I know HTML doesn't change (much) but it's at least > nice to know something you're going to be using is maintained. <...snip...> Joshua, I am happily using HTMLgen. I do think that maintenance has not been required, since HTML didn't change. It is pure Python, so it doesn't require any recompilation for Python updates. If you need HTMLgen send me an e-mail and I will send you a zipfile. kind regards, Gerrit Muller -- Gaudi systems architecting: http://www.gaudisite.nl/ > > That said, can someone recommend a good replacement for HTMLGen? I've found > good words about it (http://www.linuxjournal.com/article/2986), but every > reference to it I find points to a non-existant page > (http://starship.python.net/lib.html is 404, > http://www.python2.net/lib.html is not responding, > http://starship.python.net/crew/friedrich/HTMLgen/html/main.html is 404) > Found http://www.python.org/ftp/python/contrib-09-Dec-1999/Network/, but > that seems a bit old. > > I found http://dustman.net/andy/python/HyperText, but it's not listed in > Cheeseshop, and its latest release is over seven years ago. Granted, I > know HTML doesn't change (much) but it's at least nice to know something > you're going to be using is maintained. > > Any suggestions or pointers? > > j > From vegan16 at accesscomm.ca Thu May 3 11:53:39 2007 From: vegan16 at accesscomm.ca (malibu) Date: 3 May 2007 08:53:39 -0700 Subject: Firefighters at the site of WTC7 "Move away the building is going to blow up, get back the building is going to blow up." In-Reply-To: <1178173090.238547.62190@o5g2000hsb.googlegroups.com> References: <1178161820.731367.264500@y80g2000hsf.googlegroups.com> <1178163974.007362.13870@c35g2000hsg.googlegroups.com> <1178172877.755445.101340@q75g2000hsh.googlegroups.com> <1178173090.238547.62190@o5g2000hsb.googlegroups.com> Message-ID: <1178207619.155007.129860@o5g2000hsb.googlegroups.com> On May 3, 12:18 am, Eric Gisse wrote: > On May 2, 10:14 pm, malibu wrote: > > > On May 2, 9:46 pm, Eric Gisse wrote: > > > > On May 2, 7:10 pm, Midex wrote: > > > > [...] > > > > I guess the explanation that people were looking at the building and > > > watching its' structure deform is too rational. > > > Also, that was a Larry Silverstein impostor who > > said they were going to 'pull it'. > > ...maybe if you read the context, it would make a little more rational > sense. Fucking nutter. > > > And the only reason he took out huge amounts > > of extra insurance on the buildings two months > > before this happened was because of global > > warming, because we all know a little bit of heat > > will bring down steel buildings. > > A little heat and major structural damage. > > > > > John Gee, I'll bet all those explosions in the subfloors of WTC1 + WTC2 did some structural damage also! Come to think of it. When the firefighters got there, all the glass on the street floors was blown out. Shock wave from the plane hitting 80 floors up? Janitors and such coming up from the basement levels bleeding and dazed. Jet fuel trickling down the elevator shafts being ignited by someone's roach? And exploding? Severing the three-foot thick steel columns? All 5 dozen of them? (That's mighty fine primo, pardner!) Your brain got structural damage? Dropped on your head as a kid? Don't put that fire iron too close to the flames, honey. It'll melt and deform! John From obaudys at gmail.com Wed May 16 19:33:02 2007 From: obaudys at gmail.com (obaudys at gmail.com) Date: 16 May 2007 16:33:02 -0700 Subject: Quote aware split In-Reply-To: References: <41749080705151750m3367c65dy4d1ae6ca66c2a16b@mail.gmail.com> Message-ID: <1179358382.611993.141610@y80g2000hsf.googlegroups.com> On May 16, 8:51 pm, "BJ?rn Lindqvist" wrote: > How is the code different from shlex.split? Shlex only splits by whitespace. I needed something to split out SQL statements from a Postgresql dump, so the ideal way of doing that is to split by semicolons. However, postgresql function definitions have semicolons inside single quoted blocks which I didnt want to split by. -- Ondrej From john at datavoiceint.com Tue May 8 14:19:38 2007 From: john at datavoiceint.com (HMS Surprise) Date: 8 May 2007 11:19:38 -0700 Subject: No module named urllib In-Reply-To: References: <87tzuop8s2.fsf@gmail.com> <1178577562.498615.222340@e51g2000hsg.googlegroups.com> <87ps5cp816.fsf@gmail.com> <1178578923.067315.14440@q75g2000hsh.googlegroups.com> <1178580280.902179.248000@w5g2000hsg.googlegroups.com> <1178630341.147781.39380@y5g2000hsa.googlegroups.com> <1178633606.618416.155600@e51g2000hsg.googlegroups.com> Message-ID: <1178648377.968335.108950@p77g2000hsh.googlegroups.com> Great idea Dennis, I will look into that. Thanks, jh From byte8bits at gmail.com Mon May 21 11:43:07 2007 From: byte8bits at gmail.com (brad) Date: Mon, 21 May 2007 11:43:07 -0400 Subject: A few questions In-Reply-To: <1hyfmze.2m4hspymmbswN%aleax@mac.com> References: <1hyfmze.2m4hspymmbswN%aleax@mac.com> Message-ID: Alex Martelli wrote: > Most popular, however, is no doubt wxWindows -- > mostly because you can freely use it to develop SW which you plan to > distribute under closed-source licenses, while Qt &c force you to choose > -- either pay, or, if you even distribute your code, it will have to be > under the GPL. I'm not sure how well wxWindows works on Mac nowadays... wx Works great on Macs (10.4 at least, maybe others), Linux and Windows. We've used it for several cross-platform apps that needed GUIs. From stefan.behnel-n05pAM at web.de Thu May 10 15:19:31 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 10 May 2007 21:19:31 +0200 Subject: replacing string in xml file--revisited In-Reply-To: <1178796095.060439.40240@y5g2000hsa.googlegroups.com> References: <1178783809.444544.79640@w5g2000hsg.googlegroups.com> <1178787310.006875.204040@w5g2000hsg.googlegroups.com> <1178796095.060439.40240@y5g2000hsa.googlegroups.com> Message-ID: <46437043.8040908@web.de> saif.shakeel at gmail.com wrote: > On May 10, 1:55 pm, half.ital... at gmail.com wrote: >> from elementtree import ElementTree as et > > which module should be imported for above to work,it says > ImportError: No module named elementtree > Thanks What about trying a web search engine to answer your own question? Usually much faster for this kind of request. Stefan From SuperM at ssiveBlackHoleAtTheCenterOfTheMilkyWayGalaxy.org Thu May 3 21:10:25 2007 From: SuperM at ssiveBlackHoleAtTheCenterOfTheMilkyWayGalaxy.org (The Great Attractor) Date: Thu, 03 May 2007 18:10:25 -0700 Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> <1178162456.929395.139390@q75g2000hsh.googlegroups.com> <4639ce3e$0$29937$afc38c87@news.optusnet.com.au> <4639DB53.397D6243@hotmail.com> Message-ID: <6v1l33tht11glj7fpd1q36qo46ev7i5dvv@4ax.com> On Thu, 03 May 2007 13:53:39 +0100, Eeyore wrote: > > >Peter Webb wrote: > >> > Ask yourself WHY havn't I seen this footage before? >> > >> > **************************** >> >> OK, why haven't you seen this footage before? > >Nice response ! > >Graham > You're an utter retard. From stefan.behnel-n05pAM at web.de Mon May 14 12:45:58 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 14 May 2007 18:45:58 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476AB1.7010001@web.de> Message-ID: <46489246.8000104@web.de> Jarek Zgoda schrieb: > Stefan Behnel napisa?(a): > >>> While I can read the code with Hebrew, Russian or Greek names >>> transliterated to ASCII, I would not be able to read such code in native. >> Then maybe it was code that was not meant to be read by you? > > OK, then. As a code obfuscation measure this would fit perfectly. I actually meant it as a measure for clarity and readability for those who are actually meant to *read* the code. Stefan From steve at REMOVE.THIS.cybersource.com.au Wed May 2 18:50:37 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 03 May 2007 08:50:37 +1000 Subject: How to check if a string is empty in python? References: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> Message-ID: On Wed, 02 May 2007 13:35:47 -0700, noagbodjivictor wrote: > How to check if a string is empty in python? > if(s == "") ?? In no particular order, all of these methods will work: # test s is equal to another empty string if s == "": # assuming s is a string, test that it is empty if not s: # test s is a string and it is empty if isinstance(s, str) and not s: # test s has length 0 if len(s) == 0: # test the length of s evaluates as false if not len(s): # a long way to test the length of s if s.__len__() < 1: # a stupid way to test s is empty if bool(s) == False: # a REALLY stupid way to test s is empty if (bool(s) == False) == True: # test that appending s to itself is itself if s+s == s: # test that s has none of any character if not filter(None, [1 + s.find(chr(n)) for n in range(256)]): That last one is really only good for wasting CPU cycles. -- Steven. From nyamatongwe+thunder at gmail.com Mon May 14 04:03:39 2007 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Mon, 14 May 2007 08:03:39 GMT Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46473267$0$31532$9b622d9e@news.freenet.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis: > This PEP suggests to support non-ASCII letters (such as accented > characters, Cyrillic, Greek, Kanji, etc.) in Python identifiers. I support this to ease integration with other languages and platforms that allow non-ASCII letters to be used in identifiers. Python has a strong heritage as a glue language and this has been enabled by adapting to the features of various environments rather than trying to assert a Pythonic view of how things should work. Neil From gagsl-py2 at yahoo.com.ar Mon May 14 17:27:30 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 14 May 2007 18:27:30 -0300 Subject: tkinter button state = DISABLED References: <1179163831.016938.79840@w5g2000hsg.googlegroups.com> <1179175592.011635.103980@e51g2000hsg.googlegroups.com> Message-ID: En Mon, 14 May 2007 17:46:32 -0300, escribi?: > On May 14, 12:01 pm, Peter Otten <__pete... at web.de> wrote: >> rahulna... at yahoo.com wrote: >> > b=Button(frame, text = "Button", state = 'disabled') >> > b.bind("", >> > lambda >> > event : >> > function() >> > ) >> >> Well, the /mouse/ button /was/ released. Do you know about the >> alternative? >> >> b = Button(..., command=function) # no bind(), no lambda >> It behaves like you expect. > > So, then is it right to say that for a widget like button widget on > occurance of a 'event' the function which is bound to this event is > invoked, even if the button widget has its 'state' option set to > 'disabled'. I was assuming that if the button widget has state = > 'disabled' then even on a button event the binding function wont be > invoked. > I will take a look at the alternative code you suggested above too. Maybe there is a confusion here. You code above means that, when the event "The leftmost MOUSE BUTTON was released" happens over your BUTTON WIDGET b, your function will be called. The "alternative code" suggested is the right way; the "command" is fired when the mouse button is pressed inside the widget AND then released inside the SAME widget (and the button is not disabled). -- Gabriel Genellina From sykora.skywave at gmail.com Thu May 3 22:49:41 2007 From: sykora.skywave at gmail.com (sykora) Date: 3 May 2007 19:49:41 -0700 Subject: How do I import a variable from another module? In-Reply-To: <1178242747.807572.226360@h2g2000hsg.googlegroups.com> References: <1178242032.254096.316860@o5g2000hsb.googlegroups.com> <1178242561.677032.4440@y80g2000hsf.googlegroups.com> <1178242747.807572.226360@h2g2000hsg.googlegroups.com> Message-ID: <1178246981.412543.159030@o5g2000hsb.googlegroups.com> On May 4, 6:39 am, noagbodjivic... at gmail.com wrote: > On May 3, 9:36 pm, Andy Terrel wrote: > > > are you sure your variable isn't in some code block that wouldn't be > > read on import? Such as: > > > if __name__ == "__main___": > > actions = 1 > > No Andy, I have not put the variable in any code block Does the variable show up in the dir listing of the module? ie. >>> import qt_actions >>> dir(qt_actions) From gh at gregor-horvath.com Wed May 16 06:12:53 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Wed, 16 May 2007 12:12:53 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de><1179160242.787344.48060@h2g2000hsg.googlegroups.com> <1179258692.237438.110860@p77g2000hsh.googlegroups.com> Message-ID: Hendrik van Rooyen schrieb: > It is not so much for technical reasons as for aesthetic > ones - I find reading a mix of languages horrible, and I am > kind of surprised by the strength of my own reaction. This is a matter of taste. In some programs I use German identifiers (not unicode). I and others like the mix. My customers can understand the code better. (They are only reading it) > > "Beautiful is better than ugly" Correct. But why do you think you should enforce your taste to all of us? With this logic you should all drive Alfa Romeos! Gregor From mr.williamchang at gmail.com Fri May 25 16:55:24 2007 From: mr.williamchang at gmail.com (William Chang) Date: 25 May 2007 13:55:24 -0700 Subject: printing list, is this a bug? Message-ID: <1180126524.884163.234040@k79g2000hse.googlegroups.com> Is the different behavior between __repr__ and __str__ intentional when it comes to printing lists? Basically I want to print out a list with elements of my own class, but when I overwrite __str__, __str__ doesn't get called but if I overwrite __repr__, __repr__ will get called. Is this a bug? For example: >>> class StrElement(object): ... def __str__(self): ... return "String Element" ... >>> a = [StrElement(), StrElement()] >>> print a [<__main__.StrElement object at 0xb7dc05cc>, <__main__.StrElement object at 0xb7dc048c>] >>> print StrElement() String Element But if overwrite __repr__: >>> class ReprElement(object): ... def __repr__(self): ... return "Repr Element" ... >>> b = [ReprElement(), ReprElement()] >>> print b [Repr Element, Repr Element] >>> print ReprElement() Repr Element From willy at matthehonk.com Thu May 17 17:54:51 2007 From: willy at matthehonk.com (STEPHEN) Date: Thu, 17 May 2007 22:54:51 +0100 Subject: ~!~ Britneys New BOOBS References: <1179336272.349749.183150@q75g2000hsh.googlegroups.com> Message-ID: <5b419cF2rf6i2U1@mid.individual.net> netto 24 bottles 33l 9.99 grolch wrote in message news:1179336272.349749.183150 at q75g2000hsh.googlegroups.com... > http://scargo.in - Download pics and videos of Britneys new Boob job > see her new tits naked! > From electronixtar at gmail.com Tue May 8 06:56:27 2007 From: electronixtar at gmail.com (est) Date: 8 May 2007 03:56:27 -0700 Subject: Newbie prob: How to write a file with 3 threads? In-Reply-To: References: <1178440537.257526.40980@y5g2000hsa.googlegroups.com> <1178485944.755068.321740@y5g2000hsa.googlegroups.com> <1178522026.763041.319940@e65g2000hsc.googlegroups.com> <_lJ%h.12611$3P3.10440@newsread3.news.pas.earthlink.net> <1178587327.571785.156800@w5g2000hsg.googlegroups.com> Message-ID: <1178621787.113730.63080@e51g2000hsg.googlegroups.com> On May 8, 2:13 pm, Dennis Lee Bieber wrote: > On 7 May 2007 18:22:07 -0700, est declaimed > the following in comp.lang.python: > > > > > I guess I will write multiple files, one thread one file, and after > > all threads terminates, I combine the files. That's a cheaper > > solution, I think. > > Given your first description: > > > I need to write a file using 3 threads simutaniously, e.g. Thread 1 > > write the first byte of test.bin with an "a", second thread write the > > second byte "b", third thread write the third byte "c". Anyone could > > give a little example on how to do that? > > ... any other solution may not have worked anyway. That is, if you > really expect the three threads to interleave their output as > abcabcabcabc. If threading, you have no assurance that any single thread > will follow any other during a task switch. It all depends upon where a > task switch takes place. > > But then, your example isn't too clear of what you really are > producing for output. If, instead of "bytes", you meant that each thread > was writing logging information, the solution would be to use the > logging module -- so far as I know, the logging module /does/ perform > the needed access locking. > > OTOH, if you really mean to have three separate byte producers, > interleaving output, the only safe way would be to have /each/ have an > output Queue, and a fourth thread doing the writing using a loop of the > form: > > while True: > a = aQueue.get() > fout.write(a) > b = bQueue.get() > fout.write(b) > c = cQueue.get() > fout.write(c) > > Using the separate queues means that the writer WILL wait until the > next producer in the interleave has produced its data. Of course, this > structure has the drawback that all producers must produce the same > amount of data -- otherwise it blocks forever on the queue from the > producer has stopped generating data. > -- > 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/ I'd like to say VERY VERY VERY thank you for your detailed information, that's a lot encourage for a beginner. In fact I am writing a multi thread download ultility, and I found that very hard for me. Can you recommand any sample code where I can start with? I hope I can catch up with everyone here, I'll try my best learning python. Thank you again. From MMM at disney.com Wed May 16 10:43:23 2007 From: MMM at disney.com (MMM at disney.com) Date: Wed, 16 May 2007 14:43:23 GMT Subject: =// Homeland Security on High Alert!! Fuck Blogs and Bloggers References: <1179166411.536148.186120@w5g2000hsg.googlegroups.com> Message-ID: On Wed, 16 May 2007 10:32:20 +0100, "Gizmo." wrote: > > wrote in message >news:seah43di9vjbmqpjf8pum8nngj7d1ig666 at 4ax.com... >> On 14 May 2007 11:13:31 -0700, ready.or.special3 at gmail.com wrote: > >> Links always lead to a fucking advertisement with no pics...fuck you >> asshole.. > >And then cunts like you come along and repost spam that'd already been >blocked by decent dews feeds. > > Dirty Deeds Done Dirt Cheap Matey.... From gagsl-py2 at yahoo.com.ar Sun May 6 03:06:22 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 06 May 2007 04:06:22 -0300 Subject: Looping over lists References: <1hxlsky.tgi88sj7tfrN%aleax@mac.com> Message-ID: En Sat, 05 May 2007 05:15:32 -0300, kaens escribi?: > I think the for i in range() is more readable (Maybe because I'm > coming from a c-style syntax language background) - but what would > the benefits of using enumerate be (other that being more . . . > pythonesque?) If you want to iterate over a sequence and process each item, you could do this (as one would do in C): for i in range(len(values)): dosomethingwith(values[i]) Problems: values[i] gets translated into values.__getitem__(i), and that requires a lookup for the __getitem__ method and a function call; and you don't actually need the index i, but it's created anyway. In this case the best (and fastest) way in Python is: for item in values: dosomethingwith(item) No spurious variable, no method lookup, no aditional function call. But what if you need *also* the index? On earlier Python versions one had to go back to the first method; enumerate() was made just for this case: for i, item in enumerate(values): dosomethingwith(item, i) You get all the advantages of the iterator approach plus the index available. -- Gabriel Genellina From showell30 at yahoo.com Sat May 26 14:43:25 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sat, 26 May 2007 11:43:25 -0700 (PDT) Subject: ten small Python programs Message-ID: <162044.45569.qm@web33507.mail.mud.yahoo.com> I've always thought that the best way to introduce new programmers to Python is to show them small code examples. When you go to the tutorial, though, you have to wade through quite a bit of English before seeing any Python examples. Below is my attempt at generating ten fairly simple, representative Python programs that expose new users to most basic concepts, as well as the overall syntax. It was an interesting exercise. I constrained myself to ten lines or less, and it was pretty easy to incorporate loops, conditionals, print, open(), lists, tuples, dictionaries, and imported modules. It was harder to show classes, and my ShoppingCart class is nothing more than an encapsulation of a list, which has dubious value (although it's the start of something more useful). Anyway, here goes: ------ print 'hello world' ------ for name in ('peter', 'paul', 'mary'): print name ------ # This is a Python comment. \n is a newline name = raw_input('What is your name?\n') print 'Hi', name ------ parentRabbits, babyRabbits = (1, 1) while babyRabbits < 100: print 'This generation has %d rabbits' % babyRabbits parentRabbits, babyRabbits = (babyRabbits, parentRabbits + babyRabbits) ------ # def defines a method in Python def tax(itemCharge, taxRate = 0.05): return itemCharge * taxRate print '%.2f' % tax(11.35) print '%.2f' % tax(40.00, 0.08) ------ import re for test_string in [ '555-1212', 'ILL-EGAL']: if re.match('\d\d\d-\d\d\d\d$', test_string): print test_string, 'is a valid US local phone number' else: print test_string, 'rejected' ------ prices = {'apple': 0.40, 'banana': 0.50} myPurchase = { 'apple': 1, 'banana': 6} groceryBill = sum([prices[fruit] * myPurchase[fruit] for fruit in myPurchase]) print 'I owe the grocer $%.2f' % groceryBill ------ class ShoppingCart: def __init__(self): self.items = [] def buy(self, item): self.items.append(item) def boughtItems(self): return self.items myCart = ShoppingCart() myCart.buy('apple') myCart.buy('banana') print myCart.boughtItems() ------ # indent your Python code to put into an email import glob pythonFiles = glob.glob('*.py') pythonFiles.sort() for fn in pythonFiles: print ' ------' for line in open(fn): print ' ' + line.rstrip() print ------ import time now = time.localtime() hour = now.tm_hour if hour < 8: print 'sleeping' elif hour < 9: print 'commuting' elif hour < 17: print 'working' elif hour < 18: print 'commuting' elif hour < 20: print 'eating' elif hour < 22: print 'resting' else: print 'sleeping' ____________________________________________________________________________________ Expecting? Get great news right away with email Auto-Check. Try the Yahoo! Mail Beta. http://advision.webevents.yahoo.com/mailbeta/newmail_tools.html From nagle at animats.com Sun May 13 13:30:11 2007 From: nagle at animats.com (John Nagle) Date: Sun, 13 May 2007 10:30:11 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46473267$0$31532$9b622d9e@news.freenet.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: <9TH1i.1773$mR2.1557@newssvr22.news.prodigy.net> Martin v. L?wis wrote: > PEP 1 specifies that PEP authors need to collect feedback from the > community. As the author of PEP 3131, I'd like to encourage comments > to the PEP included below, either here (comp.lang.python), or to > python-3000 at python.org > > In summary, this PEP proposes to allow non-ASCII letters as > identifiers in Python. If the PEP is accepted, the following > identifiers would also become valid as class, function, or > variable names: L?ffelstiel, chang?, ??????, or ??? > (hoping that the latter one means "counter"). > All identifiers are converted into the normal form NFC while parsing; > comparison of identifiers is based on NFC. That may not be restrictive enough, because it permits multiple different lexical representations of the same identifier in the same text. Search and replace operations on source text might not find all instances of the same identifier. Identifiers should be required to be written in source text with a unique source text representation, probably NFC, or be considered a syntax error. I'd suggest restricting identifiers under the rules of UTS-39, profile 2, "Highly Restrictive". This limits mixing of scripts in a single identifier; you can't mix Hebrew and ASCII, for example, which prevents problems with mixing right to left and left to right scripts. Domain names have similar restrictions. John Nagle From sjmachin at lexicon.net Tue May 15 19:48:18 2007 From: sjmachin at lexicon.net (John Machin) Date: 15 May 2007 16:48:18 -0700 Subject: Name of function caller In-Reply-To: <1179269786.256165.151340@o5g2000hsb.googlegroups.com> References: <1179266351.304587.182070@n59g2000hsh.googlegroups.com> <1179267214.735025.167470@l77g2000hsb.googlegroups.com> <1179269786.256165.151340@o5g2000hsb.googlegroups.com> Message-ID: <1179272898.331951.184300@w5g2000hsg.googlegroups.com> On May 16, 8:56 am, HMS Surprise wrote: > On May 15, 5:13 pm, Paul McGuire wrote: > > > On May 15, 4:59 pm, HMS Surprise wrote: > > > > Is there a way that a function may access the doc string or func_name > > > of the caller? > > > > Thanks, > > > > jvh > > > Yes. The inspect module allows you to look up the call stack for > > information on the caller, the caller's caller, local vars, etc. > > > -- Paul > > Thanks Paul. > > Running jython 2.2. No module named inspect or cInspect > > drat... According to the current docs, inspect was new in Python 2.1. You've been in more strife than Paris Hilton recently and it's hard to keep track, but IIRC you're the guy with the badly-stuffed sys.path ... have a look on your disk(s). OTOH maybe inspect depends on the internal call stack implementation --- in that case you would need to ask on the jython mailing-list. HTH, John From duncan.booth at invalid.invalid Tue May 15 05:45:17 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 15 May 2007 09:45:17 GMT Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> <4648294F.2000704@web.de> <46487a6c$0$2400$426a74cc@news.free.fr> Message-ID: "Eric Brunel" wrote: > On Tue, 15 May 2007 09:38:38 +0200, Duncan Booth > wrote: >> Recently there has been quite a bit of publicity about the One Laptop >> Per Child project. The XO laptop is just beginning rollout to >> children and provides two main programming environments: Squeak and >> Python. It is an exciting thought that that soon there will be >> millions of children in countries such as Nigeria, Brazil, Uruguay or >> Nepal[*] who have the potential to learn to program, but tragic if >> the Python community is too arrogant to consider it acceptable to use >> anything but English and ASCII. > > You could say the same about Python standard library and keywords > then. Shouldn't these also have to be translated? One can even push > things a little further: I don't know about the languages used in the > countries you mention, but for example, a simple construction like > 'if ' will look weird to a Japanese (the > Japanese language has a "post-fix" feel: the equivalent of the 'if' > is put after the condition). So why enforce an English-like sentence > structure? > Yes, non-English speakers have to learn a set of technical words which are superficially in English, but even English native speakers have to learn non-obvious meanings, or non-English words 'str', 'isalnum', 'ljust'. That is an unavoidable barrier, but it is a limited vocabulary and a limited set of syntax rules. What I'm trying to say is that we shouldn't raise the entry bar any higher than it has to be. The languages BTW in the countries I mentioned are: in Nigeria all school children must study both their indigenous language and English, Brazil and Uruguay use Spanish and Nepali is the official language of Nepal. From whamil1 at entergy.com Mon May 7 10:02:14 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Mon, 7 May 2007 09:02:14 -0500 Subject: Strange terminal behavior after quitting Tkinter application In-Reply-To: <1178440794.659370.47230@y5g2000hsa.googlegroups.com> Message-ID: <588D53831C701746A2DF46E365C018CE01D2CA90@LITEXETSP001.etrsouth.corp.entergy.com> > From: Chris > > I'll admit to being surprised at seeing a claim that a tkinter > > application, started within an interactive session, without a mainloop, > > even runs... I could see it maybe happening from Idle, since Idle is > > running a tkinter mainloop, so the application bindings may have just > > become "added widgets" to the Idle loop (but of course, a second > > mainloop would conflict heavily). > > You can try by building a working Tkinter GUI interactively from the > standard Python interpreter, and see that the GUI works (i.e. > processes events) at the same time. > If you build it as a class (such as the code in Chris's original post) it works; if you do it all directly, nothing happens until you run mainloop(). It works, but I'm not sure that it was intended to work that way. I think your problem is related to that difference. You'll probably be better off creating a new interpreter window as part of your program, if you really need access to the interpreter alongside your GUI. You may be able to extract IDLE's interpreter window and use it directly. --- -Bill Hamilton From grante at visi.com Mon May 21 10:24:11 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 21 May 2007 14:24:11 -0000 Subject: List Moderator References: <880dece00705172218n71123b55q531ec0c5e500f208@mail.gmail.com> <880dece00705190012g4f3d3ef6v4e6c87a156708bb0@mail.gmail.com> <880dece00705191305m203bc8ep804d647c17438581@mail.gmail.com> <464F5E42.6090607@holdenweb.com> <880dece00705201305q6944986fj8f77c4b5cac09456@mail.gmail.com> <13524svhtst5dd1@corp.supernews.com> Message-ID: <1353asbpai1gqd6@corp.supernews.com> On 2007-05-21, Grant Edwards wrote: > On 2007-05-20, Dennis Lee Bieber wrote: > >>> It doesn't all go through a central point - users like me who use a news >>> server to access the list submit articles through a local news server >>> using NNTP. While there *is* a single point of access for articles >>> pulled from python.org's news server and gatewayed out as email (and for >>> which the filters you mention probably ought to help), articles I see >>> have never been processed by this interface. >>> >> Which doesn't explain why only comp.lang.python, of the several >> newsgroups I read, seems to be so spam-filled... > > Maybe I've got a better news server, but I don't see much spam > at all in c.l.p. To quantify things for curiosity's sake, I just scanned through the last 1000 postings in c.l.p. There was exactly 1 spam message and two replies to spam messages complaining about them. -- Grant Edwards grante Yow! Everybody is going at somewhere!! It's probably visi.com a garage sale or a disaster Movie!! From sturlamolden at yahoo.no Sat May 12 19:35:40 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 12 May 2007 16:35:40 -0700 Subject: Basic question In-Reply-To: <1178986686.510137.195490@p77g2000hsh.googlegroups.com> References: <1178986686.510137.195490@p77g2000hsh.googlegroups.com> Message-ID: <1179012940.444019.315070@e65g2000hsc.googlegroups.com> On May 12, 6:18 pm, "Cesar G. Miguel" wrote: > Am I missing something? Python for loops iterates over the elements in a container. It is similar to Java's "for each" loop. for j in range(10): print j if(True): j=j+2 print 'interno',j Is equivalent to: int[] range = {0,1,2,3,4,5,6,7,8,9}; for (int j : range) { system.out.writeln(j); if (true) { j += 2; system.out.writeln("iterno" + j); } } If I remember Java correctly... From sjmachin at lexicon.net Mon May 7 19:00:54 2007 From: sjmachin at lexicon.net (John Machin) Date: 7 May 2007 16:00:54 -0700 Subject: No module named urllib In-Reply-To: <1178575589.059564.226060@q75g2000hsh.googlegroups.com> References: <1178575589.059564.226060@q75g2000hsh.googlegroups.com> Message-ID: <1178578854.926104.184700@y5g2000hsa.googlegroups.com> On May 8, 8:06 am, HMS Surprise wrote: > I edited environment varialbes and have added C:\Python25\Lib to > PYTHONPATH but get the no module message when the statement That directory should already be in sys.path after a normal Python install. Likewise the PYTHONPATH environment variable should be undefined: DOS_prompt> set PYTHONPATH Environment variable PYTHONPATH not defined What was already in PYTHONPATH before you added something? Why did you think you needed to change things? > > import urllib > > is executed. > > Even tried copying the urllib file to my working directory. > > Any suggestions? From stefan.behnel-n05pAM at web.de Tue May 15 10:39:56 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 15 May 2007 16:39:56 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179238847.407605.4620@w5g2000hsg.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649BC4C.10200@web.de> <1179238847.407605.4620@w5g2000hsg.googlegroups.com> Message-ID: <4649C63C.1030508@web.de> Paul Boddie wrote: > what I'd like to see, for a change, is some kind > of analysis of the prior art in connection with this matter. Java has > had extensive UTF-8 support all over the place for ages, but either no- > one here has any direct experience with the consequences of this > support, or they are more interested in arguing about it as if it were > a hypothetical situation when it is, in fact, a real-life situation > that can presumably be observed and measured. It's difficult to extract this analysis from Java. Most people I know from the Java world do not use this feature as it is error prone. Java does not have support for *explicit* source encodings, i.e. the local environment settings win. This is bound to fail e.g. on a latin-1 system where I would like to work with UTF-8 files (which tend to work better on the Unix build server, etc.) In the Python world, these problems are solved now and will disappear when UTF-8 becomes the default encoding (note that this does not inverse the problem as people using non-utf8 encodings will then just set the respective encoding tag in their files). So there is not much Python can learn from Java here except for what it already does better. I am actually working on a couple of Java projects that use German identifiers, transliterated to prevent the encoding problems inherent to Java. The transliteration makes things harder to read than necessary - and this is only German-vs-English, i.e. simple things like 'ae' instead of '?' and 'ss' instead of '?'. But sometimes things become hard to read that way or look like different words. And it leads to all sorts of weirdly mixed names as sometimes it is easier to write the similar looking (although maybe not completely synonymous) English word instead of the transliterated German one. So, yes, in a way, the code quality in these projects suffers from developers not being able to freely write Unicode identifiers. Stefan From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu May 3 13:08:39 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 03 May 2007 19:08:39 +0200 Subject: Can I use Python instead of Joomla? In-Reply-To: <1178204011.101042.81880@l77g2000hsb.googlegroups.com> References: <1178138925.498663.252920@o5g2000hsb.googlegroups.com> <4639173e$0$2415$426a74cc@news.free.fr> <1178204011.101042.81880@l77g2000hsb.googlegroups.com> Message-ID: <463a1708$0$14565$426a34cc@news.free.fr> walterbyrd a ?crit : > On May 2, 5:38 pm, Bruno Desthuilliers > wrote: > >> You're mixing apples, fishes, and cars here. Joomla is a content >> management system, Django a framework and Python a language. > > Yes, I know, but they are all ways to create a website. If I wanted a > site which included galleries, forums, etc. and I didn't want to re- > invent the wheel, I could: > > 1) Use joomla or drupal, and possible end up "fighting the framework" > to get just what I want. > > 2) Cooble together a web-site with various scripts, either developed > by others, or myself. > > I would like to work with django, and include some python stuff. But, > the PHP environments seem to have a much richer assortment of pre- > written scripts. Most of them being of very poor quality... > If I want to include my own applications, I could develop those apps > with a popular PHP MVC called "CakePHP" and include those into joomla > or drupal. I'm not sure integrating CakePHP stuff into something like Joomla or Drupal will be that easy. > I don't know if there is anything like that with Python > development. The most advanced Python-based CMS so far is still Plone. But it's a monstruosity. If you want Python and easy integration, you'd probably be happier with Pylons. While far from finished, it's very promising, and less monolithic than Django. My 2 cents... From ericy22 at gmail.com Wed May 23 09:19:05 2007 From: ericy22 at gmail.com (Eric Yaeger) Date: 23 May 2007 06:19:05 -0700 Subject: Can I reference 1 instance of an object by more names ? In-Reply-To: References: Message-ID: <1179926345.438173.199490@u30g2000hsc.googlegroups.com> Perhaps Stef Mientki, you might be interested in copy.copy( ) and copy.deepcopy( ) ! Please see the info I have put below. On May 23, 12:44 am, Stef Mientki wrote: > One of the problems is the alias statement, assigning a second name to an object. > I've defined a class IO_port, > and I create an instance of that port with the name port_D > > port_D = IO_port('D') > thanks, > Stef Mientki > > ==================================================== The following text is an excerpt from Chapter 12 of book: How to Think Like a Computer Scientist Learning with Python by Allen B. Downey, Jeffrey Elkner and Chris Meyers [Book available for free download at http://www.thinkpython.com] =.=.=.=.=.=.=.=.=.= Chapter 12 Classes and objects [...] [...] 12.4 Sameness The meaning of the word "same" seems perfectly clear until you give it some thought, and then you realize there is more to it than you expected. For example, if you say, "Chris and I have the same car," you mean that his car and yours are the same make and model, but that they are two different cars. If you say, "Chris and I have the same mother," you mean that his mother and yours are the same person. [...] So the idea of "sameness" is different depending on the context. When you talk about objects, there is a similar ambiguity. For example, if two Points are the same, does that mean they contain the same data (coordinates) or that they are actually the same object? To find out if two references refer to the same object, use the == operator. For example: >>> p1 = Point() >>> p1.x = 3 >>> p1.y = 4 >>> p2 = Point() >>> p2.x = 3 >>> p2.y = 4 >>> p1 == p2 0 Even though p1 and p2 contain the same coordinates, they are not the same object. If we assign p1 to p2, then the two variables are aliases of the same object: >>> p2 = p1 >>> p1 == p2 1 This type of equality is called shallow equality because it compares only the references, not the contents of the objects. To compare the contents of the objects [use] deep equality... ... [...] [...] 12.8 Copying [...] [...] 12.9 Glossary class - A user-defined compound type. A class can also be thought of as a template for the objects that are instances of it. instantiate - To create an instance of a class. instance - An object that belongs to a class. object - A compound data type that is often used to model a thing or concept in the real world. constructor - A method used to create new objects. attribute - One of the named data items that makes up an instance. shallow equality - Equality of references, or two references that point to the same object. deep equality - Equality of values, or two references that point to objects that have the same value. shallow copy - To copy the contents of an object, including any references to embedded objects; implemented by the copyfunction in the copy module. Example: >>> b2 = copy.copy(b1) deep copy - To copy the contents of an object as well as any embedded objects, and any objects embedded in them, and so on; implemented by the deepcopy function in the copy module. Example: >>> b2 = copy.deepcopy(b1) =.=.=.=.=.=.=.=.=.= The preceding text is an excerpt from Chapter 12 of book: How to Think Like a Computer Scientist Learning with Python by Allen B. Downey, Jeffrey Elkner and Chris Meyers [Book available for free download at http://www.thinkpython.com] ===================================================== Bye from, Eric Yaeger Thailand From vinay_sajip at yahoo.co.uk Sat May 12 04:26:11 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 12 May 2007 01:26:11 -0700 Subject: logging module and threading In-Reply-To: References: Message-ID: <1178958371.485100.161870@y80g2000hsf.googlegroups.com> On May 12, 1:53 am, Ross Boylan wrote: > > I'm also puzzled by how the logger hierarchy works. The docs say that > everything that is logged by the kids is also logged by the parent. > That would seem to defeat what I'm trying to do above, since the > parent would get each logged event right away. However,logging.getLogger("a").error("test") > produces only a single log message indicating an associated object of "a". > The docs lead me to expect that I'd see one message from "a" and > another from root. > > When I add handlers (e.g., FileHandlers) I do get the message recorded > by each. > > Can anyone explain what's going on? > The Logger hierarchy works, in a nutshell, as follows: events passed to a logger propagate up the hierarchy until either the root, or a logger whose propagate attribute is set to a false value, is reached. At each step (i.e. logger) in the propagation, any handlers attached to that logger are offered the chance to handle the message - which means different things depending on the handler. If you add e.g. a FileHandler to the root logger and another to a logger named "a.b.c" and then log something to "a.b.c", then two handlers will each handle the message, leading to multiple output of the same event. You also don't need to buffer up messages in different threads - if your messages contain both the log event time and the thread id (which can be achieved by having %(asctime)s or %(relativeCreated)d and % (thread)d or %(threadName)s in your format string), then you can simply sort the output to group your messages together. (And since threads sometimes interact, it's often useful to see the raw output in time order.) If you do want to buffer events, MemoryHandler will do the trick. And it takes a target handler rather than logger, because it's acting as a buffer for another handler, for events which have already been entered into the system. If you're new to logging, you need to separate the ideas behind loggers and handlers in the scheme of things. Loggers are things which application developers use to register events of interest in their application, with an indication of importance (level) and an ability to filter on that. Handlers are things used by developers or admins to send information about the events to different audiences - e.g. critical errors might be emailed to someone while less critical errors are sent to console or log files. Best regards, Vinay Sajip From half.italian at gmail.com Thu May 17 02:13:35 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 16 May 2007 23:13:35 -0700 Subject: How to do basic CRUD apps with Python In-Reply-To: <1179197198.513508@smirk> References: <1179098458.333666.307750@e65g2000hsc.googlegroups.com> <464848fa$0$465$426a74cc@news.free.fr> <1179197198.513508@smirk> Message-ID: <1179382415.366424.103980@e65g2000hsc.googlegroups.com> On May 14, 7:46 pm, "James T. Dennis" wrote: > Bruno Desthuilliers wrote: > > walterbyrd a ?crit : > >> With PHP, libraries, apps, etc. to do basic CRUD are everywhere. Ajax > >> and non-Ajax solutions abound. > >> With Python, finding such library, or apps. seems to be much more > >> difficult to find. > >> I thought django might be a good way, but I can not seem to get an > >> answer on that board. > >> I would like to put together a CRUD grid with editable/deletable/ > >> addable fields, click on the headers to sort. Something that would > >> sort-of looks like an online spreadsheet. It would be nice if the > >> fields could be edited in-line, but it's not entirely necessary. > >> Are there any Python libraries to do that sort of thing? Can it be > >> done with django or cherrypy? > > You may want to have a look at turbogears's widgets. > > Admittedly I had to look up the meaning of CRUD in this context: > (http://en.wikipedia.org/wiki/Create%2C_read%2C_update_and_delete > create, read, update, and delete). > > I'm looking at Turbogears' Widgets in another window as I type > this ... but it will be awhile before I can comment on how they > might apply to the OP's needs. Actually I'm wholly unqualified > to comment on his or her needs ... but I can comment on how I > interpreted the question. > > Even with the SQLAlchemy SQLSoup examples there's still an > annoying about of boilerplate coding that has to be done in order > to create a web application for doing CRUD on a database. > > The missing element seems to be the ability to autogenerate > web forms and reports with the requisite controls in them. > > Imagine, for a moment, being able to do something like: > > >>> import sqlalchemy.ext.webcrud as crud > >>> db = crud.open(....) > >>> db.displayTopForm() > ' .... > ' > > ... and having a default "top level" web page generated with > options to query the database (or some specific table in the > database to be more specific, add new entries, etc). > > I'm thinking of some sort of class/module that would generate > various sorts of HTML forms by default, but also allow one to > sub-class each of the form/query types to customize the contents. > > It would use introspection on the database columns and constraints > to automatically generate input fields for each of the columns and > even fields for required foreign keys (or links to the CRUD for those > tables?). Ideally it would also automatically hide autogenerated > (index/key) fields, and map the table column IDs to form names (with > gettext support for l10n of those). > > I think that's the sort of thing the OP was looking for. Not the > ORM ... the the glue between the web framework and the ORM. > > -- > Jim Dennis, > Starshine: Signed, Sealed, Delivered Sounds like you're talking about rails. Do any of the python packages compare with the ease of rails? I got in just deep enough to see the possibilities of it, and then had to stop to do real work in php. I'd be very interested in Python on Rails! ~Sean From gagsl-py2 at yahoo.com.ar Mon May 7 16:21:59 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 07 May 2007 17:21:59 -0300 Subject: Latest errors on pickled objects and blob datatypes in mysql References: Message-ID: En Mon, 07 May 2007 14:08:21 -0300, krishnakant Mane escribi?: > my table is called testobj and the blob field is called obj. > now following is my query with the cursor named CSRInsert. > CSRInsert.execute("insert into testobj (obj) values > (?);",(pickled_object)) > the error is, > "type error, not all arguments formatted during string formatting ". > > can some one now figure out what could be the problem? Try exactly as advised: CSRInsert.execute("insert into testobj (obj) values (?);",(pickled_object,)) -- Gabriel Genellina From gh at gregor-horvath.com Thu May 17 14:30:06 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Thu, 17 May 2007 20:30:06 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179423799.254286.294930@w5g2000hsg.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <464C5382.6080403@v.loewis.de> <1179423799.254286.294930@w5g2000hsg.googlegroups.com> Message-ID: Istvan Albert schrieb: > > After the first time that your programmer friends need fix a trivial > bug in a piece of code that does not display correctly in the terminal > I can assure you that their mellow acceptance will turn to something > entirely different. > Is there any difference for you in debugging this code snippets? class T?rstock(object): h?he = 0 breite = 0 tiefe = 0 def _get_fl?che(self): return self.h?he * self.breite fl?che = property(_get_fl?che) #----------------------------------- class Tuerstock(object): hoehe = 0 breite = 0 tiefe = 0 def _get_flaeche(self): return self.hoehe * self.breite flaeche = property(_get_flaeche) I can tell you that for me and for my costumers this makes a big difference. Whether this PEP gets accepted or not I am going to use German identifiers and you have to be frightened to death by that fact ;-) Gregor From kyosohma at gmail.com Fri May 25 11:19:44 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 25 May 2007 08:19:44 -0700 Subject: webbrowser module bug? In-Reply-To: References: Message-ID: <1180106384.198363.14120@p47g2000hsd.googlegroups.com> On May 24, 5:03 pm, Ron Adam wrote: > Is anyone else having problems with the webbrowser module? > > Python 2.5.1c1 (release25-maint, Apr 12 2007, 21:00:25) > [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import webbrowser > >>> webbrowser.open('http://www.python.org') > True > >>> > > It opens firefox as expected, but the url is ... > > file:///home/ron/%22http://www.python.org%22 > > Which of course doesn't do what is expected. > > Any ideas? > > Ron I don't know. This works for me with Python 2.4 on Windows XP SP2. The docs don't say much (http://docs.python.org/lib/module- webbrowser.html). Maybe it would be beneficial to read the module's code? Or use the "register" command manually? Mike From johnjsal at NOSPAMgmail.com Thu May 3 15:03:38 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 03 May 2007 15:03:38 -0400 Subject: How to check if a string is empty in python? In-Reply-To: <1178139155.260722.153750@n59g2000hsh.googlegroups.com> References: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> <1178138964.503290.254060@o5g2000hsb.googlegroups.com> <1178139155.260722.153750@n59g2000hsh.googlegroups.com> Message-ID: <463a31c0$0$6845$c3e8da3@news.astraweb.com> mensanator at aol.com wrote: > On May 2, 3:49 pm, Basilisk96 wrote: >> A simple >> >> if s: >> print "not empty" >> else: >> print "empty" >> >> will do. > > How do you know that s is a string? Seems like a fair assumption given the OP's question and example. From sjmachin at lexicon.net Fri May 11 20:23:12 2007 From: sjmachin at lexicon.net (John Machin) Date: 11 May 2007 17:23:12 -0700 Subject: Simple Python REGEX Question In-Reply-To: References: <1178898871.781501.135170@p77g2000hsh.googlegroups.com> Message-ID: <1178929392.533093.114150@q75g2000hsh.googlegroups.com> On May 12, 2:21 am, Gary Herron wrote: > johnny wrote: > > I need to get the content inside the bracket. > > > eg. some characters before bracket (3.12345). > > > I need to get whatever inside the (), in this case 3.12345. > > > How do you do this with python regular expression? > > >>> import re > >>> x = re.search("[0-9.]+", "(3.12345)") > >>> print x.group(0) > > 3.12345 > > There's a lot more to the re module, of course. I'd suggest reading the > manual, but this should get you started. > >>> s = "some chars like 987 before the bracket (3.12345) etc" >>> x = re.search("[0-9.]+", s) >>> x.group(0) '987' OP sez: "I need to get the content inside the bracket" OP sez: "I need to get whatever inside the ()" My interpretation: >>> for s in ['foo(123)bar', 'foo(123))bar', 'foo()bar', 'foobar']: ... x = re.search(r"\([^)]*\)", s) ... print repr(x and x.group(0)[1:-1]) ... '123' '123' '' None From steven.bethard at gmail.com Mon May 21 12:55:29 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 21 May 2007 10:55:29 -0600 Subject: pyparsing actinos (WAS: Inverse of id()?) In-Reply-To: <1179755471.432160.84850@x18g2000prd.googlegroups.com> References: <1179618173.280286.284120@n59g2000hsh.googlegroups.com> <1179741319.122807.56960@z24g2000prd.googlegroups.com> <1179755471.432160.84850@x18g2000prd.googlegroups.com> Message-ID: <4651CF01.8080204@gmail.com> Paul McGuire wrote: > For instance, Seo Sanghyeon (I believe the same one now working on > IronPython) uses the following technique in the EBNF parser/"compiler" > that he contributed to the pyparsing examples directory: > > # list of all the grammar variable names > all_names = ''' > integer > meta_identifier > terminal_string > ... > '''.split() > > # parse actions follow > def do_integer(str, loc, toks): > return int(toks[0]) FWIW, I find that my actions never use anything but the token list, so to avoid writing a bunch of functions like the one above, I typically write:: class ParseAction(object): def __init__(self, func): self.func = func def __call__(self, string, index, tokens): return self.func(*tokens) ... # parse an integer integer.addParseAction(ParseAction(int)) ... # parse a relation object, passing appropriate strings # (or parsed objects) to the constructor relation.setParseAction(ParseAction(Relation)) I guess the integer/int and relation/Relation is a little redundant, but it's never bothered me too much. STeVe From matt.newville at gmail.com Thu May 24 23:56:08 2007 From: matt.newville at gmail.com (matt.newville at gmail.com) Date: 24 May 2007 20:56:08 -0700 Subject: Python and GUI In-Reply-To: References: <1179761984.704369.116310@b40g2000prd.googlegroups.com> <4651CDBC.1070508@ulmcnett.com> Message-ID: <1180065368.415899.108170@o5g2000hsb.googlegroups.com> > Do others think like me here? Yes!! I agree completely: Wax is not only a fantastic idea, but a very good start at an implementation of that idea. --Matt Newville From S.Mientki-nospam at mailbox.kun.nl Mon May 28 17:22:53 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Mon, 28 May 2007 23:22:53 +0200 Subject: ten small Python programs In-Reply-To: References: Message-ID: Steve Howell wrote: > --- Stef Mientki > wrote: >>>> It would even be nicer, if everybody could drop >>>> her/his examples >>>> in a standard way, so they would be automatically >>>> incorporated in >>>> something like the wxPython interactive demo. >>>> >>> Can you elaborate? >> Well if you see the above demo, >> I've the following in mind: >> - create a new-demo in a special directory >> - add some special keywords in the new-demo, in >> which treenodes it should popup >> - on restart of the demo, the new-demo is added to >> the tree >> > > To the extent that you just want a group of people to > be able to organically organize a tree-like collection > of Python examples, you could use a MoinMoin that has > sensible page names and the Local Site Map featured > turn on. Are you also suggesting the need for > something local, so that you can actually run the > programs? I don't know MoinMoin, but the answer is Yes (although maybe not for your ten snippets). First of all I think all programmers keep there own collection of code snippets, which much more valuable then "all the code code snippets from everyone". Secondly, Python is nowadays not only used by programmers, but also by e.g. Scientific users (former MatLab users), who are not interested in the code itself, but just in the results of that particular code. For these people a lot of example programs, for which they can easily see the results, make some small changes and see the result again, would be a wonderful addition. just my 2 cents, cheers, Stef Mientki From showell30 at yahoo.com Sat May 26 16:05:02 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sat, 26 May 2007 13:05:02 -0700 (PDT) Subject: ten small Python programs In-Reply-To: Message-ID: <426738.97194.qm@web33505.mail.mud.yahoo.com> --- Steven Bethard wrote: > Very cool! Do you mind putting this up on the Wiki > somewhere so that we > can link to it more easily? Maybe something like: > > http://wiki.python.org/moin/SimplePrograms > Done. > > Though the code should probably follow PEP 8 > guidelines, e.g. > under_scores instead of camelCase for object and > method names: > > http://www.python.org/dev/peps/pep-0008/ > > I think I fixed them, please see Wiki to verify. > > class ShoppingCart: > > def __init__(self): self.items = [] > > def buy(self, item): > self.items.append(item) > > def boughtItems(self): return self.items > > myCart = ShoppingCart() > > myCart.buy('apple') > > myCart.buy('banana') > > print myCart.boughtItems() > > I think boughtItems() is probably not a good example > of Python code > since in this case, you should probably just write > ``my_cart.items``. > Maybe it should define ``__len__`` instead? Or maybe > something like:: > > def select_items(self, prefix): > return [item for item in self.items if > item.startswith(prefix)] > I think the problem here is that it's hard to write a useful class in less than 10 lines of code. Can somebody else give it a try? Although I didn't call it out in the email, I tried to make each program progressively one line longer, so if somebody wants to write, say, an 11-line class example, then I will try fill in the gap with another 8-liner. Did I miss any basic concepts in the first 10 programs? Maybe an 8-liner could demonstrate command line arguments? ____________________________________________________________________________________Yahoo! oneSearch: Finally, mobile search that gives answers, not web links. http://mobile.yahoo.com/mobileweb/onesearch?refer=1ONXIC From thejaswi.puthraya at gmail.com Thu May 31 01:11:45 2007 From: thejaswi.puthraya at gmail.com (theju) Date: 30 May 2007 22:11:45 -0700 Subject: Usage of the __and__ method Message-ID: <1180588305.004419.127680@d30g2000prg.googlegroups.com> Hello all, I've two objects (both instances of a class called Person) and I want to use the __and__ method and print the combined attributes of the two instances. To be precise, here is my code.... class Person: def __init__(self,name): self.name = name def print_name(self): print self.name def __and__(self,other): self.name = '%s AND %s' %(self.name,other.name) return self.name p = Person("John") q = Person("George") r = p and q print r.print_name() Output: ----------- George None I've also tried this: class Person: def __init__(self,name): self.name = name def print_name(self): print self.name def __and__(self,other): a = Person() a.name = '%s AND %s' %(self.name,other.name) return a p = Person("John") q = Person("George") r = p and q print r.print_name() Output: ----------- George None The above output in both cases is giving me a doubt if __and__ method is over-ridable or not? The output that I am accepting is: John AND George What are the changes if to be made? Thanking You Thejaswi Puthraya http://thejuhyd.blogspot.com From khemkaamit at gmail.com Wed May 23 05:31:11 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Wed, 23 May 2007 15:01:11 +0530 Subject: how to use imaageop.scale In-Reply-To: <1179903754.084688.312200@w5g2000hsg.googlegroups.com> References: <1179903754.084688.312200@w5g2000hsg.googlegroups.com> Message-ID: <1360b7230705230231kf911b54ka94238bdf1efeaf8@mail.gmail.com> On 23 May 2007 00:02:34 -0700, Bruce wrote: > Hi, I want to compress a jpg file. e.g. a jpg file which has RGB band > (24bit per pixel), 100 * 100 size to 50 * 50 size. I > tried to use scale function in imageop module but failed. Any > suggestions about this? Thanks! Were there any exceptions/error-messasges ? Do you jpeg libraries installed for hadling jpeg format ? Cheers, -- ---- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. From kbk at shore.net Sat May 5 23:34:37 2007 From: kbk at shore.net (Kurt B. Kaiser) Date: Sat, 5 May 2007 23:34:37 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200705060334.l463Ybt2011846@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 360 open ( +4) / 3760 closed ( +4) / 4120 total ( +8) Bugs : 971 open ( +3) / 6683 closed (+10) / 7654 total (+13) RFE : 257 open ( +3) / 282 closed ( +0) / 539 total ( +3) New / Reopened Patches ______________________ test_1686475 of test_os & pagefile.sys (2007-04-28) http://python.org/sf/1709112 opened by A.B., Khalid run test_1565150(test_os.py) only on NTFS (2007-04-29) http://python.org/sf/1709599 opened by Hirokazu Yamamoto Update locale.__all__ (2007-04-30) CLOSED http://python.org/sf/1710352 opened by Humberto Di?genes PEP 318 -- add resolution and XRef (2007-05-01) CLOSED http://python.org/sf/1710853 opened by Jim Jewett PEP 3132: extended unpacking (2007-05-02) http://python.org/sf/1711529 opened by Georg Brandl syslog syscall support for SysLogLogger (2007-05-02) http://python.org/sf/1711603 opened by Luke-Jr fix for bug 1712742 (2007-05-04) http://python.org/sf/1713041 opened by Raghuram Devarakonda Fix warnings related to PyLong_FromVoidPtr (2007-05-05) http://python.org/sf/1713234 opened by Hirokazu Yamamoto Patches Closed ______________ Picky floats (2006-04-28) http://python.org/sf/1478364 closed by loewis Update locale.__all__ (2007-05-01) http://python.org/sf/1710352 closed by gbrandl Use MoveFileEx() to implement os.rename() on windows (2007-04-20) http://python.org/sf/1704547 closed by loewis PEP 318 -- add resolution and XRef (2007-05-01) http://python.org/sf/1710853 closed by gbrandl New / Reopened Bugs ___________________ test_1686475 fails when pagefile.sys does not exist (2007-04-28) CLOSED http://python.org/sf/1709282 opened by Calvin Spealman test_1686475 fails because pagefile.sys does not exist (2007-04-28) http://python.org/sf/1709284 opened by Calvin Spealman struct.calcsize() incorrect (2007-04-29) CLOSED http://python.org/sf/1709506 opened by JoelBondurant Tutorial - Section 8.3 - (2007-04-30) CLOSED http://python.org/sf/1710295 opened by elrond79 zipfile.ZipFile behavior inconsistent. (2007-05-01) http://python.org/sf/1710703 opened by Mark Flacy Ctrl+Shift block marking by words (2007-05-01) http://python.org/sf/1710718 opened by zorkin subprocess must escape redirection characters under win32 (2007-05-01) CLOSED http://python.org/sf/1710802 opened by Patrick M?zard CGIHttpServer leaves traces of previous requests in env (2007-05-03) http://python.org/sf/1711605 opened by Steve Cassidy CGIHttpServer fails if python exe has spaces (2007-05-03) http://python.org/sf/1711608 opened by Steve Cassidy SequenceMatcher bug with insert/delete block after "replace" (2007-05-03) http://python.org/sf/1711800 opened by Christian Hammond __getslice__ changes integer arguments (2007-05-03) http://python.org/sf/1712236 opened by Imri Goldberg Cannot use dict with unicode keys as keyword arguments (2007-05-04) http://python.org/sf/1712419 opened by Viktor Ferenczi urllib.quote throws exception on Unicode URL (2007-05-04) http://python.org/sf/1712522 opened by John Nagle pprint handles depth argument incorrectly (2007-05-04) http://python.org/sf/1712742 opened by Dmitrii Tisnek character set in Japanese on Ubuntu distribution (2007-05-04) http://python.org/sf/1713252 opened by Christopher Grell Error inside logging module's documentation (2007-05-05) CLOSED http://python.org/sf/1713535 opened by billiejoex Bugs Closed ___________ TimedRotatingFileHandler's doRollover opens file in "w" mode (2007-04-27) http://python.org/sf/1708538 closed by vsajip test_1686475 fails when pagefile.sys does not exist (2007-04-28) http://python.org/sf/1709282 deleted by ironfroggy struct.calcsize() incorrect (2007-04-29) http://python.org/sf/1709506 closed by loewis Tutorial - Section 8.3 - (2007-04-30) http://python.org/sf/1710295 closed by gbrandl Portability issue: os.rename behaves differently on win32 (2007-04-03) http://python.org/sf/1693753 closed by loewis subprocess must escape redirection characters under win32 (2007-05-01) http://python.org/sf/1710802 closed by astrand Bypassing __dict__ readonlyness (2005-09-24) http://python.org/sf/1303614 closed by arigo subclassing ModuleType and another built-in type (2005-04-01) http://python.org/sf/1174712 closed by arigo Error inside logging module documentation (2007-05-05) http://python.org/sf/1713535 closed by gbrandl New / Reopened RFE __________________ commands module (2007-05-05) http://python.org/sf/1713624 opened by Joseph Armbruster From duncan.booth at invalid.invalid Fri May 11 07:19:48 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 May 2007 11:19:48 GMT Subject: newb: Python Module and Class Scope References: <1178805769.658287.178240@q75g2000hsh.googlegroups.com> Message-ID: Dave Baum wrote: > In article <1178805769.658287.178240 at q75g2000hsh.googlegroups.com>, > johnny wrote: > >> scope of "def main()" interms of class A? >> >> myModule: >> >> class A: >> main() >> >> def main(): >> > > Yes, class A can access main. The name "main" will be defined at the > top level of the module, and is considered a global for that module. No, the name "main" will be defined when the execution of the 'def main()' statement is complete. It is not defined until that point. In the example given the class statement is executed before the def statement is executed so at that point main is still undefined. From nospam at noemailhere.nowhere Thu May 31 01:41:48 2007 From: nospam at noemailhere.nowhere (Anthony Irwin) Date: Thu, 31 May 2007 15:41:48 +1000 Subject: trouble with wxPython intro In-Reply-To: <1180581067.908739.252960@a26g2000pre.googlegroups.com> References: <1180581067.908739.252960@a26g2000pre.googlegroups.com> Message-ID: Daniel Gee wrote: > I'm trying to learn WxPython with the tutorial: > http://wiki.wxpython.org/Getting_Started > > But I can't seem to get the example for events to work. I pasted the > code they had directly into an interpreter and it got a dialog to > appear and the program was able to close itself, but my own copy won't > work. As far as I can see, it isn't at all different except for the > name of the main frame, and so I differ to you for help. --- code snipped ---- > #Menu setup > filemenu = wx.Menu() > filemenu.Append(wx.ID_ABOUT,"&About","Info about the program") Hi, make it the following instead. filemenu.Append(ID_ABOUT,"&About","Info about the program") > filemenu.AppendSeparator() > filemenu.Append(wx.ID_EXIT,"E&xit","Terminate the program.") And again make it the following. filemenu.Append(ID_EXIT,"E&xit","Terminate the program.") --- code snipped ---- -- Kind Regards, Anthony Irwin http://www.irwinresources.com http://www.makehomebusiness.com email: anthony at above domains, - www. From dot at dotat.at Tue May 29 09:27:02 2007 From: dot at dotat.at (Tony Finch) Date: 29 May 2007 14:27:02 +0100 (BST) Subject: vector graphics bindings, was Re: The Concepts and Confusions of Prefix, Infix, Postfix and Fully Functional Notations References: <1179936917.652372.24780@q69g2000hsb.googlegroups.com> <1oveejxwke.fsf@hod.lan.m-e-leypold.de> <465bb872$0$8729$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: <2uc*jQWLr@news.chiark.greenend.org.uk> Jon Harrop wrote: > >Anyway, are there any libraries to do hardware accelerated vector graphics >in Perl, Python, Lisp, Java or any functional language (except OCaml and F# >and excluding WPF and Silverlight)? http://www.cairographics.org/bindings/ That covers all the languages you named, plus O'Caml and Haskell. Tony. -- f.a.n.finch http://dotat.at/ GERMAN BIGHT: NORTH BECOMING CYCLONIC 4 OR 5, THEN WEST 5 OR 6. MODERATE OR ROUGH. RAIN OR DRIZZLE. MODERATE OR GOOD, OCCASIONALLY POOR. From bignose+hates-spam at benfinney.id.au Mon May 28 04:55:26 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 28 May 2007 18:55:26 +1000 Subject: Unsubscribing from the mailing list References: <1180320778.316540.296470@q19g2000prn.googlegroups.com> Message-ID: <87y7j9nx8h.fsf@benfinney.id.au> "marijuanated at gmail.com" writes: > I do not know if this is the correct group to ask this question. But > since mailman is python-based I thought i would ask here. There are a great many Python-based applications; this forum is for discussing the Python language and closely-related topics. Mailman has its own support resources that will better be able to answer your questions: -- \ "...one of the main causes of the fall of the Roman Empire was | `\ that, lacking zero, they had no way to indicate successful | _o__) termination of their C programs." -- Robert Firth | Ben Finney From tinaweb at bestemselv.com Sun May 6 02:24:25 2007 From: tinaweb at bestemselv.com (Tina I) Date: Sun, 06 May 2007 08:24:25 +0200 Subject: Init style output with python? In-Reply-To: References: Message-ID: <1cqdnYjjQ7YH6aDbRVnzvQA@telenor.com> Maxim Veksler wrote: > Is there are frame work or something in python that would allow me to > do this (quickly) ? > If not, ideas how I should I be getting this boring task of: > 1. get screen width You can look into the 'curses' module and do something like: screen = curses.initscreen() maxheight, maxwith = screen.getmaxyx() In my experience curses can be a bit tricky to work with but the online tutorials have some nice examples that help you avoid some of the pitfalls (like messing up your terminal) Tina From bj_666 at gmx.net Mon May 7 16:06:01 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 07 May 2007 22:06:01 +0200 Subject: is for reliable? References: Message-ID: In , pabloski at giochinternet.com wrote: > Hi to all I have a question about the for statement of python. I have the > following piece of code where cachefilesSet is a set that contains the > names of 1398 html files cached on my hard disk > > [snipped code] > > this code stops at the 473th file instead of reaching 1398 > > however I changed the for and substituted it with a while in this way > > while cachefilesSet: > fn = cachefilesSet.pop() > ....... > ....... > > the while loop reaches the 1398th file and is some 3-4 times faster than > the for loop > > How is this possible? Good question. ``for`` loops are of course reliable. Can you give a short self contained example that shows the behavior? Ciao, Marc 'BlackJack' Rintsch From skip at pobox.com Wed May 2 18:05:39 2007 From: skip at pobox.com (skip at pobox.com) Date: Wed, 2 May 2007 17:05:39 -0500 Subject: curses mystical error output Message-ID: <17977.2867.158091.217653@montanaro.dyndns.org> I have a fairly simple curses app which is giving me this error: addstr() returned ERR I'm trapping it and continuing. I can see that *some* of my addstring calls succeed. This one happens to be screen.addstr(row, 39, "|") where row is 3. After the screen was cleared two other calls to addstr succeeded. What's wrong with this one? Can I get a more heplful message out of curses somehow? FWIW, I am running on a Mac from a Terminal.app window which tells me it's an xterm. I am ssh'd into a Solaris host with a command like DISPLAY=:0 ssh -C -Y -X remote-host I tried simplifing the ssh command down to ssh remote-host but I still get the error. I tried setting TERM to "ansi", "vt100" and "dumb". Ansi and vt100 failed with the same error. Curses refused to run on a "dumb" terminal. I tried commenting out the particular line (it's just drawing a boundary between the left and right halves of the window, so I can live without it). A later addstr call fails. Any suggestions? Do I need to followup addstr with some sort of periodic flush() call? Thx, Skip From robert.kern at gmail.com Thu May 24 01:05:02 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 24 May 2007 00:05:02 -0500 Subject: 0 == False but [] != False? In-Reply-To: <1179982400.412340.178710@g4g2000hsf.googlegroups.com> References: <1179982400.412340.178710@g4g2000hsf.googlegroups.com> Message-ID: Rajarshi wrote: > This is a slightly naive question, but I know that 0 can be used to > represent False. So > >>>> 0 == False > True > > But, I know I can use [] to represent False as in > >>>> if not []: print 'empty' > ... > empty > > But then doing the following gives a surprising (to me!) result > >>>> [] == False > False > > Could anybody point out why this is the case? "if foo:" does not check if "foo == True" or "foo == False" but rather "bool(foo)". For empty lists, strings, tuples, dicts and some other things, "bool(foo) == False", while for lists, etc., with at least one element, "bool(foo) == True". -- 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 openopt at ukr.net Mon May 21 09:27:14 2007 From: openopt at ukr.net (dmitrey) Date: 21 May 2007 06:27:14 -0700 Subject: howto get function from module, known by string names? In-Reply-To: <1179753287.816169.311950@x35g2000prf.googlegroups.com> References: <1179228596.349933.168610@l77g2000hsb.googlegroups.com> <1179753287.816169.311950@x35g2000prf.googlegroups.com> Message-ID: <1179754033.865082.217120@z24g2000prd.googlegroups.com> Sorry, some problems with internet connection yield these messages From thorsten at thorstenkampe.de Tue May 15 08:37:53 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 15 May 2007 13:37:53 +0100 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <464996b9$0$10193$9b4e6d93@newsspool4.arcor-online.net> <4649a72d$0$10186$9b4e6d93@newsspool4.arcor-online.net> Message-ID: * Ren? Fleschenberg (Tue, 15 May 2007 14:27:26 +0200) > Thorsten Kampe schrieb: > >> That is a reason to actively encourage people to write their code in > >> English whereever possible, not one to allow non-ASCII identifiers, > >> which might even do the opposite. > > > > There is no reason to encourage or discourage people in which language > > to write their code. > > There is, because code sharing is generally a good thing. If you don't > think it is, then we'll just have to agree to disagree on that point. Just by repeating yourself you don't make your point more valid. Code sharing makes as much sense as book or car sharing. There a lots of projects where sharing code would be just nonsense. This code would be no use to anyone. From gagsl-py2 at yahoo.com.ar Tue May 22 05:04:11 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 22 May 2007 06:04:11 -0300 Subject: [Fwd: Re: managed lists?] References: <4651fe96$0$24671$426a34cc@news.free.fr> <11e49df10705220013q11c35e6axba72cc4227401ac2@mail.gmail.com> Message-ID: En Tue, 22 May 2007 04:13:38 -0300, Jorgen Bodde escribi?: > Thanks. I agree that it is only 'me' that is the one doing it wrong. > But consider this scenario: > > - Somewhere in my app I add a wrong type to an open regular list > - The app continues like it should > - After a (long) while I need to perform some search on the list, or > whatever > - Exception occurs > > It makes it hard to test this way. For example I can do something to > that list and not know about it much later .. If it blows up in my > face, I can fix it, but when that error hinders people who are using > my application, it is much worse. You could use something like this to make a "restricted list": class RestrictedList(list): def __init__(self, items, itemclass_=None): self.itemclass_ = itemclass_ for item in items: self.append(item) def check(self, item): if not isinstance(item, self.itemclass_): raise ValueError("This list can only contain %r instances" % self.itemclass_) def __setitem__(self, index, item): if not isinstance(index,int): raise NotImplementedError self.check(item) list.__setitem__(self, index, item) def __setslice__(self, *args): raise NotImplementedError def append(self, item): self.check(item) list.append(self, item) def insert(self, index, item): self.check(item) list.insert(self, index, item) def extend(self, items): for item in items: self.append(item) I think I'm catching all the ways someone could add a new item to this list. You may change the check() method to test for another type of conditions instead of isinstance; by example, to ensure that all items have a "write" method (and could be used as file-like objects to output data): def check(self, item): try: item.write except AttributeError: raise ValueError("blah blah...") -- Gabriel Genellina From yucetekol at gmail.com Wed May 30 14:11:55 2007 From: yucetekol at gmail.com (yuce) Date: 30 May 2007 11:11:55 -0700 Subject: python -- prolog bridge error In-Reply-To: <1180346661.932837.314560@o5g2000hsb.googlegroups.com> References: <1180224507.324418.52170@q69g2000hsb.googlegroups.com> <1180316448.193656.262300@o5g2000hsb.googlegroups.com> <1180346661.932837.314560@o5g2000hsb.googlegroups.com> Message-ID: <1180548715.545538.285220@q69g2000hsb.googlegroups.com> I've updated install doc for pyswip, you can have a look at: http://code.google.com/p/pyswip/wiki/INSTALL Happy hacking, Yuce From Mattia.Gentilini_REMOVE_ at _REMOVE_CNAF.INFN.IT Fri May 25 10:06:22 2007 From: Mattia.Gentilini_REMOVE_ at _REMOVE_CNAF.INFN.IT (Mattia Gentilini) Date: Fri, 25 May 2007 16:06:22 +0200 Subject: How to do this in python with regular expressions In-Reply-To: References: <1180093895.743196.75510@b40g2000prd.googlegroups.com> Message-ID: Thorsten Kampe ha scritto: >> I'm trying to parsing html with re module. > Just don't. Use an HTML parser like BeautifulSoup Or HTMLParser/htmllib. of course you can mix those and re, it'll be easier than re only. -- |\/|55: Mattia Gentilini e 55 = log2(che_palle_sta_storia) (by mezzo) |/_| ETICS project at CNAF, INFN, Bologna, Italy |\/| www.getfirefox.com www.getthunderbird.com * Using Mac OS X 10.4.9 powered by Cerebros (Core 2 Duo) * From sbassi at clubdelarazon.org Sun May 27 17:17:33 2007 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Sun, 27 May 2007 18:17:33 -0300 Subject: expat parser Message-ID: <9e2f512b0705271417n6fcc5324g6887f780788c0123@mail.gmail.com> I have this code: import xml.parsers.expat def start_element(name, attrs): print 'Start element:', name, attrs def end_element(name): print 'End element:', name def char_data(data): print 'Character data:', repr(data) p = xml.parsers.expat.ParserCreate() p.StartElementHandler = start_element p.EndElementHandler = end_element p.CharacterDataHandler = char_data fh=open("/home/sbassi/bioinfo/smallUniprot.xml","r") p.ParseFile(fh) And I get this on the output: ... Start element: sequence {u'checksum': u'E0C0CC2E1F189B8A', u'length': u'393'} Character data: u'\n' Character data: u'MPKKKPTPIQLNPAPDGSAVNGTSSAETNLEALQKKLEELELDEQQRKRL' Character data: u'\n' Character data: u'EAFLTQKQKVGELKDDDFEKISELGAGNGGVVFKVSHKPSGLVMARKLIH' ... End element: sequence ... Is there a way to have the character data together in one string? I guess it should not be difficult, but I can't do it. Each time the parse reads a line, return a line, and I want to have it in one variable. (the file is here: http://sbassi.googlepages.com/smallUniprot.xml) From john at datavoiceint.com Mon May 14 10:25:12 2007 From: john at datavoiceint.com (HMS Surprise) Date: 14 May 2007 07:25:12 -0700 Subject: Time In-Reply-To: <1179151780.870236.208590@p77g2000hsh.googlegroups.com> References: <1178916216.893542.257320@y80g2000hsf.googlegroups.com> <1178916422.065108.312920@l77g2000hsb.googlegroups.com> <1178920014.621031.301860@n59g2000hsh.googlegroups.com> <1178927105.482975.174760@y5g2000hsa.googlegroups.com> <1179151205.987222.54910@k79g2000hse.googlegroups.com> <1179151780.870236.208590@p77g2000hsh.googlegroups.com> Message-ID: <1179152712.409588.110580@e65g2000hsc.googlegroups.com> On May 14, 9:09 am, kyoso... at gmail.com wrote: > On May 14, 9:00 am, HMS Surprise wrote: > > > > > Thanks for posting. I sure am sorry that I wasted your time. I should > > have started the post stating I am using jython 2.2.3 and apparently > > it has no datetime module. But I will keep datetime in mind for future > > reference. > > > Since I had no datetime I cobbled out the following. Seems to work > > thus far. Posted here for the general amusement of the list. > > > Regards, > > > jvh > > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > > from time import * > > s = '05/11/2007 1:23 PM' > > t = s.split() > > mdy = t[0].split('/') > > > hrMn = t[1].split(':') > > if t[2] == 'PM': > > hrMn[0] = int(hrMn[0]) + 12 > > > tuple =(int(mdy[2]), int(mdy[0]), int(mdy[1]), hrMn[0], int(hrMn[1]), > > 0,0,0,0) > > print tuple > > > eTime = mktime(tuple) > > print 'eTime', eTime > > Since jython works with Java, why not use Java's time/datetime > modules? Various links abound. Here are a few: > > http://www.raditha.com/blog/archives/000552.htmlhttp://www.xmission.com/~goodhill/dates/deltaDates.htmlhttp://www.velocityreviews.com/forums/t149657-find-difference-in-date... > > Maybe those will give you some hints. > > Mike Excellent idea. Thanks Mike. jvh From jstroud at mbi.ucla.edu Mon May 7 17:13:03 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 07 May 2007 14:13:03 -0700 Subject: assisging multiple values to a element in dictionary In-Reply-To: <1178535831.870912.44220@p77g2000hsh.googlegroups.com> References: <1178535831.870912.44220@p77g2000hsh.googlegroups.com> Message-ID: saif.shakeel at gmail.com wrote: > Like i want the > key 170 to take either the name 'dataPackageID' or the name > 'LocalId'.I use this in my code,and hence if either comes it should > work . It should work to do what exactly? Cause a perturbation in the orbit of Mars, or something else entirely? James From horpner at yahoo.com Thu May 10 18:12:33 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 10 May 2007 22:12:33 GMT Subject: searching algorithm References: <7dydnfjNWbo9H97bnZ2dnUVZ_oupnZ2d@comcast.com> Message-ID: On 2007-05-10, Gordon Airporte wrote: > >> For the above (abrideged) dictionary, you would generate (use a >> fixed-width "programmers" font so the tree looks good): >> >> a >> | >> b >> | >> s >> / \ >> i o >> / / \ >> n l r >> / / \ \ >> t u v b->(absorbirati, crpisti) >> / | | >> (pelin)<-h t e->(odrije?iti, osloboditi) >> | | >> (pelin)<-e e->(apsolutan, apsolutni kod) >> >> As the user enter letters, you just march down the tree, printing >> all the words held in leaf nodes held in the current node. > > Call me dense, but how does one do this in Python - which > doesn't have pointers? Dictionaries with dictionaries within > dictionaries... (with each letter as the key and the its > children as values) is going to be extremely space inefficient, > right? Unfortunately, I don't know the space tradeoffs in Python offhand. Lists and tuples make excellent trees. The above might be stored as follows: Every node is a tuple of its letter, a list of its children, and a list of its words. So the two 'pelin' nodes would be (with 'e' referenced in the 'h' node): ('h', [('e', [], ['pelin'])], ['pelin']) That would in turn be "stored" in the t, n, i and s nodes. ('s', [('i', [('n', [('t', [('h', [('e', [], ['pelin'])], ['pelin']) [])] [])] []), ('o' trie (thanks Terry) omitted for my sanity)]) It's a lot harder to write by hand than it would be to use. My intuition says it shouldn't be terribly hard on resources for for a 180K dictionary, but I could be wrong. I'm too lazy to measure. ;) If it does turn out to be unreasonably huge, then you'd fall back on solving the problem completely with a binary search returning a range (I'm not sure of the name), which would be more expensive at run time, but might be fast enough, and would use a minimal amount of 'resources'. -- Neil Cerutti From ronpro at cox.net Mon May 28 23:46:00 2007 From: ronpro at cox.net (Ron Provost) Date: Mon, 28 May 2007 23:46:00 -0400 Subject: Circular imports Message-ID: <003801c7a1a3$e048d840$6701a8c0@aristotle> Hello, I'm in the process of porting a project from Java to python. The original project is very poorly organized. Nearly each class is depentant upon nearly every other class. Before I go playing around with the logic by moving things around and cleaning up the code, I want to get it working. However, because of all these dependancies, python is not happy about my circular imports. Is there any way to force python to accept these imports for now? the only solution I've come up with myself would be to combine all the files into one. This isn't really possible anyway because three of the files are actually automatically generated. Thanks, Ron -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyosohma at gmail.com Tue May 22 09:24:54 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 22 May 2007 06:24:54 -0700 Subject: NOOOOB In-Reply-To: <1179836760.070095.5880@y2g2000prf.googlegroups.com> References: <1179829763.464614.123920@a26g2000pre.googlegroups.com> <1179836760.070095.5880@y2g2000prf.googlegroups.com> Message-ID: <1179840294.478966.181110@36g2000prm.googlegroups.com> On May 22, 7:26 am, Giles Brown wrote: > On 22 May, 11:29, jolly wrote: > > > Hey guys, > > > I want to begin python. Does anyone know where a good starting point > > is? > > > Thanks, > > Jem > > My suggestion is have a look atwww.python.organd see if you can find > what you're looking for. > > Giles If you need reference books that delve deep into the language while being somewhat understandable, I would recommend "Programming Python" by Lutz or "Core Python Programming" by Chun. "Beginning Python" by Hetland covers just about everything you'd need to know and it includes some fairly complex examples in the back...plus it's about half the size of the other two books. Other than that, I'd with the other guys on this. The web has lots of good examples, puzzles and for most of the standard library, decent docs, although not always with good or thorough examples. Enjoy! Mike From noagbodjivictor at gmail.com Thu May 3 20:24:11 2007 From: noagbodjivictor at gmail.com (noagbodjivictor at gmail.com) Date: 3 May 2007 17:24:11 -0700 Subject: How do I output a list like the interpreter do? In-Reply-To: <1178236866.035271.81460@c35g2000hsg.googlegroups.com> References: <1178236804.658955.204140@h2g2000hsg.googlegroups.com> <1178236866.035271.81460@c35g2000hsg.googlegroups.com> Message-ID: <1178238251.343819.252370@h2g2000hsg.googlegroups.com> On May 3, 8:01 pm, noagbodjivic... at gmail.com wrote: > On May 3, 8:00 pm, noagbodjivic... at gmail.com wrote: > > > >>> s = ['a','b'] > > >>> s > > ['a', 'b'] > > > This is what I want so that I can put it in a module then import that > > module to work with my variable. > > Sorry for that typo in the title... I found a was using str(list). Do you know how to get rid of the surrounding quotes? From lanwrangler at gmail.com Wed May 2 05:48:15 2007 From: lanwrangler at gmail.com (lanwrangler at gmail.com) Date: 2 May 2007 02:48:15 -0700 Subject: Comparing bitmap images for differences? In-Reply-To: References: <1178024505.768505.262270@h2g2000hsg.googlegroups.com> Message-ID: <1178099295.314365.229660@p77g2000hsh.googlegroups.com> On May 1, 7:15 pm, "3c273" wrote: > This might get you started.http://tinyurl.com/7qexl Wow, I thought briefly along those lines but then thought "No, it can't possibly be that easy" :-) It looks like the approach given in that link could benefit hugely from using numpy to treat the bitmaps as arrays to speed up processing but that should be pretty straightforward. I'll give it a try as-is and then look at optimisation if required. Saying that, and thinking about the itch I'm trying to scratch here, I think I could also safely ignore the borders of the image so that would reduce the processing requirements anyway. Add in a FIFO file buffer so I can do pre/post-event image capture plus a spot of SMTP mail alerting and the job's done! Thanks again. Matthew. From steve at holdenweb.com Fri May 4 22:32:40 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 04 May 2007 22:32:40 -0400 Subject: Counting In-Reply-To: References: <1177873864.502180.283390@u30g2000hsc.googlegroups.com> Message-ID: James Stroud wrote: > James Stroud wrote: >> James Stroud wrote: [finally ...] > > I should really wait until I've had some coffee. Not continue, but break! > > > for i,line in enumerate(linelist): > line = line.split() > for k in line: > if keyword.iskeyword(k): > total += line.count(k) > print "The word '%s' belongs in line num: %d" % (k, i+1) > break > > print "Total keyords are: %d" % total James is actually trying to convince you of the merits of test-driven development by cleverly showing you the disadvantages of not using it. Clever approach to advocacy, James. Did you get your coffee yet? 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From aleax at mac.com Sun May 6 22:05:19 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 6 May 2007 19:05:19 -0700 Subject: My newbie annoyances so far References: <1177688082.758043.133920@r30g2000prh.googlegroups.com> <_9pYh.1787$uJ6.894@newssvr17.news.prodigy.net> <1178400807.051103.95690@q75g2000hsh.googlegroups.com> <1hxp15f.1bvtgo11ydx3cvN%aleax@mac.com> Message-ID: <1hxpfyw.oaolu9kesvabN%aleax@mac.com> John Nagle wrote: ... > >>>>The CPython implementation is unreasonably slow compared > >>>>to good implementations of other dynamic languages such > >>>>as LISP and JavaScript. ... > >>Tamarin is a just-in-time compiler for Javascript. > > > > ...and is not yet released, as far as I can tell; this makes it kind of > > diffcult to verify any kinds of claims about its speed. > > Tamarind is inside the current implementation of Flash, but it's > not into Firefox yet, apparently. The current SpiderMonkey implementation > is nothing to get excited about in terms of performance. If CPython is *unreasonably slow*, and SpiderMonkey is somewhere between 5 times slower (when CPython is totally handicapped to only using primitives that are also made avaiable by SpiderMonkey) and 15 times slower (as soon as CPython can use slightly better primitives, without any special striving for optimization), then it should logically follow that the current performance of SpiderMonkey is WELL worth (negative) "excitement" on your part -- what's 15 times worse than "unreasonably slow"?! Can you run a generic benchmark "inside the current implementation of Flash" to check out its Javascript performance? I can't, so, not having any way to verify any claims regarding its performance, I'm going to consider those claims not proven until further notice (verification by somebody I know and trust personally). > My point is that there are optimizing hard-code compiler > implementations of many dynamic languages, including LISP, Self, and > Smalltalk, but not Python. If you had not mentioned Javascript specifically, I would not have entered this thread, and indeed I consider your assertion which you now (carefully avoiding mention of Javascript:-) claim is "your point", a somewhat boring and trite restatement of well-known fact -- it's obviously _possible_ to build excellent "compilers to machine code" for dynamic languages, with sufficient effort fueled by either commercial or academic pursuits, as has been repeatedly proven for Scheme, Lisp, Smalltalk, etc, etc; and it does indeed seem that no academic or commercial entity has as yet released such a compiler for Python (though the pypy project may move in such a direction in the future, it does not appear to be part of what they have released as part of their 1.0 milestone). But I consider your specific claim about Javascript to be currently unfounded -- maybe a year from now they'll indeed release to the public a version that runs, say, 30 times faster than today's (it would have to be at least twice as fast as CPython to justify your "unreasonably slow" claim, right?)... but, even if you trust them blindly to do so, how do you know in advance what the performance of the implementation of Python with the ability to generate the fastest machine code will be a year from now?! Alex From hniksic at xemacs.org Fri May 25 10:04:36 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 25 May 2007 16:04:36 +0200 Subject: Reading a file and resuming reading. References: Message-ID: <87hcq1rocr.fsf@busola.homelinux.net> "Karim Ali" writes: > ----------------------------- > while not eof <- really want the EOF and not just an empty line! > readline by line > end while; > ----------------------------- for line in open_file: ... It will stop on EOF, not on empty line. > But also, in case for one reason or another the program crashes, I > want to be able to rexecute it and for it to resume reading from the > same position as it left. If a while loop like the one above can be > implemented I can do this simply by counting the lines! If you open the file in binary mode, you can easily keep track of the position in file: bytepos = 0 with file(filename) as f: for line in f: ... process line ... bytepos += len(line) If you need to restart the operation, simply seek to the previously known position: # restart with old bytyepos with file(filename) as f: f.seek(bytepos) for line in f: ... process line ... bytepos += len(line) From carsten at uniqsys.com Wed May 2 09:08:36 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 02 May 2007 09:08:36 -0400 Subject: Why are functions atomic? In-Reply-To: <1178083318.404304.76100@q75g2000hsh.googlegroups.com> References: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> <1178044821.864741.235260@o5g2000hsb.googlegroups.com> <1178063341.779617.289690@o5g2000hsb.googlegroups.com> <1178065685.161372.81790@y80g2000hsf.googlegroups.com> <1178083318.404304.76100@q75g2000hsh.googlegroups.com> Message-ID: <1178111316.3394.21.camel@dot.uniqsys.com> On Tue, 2007-05-01 at 22:21 -0700, Michael wrote: > Is there a reason for using the closure here? Using function defaults > seems to give better performance:[...] It does? Not as far as I can measure it to any significant degree on my computer. > This is definitely one viable solution and is essentially what I had > in mind, but I did not want to have to carry the generator arround > with me: I don't know what you mean by "carry it around." Just put it in a module and import it where you need it. An overriding theme in this thread is that you are greatly concerned with the speed of your solution rather than the structure and readability of your code. How often is your function going to get called and how much of a performance benefit are you expecting? -Carsten From steve at holdenweb.com Fri May 25 14:29:24 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 25 May 2007 14:29:24 -0400 Subject: Proxying every function in a module In-Reply-To: <4657244E.5000006@laculine.com> References: <4657244E.5000006@laculine.com> Message-ID: Josh West wrote: >> First off, don't attempt to start a new thread by replying to a previous >> one. Many newsreaders will merge the two, confusing the hell out of >> everyone and generally not helping. >> > > Ahh, yes. I see what you mean. Explains why it didn't appear the first > time I posted (until later..). > > Sorry for bother and thanks for the advice. >> Second, what makes you think you need a module? I'd have thought an >> instance of some user-defined class would have been better, as that way >> you can redefine the __getattr__() method to return appropriate functions. >> > The functions are ported from a java class static methods. I was trying > to be "pythonic" - since my 100 functions don't share state, I thought > they should be packaged as a module rather than as a class of bunch of > effectively static methods. >> This seems to work, though I haven't tested it extensively (i.e. I have >> called one instance precisely once ;-) >> >> >>> import re >> >>> pat = re.compile("([a-z]+)(.+)") >> >>> class myRewriter: >> ... def srt(self, s): >> ... m = pat.match(s) >> ... if not m: raise ValueError(s) >> ... return m.group(1), m.group(2).lower() >> ... def __getattr__(self, name): >> ... n1, n2 = name.split("_") >> ... def f(val): >> ... s1, s2 = self.srt(val) >> ... return "/%s/%s/?sort=%s_%s" % \ >> ... (n1, n2, s1, s2) >> ... return f >> ... >> >>> r = myRewriter() >> >>> r.organisations_list('dateCreated') >> '/organisations/list/?sort=date_created' >> >>> >> >> regards >> Steve >> > Genius! Embarrassingly, I hadn't realised that __getattr__() is called > when a method is invoked, thus making the method name (attribute name) > so easily available as a string. I was therefore thinking in terms of > gnarly introspection/reflection things. This is much better. > > Thanks very much > > A pleasure. Welcome to Python, where genius is available to us 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From ivoras at __fer.hr__ Sun May 13 07:30:37 2007 From: ivoras at __fer.hr__ (Ivan Voras) Date: Sun, 13 May 2007 13:30:37 +0200 Subject: __dict__ for instances? In-Reply-To: <1179029071.282774.116050@h2g2000hsg.googlegroups.com> References: <1179029071.282774.116050@h2g2000hsg.googlegroups.com> Message-ID: half.italian at gmail.com wrote: > I think you want "dir(instance)" __dict__ returns the instance Part of the problem is that dir(instance) returns a list of strings, so iterating the dir(instance) gets me strings, not methods. Alternatively, is there a way to get a "bound" instance by its name - some introspection function perhaps? > variables and values as a dictionary, but doesn't return methods. It does on a Class :( -- (\__/) (O.o) (> < ) This is Bunny. Copy Bunny into your signature to help him on his way to world domination! -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 258 bytes Desc: OpenPGP digital signature URL: From jackson at hotmail.com Fri May 25 16:55:18 2007 From: jackson at hotmail.com (Bill Jackson) Date: Fri, 25 May 2007 13:55:18 -0700 Subject: matplotlib, usetex Message-ID: Hi, I'm having some trouble plotting with the following matplotlibrc: text.usetex : True I tried clearing the cache files under ~/.matplotlib, but this did not help the problem. I'd post on the matplotlib mailing list, but I have a hard enough time browsing sourceforge's achives (frequent internal server errors). Here is some output: ---- example.py ---- import pylab pylab.plot(range(10)) pylab.show() -------------------- # python example.py --verbose-helpful matplotlib data path /usr/share/matplotlib/mpl-data $HOME=/home/me loaded rc file /home/me/matplotlibrc matplotlib version 0.87.7 verbose.level helpful interactive is False platform is linux2 numerix Numeric 24.2 font search path ['/usr/share/matplotlib/mpl-data'] CONFIGDIR=/home/me/.matplotlib loaded ttfcache file /home/me/.matplotlib/ttffont.cache backend GTK version 2.10.4 Traceback (most recent call last): File "example.py", line 2, in pylab.plot(range(10)) File "/usr/lib/python2.5/site-packages/matplotlib/pylab.py", line 2027, in plot ret = gca().plot(*args, **kwargs) File "/usr/lib/python2.5/site-packages/matplotlib/axes.py", line 2131, in plot self.autoscale_view(scalex=scalex, scaley=scaley) File "/usr/lib/python2.5/site-packages/matplotlib/axes.py", line 985, in autoscale_view self.set_xlim(XL) File "/usr/lib/python2.5/site-packages/matplotlib/axes.py", line 1227, in set_xlim self.viewLim.intervalx().set_bounds(xmin, xmax) TypeError: only length-1 arrays can be converted to Python scalars. The problem does not exist when text.usetex is False. Ideas? From bj_666 at gmx.net Thu May 3 10:29:01 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 03 May 2007 16:29:01 +0200 Subject: newbie: copy base class fields References: <1178201644.920048.205400@y5g2000hsa.googlegroups.com> Message-ID: In <1178201644.920048.205400 at y5g2000hsa.googlegroups.com>, tmp123 wrote: > The following small program gives an error: > > #!/usr/bin/python > # > > class A: > def __init__(self): > self.v1=1 > > def __repr__(self): > return "v1=%d\n" % self.v1 > > class B(A): > def __init__(self,a): > self=a > self.v2=2 > > def __repr__(self): > return A.__repr__(self) + ("v2=%d\n" % self.v2) > > x=A() > print x > > y=B(x) > print y > > > > $ ./prueba.pl > v1=1 > > Traceback (most recent call last): > File "./prueba.pl", line 23, in > print y > File "./prueba.pl", line 17, in __repr__ > return A.__repr__(self) + ("v2=%d\n" % self.v2) > File "./prueba.pl", line 9, in __repr__ > return "v1=%d\n" % self.v1 > AttributeError: B instance has no attribute 'v1' > > > It seems that the statement "self=a" is not the correct way to copy > all the fields of the base class from the __init__ argument to the new > object. This binds the local name `self` to the same object that is bound to `a`. Now you have lost the reference to the instance, so the next line sets the attribute `v2` on the object passed to the constructor of the `B` object. > Of course, it is not an option to copy one by one all the fields of > class A inside the __init__ of B. > > Several variants of the program produces similar results. > > Please, could someone explain which way is the correct way? Call the `__init__()` of `A`: class B(A): def __init__(self, a): A.__init__(self) self.v2 = 2 Ciao, Marc 'BlackJack' Rintsch From grante at visi.com Sun May 13 10:52:24 2007 From: grante at visi.com (Grant Edwards) Date: Sun, 13 May 2007 14:52:24 -0000 Subject: Setting thread priorities References: <2sy1i.2542$LR5.1451@newssvr17.news.prodigy.net> <1179048645.972142.92140@e51g2000hsg.googlegroups.com> Message-ID: <134e9h89c442t92@corp.supernews.com> On 2007-05-13, Gerald Kaszuba wrote: > Hi John > > On May 13, 4:46 pm, John Nagle wrote: >> There's no way to set thread priorities within Python, is there? > > Not exactly. You can however use the ctypes module to access the o/s > methods of pthread_setschedparam() for UNIX and SetThreadPriority() > for Windows. > > I'm not sure why this hasn't been implemented in Python. AFAICT, Python's threading paradigm seems to be based on the assumption that alls threads spend most of their time blocking on I/O or some other event. In that case priorities don't matter. Priorities only matter if multiple threads are ready to run. -- Grant Edwards grante at visi.com From larry.bates at websafe.com Wed May 30 17:05:24 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 30 May 2007 16:05:24 -0500 Subject: replace the base class In-Reply-To: <1180557641.633245.189900@p77g2000hsh.googlegroups.com> References: <1180557641.633245.189900@p77g2000hsh.googlegroups.com> Message-ID: aspineux wrote: > Hi > > I would like a kind of function able to replace the base class like > that: > > class Graph: > pass > > class Circle(Graph): > pass > > class Square(Graph): > pass > > class ColorGraph: > pass > > def Adopt(new_base_class, child_class, old_base_class): > .... > return newclass > > ColorCircle=Adopt(ColorGraph, Circle, Graph) > ColorSquare=Adopt(ColorGraph, Square, Graph) > > > I have a lot of classes (Circle, Square, ...) that inherit all from > base class Graph > I have a more powerful class ColorGraph that do the same as Graph and > more. > I want to have new classes ColorCircle, ColorSquare that share exactly > the same code has > Circle or Square but inherit from base class ColorGraph to take > benefit the new features ? > > How can I do that ? > > I can get what I want by duplicating the source of all my child > classes, > and replace any occurrence of Graph by ColorGraph. > But when the code of Circle or Square is changed, I don't want to redo > the job. > I could also have a lot of new base class : 3DGraph, ...... > > Thanks > > Alain > I believe what you are looking for is the 'as' clause on import from module import Graph as Graph class Circle(Graph): pass Circle will have Graph as its baseclass from module import ColorGraph as Graph class Circle(Graph): pass Circle will have ColorGraph as its baseclass -Larry From arkanes at gmail.com Wed May 16 18:39:08 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 16 May 2007 17:39:08 -0500 Subject: cPickle.dumps differs from Pickle.dumps; looks like a bug. In-Reply-To: <5f56302b0705161524u5902320cy11e0f67a798e8089@mail.gmail.com> References: <1179335622.006820.22460@q23g2000hsg.googlegroups.com> <1179352356.025319.43310@w5g2000hsg.googlegroups.com> <5f56302b0705161524u5902320cy11e0f67a798e8089@mail.gmail.com> Message-ID: <4866bea60705161539q19378836j108750b3e287132e@mail.gmail.com> On 5/16/07, Daniel Nogradi wrote: > > > I've found the following strange behavior of cPickle. Do you think > > > it's a bug, or is it by design? > > > > > > Best regards, > > > Victor. > > > > > > from pickle import dumps > > > from cPickle import dumps as cdumps > > > > > > print dumps('1001799')==dumps(str(1001799)) > > > print cdumps('1001799')==cdumps(str(1001799)) > > > > > > outputs > > > > > > True > > > False > > > > > > vicbook:~ victor$ 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.>>> > > quit() > > > > > > vicbook:~ victor$ uname -a > > > Darwin vicbook 8.9.1 Darwin Kernel Version 8.9.1: Thu Feb 22 20:55:00 > > > PST 2007; root:xnu-792.18.15~1/RELEASE_I386 i386 i386 > > > > If you unpickle though will the results be the same? I suspect they > > will be. That should matter most of all (unless you plan to compare > > objects' identity based on their pickled version.) > > The OP was not comparing identity but equality. So it looks like a > real bug, I think the following should be True for any function f: > > if a == b: f(a) == f(b) > > or not? > Obviously not, in the general case. random.random(x) is the most obvious example, but there's any number functions which don't return the same value for equal inputs. Take file() or open() - since you get a new file object with new state, it obviously will not be equal even if it's the same file path. For certain inputs, cPickle doesn't print the memo information that is used to support recursive and shared data structures. I'm not sure how it tells the difference, perhaps it has something to do with refcounts. In any case, it's an optimization of the pickle output, not a bug. From bj_666 at gmx.net Wed May 9 03:56:18 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 09 May 2007 09:56:18 +0200 Subject: Minor bug in tempfile module (possibly __doc__ error) References: <1178693438.689184@smirk> Message-ID: In <1178693438.689184 at smirk>, James T. Dennis wrote: > Tonight I discovered something odd in the __doc__ for tempfile > as shipped with Python 2.4.4 and 2.5: it says: > > This module also provides some data items to the user: > > TMP_MAX - maximum number of names that will be tried before > giving up. > template - the default prefix for all temporary names. > You may change this to control the default prefix. > > ... which would lead one to think that the following code would work: > > >>> import tempfile > >>> tempfile.template = 'mytest' > >>> tf = tempfile.NamedTemporaryFile() > >>> tf.name > '/tmp/mytest-XXXXXX' > > It doesn't. The source says: __all__ = [ "NamedTemporaryFile", "TemporaryFile", # high level safe interfaces "mkstemp", "mkdtemp", # low level safe interfaces "mktemp", # deprecated unsafe interface "TMP_MAX", "gettempprefix", # constants "tempdir", "gettempdir" ] Maybe the doc should be clearer in saying "constants" too. > Secondly, the author(s) of the tempfile module apparently didn't > understand this either. And no one else even noticed that the __doc__ > is wrong (or at least misleading -- since the only way I can see to > change tempfile.template is to edit the .py file! You can change it by simply assigning to the name: In [15]: tempfile.template = 'spam' In [16]: tempfile.template Out[16]: 'spam' If you want to change the outcome of the functions and objects then simply give the prefix as argument. In [21]: tempfile.mktemp(prefix='eggs') Out[21]: '/tmp/eggsBqiqZD' In [22]: a = tempfile.NamedTemporaryFile(prefix='eric') In [23]: a.name Out[23]: '/tmp/ericHcns14' > ... why can't I change that value in that other namespace? Is it > a closure? (Or like a closure?) Where is this particular aspect > of the import/namespace semantics documented? You *can* change it, but it is not used by the code in that module. Ciao, Marc 'BlackJack' Rintsch From tkpmep at hotmail.com Wed May 9 18:05:32 2007 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: 9 May 2007 15:05:32 -0700 Subject: Behavior of mutable class variables In-Reply-To: <1178745918.395377.282470@u30g2000hsc.googlegroups.com> References: <1178744257.369030.95310@w5g2000hsg.googlegroups.com> <1178745918.395377.282470@u30g2000hsc.googlegroups.com> Message-ID: <1178748332.766271.86950@e51g2000hsg.googlegroups.com> On May 9, 5:25 pm, tkp... at hotmail.com wrote: > To test some theories, I created a new class variable, an int named Diez, Thanks. It is for precisely this reason that I added another class variable - the immutable int N1. But this too keeps getting incremented on subsequent calls to simulation( ). I also tried setting the class variable N1 to 0 at the end of the simulation and also deleting all the stocks in port (see below). Nothing works - and I don't understand why. def simulation(N, par1, par2, idList, returnHistoryDir): port = [] for i in range(N): port.append( Stock(idList[i], returnHistoryDir[idList[i]] ) p[0].NStocks = 0 del port[:] results = ...... print results. From mail at timgolden.me.uk Thu May 10 10:02:20 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 10 May 2007 15:02:20 +0100 Subject: Towards faster Python implementations - theory In-Reply-To: <1178804728.527486.196400@y80g2000hsf.googlegroups.com> References: <1210i.7468$2v1.2505@newssvr14.news.prodigy.net> <1178804728.527486.196400@y80g2000hsf.googlegroups.com> Message-ID: <464325EC.5080802@timgolden.me.uk> sturlamolden wrote: > On May 8, 5:53 pm, John Nagle wrote: > >> The point here is that we don't need language changes or declarations >> to make Python much faster. All we need are a few restrictions that >> insure that, when you're doing something unusual, the compiler can >> tell. > > Franz, CMUCL, SBCL and GCL teams made Lisp almost as fast as C. A > dynamic language can be fast if the implementation is good. > > If you look at SBCL and GCL, no code is interpreted. It's all compiled > on the fly to native machine code. The compiler begins with some code > and some input data, and compiles as much as it can. Then the RT > executes the machine code, compiles again, etc. Often long stretches > of code can be compiled without break, and tight performance critical > loops are usually compiled only once. In addition to this, one needs > an efficient system to cache compiled code, in order to do the > compilation work only once. making a dynamic language fast is not > rocket science. > > We should have somthing like "GPython", a Python RT on top of a GCC > backend, similar to what the GCL team did for Lisp. There is no > obvious reason as to why Lisp should have better performance than > Python. I doubt if anyone disputes the gist of what you're saying[*], viz that Python could be made faster by using technique (a), (b) or (c) which have been successful elsewhere. At least that it's worth investgating. But the relevant bit of your last paragraph is at the start: "We should...". Unless someone or someones has the time, inclination, money, backing, wherewithal etc. to implement this or any other measure of speeding-up, it's all pie-in-the-sky. Useful, maybe, as discussion of what options are viable, but a project of this magnitude doesn't just happen in some developer's lunchbreak. Many people (and I include myself) are quite happy with Python's speed. In fact, I'm quite happy with most things about Python. Others would like to see it faster. That's great. But unless people puts their money where their mouths are, I don't see it happening. TJG [*] Actually, knowing this community, I'm sure *someone's* going to! From chris.cavalaria at free.fr Sun May 20 06:04:33 2007 From: chris.cavalaria at free.fr (Christophe Cavalaria) Date: Sun, 20 May 2007 12:04:33 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <464C5382.6080403@v.loewis.de> <1179423799.254286.294930@w5g2000hsg.googlegroups.com> <1179503525.018943.95740@u30g2000hsc.googlegroups.com> <_pq3i.1390$wH4.1177@news-server.bigpond.net.au> <464EA85E.1040508@v.loewis.de> <1179631058.310012.123480@e65g2000hsc.googlegroups.com> Message-ID: <46501d31$0$31477$426a34cc@news.free.fr> Istvan Albert wrote: > On May 19, 3:33 am, "Martin v. L?wis" wrote: > >> > That would be invalid syntax since the third line is an assignment >> > with target identifiers separated only by spaces. >> >> Plus, the identifier starts with a number (even though ? is not DIGIT >> SIX, but FULLWIDTH DIGIT SIX, it's still of category Nd, and can't >> start an identifier). > > Actually both of these issues point to the real problem with this PEP. > > I knew about them (note that the colon is also missing) alas I > couldn't fix them. > My editor would could not remove a space or add a colon anymore, it > would immediately change the rest of the characters to something > crazy. > > (Of course now someone might feel compelled to state that this is an > editor problem but I digress, the reality is that features need to > adapt to reality, moreso had I used a different editor I'd be still > unable to write these characters). The reality is that the few users who care about having chinese in their code *will* be using an editor that supports them. From arnodel at googlemail.com Fri May 4 12:17:32 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 4 May 2007 09:17:32 -0700 Subject: How safe is a set of floats? In-Reply-To: <1178288509.067493.5140@e65g2000hsc.googlegroups.com> References: <1178288509.067493.5140@e65g2000hsc.googlegroups.com> Message-ID: <1178295452.016967.158250@n59g2000hsh.googlegroups.com> On May 4, 3:21 pm, Thomas Nelson wrote: > I want to generate all the fractions between 1 and limit (with > limit>1) in an orderly fashion, without duplicates. > > def all_ratios(limit): > s = set() > hi = 1.0 > lo = 1.0 > while True: > if hi/lo not in s: > s.add(hi/lo) > yield (hi,lo) > hi += 1 > if hi/lo > limit: > lo += 1 > hi = lo > > I use a set to keep from giving duplicates; but is this safe? In C > they always tell you not to trust floating point equality comparisons, > since they may not work as you expect. My code seems fine for the > limited amount I've tested, but I'm curious: is there a gaurantee > about sets of floats? Or a warning? There won't be either, but you actually don't need to store the previous fractions. All you need to verify is that the denominator and numerator are relatively prime (i.e. their gcd is 1). That could be implemented as: ------------------------------------ from itertools import count def gcd(x, y): while x: x, y = y % x, x return y def all_ratios(limit): for d in count(1): for n in xrange(d, int(limit*d) + 1): if gcd(d, n) == 1: yield n, d ------------------------------------ HTH -- Arnaud From rene at korteklippe.de Wed May 16 06:36:26 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Wed, 16 May 2007 12:36:26 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464ad388$0$28786$426a34cc@news.free.fr> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179289167.723990.223890@u30g2000hsc.googlegroups.com> <464abd12$0$23364$426a34cc@news.free.fr> <1179307776.953405.207680@l77g2000hsb.googlegroups.com> <464ad388$0$28786$426a34cc@news.free.fr> Message-ID: <464adea8$0$23132$9b4e6d93@newsspool1.arcor-online.net> Christophe schrieb: > Who displays stack frames? Your code. Wrong. > Whose code includes unicode > identifiers? Your code. Wrong. > Whose fault is it to create a stack trace > display procedure that cannot handle unicode? You. Wrong. If you never have to deal with other people's code, congratulations to you. Many other people have to. And no, I can usualy not just tell the person to fix his code. I need to deal with it. > Even if you don't > make use of them, you still have to fix the stack trace display > procedure because the exception error message can include unicode text > *today* The error message can, but at least the function names and other identifiers can not. > You should know that displaying and editing UTF-8 text as if it was > latin-1 works very very well.s No, this only works for those characters that are in the ASCII range. For all the other characters it does not work well at all. > Also, Terminals have support for UTF-8 encodings already. Some have, some have not. And you not only need a terminal that can handle UTF-8 data, you also need a font that has a glyph for all the characters you need to handle, and you may also need a way to actualy enter those characters with your keyboard. -- Ren? From w.m.gardella.sambeth at gmail.com Tue May 8 23:49:51 2007 From: w.m.gardella.sambeth at gmail.com (w.m.gardella.sambeth at gmail.com) Date: 8 May 2007 20:49:51 -0700 Subject: Parameter checking on an interfase Message-ID: <1178682591.359947.240390@y80g2000hsf.googlegroups.com> Hi all, I am more or less new to Python, and currently am making my first "serious" program. The application is a Clinical History manager (for my wife) which stores its data on a sqlite database. After googling on this newsgroup, I have read several threads where is stated that the LBYL way of testing parameters is not a pythonic way to work, and that is preferable catch the exceptions generated trying to use an invalid parameter passed to a function. Although I am generally following this approach, the problem I see is that sqlite docs states clearly that the engine does not check that the data types passed to the SQL sentences matches the types declared for the column, and lets any kind of information to be put in any column of the table. When I code the "business objects" of the application (don't know if this is the exact term for a layer that will isolate the application from the raw database, letting me change it in a future if necessary), I realize that if I pass arguments of wrong type (say, a numeric ID instead of the patient name), the DB engine will accept that gladly, and I will finish with data that could not be consistently retrievable if I use the DB from another program (no one right now, but I think of, perhaps, statistical trends on diseases and treatments). In this case, could be reasonable add type checking LBYL style on the methods, so if passed data is of wrong type, it generates a adequate exception to be catched by the caller? In this way, the rest of the app (mostly GUI) can be coded EAFP style. As programming background, as you can guess, I have made some programming in C, VBA and JavaScript (quite procedurally). I hope that you can bring me some light about this kind of design, so I can improve my coding and get the Python way faster. Cheers! Walter Gardella PS: Excuse me if my english is not good enough, but is not my mother tongue (I'm argentinian), and if my computerish is flawed (I'm only human;)) From JarodEvans at gmail.com Tue May 29 15:28:42 2007 From: JarodEvans at gmail.com (JarodEvans at gmail.com) Date: 29 May 2007 12:28:42 -0700 Subject: Speex bindings for python 2.5 Message-ID: <1180466922.114571.46410@d30g2000prg.googlegroups.com> Hello, For a personal project, I need to use speex with Python on Win32, but pyspeex is compiled for python 2.2. Could somebody try to compile pyspeex for python 2.5 please ? Thanx a lot for your help. From howe.steven at gmail.com Mon May 14 17:22:49 2007 From: howe.steven at gmail.com (Steven Howe) Date: Mon, 14 May 2007 14:22:49 -0700 Subject: os.listdir() doesn't work ?? In-Reply-To: References: Message-ID: <4648D329.9070500@gmail.com> Stef Mientki wrote: > hello, > > I want to find all files with the extension "*.txt". > From the examples in "Learning Python, Lutz and Asher" and > from the website I see examples where you also may specify a wildcard filegroup. > > But when I try this > files = os.listdir('D:\\akto_yk\\yk_controle\\*.txt') > > I get an error message > > WindowsError: [Errno 123] The filename, directory name, or volume label syntax is incorrect: > 'D:\\akto_yk\\yk_controle\\*.txt/*.*' > > What am I doing wrong ? > > thanks, > Stef Mientki > Hi Stef, Like that name; from a passing thought, I think the os.listdir command will resolve the slash/backslash. You might try using the unix method which I think would be 'd:/akto_yk/yk_controls/*.txt'. I'm sorry, but I can't test this knowledge, as I don't have access to Windows. Alternatively you could use glob.glob, after changing directory ( via os.chdir) to get a listing. from os import chdir, getcwd from glob import glob CWD = getcwd() chdir( 'd:/akto_yk/yk_controls') filelist = glob.glob('*.txt') chdir( CWD ) Steven Howe -- HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -------------- next part -------------- An HTML attachment was scrubbed... URL: From mcl.office at googlemail.com Thu May 10 07:25:26 2007 From: mcl.office at googlemail.com (mosscliffe) Date: 10 May 2007 04:25:26 -0700 Subject: Newbie (but improving) - Passing a function name with parameters as a parameter In-Reply-To: <1178793778.002765.50660@y80g2000hsf.googlegroups.com> References: <1178785638.736644.312970@e51g2000hsg.googlegroups.com> <1178793778.002765.50660@y80g2000hsf.googlegroups.com> Message-ID: <1178796326.708718.56080@e51g2000hsg.googlegroups.com> Many thanks. I think I see what you mean. I will try 'timeit' as well. Aren't examples wonderful ? On 10 May, 11:42, Ant wrote: > As Stephan said, you can investigate the timeit module. If you want to > test it your way, wrap up your function call in another function: > > On May 10, 9:27 am, mosscliffe wrote: > ...> def timeloop(dofunction,iters=10): > ... > > > def lookup(recs,patterns): > > ... > > > myrecs = ... > > def test1(): > lookup(myrecs, ['one', 'nomatch']) > > def test2(): > lookup(myrecs, ['one', 'two']) > > > timeloop(test1, 10) > > Using timeit: > > t = timeit.Timer("lookup(myrecs, ['one', 'nomatch'])", "from __main__ > import *") > print t.timeit(10) > > -- > Ant. From attn.steven.kuo at gmail.com Tue May 22 15:22:07 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 22 May 2007 12:22:07 -0700 Subject: converting text and spans to an ElementTree In-Reply-To: References: Message-ID: <1179847553.987425.273930@a26g2000pre.googlegroups.com> On May 21, 11:02 pm, Steven Bethard wrote: > I have some text and a list of Element objects and their offsets, e.g.:: > > >>> text = 'aaa aaa aaabbb bbbaaa' > >>> spans = [ > ... (etree.Element('a'), 0, 21), > ... (etree.Element('b'), 11, 18), > ... (etree.Element('c'), 18, 18), > ... ] > > I'd like to produce the corresponding ElementTree. So I want to write a > get_tree() function that works like:: > > >>> tree = get_tree(text, spans) > >>> etree.tostring(tree) > 'aaa aaa aaabbb bbbaaa' > > Perhaps I just need some more sleep, but I can't see an obvious way to > do this. Any suggestions? > It seems you're looking to construct an Interval Tree: http://en.wikipedia.org/wiki/Interval_tree -- Hope this helps, Steven From duncan.booth at invalid.invalid Mon May 21 04:10:15 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 21 May 2007 08:10:15 GMT Subject: Inverse of id()? References: <1179618173.280286.284120@n59g2000hsh.googlegroups.com> Message-ID: "Ian Clark" wrote: > Now I tried this in the shell and got different id's for a and b, but > when I typed it into a file and ran from there the id's where always > the same. Must have something to do with other programs allocating > space faster than I can type everything out (I do have a few processes > going). Interesting. > No, what other processes are doing isn't going to affect the memory allocation within your Python process. More likely the interactive interpreter is allocating or releasing other objects when it compiles each line of input which stops you seeing the duplicated id. You can get it to reuse the id by making sure you force everything to be compiled in one go: >>> class A: pass >>> class B: pass >>> a = A();print id(a);del a;b = B();print id(b) 12948384 12948384 >>> if 1: a = A() print id(a) del a b = B() print id(b) 12948464 12948464 >>> Gabriel's point however is not that this particular sequence will always result in duplicate ids (it is just an artifact of the implementation and could change), but that ids in general are re-used so any mapping from id->object is ambiguous unless you can be certain that the object whose id you took is still alive. There are two common ways to do the reverse mapping: either store the ids and objects in a dict thereby forcing the objects to continue to exist, or store them in a weakref.WeakValueDictionary and be very careful not to access an expired (and possibly reused) id. For a completely safe technique which works with any weakly referenceable object just ignore Python's id function and write your own which never reuses an id. Then you can safely map from your own id values back to the object if it still exists or get an exception if it doesn't: >>> lastid = 0 >>> idmap = weakref.WeakValueDictionary() >>> def myid(o): global lastid lastid += 1 idmap[lastid] = o return lastid >>> def getfrommyid(id): return idmap[id] >>> a = A() >>> print myid(a) 1 >>> del a >>> b = B() >>> print myid(b) 2 >>> print getfrommyid(2) <__main__.B instance at 0x00CD43F0> >>> print getfrommyid(1) Traceback (most recent call last): File "", line 1, in print getfrommyid(1) File "", line 2, in getfrommyid return idmap[id] File "C:\Python25\Lib\weakref.py", line 54, in __getitem__ o = self.data[key]() KeyError: 1 >>> Unfortunately that won't help with the common builtin objects as they aren't weakly referenceable. From ivoras at __fer.hr__ Sun May 13 13:20:08 2007 From: ivoras at __fer.hr__ (Ivan Voras) Date: Sun, 13 May 2007 19:20:08 +0200 Subject: __dict__ for instances? In-Reply-To: <46472764$0$23138$9b4e6d93@newsspool1.arcor-online.net> References: <46472764$0$23138$9b4e6d93@newsspool1.arcor-online.net> Message-ID: Marc Christiansen wrote: > Nope, at least for PyGTK 2 :) See below. Aaah, but....! > [...] >> This looks like it should be easy, but I can't find the solution :( > > Use the doc, Luke, oops, Ivan :) > Citing the gtk.glade.XML.signal_autoconnect documentation: > def signal_autoconnect(dict) > dict: a mapping or an instance > ^^^^^^^^ I should have mentioned - I tried it already and it didn't work. The specific error I get is: "WARNING: "on_button_clicked" not callable or a tuple" once for each handler when I call autoconnect. And I've got a recent version of pyGTK (2.10.4) so it should. -- (\__/) (O.o) (> < ) This is Bunny. Copy Bunny into your signature to help him on his way to world domination! -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 258 bytes Desc: OpenPGP digital signature URL: From bulliver at badcomputer.org Thu May 24 12:22:26 2007 From: bulliver at badcomputer.org (darren kirby) Date: Thu, 24 May 2007 10:22:26 -0600 Subject: Reading (and writing?) audio file tags In-Reply-To: <1180021454.086004.126170@p47g2000hsd.googlegroups.com> References: <1180021454.086004.126170@p47g2000hsd.googlegroups.com> Message-ID: <200705241022.26608.bulliver@badcomputer.org> quoth the Paul Moore: > I'd like to write some scripts to analyze and manipulate my music > files. The files themselves are in MP3 and FLAC format (mostly MP3, > but FLAC where I ripped original CDs and wanted a lossless format). > I've no idea what form of tags are used in the files (ID3v1, ID3v2, > OGG, APE, ...) Flac files use Vorbis comments, the same that Ogg Vorbis files use. As for MP3, they use ID3v2 or ID3v1, or both. Anyway, what you want is Mutagen. It handles both Flac and Mp3 tags, as well as many others: http://www.sacredchao.net/quodlibet/wiki/Development/Mutagen > I just used whatever the program that set them up used. > I'm completely confused by the various tag formats that exist - there > seems to be little standardisation, and quite a few compatibility > pitfalls. For example, I have files with tags using accented > characters - I suspect that this causes some tools to switch format > (because I've seen what looked like corrupt data at times, which > turned out to be the program displaying the "wrong format" of tag). > > I've seen various Python libraries that talk about ID3 tag reading - > but I'm not clear if they read other tag formats (many applications > which call themselves "ID3 readers" actually handle multiple formats, > but I don't know if that's true for (Python) libraries. Also, there > seem to be few libraries that will *write* tags. ID3 = MP3 only. A lot of people call _all_ tags 'id3' tags to save having to say 'Flac tags, and Vorbis tags, and Ape tags' etc....these people are the source of your confusion. > Is there a good "music file tag handling" library for Python that's > worth looking at? I use Windows, so it would have to be for that > platform, and although I have a compiler, I don't really want to spend > a lot of time collecting and porting/building support libraries, so > I'd be looking for a binary distribution. From the read me: "Mutagen works on Python 2.3+ and has no dependencies outside the CPython standard library" so it should work on Windows I think. It is just pure Python so there you go... > In the absence of something suitable, I'll probably go back to dumping > the tags via a generic "MP3 tag reader" program, then manipulate them > as a text file, then try to do some sort of bulk reload. > > Thanks, > Paul. -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 jstroud at mbi.ucla.edu Fri May 4 05:47:42 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 04 May 2007 02:47:42 -0700 Subject: Firefighters at the site of WTC7 "Move away the building is going to blow up, get back the building is going to blow up." In-Reply-To: <1178267280.329328.133650@u30g2000hsc.googlegroups.com> References: <1178161820.731367.264500@y80g2000hsf.googlegroups.com> <1178267280.329328.133650@u30g2000hsc.googlegroups.com> Message-ID: mike3 wrote: > On May 2, 9:10 pm, Midex wrote: >> 100% EVIDENCE - SEE THE TRUTH FINALLY - ON THE GROUND VIDEO WITNESSEShttp://www.youtube.com/watch?v=YNN6apj5B2U >> >> In order to appreciate just what Truthers are talking about when they >> cry Treason over WTC7, you would want to see this History Channel >> documentary on what they claim happened to WTC7:http://www.youtube.com/watch?v=TVSxeJH_RCY >> >> Ben Chertoff can't get his story straighthttp://www.youtube.com/watch?v=9YND7XocMocj >> >> LIES LIES LIES LIES LIES >> >> 9/11 Truth Focoist Revolution. "When peaceful revolution is made >> impossible, violent revolution is inevitable" - Martin Luther King. >> How long shall they kill our prophets? Look up Focoism. Write about >> it. Spread the method. It will be how this revolution will take shape. > > Maybe they were just speaking in the heat of the moment... or does > this mean that the FIREFIGHTERS were in on the conspiracy too? > Did you know that a conspiracy becomes more and more difficult > to do the bigger it gets? Do you also know that every structural > engineer, every scientist, all of NIST, everyone would have to be > "in" on this conspiracy? > Not entirely. "A nobleman from the Baltic states, Freytag von Loringhoven was viewed with suspicion by the Nazis 'who loathed education, real culture and tradition'. Unlike Hitler's secretary, Traudl Junge, whose memoirs were published before her death two years ago, he claims he never fell under the F?hrer's spell and insists the distinction between the professional Wehrmacht and politicised Waffen-SS was real. 'After the war I had the unpleasant feeling of having served as a combustible, as heating wood, for the adventures of a charlatan,' he says. 'I had served a criminal regime while remaining loyal to my military convictions.' It was only as a prisoner of war that he realised the Nazis had murdered Jews 'on an industrial scale', he says. ' We didn't even know the names of the concentration camps.'" http://www.guardian.co.uk/germany/article/0,2763,1446410,00.html James From grante at visi.com Thu May 24 16:07:41 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 24 May 2007 20:07:41 -0000 Subject: Python and GUI References: <1179761984.704369.116310@b40g2000prd.googlegroups.com> <4651CDBC.1070508@ulmcnett.com> <5abb0$4655ee4c$d443bb3a$510@news.speedlinq.nl> Message-ID: <135bs4dfpdl8q33@corp.supernews.com> On 2007-05-24, Stef Mientki wrote: >> Finally, consider wax (http://zephyrfalcon.org/labs/wax.html). In my >> view, this is *exactly* what python needs, and its not being maintained >> anymore as far as I can tell. What I like about it is: >> >> 1) it is small...I can include the entire wax distribution in >> my app with only a 780k footprint. >> >> 2) it is a very thin layer on wx, so when something doesn't quite work, >> I can immediately fall back onto wx, mixing and matching wax and wx >> objects. it's just that the wax objects have more pythonic calling and >> use properties > > Sorry I don't know wax, but I wonder "a GUI designer without > screenshots", is that Pythonic ;-) Uh, wha? Who are you quoting about the screenshots? Wax isn't a "GUI designer", and I'm a bit lost as to what screenshots have to do with the topic at hand. -- Grant Edwards grante Yow! I'm changing the at CHANNEL ... But all I get visi.com is commercials for "RONCO MIRACLE BAMBOO STEAMERS"! From cai.haibin at gmail.com Mon May 28 03:28:50 2007 From: cai.haibin at gmail.com (james_027) Date: 28 May 2007 00:28:50 -0700 Subject: gui application on cross platform In-Reply-To: <1180335978.008908.51990@q69g2000hsb.googlegroups.com> References: <1180332092.551838.258440@z28g2000prd.googlegroups.com> <1180335978.008908.51990@q69g2000hsb.googlegroups.com> Message-ID: <1180337330.434010.42210@z28g2000prd.googlegroups.com> On May 28, 3:06 pm, Stefano Canepa wrote: > On 28 Mag, 08:01, james_027 wrote: > > > Hi, > > > I am using delphi to develop gui application, and wish to make a shift > > to python. here are some of my question/concern... > > > 1. is python develop gui application a cross platform? just like java > > swing? > > Yes. Qt, wxwidgets and pygtk run on Linux and Windows, don't know > about Macs. > > > 2. delphi makes things easy for me like coding for a specific event on > > a specific component, could it be the same for python? > > Not in the Delphi way but glade/gazpacho are good GUI designer for > gtk. > I have no experience with qtdesigner or the wx equivalent app. > > > 3. are there cool library of component like in delphi available for > > python that will make database application more usesable? > > python has dbapi, all DBs look the same, python can also use ORM like > SQLObjects and SQLALchemy > > > 4. where do I start the learning curve? I did some research and I > > don't know which one to take among wxwdiget, pygtk, and etc. > > I tried wxwidgets and pygtk, then I decided to use pygtk but it > could be I'll change my mind in the future. > > Bye > sc Thanks sc, What do you mean when you say .."all DBs look the same" what is the difference between pygtk and wxwidgets? bye james From __peter__ at web.de Wed May 23 13:32:27 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 23 May 2007 19:32:27 +0200 Subject: Properties/Decorators [WAS: Can I reference 1 instance of an object by more names ? rephrase] References: <4654289a$0$2326$426a74cc@news.free.fr> <465436E0.7040907@freakmail.de> Message-ID: Brian van den Broek wrote: > I had the same sort of question as Wildemar and I set about > investigating as any good pythonista would by typing help(apply) at > the interactive prompt. That produced a help text that started: > > Help on built-in function apply in module __builtin__: > > But: > > >>> [x for x in dir('__builtin__') if 'apply' in x] > [] > > ? If apply is in the __builtin__ module, why doesn't > dir('__builtin__') know about it? The string "__builtin__" doesn't have an apply attribute; but the __builtin__ module has: >>> import __builtin__ >>> "apply" in dir(__builtin__) True Peter From stefan.behnel-n05pAM at web.de Tue May 15 07:22:13 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 15 May 2007 13:22:13 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464993e7$0$23148$9b4e6d93@newsspool1.arcor-online.net> References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> <4648294F.2000704@web.de> <46487a6c$0$2400$426a74cc@news.free.fr> <464977D3.6010703@web.de> <464993e7$0$23148$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <464997E5.4050105@web.de> Ren? Fleschenberg wrote: > Programming is such an English-dominated culture that I even "think" in > English about it. That's sad. > My experience is: If you know so little "technical" English that you > cannot come up with well chosen English identifiers, you need to learn > it. :) This is not about "technical" English, this is about domain specific English. How big is your knowledge about, say, biological terms or banking terms in English? Would you say you're capable of modelling an application from the domain of biology, well specified in a large German document, in perfect English terms? And: why would you want to do that? Stefan From mangabasi at gmail.com Wed May 23 14:22:53 2007 From: mangabasi at gmail.com (Mangabasi) Date: 23 May 2007 11:22:53 -0700 Subject: Inheriting from Python list object(type?) In-Reply-To: Message-ID: <1179944573.636652.80700@p47g2000hsd.googlegroups.com> On May 23, 12:47 pm, "Jerry Hill" wrote: > On 23 May 2007 09:58:36 -0700, Mangabasi wrote: > > > There must be a way to inherit from the list type without having to > > redefine all the methods and attributes that regular lists have. > > Like this: > > class Point(list): > def __init__(self, x, y, z = 1): > list.__init__(self, [x, y, z]) > > def __getattr__(self, name): > if name == 'x': return self[0] > if name == 'y': return self[1] > if name == 'z': return self[2] > > def __setattr__(self, name, value): > if name == 'x': self[0] = value > if name == 'y': self[1] = value > if name == 'z': self[2] = value > > Does that show you what you need? > > -- > Jerry Hi Jerry, It is very close. It worked for many operations except when I tried >>> from numpy import array >>> p = Point(4,5) >>> a = array(p) Traceback (most recent call last): File "", line 1, in ? ValueError: invalid __array_struct__ >>> a = array([4, 5, 1]) >>> I can define an __array__ method for this to work but I am wondering if we can make this behave like a real list? Thanks for your help. From mcl.office at googlemail.com Thu May 17 05:49:57 2007 From: mcl.office at googlemail.com (mosscliffe) Date: 17 May 2007 02:49:57 -0700 Subject: Newbie: Joining Lists Message-ID: <1179395397.157566.209330@l77g2000hsb.googlegroups.com> I have been playing with GLOB and OS.PATH and it all works, but is there a better way of getting GLOB to recognise, multiple patterns at one call (ONE). Also is it possible to join lists, without the horrid concatenation code I have (TWO). I tried list.append(glob.glob(pattern)) but it error'd ----------------------- CODE ---------------------- import os import glob filenames = [] patterns = ('.\\t*.py', '.\\*.c??', '.\\*.txt') # Can these patterns for glob processing be specified in the glob call *****ONE**** for pattern in patterns: filenames = filenames + glob.glob(pattern) # Is there a better way for this line in joining lists *****TWO**** for fullfilename in filenames: (filepath, filename) = os.path.split(fullfilename) (shortname, extension) = os.path.splitext(filename) print "PATHNAME: %s FILENAME: %s SHORTNAME: %s EXTNAME: %s" % (filepath, filename, shortname, extension[1:]) --------------------------------------------------------------------- Thanks Richard Ps \\ is because I needed to get the path element for my test and windoze does not return a path element if in current directory From DELETETHISyang.news at MAILNULLdeletethis.com Sun May 20 00:26:12 2007 From: DELETETHISyang.news at MAILNULLdeletethis.com (Yang) Date: 20 May 2007 04:26:12 GMT Subject: Closing socket file descriptors Message-ID: Hi, I'm experiencing a problem when trying to close the file descriptor for a socket, creating another socket, and then closing the file descriptor for that second socket. I can't tell if my issue is about Python or POSIX. In the following, the first time through, everything works. On the second connection, though, the same file descriptor as the first connection may be re-used, but for some reason, trying to do os.read/close on that file descriptor will cause an error. Thanks in advance for any help on why this problem is occurring and/or how to resolve it (preferrably, I can continue to use file descriptors instead of resorting to socket.recv/socket.close). def handle( s ): print id(s), s print os.read( s.fileno(), 4096 ) # s.recv(4096) os.close( s.fileno() ) # s.close() svr = socket.socket() svr.bind( ( 'localhost', 8003 ) ) svr.listen( 1 ) while True: print 'accepting' s,_ = svr.accept() handle( s ) # Traceback (most recent call last): # File "./normal_server_close_error.py", line 25, in # handle( s ) # File "./normal_server_close_error.py", line 13, in handle # print os.read( s.fileno(), 4096 ) # s.recv(4096) # OSError: [Errno 9] Bad file descriptor From apatheticagnostic at gmail.com Wed May 23 02:16:58 2007 From: apatheticagnostic at gmail.com (kaens) Date: Wed, 23 May 2007 02:16:58 -0400 Subject: xml.parsers.expat loading xml into a dict and whitespace In-Reply-To: References: Message-ID: <163f0ce20705222316x7d6247a7hea019e7fd2aa2ee2@mail.gmail.com> > [1] ElementTree is in the 2.5 standard library, but if you're stuck with > an earlier python, just Google for it -- there are standalone versions I've got 2.5, and I'm not attached to expat at all. I'll check it out, thanks. From benedict.verheyen at gmail.com Wed May 30 05:24:11 2007 From: benedict.verheyen at gmail.com (Benedict Verheyen) Date: Wed, 30 May 2007 11:24:11 +0200 Subject: Key Listeners In-Reply-To: <1180510259.914953.225420@h2g2000hsg.googlegroups.com> References: <1180491273.446164.281990@q75g2000hsh.googlegroups.com> <1180510259.914953.225420@h2g2000hsg.googlegroups.com> Message-ID: bruno.desthuilliers at gmail.com schreef: > On 30 mai, 04:14, Mike wrote: >> Are there key listeners for Python? Either built in or third party? > > What is a "key listener" ? > I thought it was a rather straightforward name. Something that listens for a key. In other words, a piece of software that detects what keys are being tapped. In google, the first link is a link to the java sun home page. The first sentence on that page: "Key events indicate when the user is typing at the keyboard." Regards, Benedict From gheize at gmail.com Tue May 15 08:22:50 2007 From: gheize at gmail.com (Heizenreder Guillermo) Date: Tue, 15 May 2007 09:22:50 -0300 Subject: Hello World! Message-ID: <200705150922.50462.gheize@gmail.com> Hello World! I am new in the list -- Heizenreder Guillermo -- From drummingdavidson at gmail.com Tue May 15 20:13:33 2007 From: drummingdavidson at gmail.com (drummingdavidson at gmail.com) Date: 15 May 2007 17:13:33 -0700 Subject: The Pure Joy of Receiving PayPal Money Message-ID: <1179274413.863234.151650@e65g2000hsc.googlegroups.com> PAYPAL MAGIC!!! TURN $5 INTO $15,000 IN ONLY 30 DAYS...HERES HOW! This is a Money Scheme and Not, I repeat... This is Not a Scam!!! You have most likely seen or heard about this project on TV programs such as 20/20 and Oprah, or you may have read about it in the Wall Street Journal. If not, here it is below - revealed to you in step-by-step detail. This program is by no means new. It has been in existence in many forms for at least a decade. But in the early days, it required a lot more time and effort, as well as an investment of a few hundred dollars. However thanks to PayPal and the Internet, the investment is now virtually ZERO! And what's more, the entire process is FASTER, EASIER, and MORE LUCRATIVE than it has EVER been! Below is the email sent to me: How to Turn $5 into $15,000 in 30 Days with PayPal I WAS SHOCKED WHEN I SAW HOW MUCH MONEY CAME FLOODING INTO MY PAYPAL ACCOUNT I turned $5 into $14,706 within the first 30 days of operating the business plan that I am about to reveal to you free of charge. If you decide to take action on the following instructions, I will GUARANTEE that you will enjoy a similar return! STILL NEED PROOF? Here are just 3 testimonials from the countless individuals who decided to invest nothing more than $5 and half an hour of their time to participate in this program: "What an amazing plan! I followed your instructions just 3 weeks ago, and although I haven't made 15 grand yet, I'm already up to $9,135. I'm absolutely gob smacked." -Pam Whittemore , Ohio "Well, what can I say?... THANK YOU SO MUCH! I sent 40 e-mail's out like you said and then I just forgot about the whole thing. To be honest, I didn't really think anything would come of it. But when I checked my paypal account a week later, there was over $5,000 in After 30 days I now have over $11,000 to spend! I can't thank you enough!"-Juan Tovar, NY,NY "I was shocked when I saw how much money came flooding into my paypal account. Within 3 weeks my account balance has ballooned to $12,449. At first I thought there had been some sort of error with my account!" -Richard Barrie , Boulder,CO The only things you will need are: An email address. A Business PayPal account with at least $5 deposited in it, and just 15 to 30 minutes of your time. This program takes just half an hour to set up. After that, there is absolutely no work whatsoever to do on your part. You have absolutely NOTHING to lose, and there is NO LIMIT to the amount of income you can generate from this one single business program. Let's get started, just follow the instructions exactly as set out below and then prepare yourself for a HUGE influx of cash over the next 30 days! Here's what you need to do. . . REQUIREMENTS [THESE INSTRUCTIONS MUST BE FOLLOWED VERBATUM FOR THIS TO WORK] #1) an email address #2) a Premier or Business PayPal account Now follow the steps: 1-4 STEP #1 - Setting up your FREE PayPal Account It's extremely safe and very easy to set up a FREE PayPal account! Copy and paste this to the address bar https://www.paypal.com (notice the secure "https" within the link) Be sure to sign up for a free PREMIER or BUSINESS account (and not just a PERSONAL account) otherwise you won't be able to receive credit card payments from other people. STEP #2 - Sending PayPal money "It is an undeniable law of the universe that we must first give in order to receive." Now all you have to do is send $5.00 by way of PayPal to each of the six email addresses listed below. After setting up your free paypal account and confirming or verifying YOUR ACCOUNT AND putting (five Dollars) $5.00 into your Paypal Account use the Account tab on Paypal to send $5.00 to each of the Names on the List then move the top one and place yours in the #5 spot on the list of names #1-#5. Remember your name becomes #5. Make sure the subject of the payment says... *PLEASE PUT ME ON YOUR EMAIL LIST* (this keeps the program 100% legal.. so please don't forget!) Note: (If you do not see the full email address for the 5 members, just hit reply to this email and they will show up.) (Just in case you still haven't opened your PayPal account yet, use this link to open one in your name), https://www.paypal.com #1) dmacnab2000 at yahoo.com #2) bigwilly124_269 at hotmail.com #3) w_schans at hotmail.com #4) edruud4 at yahoo.com #5) drummingdavidson at rogers.com Remember, all of this is ABSOLUTELY LEGAL! You are creating a service! A Business... An Email List Service Business If you have any doubts, please refer to Title 18 Sec. 1302 & 1241 of the United States Postal laws. STEP #3 - Adding Your Email Address After you send your five $1.00 payments, it's your turn to add your email address to the list! Take the #1) email off the list that you see above, move the other addresses up one (5 becomes 4 & 4 becomes 3, etc) then put YOUR email address (the one used in your PayPal account) as #5) on the list. **MAKE SURE THE EMAIL YOU SUPPLY IS EXACTLY AS IT APPEARS IN YOUR PAYPAL ACCOUNT.** STEP #4 - Copy Message to 200 Newgroups, message boards,etc...... The Pure Joy of Receiving PayPal Money! You are now ready to post your copy of this message, to at least 200 newsgroups, message boards, etc. (I think there are close to 32,000 groups) All you need is 200, but remember, the more you post, the more money you make - as well as everyone else on the list! In this situation your job is to let as many people see this letter as possible. So they will make you and me rich!!!! You can even start posting the moment your email is confirmed. Payments will still appear in your PayPal account even while your bank account is being confirmed. HOW TO POST TO NEWSGROUPS & MESSAGE BOARDS Step #1) You do not need to re-type this entire letter to do your own posting. Simply put your CURSOR at the beginning of this letter and drag your CURSOR to the bottom of this document, and select 'copy' from the edit menu. This will copy the entire letter into your computer's temporary memory. Step #2) Open a blank 'Notepad' file and place your cursor at the top of the blank page. From the 'Edit' menu select 'Paste'. This will paste a copy of the letter into notepad so that you can add your email to the list. Or copy to a Word Document. and Place in the email upon completion. Step #3) Save your new Notepad file as a .txt file. If you want to do your postings in different sittings, you'll always have this file to go back to. Step #4) Use Netscape or Internet Explorer and try searching for various newsgroups, on-line forums, message boards, bulletin boards, chat sites, discussions, discussion groups, online communities, etc. EXAMPLE: go to any search engine like yahoo.com, google.com, altavista.com, excite.com - then search with subjects like? millionaire message board? or money making message board? or opportunity message board? or money making discussions? or business bulletin board? or money making forum? etc. You will find thousands & thousands of message boards. Click them one by one then you will find the option to post a new message. Step #5) Visit these message boards and post this article as a new message by highlighting the text of this letter and selecting 'Paste' from the 'Edit' menu. Fill in the Subject, this will be the header that everyone sees as they scroll thru the list of postings in a particular group, click the post message button. You're done with your first one! Congratulations! THAT'S IT!! All you have to do is jump to different newsgroups and post away. After you get the hang of it, it will take about 30 seconds for each newsgroup! REMEMBER, THE MORE NEWSGROUPS AND/OR MESSAGE BOARDS YOU POST IN, THE MORE MONEY YOU WILL MAKE!! BUT YOU HAVE TO POST A MINIMUM OF 200** That's it! You will begin receiving money within days! **JUST MAKE SURE THE EMAIL YOU SUPPLY IS EXACTLY AS IT APPEARS ON PAYPAL.** Explanation of why it works so well: $$$$$ NOW THE WHY PART: Out of 200 postings, say I receive only 5 replies (a very low example). So then I Made $5.00 with my email at #5 on the letter. Now, each of the 5 persons who just sent me $1.00 make the MINIMUM 200 postings, each with my email at #5 and only 5 persons respond to each of the original 5, that is another $25.00 for me, now those 25 each make 200 MINIMUM posts with my email at #4 and only 5 replies each, I will bring in an additional $125.00! Now, those 125 persons turn around and post the MINIMUM 200 with my email at #3 and only receive 5 replies each, I will make an additional $625.00! OK, now here is the fun part, each of those 625 persons post a MINIMUM 200 letters with my email at #2 and they only receive 5 replies that just made me $3,125.00!!! Those 3,125 persons will all deliver this message to 200 newsgroups with my email at #1 and if still 5 persons per 200 newsgroups react I will receive $15,625.00! With an original investment of only $5.00! AMAZING!! When your email is no longer on the list, you just take latest posting in the newsgroups, and send out another $5.00 to emails on the list, putting your email at number 5 again. And start posting again. The thing to remember is, thousands of people all over the world are joining the internet and reading these articles everyday, JUST LIKE YOU are now!! So can you afford $5.00?? And see if it really works?? I think so? People have said, what if the plan is played out and no one sends you the money? So what are the chances of that happening when there are tons of new honest users and new honest people who are joining the internet and newsgroups everyday and are willing to give it a try? Estimates are at 20,000 to 50,000 new users everyday, with thousands of those joining the actual Internet. Remember, play FAIRLY and HONESTLY and this will work. This really isn't another one of those crazy scams! As long as people FOLLOW THROUGH with sending out $5.00, it works! With warm wishes, bless you and your loved ones, https://www.paypal.com $$$$$ REMEMBER, IT IS 100% LEGAL! DON'T PASS THIS UP From steven at REMOVE.THIS.cybersource.com.au Tue May 8 03:40:52 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 08 May 2007 07:40:52 -0000 Subject: change of random state when pyc created?? References: <1178408359.113807.181570@l77g2000hsb.googlegroups.com> Message-ID: On Tue, 08 May 2007 02:12:27 +0000, Alan Isaac wrote: > "Steven D'Aprano" wrote in > message > news:pan.2007.05.06.06.00.17.629591 at REMOVE.THIS.cybersource.com.au... >> If you want to send me the modules, I will have a look at them as well. >> Many eyes make for shallow bugs... > > Dustan and John Machin have confirmed the apparent bug, and I have sent > you the files. Explanation welcome!! My testing suggests the bug is *not* to do with pyc files at all. I'm getting different results when running the files, even when the directory is read-only (and therefore no pyc files can be created). My results suggest that setting the seed to the same value does NOT give identical results, *even though* the random number generator is giving the same results. So I think we can discount the issue being anything to do with either the .pyc files or the random number generator. -- Steven. From mblume at socha.net Wed May 16 12:53:31 2007 From: mblume at socha.net (Martin Blume) Date: Wed, 16 May 2007 18:53:31 +0200 Subject: Execute commands from file References: <1179320782.594398.67980@u30g2000hsc.googlegroups.com> Message-ID: <464b370c$0$3808$5402220f@news.sunrise.ch> "tmp123" schrieb > > We have very big files with python commands > (more or less, 500000 commands each file). > > It is possible to execute them command by command, inp = open(cmd_file) for line in inp: exec line might help. You don't get quite the same feeling as "like if the commands was typed one after the other in a interactive session", but perhaps this helps. Warning: the code above is without any error checks. You might also run into security problems, the example above assumes you trust your input. HTH. YMMV. Martin From Wiseman1024 at gmail.com Sat May 5 21:44:17 2007 From: Wiseman1024 at gmail.com (Wiseman) Date: 5 May 2007 18:44:17 -0700 Subject: Python regular expressions just ain't PCRE In-Reply-To: References: <1178323901.381993.47170@e65g2000hsc.googlegroups.com> <1178380335.646708.260540@h2g2000hsg.googlegroups.com> Message-ID: <1178415857.871479.190020@u30g2000hsc.googlegroups.com> On May 5, 6:28 pm, dus... at v.igoro.us wrote: > I'm not sure what your skill level is, but I would suggest studying the > code, starting in on a patch for one or more of these features, and then > corresponding with the module's maintainers to improve your patch to the > point where it can be accepted. I'll consider creating a new PCRE module for Python that uses the latest version PCRE library. It'll depend on my time availability, but I can write Python extensions, and I haven't used PCRE in a long time, and I recall it was a bit of a hassle, but I could get it done. From rene at korteklippe.de Wed May 16 04:34:53 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Wed, 16 May 2007 10:34:53 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649dd55$0$23144$9b4e6d93@newsspool1.arcor-online.net> <464a25e9$0$10188$9b4e6d93@newsspool4.arcor-online.net> <464A3354.4060205@web.de> Message-ID: <464ac22c$0$20297$9b4e6d93@newsspool3.arcor-online.net> Marc 'BlackJack' Rintsch schrieb: > There are potential users of Python who don't know much english or no > english at all. This includes kids, old people, people from countries > that have "letters" that are not that easy to transliterate like european > languages, people who just want to learn Python for fun or to customize > their applications like office suites or GIS software with a Python > scripting option. Make it an interpreter option that can be turned on for those cases. -- Ren? From mailme.gurpreet at gmail.com Thu May 3 03:35:36 2007 From: mailme.gurpreet at gmail.com (mailme.gurpreet at gmail.com) Date: 3 May 2007 00:35:36 -0700 Subject: FInd files with .so extension In-Reply-To: <1178168321.581307.284750@y5g2000hsa.googlegroups.com> References: <1178168321.581307.284750@y5g2000hsa.googlegroups.com> Message-ID: <1178177736.311631.254980@q75g2000hsh.googlegroups.com> On May 3, 9:58 am, pradeep nair wrote: > HI, > > How do i find files with .so extension using python . Hi pradeep This piece of code should help you import os,re def findfile(filepattern, base = '.'): regex = re.compile(filepattern) matches = [] for root,dirs,files in os.walk(base): for f in files: if regex.match(f): matches.append(root + '/' + f) return matches HAPPY CODING From nogradi at gmail.com Thu May 3 10:37:07 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Thu, 3 May 2007 16:37:07 +0200 Subject: sqlite for mac? In-Reply-To: <1178165109.102244.188860@c35g2000hsg.googlegroups.com> References: <1177993261.572563.70370@n76g2000hsh.googlegroups.com> <5f56302b0705010308h5c3f64a8ka05cd92de879f6bd@mail.gmail.com> <1178165109.102244.188860@c35g2000hsg.googlegroups.com> Message-ID: <5f56302b0705030737t75301640i9049a2f814e566f1@mail.gmail.com> > > >> Does sqlite come in a mac version? > > > > > The interface (pysqlite) is part of the python 2.5 standard library > > > but you need to install sqlite itself separately (as far as I > > > remember) fromwww.sqlite.org > > > > http://developer.apple.com/documentation/MacOSX/Conceptual/OSX_Techno... > > > > I downloaded pysqlite, ran the setup script, and tested the > installation and everything worked fine. However, if I try to import > either sqlite, sqlite2, or sqlite3 into a python program, I get an > error saying there's no such module. > > I assume that means pysqlite cannot see the installation of SQlite > that came preinstalled on my mac. My python book says to download the > SQlite source where automatic code generation has already been > performed. I did that. Then my book says says to follow the > instructions in the README file. However, the download only has two > files: sqlite3.c and sqlite3.h. As a result, I don't know what to > do. If all tests ran fine then pysqlite can see your sqlite installation. How are you importing sqlite? It's usually something like "from pysqlite2 import dbapi2 as sqlite" not simply "import sqlite". If you go to the test directory where everything works you can see how those modules import it and that should definitely work for you as well. HTH, Daniel From collver at peak.org Thu May 3 09:54:07 2007 From: collver at peak.org (Ben Collver) Date: Thu, 03 May 2007 06:54:07 -0700 Subject: Python user group in Portland, OR? In-Reply-To: <1178079938.469358.318960@p77g2000hsh.googlegroups.com> References: <1178054753.732189.137230@h2g2000hsg.googlegroups.com> <1178057364.942127.203200@n76g2000hsh.googlegroups.com> <1178079938.469358.318960@p77g2000hsh.googlegroups.com> Message-ID: bradallen wrote: > I would be happy to meet with you and any other Portland Python > programmers to talk about ideas for organizing a user group. > There is also some good discussion about it on the Python Advocacy > the mailing list, because PSF has begun an effort to foster and > promote > user groups. I don't use Ruby, but I read the blog of a dude in Portland who went to the Ruby user group. He said that the programmers there spent as much time talking about Python and Perl as they did about Ruby, so you might be interested in that. Ben From steve at holdenweb.com Sat May 26 17:03:03 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 26 May 2007 17:03:03 -0400 Subject: Why isn't this query working in python? In-Reply-To: <1180207521.072958.322770@p47g2000hsd.googlegroups.com> References: <1180103946.552760.239200@p47g2000hsd.googlegroups.com> <6e42ec490705250751i89d3cf3v3a3062690d0284aa@mail.gmail.com> <1180207521.072958.322770@p47g2000hsd.googlegroups.com> Message-ID: erikcw wrote: > On May 25, 11:28 am, Carsten Haese wrote: >> On Fri, 2007-05-25 at 09:51 -0500, Dave Borne wrote: >>>> I'm trying to run the following query: >>> ... >>>> member_id=%s AND expire_date > NOW() AND completed=1 AND (product_id >>> Shouldn't you be using the bind variable '?' instead of '%s' ? >> The parameter placeholder for MySQLdb is, indeed and unfortunately, %s. >> The OP is using parameter substitution correctly, though in an >> obfuscated fashion. 'sql' is a misnamed tuple containing both the query >> string *and* the parameters, which is being unpacked with '*' into two >> arguments to the execute call. >> >> The only problem I see is that the parameters should be a sequence, i.e. >> (self.uid,) instead of just (self.uid). >> >> HTH, >> >> -- >> Carsten Haesehttp://informixdb.sourceforge.net > > I tried adding the comma to make it a sequence - but now change. > > ('SELECT payment_id FROM amember_payments WHERE member_id=%s AND > expire_date > NOW() AND completed=1 AND (product_id >11 AND product_id > <21)', (1608L,)) > () > > What else could it be? > > Thanks! > Erik > It *could* be that there aren't any data meeting the criteria in your query. Is there any chance that the current date/time has passed the expire date since you ran the query manually? 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From klaus at seistrup.dk Sun May 20 23:44:14 2007 From: klaus at seistrup.dk (Klaus Alexander Seistrup) Date: Mon, 21 May 2007 03:44:14 +0000 (UTC) Subject: List Moderator References: <880dece00705172218n71123b55q531ec0c5e500f208@mail.gmail.com> <880dece00705190012g4f3d3ef6v4e6c87a156708bb0@mail.gmail.com> <880dece00705191305m203bc8ep804d647c17438581@mail.gmail.com> <464F5E42.6090607@holdenweb.com> <880dece00705201305q6944986fj8f77c4b5cac09456@mail.gmail.com> <13524svhtst5dd1@corp.supernews.com> Message-ID: Grant Edwards wrote: > Maybe I've got a beter news server, but I don't see much > spam at all in c.l.p. Neither do I. Cheers, -- Klaus Alexander Seistrup http://klaus.seistrup.dk/ From aisaac at american.edu Wed May 9 16:35:27 2007 From: aisaac at american.edu (Alan G Isaac) Date: Wed, 09 May 2007 15:35:27 -0500 Subject: change of random state when pyc created?? In-Reply-To: References: <5ae25fF2oggbqU1@mid.uni-berlin.de> Message-ID: Robert Kern wrote: > http://docs.python.org/lib/typesmapping.html > """ > Keys and values are listed in an arbitrary order which is non-random, varies > across Python implementations, and depends on the dictionary's history of > insertions and deletions. > """ Even this does not tell me that if I use a specified implementation that my results can vary from run to run. That is, it still does not communicate that rerunning an *unchanged* program with an *unchanged* implementation can produce a change in results. Alan Isaac From john at datavoiceint.com Fri May 11 12:57:14 2007 From: john at datavoiceint.com (HMS Surprise) Date: 11 May 2007 09:57:14 -0700 Subject: Better way to isolate string In-Reply-To: References: <1178896888.721679.207240@n59g2000hsh.googlegroups.com> <1178897702.872729.72050@y5g2000hsa.googlegroups.com> Message-ID: <1178902634.954279.29060@p77g2000hsh.googlegroups.com> On May 11, 10:45 am, Tim Golden wrote: > HMS Surprise wrote: > > I suppose a one liner would look better, but I am alway leery of these > > things 'breaking'. > > > t = s.split('">')[-1].split('<')[0] > > s ='G132153' > > Only if you're competing in an obscurity competition ;) > > If you're really confined to built-ins (ie you can't import > a single module) then just go with your original solution. > Why not? > > If you can import modules, then you want to look > at the urlparser and cgi modules, I suspect. > > TJG Thanks for replying Tim. Good point. jh From S.Mientki-nospam at mailbox.kun.nl Wed May 9 05:00:00 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Wed, 09 May 2007 11:00:00 +0200 Subject: view workspace, like in MatLab ? Message-ID: <46418D90.6030207@mailbox.kun.nl> hello, is there a function / library / IDE that displays all the user defined variables, like the workspace in MatLab ? thanks, Stef Mientki From beliavsky at aol.com Fri May 18 15:20:28 2007 From: beliavsky at aol.com (Beliavsky) Date: 18 May 2007 12:20:28 -0700 Subject: Python compared to other language In-Reply-To: References: Message-ID: <1179516027.425206.67680@o5g2000hsb.googlegroups.com> On May 18, 3:04 pm, scott wrote: > Hi all, > > I have been looking at the various programming languages available. I > have programed in Basic since I was a teenager and I also have a basic > understanding of C, but I want something better. > > Can anybody tell me the benefits and weaknesses of using Python? That question has been asked hundreds of times here -- read the archives of this group and language comparisons on the web, for example the one by Eric Raymond at http://www.faqs.org/docs/artu/languageschapter.html . Even better, try the language and draw your own conclusions. From gregcorradini at gmail.com Wed May 9 09:04:24 2007 From: gregcorradini at gmail.com (Greg Corradini) Date: Wed, 9 May 2007 06:04:24 -0700 (PDT) Subject: Boolean confusion In-Reply-To: References: <10393362.post@talk.nabble.com> Message-ID: <10393765.post@talk.nabble.com> On 2007-05-09, Greg Corradini wrote: > > Hello all, > I'm having trouble understanding why the following code evaluates as it > does: > >>>> string.find('0200000914A','.') and len('0200000914A') > 10 > True >>>> len('0200000914A') > 10 and string.find('0200000914A','.') > -1 > > In the 2.4 Python Reference Manual, I get the following explanation for > the > 'and' operator in 5.10 Boolean operations: > " The expression x and y first evaluates x; if x is false, its value is > returned; otherwise, y is evaluated and the resulting value is returned." > > Based on what is said above, shouldn't my first expression ( > string.find('0200000914A','.') and len('0200000914A') > 10) evaluate to > false b/c my 'x' is false? And shouldn't the second expression evaluate to > True? >The find method doesn't return a boolean, but returns the index where >the substring was found with -1 indicating it wasn't found. If you just >want to check wether one string is a substring of an other, use the in >operator. >>> '.' in '0200000914A' and len('0200000914A') > 10 False >>> len('0200000914A') > 10 and '.' in '0200000914A' False Thank you Diez and Antoon for demystifing this problem. I see where I've been going wrong. -- View this message in context: http://www.nabble.com/Boolean-confusion-tf3715438.html#a10393765 Sent from the Python - python-list mailing list archive at Nabble.com. From phd at phd.pp.ru Thu May 10 10:54:47 2007 From: phd at phd.pp.ru (Oleg Broytmann) Date: Thu, 10 May 2007 18:54:47 +0400 Subject: SQLObject 0.7.7 Message-ID: <20070510145447.GB18313@phd.pp.ru> Hello! I'm pleased to announce the 0.7.7 release of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.7.7 News and changes: http://sqlobject.org/docs/News.html What's New ========== News since 0.7.6 ---------------- Bug Fixes --------- * Fixed a bug in SQLRelatedJoin that ignored per-instance connection. * Fixed a bug in MySQL connection in case there is no charset in the DB URI. For a more complete list, please see the news: http://sqlobject.org/docs/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From kerny404 at gmail.com Mon May 14 07:46:33 2007 From: kerny404 at gmail.com (andrea) Date: 14 May 2007 04:46:33 -0700 Subject: Path python versions and Macosx In-Reply-To: <1178924996.452067.308320@h2g2000hsg.googlegroups.com> References: <1178915809.065874.133030@o5g2000hsb.googlegroups.com> <1178924996.452067.308320@h2g2000hsg.googlegroups.com> Message-ID: <1179143193.232099.285980@u30g2000hsc.googlegroups.com> On 12 Mag, 01:09, half.ital... at gmail.com wrote: > On May 11, 1:36 pm, andrea wrote: > > > > > Hi everyone, > > I use python on macosx with textmate as editor (great program). > > > I also use macport to install unix programs from the command line and > > I find it great too. > > Well I would like to have all my modules in the path when I'm using > > textmate AND when I use the commandline (ipython), but because > > textmate and the command line use different python versions they also > > search in different places.. > > > I found somewhere to write .pythonrc.py like this > > > #!/usr/bin/env python > > import sys > > PATH='/opt/local/lib/python2.4/site-packages/' > > sys.path.append(PATH) > > del sys > > > But it doesn't work either, I also tried to append this > > PATH="/Library/Frameworks/Python.framework/Versions/Current/bin:/opt/ > > local/lib/python2.4/site-packages:${PATH} > > to .bash_profile but nothing. > > > Where should I set this variables?? > > > Thanks a lot > > You can set environment variables for gui apps with this freeware:http://www.versiontracker.com/dyn/moreinfo/macosx/15073 > > You can edit some text files as well, but this thing just makes it > much easier. > > ~Sean Ok thanks, but why it doesn't work setting the .bash_profile?? What should I set manually theorically?? The problem is also that I have many modules for python 2.4 and trying to import them from the 2.5 of course gives errors.. I installed them with macports (compiling), how can I make them switch to 2.5??? thanks From gagsl-py2 at yahoo.com.ar Wed May 16 15:11:52 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 16 May 2007 16:11:52 -0300 Subject: tkinter button state = DISABLED References: <1179163831.016938.79840@w5g2000hsg.googlegroups.com> <1179175592.011635.103980@e51g2000hsg.googlegroups.com> <03f601c7979e$83559740$03000080@hendrik> Message-ID: En Wed, 16 May 2007 03:22:17 -0300, Hendrik van Rooyen escribi?: > "Gabriel Genellina" wrote: > >> Maybe there is a confusion here. You code above means that, when the >> event >> "The leftmost MOUSE BUTTON was released" happens over your BUTTON WIDGET >> b, your function will be called. > > I have never seen this working in Tkinter, unless the button was pressed > on the > widget > in question - and worse, once you have clicked down on a ButtonRelease > binding > you can move the mouse pointer anywhere you like, even out of the > application > and when you release it, the bound function is called... > > Its either a bug or a feature, I don't know. Uhmm... I'm not sure I understand you completely. I only said that the "command" is fired only when the mouse button is pressed on the widget, AND released inside the same widget. If both events don't happen in the same widget, "command" won't fire. Maybe you are saying the same thing... anyway I'm not a Tk expert. -- Gabriel Genellina From newsuser at stacom-software.de Tue May 29 08:03:06 2007 From: newsuser at stacom-software.de (Alexander Eisenhuth) Date: Tue, 29 May 2007 14:03:06 +0200 Subject: PyQt: Is signal / slot really working across threads? In-Reply-To: References: Message-ID: Ok, thanks. Phil Thompson schrieb: > On Tuesday 29 May 2007 11:58 am, Alexander Eisenhuth wrote: >> Hello pyqt users, >> >> i tried to use signal / slot across threads. With the following example I >> want to emit a signal when the thread loop is entered. The connected slot >> is never called. Why? >> >> Any help is very welcome ... >> >> Alexander >> >> import time >> import sys >> import PyQt4 >> from PyQt4.QtCore import (QObject, QThread) >> SIGNAL = PyQt4.QtCore.SIGNAL >> >> class CancelableQtThread_(QThread): >> >> def __init__(self): >> QThread.__init__(self) >> self.sigStarted = SIGNAL("sigStarted()") >> >> def run(self): >> print "Enter thread" >> self.emit(self.sigStarted) >> time.sleep(0.1) >> print "Leave thread" >> >> class TestSigSlot(QObject): >> >> def __init__(self): >> QObject.__init__(self) >> self._thread = CancelableQtThread_() >> self.connect(self._thread, self._thread.sigStarted, self.Called) >> self._thread.start() >> >> time.sleep(1.0) >> >> def Called(self): >> print "Called !" >> >> if __name__ == "__main__": >> obj = TestSigSlot() > > Signals across threads are implemented using the event loop. You don't have an > event loop running in your main thread - you don't even have a > QCoreApplication instance. > > Phil From yaogzhan at gmail.com Sat May 12 23:54:19 2007 From: yaogzhan at gmail.com (=?utf-8?B?6Km55YWJ6ICA?=) Date: 12 May 2007 20:54:19 -0700 Subject: Read from Windows Address Book (.wab file format) ? In-Reply-To: <1178999874.671116.318900@k79g2000hse.googlegroups.com> References: <1178994641.809507.127690@l77g2000hsb.googlegroups.com> <1178999874.671116.318900@k79g2000hse.googlegroups.com> Message-ID: <1179028459.918936.82370@e65g2000hsc.googlegroups.com> On May 13, 3:57 am, rynt wrote: > On May 12, 11:30 am, ??? wrote: > > > Hi all! > > > I wonder if there's any Python module that could read from .wab file. > > I googled but found nothing useful. Any idea? Thanks :) > > > Rio > > Hi Rio, > > Don't know if there's a python module for this, but this link, > > http://msdn2.microsoft.com/en-us/library/ms629361.aspx > > defines the MS API for the address book, so you could roll your own. > > If all you need is to read the data though, you could export the > address data into a CSV file (Python DOES have a module for this) or > VCard format. IIRC, someone on this newsgroup was talking about VCard > just the other day. > > HTH > > rynt Hi Rynt, Thanks for your help :) I looked the MSDN page but it seemed that at least I need Windows to use its DLL, while unfortunately I'm on Linux. I need to read (and later write) .wab from other Win users. CSV is fine, and that's how I am doing it right now. The problem is I cannot automate the process of exporting .wab to .csv on Linux. Also, I lose all the identity-property mapping in .wab since .csv is really a flat 2D table. Any other suggesions? :) Rio From giles_brown at hotmail.com Tue May 22 08:26:00 2007 From: giles_brown at hotmail.com (Giles Brown) Date: 22 May 2007 05:26:00 -0700 Subject: NOOOOB In-Reply-To: <1179829763.464614.123920@a26g2000pre.googlegroups.com> References: <1179829763.464614.123920@a26g2000pre.googlegroups.com> Message-ID: <1179836760.070095.5880@y2g2000prf.googlegroups.com> On 22 May, 11:29, jolly wrote: > Hey guys, > > I want to begin python. Does anyone know where a good starting point > is? > > Thanks, > Jem My suggestion is have a look at www.python.org and see if you can find what you're looking for. Giles From hardcoded.software at gmail.com Thu May 3 21:41:57 2007 From: hardcoded.software at gmail.com (Virgil Dupras) Date: 3 May 2007 18:41:57 -0700 Subject: Decorating class member functions In-Reply-To: <1178242415.863006.138860@l77g2000hsb.googlegroups.com> References: <1178241696.641350.292210@n59g2000hsh.googlegroups.com> <1178242415.863006.138860@l77g2000hsb.googlegroups.com> Message-ID: <1178242917.558709.20710@n59g2000hsh.googlegroups.com> On May 3, 9:33 pm, Virgil Dupras wrote: > On May 3, 9:21 pm, Andy Terrel wrote: > > > > > Okay does anyone know how to decorate class member functions? > > > The following code gives me an error: > > > Traceback (most recent call last): > > File "decorators2.py", line 33, in > > s.update() > > File "decorators2.py", line 13, in __call__ > > retval = self.fn.__call__(*args,**kws) > > TypeError: update() takes exactly 1 argument (0 given) > > > ------------------ > > > #! /usr/bin/env python > > > class Bugger (object): > > def __init__ (self, module, fn): > > self.module = module > > self.fn = fn > > > def __call__ (self,*args, **kws): > > ret_val = self.fn(*args,**kws) > > return ret_val > > > def instrument (module_name): > > ret_val = lambda x: Bugger(module_name, x) > > return ret_val > > > class Stupid: > > def __init__(self): > > self.val = 1 > > > @instrument("xpd.spam") > > def update(self): > > self.val += 1 > > > s = Stupid() > > s.update() > > A decorator is a function that takes one single parameter: a function. > "instrument" must return a decorator. Oh wait, I just embarrassed myself. Nevermind my last post. From sjmachin at lexicon.net Sat May 5 17:44:59 2007 From: sjmachin at lexicon.net (John Machin) Date: 5 May 2007 14:44:59 -0700 Subject: Python regular expressions just ain't PCRE In-Reply-To: <1178380335.646708.260540@h2g2000hsg.googlegroups.com> References: <1178323901.381993.47170@e65g2000hsc.googlegroups.com> <1178380335.646708.260540@h2g2000hsg.googlegroups.com> Message-ID: <1178401499.480169.140940@e65g2000hsc.googlegroups.com> On May 6, 1:52 am, Wiseman wrote: > On May 5, 5:12 am, "Terry Reedy" wrote: > > > I believe the current Python re module was written to replace the Python > > wrapping of pcre in order to support unicode. > > I don't know how PCRE was back then, but right now it supports UTF-8 > Unicode patterns and strings, and Unicode character properties. Maybe > it could be reintroduced into Python? "UTF-8 Unicode" is meaningless. Python has internal unicode string objects, with comprehensive support for converting to/from str (8-bit) string objects. The re module supports unicode patterns and strings. PCRE "supports" patterns and strings which are encoded in UTF-8. This is quite different, a kludge, incomparable. Operations which inspect/ modify UTF-8-encoded data are of interest only to folk who are constrained to use a language which has nothing resembling a proper unicode datatype. > > At least today, PCRE supports recursion and recursion check, > possessive quantifiers and once-only subpatterns (disables > backtracking in a subpattern), callouts (user functions to call at > given points), and other interesting, powerful features. The more features are put into a regular expression module, the more difficult it is to maintain and the more the patterns look like line noise. There's also the YAGNI factor; most folk would restrict using regular expressions to simple grep-like functionality and data validation -- e.g. re.match("[A-Z][A-Z]?[0-9]{6}[0-9A]$", idno). The few who want to recognise yet another little language tend to reach for parsers, using regular expressions only in the lexing phase. If you really want to have PCRE functionality in Python, you have a few options: (1) create a wrapper for PCRE using e.g. SWIG or pyrex or hand- crafting (2) write a PEP, get it agreed, and add the functionality to the re module (3) wait until someone does (1) or (2) for free (4) fund someone to do (1) or (2) HTH, John From steve at holdenweb.com Sat May 19 13:38:04 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 19 May 2007 13:38:04 -0400 Subject: docs patch: dicts and sets In-Reply-To: <1179593927.503393.127350@u30g2000hsc.googlegroups.com> References: <_5-dnU7aIN73j9LbnZ2dnUVZ_uCinZ2d@comcast.com> <1179593927.503393.127350@u30g2000hsc.googlegroups.com> Message-ID: 7stud wrote: > On May 19, 9:06 am, Steven Bethard wrote: >> Alan Isaac wrote: >>> I submitted the language based on Bill and Carsten's proposals: >>> https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1721372&... >>> That language has been rejected. >>> You many want to read the discussion and see if >>> acceptible language still seems discoverable. >> Seems to me that you're focusing on the wrong part of the docs. The >> source of this "bug" is not sets or dicts, but the default __hash__ >> method implementation. Why don't you propose adding something like: >> >> The default __hash__ method is based on an object's id(), and can >> therefore change between different iterations of the same program. >> >> to the docs for __hash__: >> >> http://docs.python.org/ref/customization.html >> >> Then if you really feel you need to add something for sets and dicts, >> you can add a cross-reference to the __hash__ docs. >> >> STeVe > > > Here's an idea--add All the proposed changes to the docs. Why not > allow user's to add any explanations to the docs that they want? Then > readers can choose the explanations that make the most sense to them. > It would eliminate endless, petty discussions about what minutiae are > more important, and it would allow people to spend their time on more > productive efforts. And it would improve the docs exponentially. > Except in those instances where users added information that was explicitly wrong. Which any reader of this newsgroup knows is all too easy to do. So there would need to be some editorial control. Which would take effort that may not currently be available. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From kirk at jobspam/mapssluder.net Fri May 18 13:44:41 2007 From: kirk at jobspam/mapssluder.net (Kirk Job Sluder) Date: Fri, 18 May 2007 17:44:41 GMT Subject: (Modular-)Application Framework / Rich-Client-Platform in Python References: <8ea03$464dc950$d443bb3a$5229@news.speedlinq.nl> Message-ID: Stef Mientki writes: > I took a look at Eclipse page you mentioned but after reading the > first page I still don't understand what you mean (and I never read > beyond the first page ;-). > With a plugin system, I can think of a complete operating system, > or I can think of something like a DTP, or simply Word, > or I can think of something like Signal WorkBench > etc. The approach taken by Eclipse is exactly like that taken by emacs so many years ago of creating a minimalist framework that offers a bare bones user interface and services for running libraries. Everything else is a plug-in library that changes the behavior of that interface. So if you want an editor for language "foo," you would customize a "view" interface to display foo objects, and an "editor" interface to display and modify "foo" text. You might customize other "view" objects to display documentation, compilation, and debugging information. (The fact that Eclipse and emacs are both rather lean programs is obsucred by the sheer quantity of plug-ins that have become a part of the standard installation.) > cheers, > Stef Mientki > > -- Kirk Job Sluder From a.schmolck at gmail.com Sun May 13 18:26:25 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: Sun, 13 May 2007 23:26:25 +0100 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: Jarek Zgoda writes: > Martin v. L?wis napisa?(a): > >> So, please provide feedback, e.g. perhaps by answering these >> questions: >> - should non-ASCII identifiers be supported? why? > > No, because "programs must be written for people to read, and only > incidentally for machines to execute". Using anything other than "lowest > common denominator" (ASCII) will restrict accessibility of code. This is > not a literature, that requires qualified translators to get the text > from Hindi (or Persian, or Chinese, or Georgian, or...) to Polish. > > While I can read the code with Hebrew, Russian or Greek names > transliterated to ASCII, I would not be able to read such code in native. Who or what would force you to? Do you currently have to deal with hebrew, russian or greek names transliterated into ASCII? I don't and I suspect this whole panic about everyone suddenly having to deal with code written in kanji, klingon and hieroglyphs etc. is unfounded -- such code would drastically reduce its own "fitness" (much more so than the ASCII-transliterated chinese, hebrew and greek code I never seem to come across), so I think the chances that it will be thrust upon you (or anyone else in this thread) are minuscule. Plenty of programming languages already support unicode identifiers, so if there is any rational basis for this fear it shouldn't be hard to come up with -- where is it? 'as BTW, I'm not sure if you don't underestimate your own intellectual faculties if you think couldn't cope with greek or russian characters. On the other hand I wonder if you don't overestimate your ability to reasonably deal with code written in a completely foreign language, as long as its ASCII -- for anything of nontrivial length, surely doing anything with such code would already be orders of magnitude harder? From jstroud at mbi.ucla.edu Thu May 3 15:34:53 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 03 May 2007 12:34:53 -0700 Subject: Article on wxPython ToolKit for Mac OS X In-Reply-To: <1178204986.383057.264690@y80g2000hsf.googlegroups.com> References: <1178204986.383057.264690@y80g2000hsf.googlegroups.com> Message-ID: miah_gbg wrote: > Hi there! > > Just wanted to let people know in this group that I have recently > (April 24th) published an introductory article on wxPython and Mac OS > X. It is available here: http://www.macdevcenter.com/ > > Hope someone finds it useful. > > Regards, > > Jeremiah > For the impatient: http://tinyurl.com/2z6qeq James From john at datavoiceint.com Tue May 8 22:50:38 2007 From: john at datavoiceint.com (HMS Surprise) Date: 8 May 2007 19:50:38 -0700 Subject: String parsing In-Reply-To: References: <1178672992.522463.228620@l77g2000hsb.googlegroups.com> <1178676374.081202.74850@e51g2000hsg.googlegroups.com> Message-ID: <1178679038.451017.139290@p77g2000hsh.googlegroups.com> Thanks all. Carsten, you are here early and late. Do you ever sleep? ;^) From walterbyrd at iname.com Thu May 3 22:03:00 2007 From: walterbyrd at iname.com (walterbyrd) Date: 3 May 2007 19:03:00 -0700 Subject: Can I use Python instead of Joomla? In-Reply-To: <463a1708$0$14565$426a34cc@news.free.fr> References: <1178138925.498663.252920@o5g2000hsb.googlegroups.com> <4639173e$0$2415$426a74cc@news.free.fr> <1178204011.101042.81880@l77g2000hsb.googlegroups.com> <463a1708$0$14565$426a34cc@news.free.fr> Message-ID: <1178244180.655884.65490@o5g2000hsb.googlegroups.com> On May 3, 11:08 am, Bruno Desthuilliers wrote: > I'm not sure integrating CakePHP stuff into something like Joomla or > Drupal will be that easy. I don't know either. But, there are projects called "jake" and "drake" which are specifically geared toward intergrating cakephp with joomla and drupal, respectively. From showell30 at yahoo.com Sat May 26 21:48:45 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sat, 26 May 2007 18:48:45 -0700 (PDT) Subject: ten small Python programs In-Reply-To: <1180229019.873381.52800@m36g2000hse.googlegroups.com> Message-ID: <603384.96362.qm@web33514.mail.mud.yahoo.com> --- Paul McGuire wrote: > I ***love*** this "10 Little Programs" idea! As > soon as I get a > breathing space, I'm going to add a "10 Little > Parsers" page to the > pyparsing wiki! > Thanks. :) I'm thinking you could actually have a progression from a 1 line program up to a 50-line program. The number 50 is kind of arbitrary, but my gut says that by a 50-line program, you will have demonstrated almost every useful concept. > > > > > > class ShoppingCart: > > > def __init__(self): self.items = [] > > > def buy(self, item): > self.items.append(item) > > > def boughtItems(self): return self.items > > > myCart = ShoppingCart() > > > myCart.buy('apple') > > > myCart.buy('banana') > > > print myCart.boughtItems() > > If you want to nitpick, I'd rather go after the > one-liner methods with > the body on the same line as the def statement. > Agreed. I didn't like that either. > How's this for a better non-trivial method example: > > MAX_ITEMS_FOR_EXPRESS_LANE = 10 > def canUseExpressLane(self): > return (len(self.items) <= > MAX_ITEMS_FOR_EXPRESS_LANE) > > or call it "can_use_express_lane" if you must. > Yep, that sounds more in the ballpark of what I'd want to show, versus a weakish class that just encapulates a list. Here's my challenge to whoever wants to take it--write (or find) a program with 20 or fewer lines that sufficiently motivates the need for classes, has decent Python style, and is newbie friendly. The tutorial has this example, which is useful for demonstrating the syntax of classes, but it doesn't actually do anything interesting: class MyClass: "A simple example class" i = 12345 def f(self): return 'hello world' It also has a ComplexNumber class, but I don't want to scare away mathphobes. It does have this idiom, which I think is worth putting somewhere into the progression. class Employee: pass john = Employee() # Create an empty employee record # Fill the fields of the record john.name = 'John Doe' john.dept = 'computer lab' john.salary = 1000 ____________________________________________________________________________________Take the Internet to Go: Yahoo!Go puts the Internet in your pocket: mail, news, photos & more. http://mobile.yahoo.com/go?refer=1GNXIC From luismgz at gmail.com Wed May 16 23:55:54 2007 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M=2E_Gonz=E1lez?=) Date: 16 May 2007 20:55:54 -0700 Subject: Python Web Programming - looking for examples of solid high-traffic sites In-Reply-To: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> Message-ID: <1179374154.033829.206240@u30g2000hsc.googlegroups.com> On May 16, 6:04 pm, Victor Kryukov wrote: > Hello list, > > our team is going to rewrite our existing web-site, which has a lot of > dynamic content and was quickly prototyped some time ago. > > Today, as we get better idea of what we need, we're going to re-write > everything from scratch. Python is an obvious candidate for our team: > everybody knows it, everybody likes it, it has *real* objects, nice > clean syntax etc. > > Our main requirement for tools we're going to use is rock-solid > stability. As one of our team-members puts it, "We want to use tools > that are stable, has many developer-years and thousands of user-years > behind them, and that we shouldn't worry about their _versions_." The > main reason for that is that we want to debug our own bugs, but not > the bugs in our tools. > > Our problem is - we yet have to find any example of high-traffic, > scalable web-site written entirely in Python. We know that YouTube is > a suspect, but we don't know what specific python web solution was > used there. > > TurboGears, Django and Pylons are all nice, and provides rich features > - probably too many for us - but, as far as we understand, they don't > satisfy the stability requirement - Pylons and Django hasn't even > reached 1.0 version yet. And their provide too thick layer - we want > something 'closer to metal', probably similar to web.py - > unfortunately, web.py doesn't satisfy the stability requirement > either, or so it seems. > > So the question is: what is a solid way to serve dynamic web pages in > python? Our initial though was something like python + mod_python + > Apache, but we're told that mod_python is 'scary and doesn't work very > well'. > > And althoughhttp://www.python.org/about/quotes/lists many big names > and wonderful examples, be want more details. E.g. our understanding > is that Google uses python mostly for internal web-sites, and > performance is far from perfect their. YouTube is an interesting > example - anybody knows more details about that? > > Your suggestions and comments are highly welcome! > > Best Regards, > Victor. Take a look at reddit.com . It's been developed with WEBPY and it receives millions of visits every day. There are also many sites built with Django (check their website) with a lot of traffic and very good performance And I'm sure other frameworks can show other success stories... just check their websites. Luis From johnjsal at NOSPAMgmail.com Wed May 2 11:37:14 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 02 May 2007 11:37:14 -0400 Subject: Any way to refactor this? In-Reply-To: <461ff01c$0$29118$426a74cc@news.free.fr> References: <461fe75c$0$11278$c3e8da3@news.astraweb.com> <461ff01c$0$29118$426a74cc@news.free.fr> Message-ID: <4638af08$0$448$c3e8da3@news.astraweb.com> Bruno Desthuilliers wrote: > From a purely efficiency POV, there are some obviously possible > improvements. The first one is to alias visual.cylinder, so you save on > lookup time. The other one is to avoid useless recomputation of > -hatch_length and hatch_length*2. > > def _create_3D_xhatches(): > cy = visual.cylinder > for x in xrange(-axis_length, axis_length + 1): > if x == 0: continue > b = -hatch_length > c = hatch_length*2 > cy(pos=(x, b, 0), axis=(0, c, 0), radius=hatch_radius) > cy(pos=(x, 0, b), axis=(0, 0, c), radius=hatch_radius) > cy(pos=(b, x, 0), axis=(c, 0, 0), radius=hatch_radius) > cy(pos=(0, x, b), axis=(0, 0, c), radius=hatch_radius) > cy(pos=(b, 0, x), axis=(c, 0, 0), radius=hatch_radius) > cy(pos=(0, b, x), axis=(0, c, 0), radius=hatch_radius) Doesn't this call to "cy" still call the function multiple times? From kelvin.you at gmail.com Tue May 29 00:57:39 2007 From: kelvin.you at gmail.com (=?gb2312?B?yMvR1MLkyNXKx8zs0cSjrM37vKvM7NHEsru8+7zS?=) Date: 28 May 2007 21:57:39 -0700 Subject: how to print the GREEK CAPITAL LETTER delta under utf-8 encoding Message-ID: <1180414659.066482.236370@i38g2000prf.googlegroups.com> I lookup the utf-8 form of delta from the link. http://www.fileformat.info/info/unicode/char/0394/index.htm and then I want to print it in the python ( I work under windows) #!/usr/bin/python #coding=utf-8 print "\xce\x94" but the result is not the 'delta' but an unknown character. From arkanes at gmail.com Thu May 31 13:10:07 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 31 May 2007 12:10:07 -0500 Subject: Python memory handling In-Reply-To: <1180627331.756615.132650@k79g2000hse.googlegroups.com> References: <1180611604.247696.149060@h2g2000hsg.googlegroups.com> <1180627331.756615.132650@k79g2000hse.googlegroups.com> Message-ID: <4866bea60705311010t31aa5364u89867354d1844b37@mail.gmail.com> > Like: > import pool > pool.free() > pool.limit(size in megabytes) > > Why not letting the user choosing that, why not giving the user more > flexibility ? > I will try later under linux with the latest stable python > > Regards, > FP > The idea that memory allocated to a process but not being used is a "cost" is really a fallacy, at least on modern virtual memory sytems. It matters more for fully GCed languages, where the entire working set needs to be scanned, but the Python GC is only for breaking refcounts and doesn't need to scan the entire memory space. There are some corner cases where it matters, and thats why it was addressed for 2.5, but in general it's not something that you need to worry about. From carlos.hanson at gmail.com Fri May 4 09:40:22 2007 From: carlos.hanson at gmail.com (Carlos Hanson) Date: Fri, 4 May 2007 06:40:22 -0700 Subject: Organizing code - import question In-Reply-To: <463A0EC6.3010008@bryant.edu> References: <1178207662.200235.252900@e65g2000hsc.googlegroups.com> <463A0EC6.3010008@bryant.edu> Message-ID: On 5/3/07, Brian Blais wrote: > Carlos Hanson wrote: > > It looks like you need __init__.py in MyPackage. Then you can import > > starting with MyPackage. For example, you might use one of the > > following: > > > > import MyPackage > > from MyPackage.Common import * > > etc > > > > that means that MyPackage must be in the sys path too? It doesn't seem like a > contained-module sees the container in any way. > That is exactly right. Without being in the sys path, Python does not know where to look to resolve the import statements. -- Carlos Hanson From bob at snee.com Tue May 22 20:37:23 2007 From: bob at snee.com (bob at snee.com) Date: 22 May 2007 17:37:23 -0700 Subject: trying to gzip uncompress a StringIO In-Reply-To: <46536E01.2080702@lexicon.net> Message-ID: <1179880643.556124.93910@p47g2000hsd.googlegroups.com> Perfect, thanks! Now I have a working WMF file and everything. Bob From srinivas.gundelli at googlemail.com Tue May 15 08:51:39 2007 From: srinivas.gundelli at googlemail.com (IT Recruiter) Date: 15 May 2007 05:51:39 -0700 Subject: Urgently looking for Python with Django Developers - London Message-ID: <1179233499.932473.216830@n59g2000hsh.googlegroups.com> About Me: I am an IT Resourcing Consultant providing unique staffing services to my client based in London. I am looking for a superstar using his web development skills to manage and improve the frontend as well as backend coding of the website. Client: A web based mobile auction and shopping site primarily built with python on Django framework The Superstar: Should be involved in Django / Python designing models, testing Django applications, writing template tags, views, middleware and decorators. Should know the principle of Don't Repeat Yourself (DRY), separation of URLs. Be updated with the Pythonista and advanced language features. What it takes to be a Super... Superstar : Very well associated with the web : Knows Semantic HTML Super CSS skills Good JS Prototype/ Behaviour/ Progressive enhancement Appreciation of user experience, building a consistent,clear User Interface (UI) Know-how the mobile tech': WAP 2.0/ XHTML-MP SMS/ MMS The position is permanent in LONDON Pay the Superstar as per the current market For detailed responsibilities email me with a copy of your profile at srinivas.gundelli at googlemail.com or call +44(0)1707 752 000 Dont brush aside this exciting opportunity !! Do let our interested friends know ... Cheers, Srini From tommy.nordgren at comhem.se Sat May 19 13:31:26 2007 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Sat, 19 May 2007 19:31:26 +0200 Subject: No Python for Blackberry? In-Reply-To: <1179537588.505753.275200@q75g2000hsh.googlegroups.com> References: <1179537588.505753.275200@q75g2000hsh.googlegroups.com> Message-ID: On 19 maj 2007, at 03.19, walterbyrd wrote: > I could not find a version of Python that runs on a Blackberrry. > > I'm just amazed. A fairly popular platform, and no Python > implementation? > Download the sources and try compiling it yourself. On most platforms Expand the archive. Then either: Give the command ./configure (in the exanded python directory) Or create a directory (For example 'build-python') it the directory that CONTAINS the python distribution directory. And then execute the command ..//configure (in the directory 'build' of the previous step) then give the commands: make make check sudo make install [whereupon the systom will ask for your administrator password] ------------------------------------- This sig is dedicated to the advancement of Nuclear Power Tommy Nordgren tommy.nordgren at comhem.se From deets at nospam.web.de Tue May 22 07:54:57 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 22 May 2007 13:54:57 +0200 Subject: Simple omniORBpy example throws exception with error 0x41540002 References: <1179833680.255391.198490@x18g2000prd.googlegroups.com> Message-ID: <5bg40hF2moliaU1@mid.uni-berlin.de> Samuel wrote: > Hi, > > I am trying to get the files from this tutorial to work: > http://www.grisby.org/presentations/py10code.html > > Direct link to the files: > http://www.grisby.org/presentations/py10code/adder.idl > http://www.grisby.org/presentations/py10code/adderServer.py > > It produces the following error: > > $ omniidl -bpython adder.idl && python adderServer.py > Traceback (most recent call last): > File "adderServer.py", line 23, in > nameRoot = nameRoot._narrow(CosNaming.NamingContext) > File "/usr/lib/python2.5/site-packages/omniORB/CORBA.py", line 667, > in _narrow > return _omnipy.narrow(self, dest._NP_RepositoryId) > omniORB.CORBA.TRANSIENT: Minor: 0x41540002, COMPLETED_NO. > > According to Google this might mean "Connect failed", however, I don't > understand why the server would open a connection. I expected it to > simply listen on a socket, but I probably just don't understand how it > works. > > Can anyone please explain this? It indeed does open a connection - because it wants to register with a NameServer. This is basically a bootstrapping-problem. You have to somehow distribute object references to connect clients to servers. You can do so by using persistent IORs and configure these for the client. You can also place them on a network-location somehow. Or you can configure a name-server for your ORB, and if that name-server is the same for the server, you can look-up an object reference there. This is what the example-code tries to do. So - the easiest solution for now would be to start the omniORB nameserver. On my ubuntu, that's a matter of installing it via apt. Diez From jorgen.maillist at gmail.com Thu May 24 04:32:32 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Thu, 24 May 2007 10:32:32 +0200 Subject: [Fwd: Re: managed lists?] In-Reply-To: <46534b25$0$19922$426a74cc@news.free.fr> References: <4651fe96$0$24671$426a34cc@news.free.fr> <11e49df10705220013q11c35e6axba72cc4227401ac2@mail.gmail.com> <46534b25$0$19922$426a74cc@news.free.fr> Message-ID: <11e49df10705240132l365bee3cy9d5ba5e8f0e57755@mail.gmail.com> @ Larry, As much as I like to follow the idiom that Python has, I do not see the usefulness of making an add function that checks the interface that other objects might need. Besides the fact it is a bit overhead and not to mention performance draining, in an application that I develop myself, without plugin architecture (not yet) etc, it is a bit much to do that. I agree with the writing C in Python, it is all I know, because that is the language I started with. This is my first big project and most certainly when evaluating this when it is finished I will come to the conclusion it was all for nothing ;-) I will change to extend() and maybe drop the type safety, but I do wish to keep the list functionality as I find it more logical to write song.categories.append() Then creating a method in song called AddCategory() and kind of duplicating the list functionality there. Thank you for the guide lines and the nice comments! They are really helpful. @ Bruno, > list. The right solution IMHO is to *not* expose these lists as part of > the interface - after all, the fact that tabs and tunes are stored in > lists is an implementation detail -, and to add the necessary API to the > Song object - ie : Song.add_tune, Song.add_tab, Song.iter_tunes, > Song.iter_tabs, etc. Then you just have to add some assert statements in > the add_XXX methods so you'll be warned at the right time when some part This is how I did it before, I created Song.AddTab, Song.DeleteTab, then there was a category class which also needed adding, deleting, clearing, and soon my whole Song object was filled with relational methods which were basically a copy of the list, with a check on the presence of the class in the list. Then I realized, a managed list with self-check capability solves this because I do not like to duplicate code, but now that I think of it, the type check might be a bit too much. Like said, the list solution you described and the solution I use, are basically the same, I encapsulated a list [] in a class, with some extra methods to warn the 'owner' of the list that something is changed. > Oh, yes, while we're at it, and in case you don't know yet: the Python > idiom for implementation attributes (including methods - remember, > everything is an object) is to prefix them with a single underscore. Ok, but why is that? I do know semi-private symbols can be realised using two underscores, and if I wish to hide a list / index / etc so it cannot accidentally changed, would I not use double underscores? Thanks for your extensive help! - Jorgen From jyoung79 at kc.rr.com Sun May 20 23:52:03 2007 From: jyoung79 at kc.rr.com (jay) Date: Sun, 20 May 2007 22:52:03 -0500 Subject: A few questions Message-ID: Hi, I'm totally new to Python and was hoping someone might be able to answer a few questions for me: 1. What are your views about Python vs Perl? Do you see one as better than the other? 2. Is there a good book to start with while learning Python? I'm currently reading 'Python Essential Reference' by David M. Beazley. So far it looks like a pretty good book, but would like more tutorials to work with (I've also been reading through the tutorials at 'python.org' which has some excellent stuff!). 3. Currently, I write most of my code with Xcode (on the Mac platform) using Applescript. This gives me GUI capabilities. Is there anything you'd recommend that I could use for Python that would give me a GUI interface? I'd like this to be able to work for both the Mac and Windows platforms. I've been reading a little about 'Claro Graphics Toolkit' and 'PyGUI'... would you recommend either of those? I'll be writing code on a Mac so I need something that will run on that system. Thanks for looking at my questions. Jay From martin at v.loewis.de Thu May 17 18:50:30 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 18 May 2007 00:50:30 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <464C5382.6080403@v.loewis.de> <1179423799.254286.294930@w5g2000hsg.googlegroups.com> <464CD15A.9070409@v.loewis.de> Message-ID: <464CDC36.1030709@v.loewis.de> Neil Hodgson schrieb: > Martin v. L?wis: > >> ... regardless of whether this PEP gets accepted >> or not (which it just did). > > Which version can we expect this to be implemented in? The PEP says 3.0, and the planned implementation also targets that release. Regards, Martin From gagsl-py2 at yahoo.com.ar Sat May 12 00:22:20 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 12 May 2007 01:22:20 -0300 Subject: os.popen on windows: loosing stdout of child process References: Message-ID: En Sat, 12 May 2007 00:46:16 -0300, Greg Ercolano escribi?: > When I use os.popen(cmd,'w'), I find that under windows, the stdout > of the child process disappears, instead of appearing in the DOS window > the script is invoked from. eg: [...] > When I run the same python program on a unix box, the output > from 'nslookup' appears in the terminal, as I'd expect. > > Shouldn't popen() be consistent in its handling of the child's > stdout and stderr across platforms? > > Maybe I'm missing something, being somewhat new to python, but > an old hand at unix and win32 and functions like popen(). Didn't > see anything in the docs for popen(), and I googled around quite > a bit on the web and groups for eg. 'python windows popen stdout lost' > and found nothing useful. Using the subprocess module is the recommended approach (as you can see on the os.popen documentation) and does what you want: C:\TEMP>type foo2.py import subprocess p = subprocess.Popen("nslookup", stdin=subprocess.PIPE) p.stdin.write("google.com\n") p.stdin.close() C:\TEMP>python foo2.py C:\TEMP>Servidor predeterminado: coyote.softlabbsas.com.ar Address: 192.168.0.116 > Servidor: coyote.softlabbsas.com.ar Address: 192.168.0.116 Respuesta no autoritativa: Nombre: google.com Addresses: 64.233.187.99, 64.233.167.99, 72.14.207.99 > C:\TEMP> For more info about subprocess usage, see http://docs.python.org/lib/module-subprocess.html -- Gabriel Genellina From kyosohma at gmail.com Wed May 23 15:21:17 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 23 May 2007 12:21:17 -0700 Subject: Namespace issue In-Reply-To: Message-ID: <1179948076.962679.258870@k79g2000hse.googlegroups.com> On May 23, 1:20 pm, Ritesh Raj Sarraf wrote: > Hi, > > I need a little help in understanding how Namespaces and scoping works with > Classes/Functions in Python. > > Here's my code: > class FetchData: > def __init__(self, dataTypes=["foo", "bar", "spam"], archive=False): > > self.List = [] > self.Types = dataTypes > > if archive: > self.Archiver = Archiver(True) > > def FetchData(self, PackageName, Filename=None): > > try: > import my_module > except ImportError: > return False > > if Filename != None: > try: > file_handle = open(Filename, 'a') > except IOError: > sys.exit(1) > > (amnt, header, self.List) = my_module.get_data(PackageName) > > This is the only way this code will work. > > As per my understanding, the bad part is that on every call of the method > FetchData(), an import would be done. > > To not let that happen, I can put the import into __init__(). But when I put > in there, I get a NameError saying that my_module is not available even > though it got imported. > All I noticed is that the import has to be part of the method else I end up > getting a NameError. But always importing my_module is also not good. > > What is the correct way of doing this ? > IMO, ideally it should be part of __init__() and be imported only when the > class is instantiated. > > Thanks, > Ritesh > -- > If possible, Please CC me when replying. I'm not subscribed to the list. The reason you can't put the import into the __init__ is that that is also a method, so the imported module is only available to that method's namespace. This is also true if you had put the import into any other method. The only way to make it global is to put your class into its own module and put the import before the class creation. Depending on how your instantiating the class, you may not need to worry about the whole importing thing. If you have all your code like this: class something(obj): def __init__(self): #do something def grabData(self): # do something import module x = something() y = something() Then the module gets imported only once. See http://www.python.org/search/hypermail/python-1993/0342.html I'm not sure what happens when you have one module calling another module that import a third module though. Mike From quasi at null.set Mon May 7 17:22:37 2007 From: quasi at null.set (quasi) Date: Mon, 07 May 2007 16:22:37 -0500 Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> <08qk33t594ih0ulmjmev90d22lkfnotgoe@4ax.com> <463C2A3A.8332D211@hotmail.com> <0k8p33h90bp5tfajedb4bmd2eik8gfi2ho@4ax.com> Message-ID: On Mon, 7 May 2007 10:55:55 -0400, James Beck wrote: >In article <0k8p33h90bp5tfajedb4bmd2eik8gfi2ho at 4ax.com>, quasi at null.set >says... >> On Sat, 05 May 2007 07:54:50 +0100, Eeyore >> wrote: >> >> > >> > >> >quasi wrote: >> > >> >> Gib Bogle wrote: >> >> >> >> >Ah, so the firefighters were in on the conspiracy! >> >> >> >> No, but the firefighters are very much aware that there is more to >> >> 9/11 than has been officially revealed. >> >> >> >> This is even more true at Pentagon. The firefighters there brought >> >> dogs trained to search for survivors and/or remains >> > >> >Sounds like good practice. >> > >> > >> >> and found nothing. >> > >> >And the significance of this is ? >> >> The plane was supposed to have passengers. >> >> quasi >> >Yep, and they found them all, therefore, there were none for the dogs to >find. You pretty much made that up. They found nothing -- no bodies, no body parts, no blood, no bones, no luggage, no rings (do gold rings melt at jet fuel temperatures?), no jewelry (do diamonds melt at jet fuel temperatures?), no plane seats, no silverware (ok, maybe they only had plastic). In other words, an immediate mystery to the firefighters was the lack of any indication that the plane had passengers. Even if you believe that most of the passengers were essentially incinerated, it's not believable that all of them were. Some of the bodies should have been recoverable right at the scene. Weeks later, parts of the wreckage were supposedly "analyzed" at a government lab, and the official report claims they were able to isolate DNA for many of the passengers. It doesn't ring true. quasi From stefan.sonnenberg at pythonmeister.com Mon May 7 11:16:09 2007 From: stefan.sonnenberg at pythonmeister.com (Stefan Sonnenberg-Carstens) Date: Mon, 7 May 2007 17:16:09 +0200 (CEST) Subject: problem with quoted strings while inserting into varchar field of database. In-Reply-To: <1178549447.3360.24.camel@dot.uniqsys.com> References: <1178475772.423687.118800@e65g2000hsc.googlegroups.com> <1178526655.933789.294700@h2g2000hsg.googlegroups.com> <1178530363.516882.228380@l77g2000hsb.googlegroups.com> <1178548015.856661.308070@u30g2000hsc.googlegroups.com> <1178549447.3360.24.camel@dot.uniqsys.com> Message-ID: <1068189.22533.BlRUCl8VTQA=.1178550969.squirrel@webmailer.hosteurope.de> On Mo, 7.05.2007, 16:50, Carsten Haese wrote: > On Mon, 2007-05-07 at 07:26 -0700, Daniele Varrazzo wrote: >> > >> >> > cur.execute("INSERT INTO datatable (data) VALUES (%s);", >> > >> >> > (pickled_data,)) >> >> > %s is not a placeholder IMHO. >> >> > What happens when using %s is, that the string given will be inserted >> where >> > %s is; that is something python does as with every print or such. >> >> It is indeed. The behavior you describe would be true if i had used >> the "%" operator. Read better what i have written: There is no "%" >> operator. > > This confusion is precisely why I think the (py)format paramstyles > should be deprecated in a future version of the DB-API spec. Question > marks make it immediately obvious that something other than string > formatting is happening, and if I'm not mistaken, question marks are SQL > standard. > > -- > Carsten Haese > http://informixdb.sourceforge.net > > > -- > http://mail.python.org/mailman/listinfo/python-list > > At least, qmark style is well known to people working with prepared stmts etc. They look "natural" - and avoid (even my!) mistakes. On python-forum.de there was a discussion regarding inserting data into a sqlite db recently. If I remember correctly the guy was using the "%s" % data approach (yes, % operator) and failed. The pysqlite driver did the right thing using the qmark style. Even in the "Python phrasebook" there are examples of this ugly style. A deprecation warning for now would be fine. From kylotan at gmail.com Wed May 30 10:15:05 2007 From: kylotan at gmail.com (Ben Sizer) Date: 30 May 2007 07:15:05 -0700 Subject: Windows build of PostgreSQL library for 2.5 Message-ID: <1180534505.421166.83700@q66g2000hsg.googlegroups.com> I've been looking for a Windows version of a library to interface to PostgreSQL, but can only find ones compiled under Python version 2.4. Is there a 2.5 build out there? -- Ben Sizer From bignose+hates-spam at benfinney.id.au Mon May 21 20:28:01 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 22 May 2007 10:28:01 +1000 Subject: Types in Python (was: managed lists?) References: Message-ID: <87bqgdg0ry.fsf@benfinney.id.au> "Jorgen Bodde" writes: > I still have to get used to the lack of (strong) types, Python does not have weak types, it has strong types. An object knows its type, and the rules on coercion to other types are minimal and well-defined. Python does not have static typing, it has dynamic typing. A name can be bound and re-bound to any type of object through the lifetime of the program. or do a web search for: weak strong dynamic static python > and it sometimes frustates me to no end that a wrongly given > argument explodes somewhere deep inside my application without > giving any clue why it blew up in the first place.. I'm not sure what you mean here. The exception raised should say what the problem is; can you give an example of what you're talking about? > Right now i have a list in a class that I export as a member > variable to the outside world, it is a standard list (e.g. [] ) but > I wish to have a stronger type checking when adding objects, that > only some objects are allowed and others are not. This is a poor idiom in Python. The object system allows powerful polymorphism: the only thing that your application should be checking is if the objects *can be used* in a particular way, not that they belong to a specific subset of the type hierarchy. > It was quite easy to create it, but I wonder if there is already a > standard solution for lists that carry only objects of a single > type? Wrap the code that *uses* that list in a 'try: ... except FooError:' structure, to catch and report errors when the objects in the list don't exhibit the correct behaviour. This way, if Frank extends a totally unrelated type so that it behaves as your code expects (e.g. has the appropriate attributes, has methods that respond appropriately), he can insert objects of that type into the list and it will work correctly. > I solved it now, by using isinstance() and giving the class name as > argument to the list This breaks polymorphism: objects of the type Frank created will fail this test, even though they will work perfectly well without that heavy-handed isinstance() restriction. > (thank god that everything in Python is an object ;-) ) where I > check against when adding, but re-inventing the wheel is silly > ofcourse Indeed. Hopefully you will allow for polymorphism in your code. -- \ "Probably the earliest flyswatters were nothing more than some | `\ sort of striking surface attached to the end of a long stick." | _o__) -- Jack Handey | Ben Finney From kensmith at rahul.net Thu May 3 09:41:20 2007 From: kensmith at rahul.net (MooseFET) Date: 3 May 2007 06:41:20 -0700 Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? In-Reply-To: <1178169863.602236.287420@p77g2000hsh.googlegroups.com> References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> <57li33hegq8g81bbcru09gagbpqp6eq3cp@4ax.com> <1178163168.661168.19700@p77g2000hsh.googlegroups.com> <1178169863.602236.287420@p77g2000hsh.googlegroups.com> Message-ID: <1178199680.298670.157580@n76g2000hsh.googlegroups.com> On May 2, 10:24 pm, Major Quaternion Dirt Quantum wrote: > maybe, "pulled" is just a firefighteresque synonym > for gravity doing its thing -- still not subsumed > in the Standard Model of physicists, so, There. y'know, > sort of like, how it is, pilots refer to going "out" and "in," > instead of up & down. You can also try "pull" as a term for a general alarm that says get everyone out of there. It could be from "pull the alarm" a term for triggering an alarm manually or "pull the troops out" a term for getting soldiers out of a location. [.....] > thus: > if you can't prove that all Fermat numbers are pairwise coprime, > again! But .... but .... I've got a video of someone saying it. That *proves* it doesn't it. From google at mrabarnett.plus.com Tue May 15 19:51:40 2007 From: google at mrabarnett.plus.com (MRAB) Date: 15 May 2007 16:51:40 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers - ambiguity issues In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649BC4C.10200@web.de> <1179238847.407605.4620@w5g2000hsg.googlegroups.com> <4649C63C.1030508@web.de> <1179242328.800088.246620@h2g2000hsg.googlegroups.com> <4649D4A5.5060102@web.de> <1179247724.234869.47310@l77g2000hsb.googlegroups.com> <4649E730.9000609@web.de> Message-ID: <1179273100.030381.120880@h2g2000hsg.googlegroups.com> On May 15, 6:44 pm, John Nagle wrote: > There are really two issues here, and they're being > confused. > > One is allowing non-English identifiers, which is a political > issuer. The other is homoglyphs, two characters which look the same. > The latter is a real problem in a language like Python with implicit > declarations. If a maintenance programmer sees a variable name > and retypes it, they may silently create a new variable. > > If Unicode characters are allowed, they must be done under some > profile restrictive enough to prohibit homoglyphs. I'm not sure > if UTS-39, profile 2, "Highly Restrictive", solves this problem, > but it's a step in the right direction. This limits mixing of scripts > in a single identifier; you can't mix Hebrew and ASCII, for example, > which prevents problems with mixing right to left and left to right > scripts. Domain names have similar restrictions. > > We have to have visually unique identifiers. > > There's also an issue with implementations that interface > with other languages. Some Python implementations generate > C, Java, or LISP code. Even CPython will call C code. > The representation of external symbols needs to be standardized > across those interfaces. > Surely it should be possible programmatically to compare the visual appearance of the characters and highlight ones which are similar, or colour-code various subsets when required. From martin at browns-nospam.co.uk Fri May 25 05:21:16 2007 From: martin at browns-nospam.co.uk (Martin Evans) Date: Fri, 25 May 2007 10:21:16 +0100 Subject: Invalid thread state for this thread References: Message-ID: Just in case anyone else has seen this problem, after upgrading to 2.4.4 the problem appears to have resolved itself. >I know this has been seen before but it is not making too much sense (after >reading many posts). It all appears to work fine but then dies after about >40 invocations. > > My app has Python embedded, it is embedded as part of a dll which > initializes python and finalizes on load and unload (see below). When a > script needs to be run, I create a new thread, let the script complete and > close the thread. > > The thread contains the following type arrangement: > > PythonThread() > { > hScriptFile = OpenScriptFile(m_szActiveScript); > PyEval_AcquireLock(); > pInterpreter = Py_NewInterpreter(); > Py_SetProgramName(szModuleFileName); > PyRun_SimpleFile(hScriptFile,m_szActiveScript); > PyErr_Clear(); > Py_EndInterpreter(pInterpreter); > PyEval_ReleaseLock(); > } > > This appears to work fine accept that after around 30-40 invocations I > always get the "Invalid thread state for this thread". ie the app and dll > stay loaded and I click my "run" button manually about 40 times. In this > test it is a simple "hello world" type script. The size of the script does > not appear to matter. > > The dll is coded something like this: > > DllLoad() > { > Py_Initialize(); > PyEval_InitThreads(); > m_mainThreadState = PyThreadState_Get(); > PyEval_ReleaseLock(); > } > > DllUnload() (not called as part of this test) > { > PyEval_AcquireLock(); > PyThreadState_Swap(m_mainThreadState); > Py_Finalize(); > } > > The app has been designed to allow a second interpreter to run > independently (thus the need for multiple thread support) and this also > appears to work fine, but for this test only this one thread was used. I > have a compiled version of 2.4.2. > > Any ideas would be appreciated. > > Martin From mail at microcorp.co.za Thu May 17 03:30:57 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 17 May 2007 09:30:57 +0200 Subject: tkinter button state = DISABLED References: <1179163831.016938.79840@w5g2000hsg.googlegroups.com><1179175592.011635.103980@e51g2000hsg.googlegroups.com><03f601c7979e$83559740$03000080@hendrik> Message-ID: <019801c79856$964bade0$03000080@hendrik> "Gabriel Genellina" wrote: >En Wed, 16 May 2007 03:22:17 -0300, Hendrik van Rooyen > escribi?: > >> "Gabriel Genellina" wrote: >> >>> Maybe there is a confusion here. You code above means that, when the >>> event >>> "The leftmost MOUSE BUTTON was released" happens over your BUTTON WIDGET >>> b, your function will be called. >> >> I have never seen this working in Tkinter, unless the button was pressed >> on the >> widget >> in question - and worse, once you have clicked down on a ButtonRelease >> binding >> you can move the mouse pointer anywhere you like, even out of the >> application >> and when you release it, the bound function is called... >> >> Its either a bug or a feature, I don't know. > >Uhmm... I'm not sure I understand you completely. I only said that the >"command" is fired only when the mouse button is pressed on the widget, >AND released inside the same widget. If both events don't happen in the >same widget, "command" won't fire. Maybe you are saying the same thing... >anyway I'm not a Tk expert. No command is ok and you have described it right - its ButtonRelease that seems broken to me - Hendrik From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon May 14 11:04:15 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 14 May 2007 17:04:15 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <4648294F.2000704@web.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> <4648294F.2000704@web.de> Message-ID: <46487a6c$0$2400$426a74cc@news.free.fr> Stefan Behnel a ?crit : > Bruno Desthuilliers wrote: >> but CS is english-speaking, period. > > That's a wrong assumption. I've never met anyone *serious* about programming and yet unable to read and write CS-oriented technical English. > I understand that people can have this impression > when they deal a lot with Open Source code, but I've seen a lot of places > where code was produced that was not written to become publicly available (and > believe me, it *never* will become Open Source). Yeah, fine. This doesn't mean that all and every people that may have to work on this code is a native speaker of the language used - or even fluent enough with it. From slewin at rogers.com Fri May 18 15:04:03 2007 From: slewin at rogers.com (scott) Date: Fri, 18 May 2007 15:04:03 -0400 Subject: Python compared to other language Message-ID: <464DF8A3.90704@rogers.com> Hi all, I have been looking at the various programming languages available. I have programed in Basic since I was a teenager and I also have a basic understanding of C, but I want something better. Can anybody tell me the benefits and weaknesses of using Python? -- Your friend, Scott Sent to you from a Linux computer using Kubuntu Version 7.04 (Feisty Fawn) From horpner at yahoo.com Thu May 10 14:32:46 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 10 May 2007 18:32:46 GMT Subject: searching algorithm References: Message-ID: On 2007-05-10, Gigs_ wrote: > Hi all! > > I have text file (english-croatian dictionary) with words in it > in alphabetical order. This file contains 179999 words in this > format: english word: croatian word > > I want to make instant search for my gui Instant search, i mean > that my program search words and show words to user as user > type letters. yes, it needs to be fast > > Can someone give me some points (approaches) how to make this > Should i make indexes and go with file.seek > > or should breake dictionary in peaces and put words that start > with a in one and with b in another... > > So if i have this words > [abridged dictionary below] > absinth:pelin > absinthe:pelin > absolute:apsolutan > absolute:apsolutni kod > absolve:odrije?iti > absolve:osloboditi > absorb:absorbirati > absorb:apsorbirati > absorb:crpsti > > if user type: "abs" program should list all words above in > english and in croatian if user type: "absorb" than program > should list last 3 words in english and in croatian A solution that solves the problem with a data structure might be a multi-tree. Each node points at a set of following letters, and a set of croatian translations, either of which might be empty, making the node a leaf. For the above (abrideged) dictionary, you would generate (use a fixed-width "programmers" font so the tree looks good): a | b | s / \ i o / / \ n l r / / \ \ t u v b->(absorbirati, crpisti) / | | (pelin)<-h t e->(odrije?iti, osloboditi) | | (pelin)<-e e->(apsolutan, apsolutni kod) As the user enter letters, you just march down the tree, printing all the words held in leaf nodes held in the current node. -- Neil Cerutti We shall reach greater and greater platitudes of achievement. --Richard J. Daley From peter_7003 at yahoo.com Thu May 3 13:44:36 2007 From: peter_7003 at yahoo.com (Peter Fischer) Date: Thu, 3 May 2007 10:44:36 -0700 (PDT) Subject: how to use Dispatch to open an application in win32com.client In-Reply-To: <4639A3CF.4000500@timgolden.me.uk> Message-ID: <285805.15254.qm@web63402.mail.re1.yahoo.com> Dear Python/DCOM experts, I just tried to do a remote dispatch of Google Earth in DCOM, but it didn't work: import pythoncom, win32com.client clsctx=pythoncom.CLSCTX_LOCAL_SERVER i = win32com.client.DispatchEx("GoogleEarth.ApplicationGE", "IAD-PC10", clsctx=clsctx) Here is the error message I get: Traceback (most recent call last): File "Z:\Programming\Eclipse_3_2_2_Workspace\Pytest2\src\root\nested\example.py", line 5, in i = win32com.client.DispatchEx("GoogleEarth.ApplicationGE", "Remote_PC", clsctx=clsctx) File "Z:\Applications\Programming\Python25_win\Lib\site-packages\win32com\client\__in it__.py", line 112, in DispatchEx dispatch = pythoncom.CoCreateInstanceEx(clsid, None, clsctx, serverInfo, (pythoncom.IID_IDispatch,))[0] pywintypes.com_error: (-2147023174, 'The RPC server is not available.', None, None) Does anyone know what I am doing wrong? I read in Mark Hammonds book 'Python Programming on Win32' and suspect that the clsctx parameter must be something like CLSCTX_REMOTE_SERVER instead the LOCAL variant above, but I am not sure. Furthermore the dcomcnfg tool seems to have changed and crashes when I select 'component Services' in the tree to the left and then 'Computer'. The book is from year 2000 and therefore is not for Windows XP, but I use Windows XP Professional. Do I still have to use dcomcnfg to activate and configure DCOM on the serving machine where I want to start Google Earth? If anyone could tell me how to start Google Earth remotely using python and DCOM that would be awesome! Best regards, Peter. --------------------------------- Ahhh...imagining that irresistible "new car" smell? Check outnew cars at Yahoo! Autos. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Sun May 13 19:54:46 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 13 May 2007 20:54:46 -0300 Subject: Finally started on python.. References: Message-ID: En Sat, 12 May 2007 14:09:06 -0300, Roger Gammans escribi?: > Having known about python since around the turn of the century , > I finally found a (actually two) reason to learn it. Welcome! > Does the python communitity have something like Perl's CPAN and > is there already something there taht does this or would it > be something that I could give back? Is there a naming > convention for such modules in python - I couldn't easly detect > one looking at the library which whip with python in Debian. See the Python wiki pages, you can get the answer to these and many more questions: http://wiki.python.org/moin/PublishingPythonModules and http://wiki.python.org/moin/PythonStyle -- Gabriel Genellina From kakeez at hotmail.com Thu May 24 08:28:06 2007 From: kakeez at hotmail.com (Karim Ali) Date: Thu, 24 May 2007 12:28:06 +0000 Subject: Call script which accepts com. line par. from another scriptanderror control In-Reply-To: Message-ID: >Karim Ali wrote: > > > What I still dont know though is how do I handle the fact that the first > > script is expecting command line parameters. I would like to be able to > > replace the command line parameters by a variable such that the second > > script can call: first_script.main("command line"). Is this possible? > >I think it is better to pass a list of arguments > ># first_script.py > >def main(args=None): > parser = optparse.OptionParser() > # add options > options, positional_args = parser.parse_args(args) > # process > >if __name__ == "__main__": > # will read options from the command line > # if module is invoked as a standalone script > main() > ># second_script.py > >import first_script >first_script.main(["-f", "--bar", "what", "you want"]) > >That way you don't have to deal with escaping spaces etc. > >Peter > >-- >http://mail.python.org/mailman/listinfo/python-list Thanks Peter. That does the trick! Karim _________________________________________________________________ New Windows Live Hotmail is here. Upgrade for free and get a better look. www.newhotmail.ca?icid=WLHMENCA150 From sjmachin at lexicon.net Thu May 17 20:13:49 2007 From: sjmachin at lexicon.net (John Machin) Date: 17 May 2007 17:13:49 -0700 Subject: omissions in python docs? In-Reply-To: References: <1179419983.750044.65030@n59g2000hsh.googlegroups.com> Message-ID: <1179447228.985134.64860@y80g2000hsf.googlegroups.com> On May 18, 9:24 am, "Gabriel Genellina" wrote: > En Thu, 17 May 2007 13:39:43 -0300, 7stud > escribi?: > > > 2) The fnmatch module does not even mention translate(). > > > I have a hard time believing I am the first one to notice those > > omissions. > > At least for 2) you're late. It's already documented on 2.5.1:http://sourceforge.net/tracker/index.php?func=detail&aid=1630844&grou... > Not quite. All that says is that you raised the problem and that somebody else's patch was accepted. It's not in 2.5.1 AFAICT: not in "current docs" on Python website, not in CHM file distributed with Windows version of Python 2.5.1 It is in "development docs'" (2.6a0) on Python website. Nit-pickingly yours, John From kyosohma at gmail.com Tue May 22 15:35:34 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 22 May 2007 12:35:34 -0700 Subject: Create an XML document In-Reply-To: <1179846012.972391.160800@z28g2000prd.googlegroups.com> References: <1179846012.972391.160800@z28g2000prd.googlegroups.com> Message-ID: <1179862534.824106.87950@h2g2000hsg.googlegroups.com> On May 22, 10:00 am, kyoso... at gmail.com wrote: > Hi all, > > I am attempting to create an XML document dynamically with Python. It > needs the following format: > > > > 1179775800 > 1800 > > > > I tried using minidom with the following code: > > > > from xml.dom.minidom import Document > > doc = Document() > > zappt = doc.createElement('zAppointments') > zappt.setAttribute('reminder', '15') > doc.appendChild(zappt) > > appt = doc.createElement('appointment') > zappt.appendChild(appt) > > begin = doc.createElement('begin') > appt.appendChild(begin) > f = file(r'path\to\file.xml', 'w') > f.write(doc.toprettyxml(indent=' ')) > f.close() > > > > This gives me the following: > > > > > > > > > > How do I get Python to put values into the elements by tag name? I can > parse my documents just fine, but now I need to edit them and write > them out to a file for an application I am working on. I am sure I am > missing something obvious. > > Thanks a lot! > > Mike Thanks Nis. Your code worked great. For some reason, Google Groups seems hosed up today and makes seeing replies impossible on some posts. Maximus - What the? You told me to use "createTextNode" and then you used "doc.createTextElement". I think I know what you mean though. Thank you both for your advice. It works now. Mike From __peter__ at web.de Sun May 13 13:48:42 2007 From: __peter__ at web.de (Peter Otten) Date: Sun, 13 May 2007 19:48:42 +0200 Subject: Using "subprocess" without lists. . .? References: Message-ID: Steven Bethard wrote: > You could always call "ls -al | grep -i test".split(). Or better, shlex.split(). Peter From afriere at yahoo.co.uk Wed May 16 22:14:38 2007 From: afriere at yahoo.co.uk (Asun Friere) Date: 16 May 2007 19:14:38 -0700 Subject: zipfile stupidly broken In-Reply-To: References: Message-ID: <1179368078.682948.291370@n59g2000hsh.googlegroups.com> On May 17, 5:38 am, "Gabriel Genellina" wrote: > This is not a good place for reporting bugs - use http://sourceforge.net/bugs/?group_id=5470 I disagree. Given that most suspected bugs aren't, new users especially would be wise to post their "bugs' here before filing a bug report. From aleax at mac.com Mon May 7 23:41:11 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 7 May 2007 20:41:11 -0700 Subject: randomly write to a file References: <1178567497.042096.82940@w5g2000hsg.googlegroups.com> <1178574062.496137.11640@y5g2000hsa.googlegroups.com> <1hxre1l.15ydbuikdt4dsN%aleax@mac.com> Message-ID: <1hxrfyb.ms8lp3tn9qpmN%aleax@mac.com> Steven D'Aprano wrote: ... > Hang on, as I understand it, Nick just suggesting using SQlite for > holding indexes into the file! That's why I said it was overkill. So > whether the indexes are in a list or a database, you've _still_ got to > deal with writing to the file. > > If I've misunderstood Nick's suggestion, if he actually meant to read the > entire text file into the database, well, that's just a heavier version > of reading the file into a list of strings, isn't it? If the database > gives you more and/or better functionality than file.readlines(), then I > have no problem with using the right tool for the job. Ah well, I may have misunderstood myself. I'd keep the whole thing in an SQlite table, definitely NOT a table + an external file -- no, that's not going to be heavier than reading things in memory, SQLite is smarter than one might think:-). Obviously, I'm assuming that one's dealing with an amount of data that doesn't just comfortably and easily fit in memory, or at least one that gives pause at the thought of sucking it all into memory and writing it back out again at every program run. Alex From nyamatongwe+thunder at gmail.com Wed May 16 05:36:28 2007 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Wed, 16 May 2007 09:36:28 GMT Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179302916.340760.177420@h2g2000hsg.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179153757.844925.14230@p77g2000hsh.googlegroups.com> <4648DF39.70901@v.loewis.de> <1179302916.340760.177420@h2g2000hsg.googlegroups.com> Message-ID: Lorenzo Gatti: > Ok, maybe you considered listing characters but you earnestly decided > to follow an authority; but this reliance on the Unicode standard is > not a merit: it defers to an external entity (UAX 31 and the Unicode > database) a foundation of Python syntax. PEP 3131 uses a similar definition to C# except that PEP 3131 disallows formatting characters (category Cf). See section 9.4.2 of http://www.ecma-international.org/publications/standards/Ecma-334.htm Neil From hlubenow2 at gmx.net Thu May 3 16:05:03 2007 From: hlubenow2 at gmx.net (hlubenow) Date: Thu, 03 May 2007 22:05:03 +0200 Subject: Using python with MySQL References: <1178048415.272711.261930@n59g2000hsh.googlegroups.com> Message-ID: HMS Surprise wrote: > Greetings, > > I need to peform some simple queries via MySQL. Searching the list I > see that folks are accessing it with python. I am very new to python > and pretty new to MySQL too. Would appreciate it if you could point me > to some documentation for accessing MySQL via python. Something of the > "Python and MySQL for Dummies" caliber would be about my speed, but of > course I will be thankful for anything offered. > > Thanks, > > jvh There's even another approach: If you're on Linux, Qt3 may be available. Install its Python-bindings. Given a database "MyDatabase", with password "MyPassword" for user "root" and inside the database a table "MyTable", you can then do something like this: ---------------------------------------------------- #!/usr/bin/env python from qt import * import sys from qtsql import QSqlDatabase, QSqlQuery app = QApplication(sys.argv) DB = QSqlDatabase("QMYSQL3", "MyDatabase", app) DB.setDatabaseName("MyDatabase") DB.setUserName("root") DB.setPassword("MyPassword") DB.setHostName("localhost") DB.open() c = DB.execStatement("select * from MyTable") while c.next(): print c.value(0).toString() print c.value(1).toString() print c.value(2).toString() print c.value(3).toString() c.first() c2 = DB.execStatement("select count(*) from MyTable") c2.next() print c2.value(0).toString() ---------------------------------------------------- Some further documentation: http://www.arl.hpc.mil/ice/Manuals/PyQt/t1.html http://doc.trolltech.com/4.2/database.html H. From sjmachin at lexicon.net Sun May 20 08:12:30 2007 From: sjmachin at lexicon.net (John Machin) Date: Sun, 20 May 2007 22:12:30 +1000 Subject: converting strings to most their efficient types '1' --> 1, 'A' ---> 'A', '1.2'---> 1.2 In-Reply-To: <1179658331.911424.173140@e65g2000hsc.googlegroups.com> References: <1179529661.555196.13070@k79g2000hse.googlegroups.com> <1179551680.283157.19000@y80g2000hsf.googlegroups.com> <464FA156.2070704@lexicon.net> <1179658331.911424.173140@e65g2000hsc.googlegroups.com> Message-ID: <46503B2E.6030902@lexicon.net> On 20/05/2007 8:52 PM, Paddy wrote: > On May 20, 2:16 am, John Machin wrote: >> On 19/05/2007 3:14 PM, Paddy wrote: >> >> >> >>> On May 19, 12:07 am, py_genetic wrote: >>>> Hello, >>>> I'm importing large text files of data using csv. I would like to add >>>> some more auto sensing abilities. I'm considing sampling the data >>>> file and doing some fuzzy logic scoring on the attributes (colls in a >>>> data base/ csv file, eg. height weight income etc.) to determine the >>>> most efficient 'type' to convert the attribute coll into for further >>>> processing and efficient storage... >>>> Example row from sampled file data: [ ['8','2.33', 'A', 'BB', 'hello >>>> there' '100,000,000,000'], [next row...] ....] >>>> Aside from a missing attribute designator, we can assume that the same >>>> type of data continues through a coll. For example, a string, int8, >>>> int16, float etc. >>>> 1. What is the most efficient way in python to test weather a string >>>> can be converted into a given numeric type, or left alone if its >>>> really a string like 'A' or 'hello'? Speed is key? Any thoughts? >>>> 2. Is there anything out there already which deals with this issue? >>>> Thanks, >>>> Conor >>> You might try investigating what can generate your data. With luck, >>> it could turn out that the data generator is methodical and column >>> data-types are consistent and easily determined by testing the >>> first or second row. At worst, you will get to know how much you >>> must check for human errors. >> Here you go, Paddy, the following has been generated very methodically; >> what data type is the first column? What is the value in the first >> column of the 6th row likely to be? >> >> "$39,082.00","$123,456.78" >> "$39,113.00","$124,218.10" >> "$39,141.00","$124,973.76" >> "$39,172.00","$125,806.92" >> "$39,202.00","$126,593.21" >> >> N.B. I've kindly given you five lines instead of one or two :-) >> >> Cheers, >> John > > John, > I've had cases where some investigation of the source of the data has > completely removed any ambiguity. I've found that data was generated > from one or two sources and been able to know what every field type is > by just examining a field that I have determined wil tell me the > source program that generated the data. The source program that produced my sample dataset was Microsoft Excel (or OOo Calc or Gnumeric); it was induced to perform a "save as CSV" operation. Does that help you determine the true nature of the first column? > > I have also found that the flow generating some data is subject to > hand editing so have had to both put in extra checks in my reader, and > on some occasions created specific editors to replace hand edits by > checked assisted hand edits. > I stand by my statement; "Know the source of your data", its less > likely to bite! > My dataset has a known source, and furthermore meets your "lucky" criteria (methodically generated, column type is consistent) -- I'm waiting to hear from you about the "easily determined" part :-) Cheers, John From dborne at gmail.com Fri May 25 10:51:01 2007 From: dborne at gmail.com (Dave Borne) Date: Fri, 25 May 2007 09:51:01 -0500 Subject: Why isn't this query working in python? In-Reply-To: <1180103946.552760.239200@p47g2000hsd.googlegroups.com> References: <1180103946.552760.239200@p47g2000hsd.googlegroups.com> Message-ID: <6e42ec490705250751i89d3cf3v3a3062690d0284aa@mail.gmail.com> > I'm trying to run the following query: ... > member_id=%s AND expire_date > NOW() AND completed=1 AND (product_id Shouldn't you be using the bind variable '?' instead of '%s' ? (I'm asking because I'm not entirely sure how the execute command is doing the substitution) -Dave From http Fri May 18 03:02:52 2007 From: http (Paul Rubin) Date: 18 May 2007 00:02:52 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> <4648252D.5020704@web.de> <46483740.4050406@web.de> <46498cb1$0$6411$9b4e6d93@newsspool2.arcor-online.net> <464C46A4.1060200@v.loewis.de> Message-ID: <7xwsz61un7.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > If you doubt the claim, please indicate which of these three aspects > you doubt: > 1. there are programmers which desire to defined classes and functions > with names in their native language. > 2. those developers find the code clearer and more maintainable than > if they had to use English names. > 3. code clarity and maintainability is important. I think it can damage clarity and maintainability and if there's so much demand for it then I'd propose this compromise: non-ascii identifiers are allowed but they produce a compiler warning message (including from eval and exec). You can suppress the warning message with a command line option. From google at mrabarnett.plus.com Sun May 6 17:26:46 2007 From: google at mrabarnett.plus.com (MRAB) Date: 6 May 2007 14:26:46 -0700 Subject: unable to construct tuple with one item In-Reply-To: References: <271115400705060523t2f1c23e4ndc87e612384d4951@mail.gmail.com> Message-ID: <1178486806.743481.24580@y5g2000hsa.googlegroups.com> On May 6, 4:04 pm, Mel Wilson wrote: > Vyacheslav Maslov wrote: > > So, the main question is why using syntax like [X] python constuct list > > with > > one item, but when i try to construct tuple with one item using similar > > syntax (X) python do nothing? > > Because `(` and `)` are used in expressions to bracket sub-expressions. > > a = (4 + 3) * 2 > > means: add 4 to 3, multiply the sum by 2. It can't mean: make a tuple > containing 7 and extend it to 7,7 . > > The real constructor for tuples is `,`. When you see parens around > tuple creation they're there to bracket the sub-expression that > creates the tuple. You see new tuples without parens all the time: > > for i, thing in enumerate (things): ... > > starter, main_course, dessert, beverage = order_meal (*hunger) > > etc. > > Mel. > If it's the comma that makes the tuple, then wouldn't [1, 2] make a 2- tuple in a list, ie == [(1, 2)]? Hmm... From michael.forbes at gmail.com Fri May 4 02:36:11 2007 From: michael.forbes at gmail.com (Michael) Date: 3 May 2007 23:36:11 -0700 Subject: Why are functions atomic? In-Reply-To: References: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> <1178044821.864741.235260@o5g2000hsb.googlegroups.com> <1178063341.779617.289690@o5g2000hsb.googlegroups.com> <1178065685.161372.81790@y80g2000hsf.googlegroups.com> <1178083318.404304.76100@q75g2000hsh.googlegroups.com> Message-ID: <1178260571.160570.299160@p77g2000hsh.googlegroups.com> On May 2, 6:08 am, Carsten Haese wrote: > On Tue, 2007-05-01 at 22:21 -0700, Michael wrote: > > Is there a reason for using the closure here? Using function defaults > > seems to give better performance:[...] > > It does? Not as far as I can measure it to any significant degree on my > computer. I agree the performance gains are minimal. Using function defaults rather than closures, however, seemed much cleaner an more explicit to me. For example, I have been bitten by the following before: >>> def f(x): ... def g(): ... x = x + 1 ... return x ... return g >>> g = f(3) >>> g() Traceback (most recent call last): File "", line 1, in File "", line 3, in g UnboundLocalError: local variable 'x' referenced before assignment If you use default arguments, this works as expected: >>> def f(x): ... def g(x=x): ... x = x + 1 ... return x ... return g >>> g = f(3) >>> g() 4 The fact that there also seems to be a performance gain (granted, it is extremely slight here) led me to ask if there was any advantage to using closures. It seems not. > An overriding theme in this thread is that you are greatly concerned > with the speed of your solution rather than the structure and > readability of your code. Yes, it probably does seem that way, because I am burying this code deeply and do not want to revisit it when profiling later, but my overriding concern is reliability and ease of use. Using function attributes seemed the best way to achieve both goals until I found out that the pythonic way of copying functions failed. Here was how I wanted my code to work: @define_options(first_option='abs_tol') def step(f,x,J,abs_tol=1e-12,rel_tol=1e-8,**kwargs): """Take a step to minimize f(x) using the jacobian J. Return (new_x,converged) where converged is true if the tolerance has been met. """ return (x + dx, converged) @define_options(first_option='min_h') def jacobian(f,x,min_h=1e-6,max_h=0.1): """Compute jacobian using a step min_h < h < max_h.""" return J class Minimizer(object): """Object to minimize a function.""" def __init__(self,step,jacobian,**kwargs): self.options = step.options + jacobian.options self.step = step self.jacobian = jacobian def minimize(self,f,x0,**kwargs): """Minimize the function f(x) starting at x0.""" step = self.step jacobian = self.jacobian step.set_options(**kwargs) jacobian.set_options(**kwargs) converged = False while not converged: J = jacobian(f,x) (x,converged) = step(f,x,J) return x @property def options(self): """List of supported options.""" return self.options The idea is that one can define different functions for computing the jacobian, step etc. that take various parameters, and then make a custom minimizer class that can provide the user with information about the supported options etc. The question is how to define the decorator define_options? 1) I thought the cleanest solution was to add a method f.set_options() which would set f.func_defaults, and a list f.options for documentation purposes. The docstring remains unmodified without any special "wrapping", step and jacobian are still "functions" and performance is optimal. 2) One could return an instance f of a class with f.__call__, f.options and f.set_options defined. This would probably be the most appropriate OO solution, but it makes the decorator much more messy, or requires the user to define classes rather than simply define the functions as above. In addition, this is at least a factor of 2.5 timese slower on my machine than option 1) because of the class instance overhead. (This is my only real performance concern because this is quite a large factor. Otherwise I would just use this method.) 3) I could pass generators to Minimize and construct the functions dynamically. This would have the same performance, but would require the user to define generators, or require the decorator to return a generator when the user appears to be defining a function. This just seems much less elegant. ... @define_options_generator(first_option='min_h') def jacobian_gen(f,x,min_h=1e-6,max_h=0.1): """Compute jacobian using a step min_h < h < max_h.""" return J class Minimizer(object): """Object to minimize a function.""" def __init__(self,step_gen,jacobian_gen,**kwargs): self.options = step_gen.options + jacobian_gen.options self.step_gen = step_gen self.jacobian_gen = jacobian_gen def minimize(self,f,x0,**kwargs): """Minimize the function f(x) starting at x0.""" step = self.step_gen(**kwargs) jacobian = self.jacobian_gen(**kwargs) converged = False while not converged: J = jacobian(f,x) (x,converged) = step(f,x,J) return x ... 4) Maybe there is a better, cleaner way to do this, but I thought that my option 1) was the most clear, readable and fast. I would appreciate any suggestions. The only problem is that it does use mutable functions, and so the user might be tempted to try: new_step = copy(step) which would fail (because modifying new_step would also modify step). I guess that this is a pretty big problem (I could provide a custom copy function so that new_step = step.copy() would work) and I wondered if there was a better solution (or if maybe copy.py should be fixed. Checking for a defined __copy__ method *before* checking for pre-defined mutable types does not seem to break anything.) Thanks again everyone for your suggestions, it is really helping me learn about python idioms. Michael. From john at datavoiceint.com Wed May 16 12:57:30 2007 From: john at datavoiceint.com (HMS Surprise) Date: 16 May 2007 09:57:30 -0700 Subject: Declaring variables Message-ID: <1179334649.990688.73320@o5g2000hsb.googlegroups.com> I looked in the language but did not find a switch for requiring variables to be declared before use. Is such an option available? Thanks, jvh From kyosohma at gmail.com Thu May 31 10:14:04 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 31 May 2007 07:14:04 -0700 Subject: How do I Extract Attachment from Newsgroup Message In-Reply-To: <1180619689.128854.29180@q75g2000hsh.googlegroups.com> References: <1180619689.128854.29180@q75g2000hsh.googlegroups.com> Message-ID: <1180620843.925344.288720@u30g2000hsc.googlegroups.com> On May 31, 8:54 am, "snewma... at gmail.com" wrote: > I'm parsing NNTP messages that have XML file attachments. How can I > extract the encoded text back into a file? I looked for a solution > with mimetools (the way I'd approach it for email) but found nothing. > > Here's a long snippet of the message: > > >>> n.article('116431') > > ('220 116431 article', '116431', > '', ['MIME-Version: 1.0', 'Message-ID: > ', 'Content-Type: Multipart/Mixed;', ' > boundary="------------Boundary-00=_A5NJCP3FX6Y5BI3BH890"', 'Date: Thu, > 24 May 2007 07:41:34 -0400 (EDT)', 'From: Newsclip ', > 'Path: newsclip.ap.org!flounder.ap.org!flounder', 'Newsgroups: > ap.spanish.online,ap.spanish.online.business', 'Keywords: MUN ECO > PETROLEO PRECIOS', 'Subject: MUN ECO PETROLEO PRECIOS', 'Summary: ', > 'Lines: 108', 'Xref: newsclip.ap.org ap.spanish.online:938298 > ap.spanish.online.business:116431', '', '', '-------------- > Boundary-00=_A5NJCP3FX6Y5BI3BH890', 'Content-Type: Text/Plain', > 'Content-Transfer-Encoding: 8bit', 'Content-Description: text, > unencoded', '', '(AP) Precios del crudo se mueven sin rumbo claro', > 'Por GEORGE JAHN', 'VIENA', 'Los precios > > ... (truncated for length) ... > > '', '___', '', 'Editores: Derrick Ho, periodista de la AP en Singapur, > contribuy\xf3 con esta informaci\xf3n.', '', '', '-------------- > Boundary-00=_A5NJCP3FX6Y5BI3BH890', 'Content-Type: Text/Xml', 'Content- > Transfer-Encoding: base64', 'Content-Description: text, base64 > encoded', '', > 'PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPCFET0NUWVBFIG5pdGYgU1lT', > 'VEVNICJuaXRmLmR0ZCI+CjxuaXRmPgogPGhlYWQ > +CiAgPG1ldGEgbmFtZT0iYXAtdHJhbnNyZWYi', > 'IGNvbnRlbnQ9IlNQMTQ3MiIvPgogIDxtZXRhIG5hbWU9ImFwLW9yaWdpbiIgY29udGVudD0ic3Bh', > 'bm9sIi8+CiAgPG1ldGEgbmFtZT0iYXAtc2VsZWN0b3IiIGNvbn This looks like what you might be looking for: http://mail.python.org/pipermail/python-list/2004-June/265018.html Not sure if you'll need this or not, but here's some info on encoding/ decoding files: http://www.jorendorff.com/articles/unicode/python.html There are lots of ways to parse xml. I use the minidom module myself. Mike From CRhode at LacusVeris.com Thu May 31 11:59:10 2007 From: CRhode at LacusVeris.com (Chuck Rhode) Date: Thu, 31 May 2007 10:59:10 -0500 Subject: PEP 8 style enforcing program References: <1180613790.317480.314600@p47g2000hsd.googlegroups.com> Message-ID: montyphyton wrote this on Thu, 31 May 2007 05:16:30 -0700. My reply is below. > I understand that there are a lot of code beautifiers out there, but > i haven't seen one specially tailored for Python. Consider PythonTidy: o http://lacusveris.com/PythonTidy/PythonTidy.python -- .. Chuck Rhode, Sheboygan, WI, USA .. Weather: http://LacusVeris.com/WX .. 75? ? Wind SSE 9 mph ? Sky haze. From kyosohma at gmail.com Tue May 29 14:16:09 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 29 May 2007 11:16:09 -0700 Subject: Tkinter Listbox - Different Text colors in one listbox In-Reply-To: <1180458123.139727.182500@d30g2000prg.googlegroups.com> References: <1180458123.139727.182500@d30g2000prg.googlegroups.com> Message-ID: <1180462569.668579.12550@u30g2000hsc.googlegroups.com> On May 29, 12:02 pm, rahulna... at yahoo.com wrote: > Hi, > Is it possible to have different items in a listbox in different > colors? Or is it just one color for all items in a listbox? > Thanks > Rahul Looks like it has to be the same color and font: http://www.pythonware.com/library/tkinter/introduction/listbox.htm Maybe there's a custom listbox in the PMW or Tix modules? It would appear that wxPython has a control that does allow different colors (and likely, fonts) called wx.HtmlListBox. I assume it would allow any kind of html, although I've never played with it for sure. The demo seems to imply that though. Mike From kay.schluehr at gmx.net Sun May 27 06:58:42 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 27 May 2007 03:58:42 -0700 Subject: totally lost newbie In-Reply-To: <1180261154.969654.147850@n15g2000prd.googlegroups.com> References: <1180261154.969654.147850@n15g2000prd.googlegroups.com> Message-ID: <1180263522.664695.13030@k79g2000hse.googlegroups.com> On May 27, 12:19 pm, mark wrote: > Hi all > > I posted earlier on this but have changed my approach so here is my > latest attempt at solving a problem. I have been working on this for > around 12 hours straight and am still struggling with it. > > Write a program that reads the values for a random list of cards from > a file, where each line in the file specifies a single card with the > rank and then the suit separated by a space. The rank should be an > integer in the range of 1 to 13 (Ace:1, King:13), while the suit > should be a lower case character in the set { 'h', 'd', 'c', 's' }. > Sort the card entries into suits ordered by rank, and print out the > ordered list. Hint: sort the list first by rank, and then by suit. > > The format of the cards.txt file is; > > 1 h > 1 d > 13 c > 10 s > > and so on for the whole deck. > > Can someone help me to get the mycomp function to work. > > Any help appreciated > > J > > def read_cards(filename): > > cards = [] > for card in open(filename, 'r'): > # strip the trailing newline character > cards.append(card.strip()) > return cards > > filename = 'cards.txt' > cards = read_cards(filename) > > def cards_str2tup(cards): > > cards_tup = [] > for card in cards: > rank, suit = card.split() > cards_tup.append((suit, int(rank))) > return cards_tup > > def cards_tup2str(cards_tup): > > cards = [] > space = ' ' > for tup in cards_tup: > suit, rank = tup > s = str(rank) + space + suit > cards.append(s) > return cards > > def mycmp( a, b): > #define the order in which the characters are to be sorted > order = [ 'h', 'd', 'c', 's' ] > # if the characters from each element ARENT the same > if a[1] <> b[1]: > #return the result of comparing the index of each elements > character in the order list > return cmp( order.index( a[1] ), order.index( b[1] ) ) > #otherwise > else : > #return the result of comparing each elements number > return cmp( a[0], b[0] ) > > cards.sort( mycmp ) > #print cards You need to exploit the lexicographic order as in the following function. def sort_carddeck(card_deck_pairs): # card deck pairs have to be a list of # the form [(rank1, suit1), (rank1, suit2),...] suit_order = [ 'h', 'd', 'c', 's' ] def cmp(p1, p2): i1 = suit_order.index(p1[1]) i2 = suit_order.index(p2[1]) if i1 References: <1178475772.423687.118800@e65g2000hsc.googlegroups.com> <1178526655.933789.294700@h2g2000hsg.googlegroups.com> <1178530363.516882.228380@l77g2000hsb.googlegroups.com> Message-ID: <1068189.12475.BlRUCl8VTQA=.1178546133.squirrel@webmailer.hosteurope.de> On Mo, 7.05.2007, 11:32, Daniele Varrazzo wrote: > On 7 Mag, 10:46, "Stefan Sonnenberg-Carstens" > wrote: >> On Mo, 7.05.2007, 10:30, Daniele Varrazzo wrote: >> >> > On 7 Mag, 08:55, "krishnakant Mane" wrote: >> >> On 6 May 2007 11:22:52 -0700, Daniele Varrazzo >> >> >> Every serious database driver has a >> >> complete and solid SQL escaping >> >> > mechanism. This mechanism tipically involves putting placeholders >> in >> >> > your SQL strings and passing python data in a separate tuple or >> >> > dictionary. Kinda >> >> >> > cur.execute("INSERT INTO datatable (data) VALUES (%s);", >> >> > (pickled_data,)) >> >> >> I will try doing that once I get back to the lab. >> >> mean while I forgot to mention in my previous email that I use >> MySQLdb >> >> for python-mysql connection. >> >> Why not use qmark parameter passing (PEP 249) ? >> >> cur.execute("INSERT INTO datatable (data) VALUES (?);" , >> (pickled_data,)) >> >> Then the DB driver will take care for you. > >>>> import MySQLdb >>>> print MySQLdb.paramstyle > format > > MySQLdb (as many other drivers) use format parameter passing. Not much > difference w.r.t. qmark, at least when passing positional parameters: > the placeholder is "%s" instead of "?". A difference is that "format" > also allows named parameters (actually it should have been "pyformat", > but IIRC MySQLdb can also use named placeholders, even if they > advertise "format"). > > Anyway it is only a matter of placeholder style: they both allow the > driver to take care of data escaping, the concept the OT didn't know > about. > > -- Daniele > > -- > http://mail.python.org/mailman/listinfo/python-list > > %s is not a placeholder IMHO. What happens when using %s is, that the string given will be inserted where %s is; that is something python does as with every print or such. By using the qmark style, it is up the the implementation of the cursor.execute method to decide what to do. python itself, and it's string implementation, don't know anything to do with the qmark. So, IMHO it *makes* a difference: with %s the execute function sees a string and nothing more as the parameters are consumed away by the % substitution. with ?, the execute implementation must do it's best, it gets a string and a list/tuple with values. Cheers, Stefan From gagsl-py2 at yahoo.com.ar Sat May 19 17:09:06 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 19 May 2007 18:09:06 -0300 Subject: zipfile [module and file format, both] stupidly broken References: Message-ID: En Sat, 19 May 2007 14:00:01 -0300, Martin Maney escribi?: > BTW, thanks for the pointer someone else gave to the proper place for > posting bugs. I'd had the silly idea that I would be able to find that > easily at www.python.org, but if I had then I'd not have posted here > and had so much fun. My microwave oven doesn't work very well, it's rather new and I want it fixed. I take the manual, go to the last pages, and find how to contact the factory. A module in the Python Standard Library has a bug. I take the Python Library Reference manual, go to the last pages (Appendix B), and find how to properly report a bug. -- Gabriel Genellina From castironpi at gmail.com Wed May 9 22:15:02 2007 From: castironpi at gmail.com (castironpi at gmail.com) Date: 9 May 2007 19:15:02 -0700 Subject: Checking if string inside quotes? In-Reply-To: <1178761682.334958.246010@y5g2000hsa.googlegroups.com> References: <1178745091.682071.128670@w5g2000hsg.googlegroups.com> <1178761682.334958.246010@y5g2000hsa.googlegroups.com> Message-ID: <1178763302.429838.284960@o5g2000hsb.googlegroups.com> On May 9, 8:48 pm, half.ital... at gmail.com wrote: > On May 9, 2:31 pm, "Michael Yanowitz" wrote: > > > > > Thanks, but it is a little more complicated than that, > > the string could be deep in quotes. > > > The problem is in string substitution. > > Suppose I have a dictionary with MY_IP : "172.18.51.33" > > > I need to replace all instances of MY_IP with "172.18.51.33" > > in the file. > > It is easy in cases such as: > > if (MY_IP == "127.0.0.1"): > > > But suppose I encounter:" > > ("(size==23) and (MY_IP==127.0.0.1)") > > > In this case I do not want: > > ("(size==23) and ("172.18.51.33"==127.0.0.1)") > > but: > > ("(size==23) and (172.18.51.33==127.0.0.1)") > > without the internal quotes. > > How can I do this? > > I presumed that I would have to check to see if the string > > was already in quotes and if so remove the quotes. But not > > sure how to do that? > > Or is there an easier way? > > > Thanks in advance: > > Michael Yanowitz > > > -----Original Message----- > > From: python-list-bounces+m.yanowitz=kearfott.... at python.org > > > [mailto:python-list-bounces+m.yanowitz=kearfott.... at python.org]On Behalf > > Of half.ital... at gmail.com > > Sent: Wednesday, May 09, 2007 5:12 PM > > To: python-l... at python.org > > Subject: Re: Checking if string inside quotes? > > > On May 9, 1:39 pm, "Michael Yanowitz" wrote: > > > Hello: > > > > If I have a long string (such as a Python file). > > > I search for a sub-string in that string and find it. > > > Is there a way to determine if that found sub-string is > > > inside single-quotes or double-quotes or not inside any quotes? > > > If so how? > > > > Thanks in advance: > > > Michael Yanowitz > > > I think the .find() method returns the index of the found string. You > > could check one char before and then one char after the length of the > > string to see. I don't use regular expressions much, but I'm sure > > that's a more elegant approach. > > > This will work. You'll get in index error if you find the string at > > the very end of the file. > > > s = """ > > foo > > "bar" > > """ > > findme = "foo" > > index = s.find(findme) > > > if s[index-1] == "'" and s[index+len(findme)] == "'": > > print "single quoted" > > elif s[index-1] == "\"" and s[index+len(findme)] == "\"": > > print "double quoted" > > else: > > print "unquoted" > > > ~Sean > > > --http://mail.python.org/mailman/listinfo/python-list > > In that case I suppose you'd have to read the file line by line and if > you find your string in the line then search for the indexes of any > matching quotes. If you find matching quotes, see if your word lies > within any of the quote indexes. > > #!/usr/bin/env python > > file = open("file", 'r') > findme= "foo" > for j, line in enumerate(file): > found = line.find(findme) > if found != -1: > quotecount = line.count("'") > quoteindexes = [] > start = 0 > for i in xrange(quotecount): > i = line.find("'", start) > quoteindexes.append(i) > start = i+1 > > f = False > for i in xrange(len(quoteindexes)/2): > if findme in > line[quoteindexes.pop(0):quoteindexes.pop(0)]: > f = True > print "Found %s on line %s: Single-Quoted" % (findme, j > +1) > if not f: > print "Found %s on line %s: Not quoted" % (findme, j+1) > > It's not pretty but it works. > > ~Sean This approach omits double-quoted strings, escaped single-quotes "'a \'b' my tag", triple-quoted strings, as well as multi-line strings of any type. Depends what constraints you can sacrifice. Maybe character-at-a- time, or manually untokenize the solution above. For generic input, use mine. From Maksim.Kasimov at gmail.com Fri May 25 07:03:05 2007 From: Maksim.Kasimov at gmail.com (sim.sim) Date: 25 May 2007 04:03:05 -0700 Subject: just a bug (was: xml.dom.minidom: how to preserve CRLF's inside CDATA?) In-Reply-To: References: <1179841504.782279.86490@u36g2000prd.googlegroups.com> <1180082137.329142.45350@p77g2000hsh.googlegroups.com> Message-ID: <1180090985.066935.218250@h2g2000hsg.googlegroups.com> On 25 ???, 12:45, Marc 'BlackJack' Rintsch wrote: > In <1180082137.329142.45... at p77g2000hsh.googlegroups.com>, sim.sim wrote: > > Below the code that tryes to parse an well-formed xml, but it fails > > with error message: > > "not well-formed (invalid token): line 3, column 85" > > How did you verified that it is well formed? `xmllint` barf on it too. you can try to write iMessage to file and open it using Mozilla Firefox (web-browser) > > > The "problem" within CDATA-section: it consists a part of utf-8 > > encoded string wich was splited (widely used for memory limited > > devices). > > > When minidom parses the xml-string, it fails becouse it tryes to convert > > into unicode the data within CDATA-section, insted of just to return the > > value of the section "as is". The convertion contradicts the > > specificationhttp://www.w3.org/TR/REC-xml/#sec-cdata-sect > > An XML document contains unicode characters, so does the CDTATA section. > CDATA is not meant to put arbitrary bytes into a document. It must > contain valid characters of this typehttp://www.w3.org/TR/REC-xml/#NT-Char(linked from the grammar of CDATA in > your link above). > > Ciao, > Marc 'BlackJack' Rintsch my CDATA-section contains only symbols in the range specified for Char: Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] filter(lambda x: ord(x) not in range(0x20, 0xD7FF), iMessage) From siona at chiark.greenend.org.uk Wed May 9 09:47:39 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 09 May 2007 14:47:39 +0100 (BST) Subject: N00b question on Py modules References: <1178521238.333095.111370@h2g2000hsg.googlegroups.com> <1178535840.526299.126700@e65g2000hsc.googlegroups.com> Message-ID: wrote: >Thanks a lot for the responses ppl. Python's treatment of global >variables was an eye-opener. I have coded in Java & C/C++ in the past >and there the behaviour is diametrically opposite. How so? Python style gurus discourage use of global variables. So does all the C++ (and to a lesser extent C) advice I've ever encountered. And Java outright forbids the concept. It's one area where there seems to be universal agreement. -- \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 thorsten at thorstenkampe.de Tue May 15 08:13:37 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 15 May 2007 13:13:37 +0100 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <1hy2qg3.iqfvwnrvr9kjN%aleax@mac.com> <46482624.6050507@web.de> <7xd512onsx.fsf@ruckus.brouhaha.com> <464951EF.7030900@web.de> <464997a5$0$10193$9b4e6d93@newsspool4.arcor-online.net> Message-ID: * Ren? Fleschenberg (Tue, 15 May 2007 13:21:10 +0200) > Stefan Behnel schrieb: > > "go to" is not meant for clarity, nor does it encourage code readability. > > Some people would argue that position. > > > But that's what this PEP is about. > > IMHO, this PEP does not encourage clarity and readability, it > discourages it. > Identifiers which my terminal cannot even display surely > are not very readable. This PEP is not about you. It's about people who write in their native language and who are forced to use a dodgy transcription from characters of their own language to ASCII. From tgrav at mac.com Fri May 4 21:40:53 2007 From: tgrav at mac.com (Tommy Grav) Date: Fri, 4 May 2007 21:40:53 -0400 Subject: Looping over lists Message-ID: <64D2C5F9-2896-47C3-8606-B021DB9D378A@mac.com> I have a list: a = [1., 2., 3., 4., 5.] I want to loop over a and then loop over the elements in a that is to the right of the current element of the first loop In C this would be equivalent to: for(i = 0; i < n; i++) { for(j=i+1; j < n; j++) { print a[i], a[j] and should yield: 1. 2. 1. 3. 1. 4. 1. 5. 2. 3. 2. 4. 2. 5. 3. 4. 3. 5. 4. 5. Can anyone help me with the right approach for this in python? Cheers Tommy From pete.losangeles at gmail.com Wed May 30 17:11:44 2007 From: pete.losangeles at gmail.com (MisterPete) Date: 30 May 2007 14:11:44 -0700 Subject: print bypasses calling write method for objects inheriting from file? In-Reply-To: References: <1180508789.556984.204520@o11g2000prd.googlegroups.com> Message-ID: <1180559504.670828.11540@x35g2000prf.googlegroups.com> On May 31, 5:54 am, Peter Otten <__pete... at web.de> wrote: > Gabriel Genellina wrote: > > En Wed, 30 May 2007 04:24:30 -0300, Peter Otten <__pete... at web.de> > > escribi?: > > >>> I created an object that inherits from file and was a bit surprised to > >>> find thatprintseems to bypass the write method for objects > >>> inheriting from file. An optimization I suppose. Does this surprise > >>> anyone else at all or am I missing something? > > >> No, your analysis is correct, though I'd consider optimization an > >> euphemism > >> for bug here. Noone was annoyed enough to write a patch, it seems. > > > A one-line patch, I guess, PyFile_CheckExact instead of PyFile_Check. Or a > > few lines, checking if the write method is still the builtin one. As this > > is the third time I see this question I'll try to submit the patch. > > Good idea ;) Don't know if it is still applicable, but here's a patch by > Jeff Epler: > > http://groups.google.com/group/comp.lang.python/msg/91d46ff2e05e1476 > > Peter Thanks for the quick replies! I forgot to mention that I was using Python v2.4.3 but it sounds like it is still a problem anyway. Thanks Peter and Gabriel. From michael at jedimindworks.com Sun May 20 08:49:57 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Sun, 20 May 2007 07:49:57 -0500 Subject: Unable to strip \n characters In-Reply-To: References: <1179658203.040541.220800@p77g2000hsh.googlegroups.com> Message-ID: <58A5C157-A30A-4452-89D7-4AE48D2AECB8@jedimindworks.com> On May 20, 2007, at 7:41 AM, Michael Bentley wrote: > (upload.strip()) Oops: (upload.strip(),) or upload.strip() From rene at korteklippe.de Tue May 15 08:27:26 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 15 May 2007 14:27:26 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <464996b9$0$10193$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <4649a72d$0$10186$9b4e6d93@newsspool4.arcor-online.net> Thorsten Kampe schrieb: >> That is a reason to actively encourage people to write their code in >> English whereever possible, not one to allow non-ASCII identifiers, >> which might even do the opposite. > > There is no reason to encourage or discourage people in which language > to write their code. There is, because code sharing is generally a good thing. If you don't think it is, then we'll just have to agree to disagree on that point. > Code that's meant to be shared makes just a tiny > percentage of all the code written right this moment. > > This "ready to be shared" code is neither better nor worse than > "closed" german or chinese-only code. The implementaton of this PEP would not make Chinese-only Python code possible. It would only make a Chinese-English gibberish without ASCII transliteration possible. Also, alot of code that starts out as "closed" and not meant to be shared is shared at some point (this is how we got Zope, AFAIK), and this is a thing that should be encouraged. -- Ren? From gagsl-py2 at yahoo.com.ar Tue May 8 21:43:44 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 08 May 2007 22:43:44 -0300 Subject: String parsing References: <1178672992.522463.228620@l77g2000hsb.googlegroups.com> Message-ID: En Tue, 08 May 2007 22:09:52 -0300, HMS Surprise escribi?: > The string below is a piece of a longer string of about 20000 > characters returned from a web page. I need to isolate the number at > the end of the line containing 'LastUpdated'. I can find > 'LastUpdated' with .find but not sure about how to isolate the > number. 'LastUpdated' is guaranteed to occur only once. Would > appreciate it if one of you string parsing whizzes would take a stab > at it. > > > > > > > >
    align="center" You really should use an html parser here. But assuming that the page will not change a lot its structure you could use a regular expression like this: expr = re.compile(r'name\s*=\s*"LastUpdated"\s+value\s*=\s*"(.*?)"', re.IGNORECASE) number = expr.search(text).group(1) (Handling of "not found" and "duplicate" cases is left as an exercise for the reader) Note that is as valid as your html, but won't match the expression. -- Gabriel Genellina From showell30 at yahoo.com Sun May 27 13:57:29 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 27 May 2007 10:57:29 -0700 (PDT) Subject: itertools.groupby In-Reply-To: <1180286272.100790.131670@q75g2000hsh.googlegroups.com> Message-ID: <474296.49047.qm@web33508.mail.mud.yahoo.com> --- 7stud wrote: > Bejeezus. The description of groupby in the docs is > a poster child > for why the docs need user comments. I would suggest an example with a little more concreteness than what's currently there. For example, this code... import itertools syslog_messages = [ 'out of file descriptors', 'out of file descriptors', 'unexpected access', 'out of file descriptors', ] for message, messages in itertools.groupby(syslog_messages): print message, len(list(messages)) ...produces this... out of file descriptors 2 unexpected access 1 out of file descriptors 1 ____________________________________________________________________________________Get the free Yahoo! toolbar and rest assured with the added security of spyware protection. http://new.toolbar.yahoo.com/toolbar/features/norton/index.php From srikrishnamohan at gmail.com Wed May 9 04:45:20 2007 From: srikrishnamohan at gmail.com (km) Date: Wed, 9 May 2007 14:15:20 +0530 Subject: __getattr__ and __getattribute__ In-Reply-To: References: Message-ID: Oh thats lucid! thanks for the explanation. regards KM ------------------------------------------------------------- On 5/9/07, Gabriel Genellina wrote: > > En Tue, 08 May 2007 08:22:03 -0300, km > escribi?: > > > i find it difficult to understand the difference between the magic > > methods > > __getattr__ and __getattribute__ > > and so donot know when to use former or later. > > can someone brief me on it ? > > This is better understood with a bit of history. > On earlier Python versions (before 2.2) the only object model available > was what we now call "classic classes". > Classic instances hold their attributes in a dictionary, called __dict__. > Attribute lookup starts at this instance dictionary; if not found, > continues in the class, and its parent class, all along the inheritance > tree. If still not found, __getattr__ (if it exists) is called, and should > return the attribute value or raise AttributeError. That is, __getattr__ > is called *last*, and *only* when the attribute was not previously found > in the usual places. > > Since Python 2.2, there are "new style classes" available; they inherit > directly or indirectly from object. A new style instance may not even have > a __dict__. An existing __getattribute__ method is tried *first*; it > should return the attribute value or raise AttributeError. If no custom > __getattribute__ exists, the default object.__getattribute__ is used. As a > last resort, if __getattr__ is defined, it is called. > > OTOH, there is a single version of __setattr__, which is always invoked > when setting an attribute. > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From QncyMI at netscape.net Thu May 3 01:24:23 2007 From: QncyMI at netscape.net (Major Quaternion Dirt Quantum) Date: 2 May 2007 22:24:23 -0700 Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? In-Reply-To: <1178163168.661168.19700@p77g2000hsh.googlegroups.com> References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> <57li33hegq8g81bbcru09gagbpqp6eq3cp@4ax.com> <1178163168.661168.19700@p77g2000hsh.googlegroups.com> Message-ID: <1178169863.602236.287420@p77g2000hsh.googlegroups.com> maybe, "pulled" is just a firefighteresque synonym for gravity doing its thing -- still not subsumed in the Standard Model of physicists, so, There. y'know, sort of like, how it is, pilots refer to going "out" and "in," instead of up & down. Zogby clientlist, VERY cool; what great organizations I will assume them to be -- if any one else wants to look at it & report back.... lies, polls, statistics; how they, for instance, leveraged the Governeurateur, during the Recall, by the art of dysmissing "less likely voters" that they had interviewed, because they were a) Democrats, and b) were removed by some other signal processing techniques; what it is?... thank gawd for Zogby et al ad vomitorium; with over 40% electronic voting, how *else* will you know? I liked the "WTC7 for Sheeple" thing; what station, did you say, broadcast it?... well, even though I have no audio on this terminal, I still learned a couple of things ... kind of a tedious exercise, though. anyway, I know, you were not suggesting that (--with the rather obvious burning on the other side, that was away from most of your videos, and after teh catastrophic collapse and/or demolition of both, huge towers into the gigantic subway--) the commanding officers should have kept them inside the evacuated building, til it fell. it could only be interpreted in that way "with malice aforethought," or by someone whose deployment of English was less nuanced than yours; 10-4? so, what sort of "fire-fighting action" should they have been engaged in at WTC7 -- more of those red-painted extinguishers, or phoning the Forest Service? keep breathing, while you're typing! > Sure, you have firefighters and all the first responders telling you > LIVE in the video that the building is going to be pulled down. > Voting Age Americans are fucking retarded:http://www.zogby.com/search/ReadNews.dbm?yourself:http://www.zogby.com/about/clients.cfm http://www.youtube.com/watch?v=YNN6apj5B2U http://www.youtube.com/watch?v=TVSxeJH_RCY http://www.youtube.com/watch?v=9YND7XocMocj thus: here's a question that came-up recently, in battling with the controlled-demo advocates at the Promenade: how is it that the metal was still molten, after weeks?... it seems that an additional hypothesis is required, to explain that. because, I doubt that there was sufficient nukular material "left-over" from a hypothetical suitcase-device. publications:http://www.physics.uiowa.edu/~cgrabbe/writing/ research.html thus: have you seen the old analysis by the MIT Head Welder, that I only saw a couple of weeks ago? http://www.rwgrayprojects.com/synergetics/plates/figs/plate01.html thus: why do Dick, Borat, Osama, Harry P., Rumsfeld and Tony B. want us to underwrite the 3rd British Invasion of Sudan, so badly?... anyway, Bertrand Russel published a jeremyad in the Bulletin of the Atomic Scientists, while the USA was the only thermonukey power, that we should bomb the SU into the Stone Age; that's your British "pacifist," whether before or after he went nuts because of Godel's proof. thus: if you can't prove that all Fermat numbers are pairwise coprime, again! Darfur 'Mini-Summit' http://www.larouchepub.com/other/1998/rice_2546.html thus: uh yeah; Borat wants you in Sudan, why, Baby?... Harry Potter wants you in Iran -- yeah, Baby; shag'US with a spoon? --DARFURIA CONSISTS OF ARABs & nonARABs; NEWS-ITEM: we are marching to Darfuria, Darfuria, Darfuria! Harry Potter IIX, ?Ordeal @ Oxford//Sudan ^ Aircraft Carrier! http://larouchepub.com/other/2007/3410caymans_hedges.html ALgoreTHEmovieFORpresident.COM: http://larouchepub.com/eirtoc/site_packages/2007/al_gore.html From b.r.willems at gmail.com Tue May 1 20:17:14 2007 From: b.r.willems at gmail.com (Bart Willems) Date: Tue, 01 May 2007 20:17:14 -0400 Subject: python win32com excel problem In-Reply-To: <4KQZh.214$o47.98@newsfe12.lga> References: <4KQZh.214$o47.98@newsfe12.lga> Message-ID: Bart Willems wrote: > Autofit is a method. Also, columns are a method of a worksheet - try: > xlApp.Worksheets.Columns("C:K").Autofit() Silly me. That is of course xlApp.Activesheet.Columns("C:K").Autofit() On a sidenote, you can refer to a worksheet with xlApp.Worksheets(Name) as well. From http Mon May 28 23:18:18 2007 From: http (Paul Rubin) Date: 28 May 2007 20:18:18 -0700 Subject: itertools.groupby References: <1180286272.100790.131670@q75g2000hsh.googlegroups.com> <7xveecr5xx.fsf@ruckus.brouhaha.com> <6Y6dnb0mTLsaCsbbnZ2dnUVZ_hCdnZ2d@comcast.com> Message-ID: <7xabvo71xh.fsf@ruckus.brouhaha.com> Gordon Airporte writes: > "itertools.groupby_except_the_notion_of_uniqueness_is_limited_to- > _contiguous_runs_of_elements_having_the_same_key()" doesn't have much > of a ring to it. I guess this gets back to documentation problems, > because the help string says nothing about this limitation: > > ''' > class groupby(__builtin__.object) > | groupby(iterable[, keyfunc]) -> create an iterator which returns > | (key, sub-iterator) grouped by each value of key(value). > | > ''' I wouldn't call it a "limitation"; it's a designed behavior which is the right thing for some purposes and maybe not for others. For example, groupby (as currently defined) works properly on infinite sequences, but a version that scans the entire sequence to get bring together every occurrence of every key would fail in that situation. I agree that the doc description could be reworded slightly. From carsten at uniqsys.com Sun May 27 20:35:28 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sun, 27 May 2007 20:35:28 -0400 Subject: Why isn't this query working in python? In-Reply-To: References: <1180103946.552760.239200@p47g2000hsd.googlegroups.com> <6e42ec490705250751i89d3cf3v3a3062690d0284aa@mail.gmail.com> <1180207521.072958.322770@p47g2000hsd.googlegroups.com> <1180225290.235515.274000@q19g2000prn.googlegroups.com> <1180279833.131269.136770@w5g2000hsg.googlegroups.com> Message-ID: <1180312528.3155.22.camel@localhost.localdomain> On Sun, 2007-05-27 at 16:39 -0400, davelist at mac.com wrote: > > sql = """SELECT payment_id FROM amember_payments WHERE > > member_id=%s AND expire_date > NOW() AND completed=1 AND (product_id > >>> 11 AND product_id <21)""", (self.uid) > > > > > And doesn't the above comma, need to be a percent symbol? No. The poster is using parameter passing, not string formatting. -- Carsten Haese http://informixdb.sourceforge.net From johs at siz-nospam-efitter.com Tue May 1 00:36:58 2007 From: johs at siz-nospam-efitter.com (johannes) Date: Tue, 01 May 2007 04:36:58 GMT Subject: Free Windows Vista Download References: <1177866404.344342.175400@h2g2000hsg.googlegroups.com> Message-ID: <4636C40E.BA8D31C1@siz-nospam-efitter.com> Spin Dryer wrote: > > On Sun, 29 Apr 2007 20:23:22 -0400, ["Alvin Bruney [MVP]" without an email address>] said :- > > >That's a misleading post, you should indicate that this is an evaluation > >copy. > > You did it again Sonny, making yourself look a total fool. > > Will you stop top posting replies to spam and _leaving the spamed site > attached_. There is always 1. From sjdevnull at yahoo.com Wed May 16 15:37:44 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 16 May 2007 12:37:44 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179333797.634234.245830@k79g2000hse.googlegroups.com> Message-ID: <1179344264.595644.136440@h2g2000hsg.googlegroups.com> On May 16, 12:54 pm, Gregor Horvath wrote: > Istvan Albert schrieb: > > > Here is something that just happened and relates to this subject: I > > had to help a student run some python code on her laptop, she had > > Windows XP that hid the extensions. I wanted to set it up such that > > the extension is shown. I don't have XP in front of me but when I do > > it takes me 15 seconds to do it. Now her Windows was set up with some > > asian fonts (Chinese, Korean not sure), looked extremely unfamiliar > > and I had no idea what the menu systems were. We have spent quite a > > bit of time figuring out how to accomplish the task. I had her read me > > back the options, but something like "hide extensions" comes out quite > > a bit different. Surprisingly tedious and frustrating experience. > > So the solution is to forbid Chinese XP ? > It's one solution, depending on your support needs. Independent of Python, several companies I've worked at in Ecuador (entirely composed of native Spanish-speaking Ecuadoreans) use the English-language OS/application installations--they of course have the Spanish dictionaries and use Spanish in their documents, but for them, having localized application menus generates a lot more problems than it solves. From rohitsethidce at gmail.com Thu May 24 04:08:57 2007 From: rohitsethidce at gmail.com (rohit) Date: 24 May 2007 01:08:57 -0700 Subject: read file to a dictionary In-Reply-To: References: <1179962203.201472.104500@q19g2000prn.googlegroups.com> Message-ID: <1179994137.289599.164100@n15g2000prd.googlegroups.com> ohh i think i forgot to include intricate details in dictionary i use the following: value: name of a file existing on disk Key : a unique number assigned to each file ,with no. assigned in increasing order to file appearing earlier in the "english dictionary" thanks rohit From gh at gregor-horvath.com Thu May 17 09:41:47 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Thu, 17 May 2007 15:41:47 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464C5936.5020003@v.loewis.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649dd55$0$23144$9b4e6d93@newsspool1.arcor-online.net> <464a25e9$0$10188$9b4e6d93@newsspool4.arcor-online.net> <1179291296.561359.286230@h2g2000hsg.googlegroups.com> <464ab64f$0$10185$9b4e6d93@newsspool4.arcor-online.net> <464AB9F2.60906@web.de> <464ac189$0$20297$9b4e6d93@newsspool3.arcor-online.net> <464ac493$0$6394$9b4e6d93@newsspool2.arcor-online.net> <464add30$0$6401$9b4e6d93@newsspool2.arcor-online.net> <464C5936.5020003@v.loewis.de> Message-ID: Martin v. L?wis schrieb: > I've reported this before, but happily do it again: I have lived many > years without knowing what a "hub" is, and what "to pass" means if > it's not the opposite of "to fail". Yet, I have used their technical > meanings correctly all these years. That's not only true for computer terms. In the German Viennese slang there are a lot of Italian, French, Hungarian, Czech, Hebrew and Serbocroatien words. Nobody knows the exact meaning in their original language (nor does the vast majority actually speak those languages), but all are used in the correct original context. Gregor From jorgen.maillist at gmail.com Sun May 13 08:53:42 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Sun, 13 May 2007 14:53:42 +0200 Subject: Real globals inside a module In-Reply-To: <20070513121344.GB4875@laptux.workaround.org> References: <11e49df10705130241s179297f9q68bb799f8d1ec1b3@mail.gmail.com> <20070513121344.GB4875@laptux.workaround.org> Message-ID: <11e49df10705130553h3f29e02m782091d9100bf89@mail.gmail.com> great! Thanks it makes perfect sense, but before attempting some code rewrite I just wanted to be sure ;-) Regards, - Jorgen On 5/13/07, Christoph Haas wrote: > On Sun, May 13, 2007 at 11:41:12AM +0200, Jorgen Bodde wrote: > > I am wrestling with some architecture inside my app. Let's say I have > > a tunings collection, which contains e.g. 23 types of guitar tunings. > > In my song object I want to restore a relation between one of the > > tuning objects inside the tunings module. > > > > I already figured out I need somethign like a global collection inside > > the tunings module,. but how global is it? When I am inside my app > > object, and import the tunings module, can I access the same global > > class as when I am inside my songs module and load the tunings module? > > You are on the right way. If you import the same module a second time in > another place of your application you get access to the exact same data. > That is called a "singleton". I often use such a singleton for global > configuration data. > > > So basically I want to access the same global list in both modules, > > but not re-create the list in every module since it should be restored > > by the database layer once. > > Import your global module and just run the initalisation once. That > should do it. > > > Thanks for any advice, I do not want to make a global manager object > > that I need to pass around all the time, that would be silly.. > > Indeed. That would suck. > > Christoph > > -- > http://mail.python.org/mailman/listinfo/python-list > From sjmachin at lexicon.net Wed May 2 19:01:05 2007 From: sjmachin at lexicon.net (John Machin) Date: 2 May 2007 16:01:05 -0700 Subject: Slicing Arrays in this way In-Reply-To: References: <4638fe20$0$16403$88260bb3@free.teranews.com> Message-ID: <1178146865.383519.326430@c35g2000hsg.googlegroups.com> On May 3, 8:55 am, Steven D'Aprano wrote: > On Wed, 02 May 2007 15:03:24 -0700, Tobiah wrote: > > > >>> elegant_solution([1,2,3,4,5,6,7,8,9,10]) > > [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] > > Wow! That's impressive. What version of Python are you using? When I try > it, I get this: > > >>> elegant_solution([1,2,3,4,5,6,7,8,9,10]) > > Traceback (most recent call last): > File "", line 1, in > NameError: name 'elegant_solution' is not defined > The OP has already confessed. Don't rub it in. From kyosohma at gmail.com Thu May 3 17:24:05 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 3 May 2007 14:24:05 -0700 Subject: How to replace the last (and only last) character in a string? In-Reply-To: <1178203453.579755.323410@p77g2000hsh.googlegroups.com> References: <1178202464.201578.211150@c35g2000hsg.googlegroups.com> <1178203052.794524.223790@o5g2000hsb.googlegroups.com> <1178203453.579755.323410@p77g2000hsh.googlegroups.com> Message-ID: <1178227445.038501.170930@n76g2000hsh.googlegroups.com> On May 3, 9:44 am, Johny wrote: > On May 3, 4:37 pm, kyoso... at gmail.com wrote: > > > > > On May 3, 9:27 am, Johny wrote: > > > > Let's suppose > > > s='12345 4343 454' > > > How can I replace the last '4' character? > > > I tried > > > string.replace(s,s[len(s)-1],'r') > > > where 'r' should replace the last '4'. > > > But it doesn't work. > > > Can anyone explain why? > > > > Thanks > > > L. > > > I think the reason it's not working is because you're doing it kind of > > backwards. For one thing, the "string" module is deprecated. I would > > do it like this: > > > s = s.replace(s[len(s)-1], 'r') > > > Although that is kind of hard to read. But it works. > > > Mike > > Mike it does NOT work for me.>>> s.replace(s[len(s)-1], 'r') > > '123r5 r3r3 r5r' > > I need only the last characte Yeah...I'm an idiot. Sorry about that. Listen to the other users! Mike From vatamane at gmail.com Wed May 9 06:04:09 2007 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 9 May 2007 03:04:09 -0700 Subject: Multiple regex match idiom In-Reply-To: <87r6pqxtgh.fsf@busola.homelinux.net> References: <87r6pqxtgh.fsf@busola.homelinux.net> Message-ID: <1178705049.150694.274750@o5g2000hsb.googlegroups.com> On May 9, 5:00 am, Hrvoje Niksic wrote: > I often have the need to match multiple regexes against a single > string, typically a line of input, like this: > > if (matchobj = re1.match(line)): > ... re1 matched; do something with matchobj ... > elif (matchobj = re2.match(line)): > ... re2 matched; do something with matchobj ... > elif (matchobj = re3.match(line)): > .... > > Of course, that doesn't work as written because Python's assignments > are statements rather than expressions. The obvious rewrite results > in deeply nested if's: > > matchobj = re1.match(line) > if matchobj: > ... re1 matched; do something with matchobj ... > else: > matchobj = re2.match(line) > if matchobj: > ... re2 matched; do something with matchobj ... > else: > matchobj = re3.match(line) > if matchobj: > ... > > Normally I have nothing against nested ifs, but in this case the deep > nesting unnecessarily complicates the code without providing > additional value -- the logic is still exactly equivalent to the > if/elif/elif/... shown above. > > There are ways to work around the problem, for example by writing a > utility predicate that passes the match object as a side effect, but > that feels somewhat non-standard. I'd like to know if there is a > Python idiom that I'm missing. What would be the Pythonic way to > write the above code? Hrvoje, To make it more elegant I would do this: 1. Put all the ...do somethings... in functions like re1_do_something(), re2_do_something(),... 2. Create a list of pairs of (re,func) in other words: dispatch=[ (re1, re1_do_something), (re2, re2_do_something), ... ] 3. Then do: for regex,func in dispatch: if regex.match(line): func(...) Hope this helps, -Nick Vatamaniuc From claird at lairds.us Fri May 18 16:27:54 2007 From: claird at lairds.us (Cameron Laird) Date: Fri, 18 May 2007 20:27:54 +0000 Subject: Python compared to other language References: <1179516027.425206.67680@o5g2000hsb.googlegroups.com> Message-ID: In article <1179516027.425206.67680 at o5g2000hsb.googlegroups.com>, Beliavsky wrote: >On May 18, 3:04 pm, scott wrote: >> Hi all, >> >> I have been looking at the various programming languages available. I >> have programed in Basic since I was a teenager and I also have a basic >> understanding of C, but I want something better. >> >> Can anybody tell me the benefits and weaknesses of using Python? > >That question has been asked hundreds of times here -- read the >archives of this group and language comparisons on the web, for >example the one by Eric Raymond at >http://www.faqs.org/docs/artu/languageschapter.html >. > >Even better, try the language and draw your own conclusions. > "... [T]ry the language and draw your own conclusions" is better advice than the original questioner might realize, for he doesn't yet know how low is the cost to get started with Python . In the meantime, might be of interest. From martin at v.loewis.de Wed May 2 16:58:14 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 02 May 2007 22:58:14 +0200 Subject: Tcl-tk 8.5? In-Reply-To: <46382248$0$5105$ba4acef3@news.orange.fr> References: <46382248$0$5105$ba4acef3@news.orange.fr> Message-ID: <4638fb66$0$1098$9b622d9e@news.freenet.de> > Any plan to integrate Tcl 8.5 in standard Python? Sure: once Tcl 8.5 is released, it will be integrated with the next major version of Python. That might be Python 2.6, 3.0, 3.1,... depending on how long it takes to release Tcl 8.5. In any case, "integration" is necessary only for binary releases. If you compile Python yourself, you are free to integrate Python with Tcl 8.5a4 if you so desire. Regards, Martin From victor.kryukov at gmail.com Wed May 16 13:13:42 2007 From: victor.kryukov at gmail.com (Victor Kryukov) Date: 16 May 2007 10:13:42 -0700 Subject: cPickle.dumps differs from Pickle.dumps; looks like a bug. Message-ID: <1179335622.006820.22460@q23g2000hsg.googlegroups.com> Hello list, I've found the following strange behavior of cPickle. Do you think it's a bug, or is it by design? Best regards, Victor. from pickle import dumps from cPickle import dumps as cdumps print dumps('1001799')==dumps(str(1001799)) print cdumps('1001799')==cdumps(str(1001799)) outputs True False vicbook:~ victor$ 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. >>> quit() vicbook:~ victor$ uname -a Darwin vicbook 8.9.1 Darwin Kernel Version 8.9.1: Thu Feb 22 20:55:00 PST 2007; root:xnu-792.18.15~1/RELEASE_I386 i386 i386 From deets at nospam.web.de Tue May 15 08:28:52 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 15 May 2007 14:28:52 +0200 Subject: Recursion limit problems References: <1178921877.442519.165740@u30g2000hsc.googlegroups.com> <1179156916.706892.144770@y80g2000hsf.googlegroups.com> Message-ID: <5atnc4F2pkv2eU1@mid.uni-berlin.de> > with the same hash value. > That is, you should define __hash__ and one of (__cmp__ or __eq__). > __neq__ (inequality) isn't required nor used by dict/set implementation. > (Anyway, Python will transform a!=b into not(a==b), if __neq__ isn't > defined). Neither <, <=, >, >= are used. No, it won't: http://docs.python.org/ref/customization.html#l2h-190 """ There are no implied relationships among the comparison operators. The truth of x==y does not imply that x!=y is false. Accordingly, when defining __eq__(), one should also define __ne__() so that the operators will behave as expected. """ --------------------- class Foo(object): def __eq__(self, other): print "__eq__" return id(self) == id(other) Foo() == Foo() Foo() != Foo() --------------- will give you only one call to __eq__ Diez From mail at timgolden.me.uk Fri May 25 01:06:52 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 25 May 2007 06:06:52 +0100 Subject: File monitoring for all drive In-Reply-To: <1180049186.804822.5060@a26g2000pre.googlegroups.com> References: <1180049186.804822.5060@a26g2000pre.googlegroups.com> Message-ID: <46566EEC.1080305@timgolden.me.uk> rohit wrote: > hi > i want to detect all file change operations(rename,delete,create....) > on ALL THE DRIVES of the hard disk > using the method ReadDirectoryChanges API , i.e program no. 3 in the > webpage http://tgolden.sc.sabren.com/python/win32_how_do_i/watch_directory_for_changes.html > . > Please suggest some modification to the program so that i can detect > changes to ALL the drives > (to detect changes on c:\ set > path_to_watch = "." to "c:\\" but this works for only one drive Well, to answer the question specifically: since the Windows filesstem has no concept of a "root" above the drive letters, the simplest thing to do is to kick off a thread or a subprocess or what-have-you for each drive letter. The *shell* has the concept of a "My Computer" which notionally sits above the various drives, but since it isn't itself a drive and since I assume you're only interested in local drives anyway and not the rest of the shell-y stuff which sits underneath it, you'd end up querying for local drives and going the same path in any case. TJG From martin at v.loewis.de Wed May 2 16:55:23 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 02 May 2007 22:55:23 +0200 Subject: Why are functions atomic? In-Reply-To: References: <1178017578.297894.50690@y80g2000hsf.googlegroups.com> <1178044821.864741.235260@o5g2000hsb.googlegroups.com> <1178063341.779617.289690@o5g2000hsb.googlegroups.com> <1178065685.161372.81790@y80g2000hsf.googlegroups.com> <463816a9$0$9276$9b622d9e@news.freenet.de> Message-ID: <4638FABB.3060305@v.loewis.de> >> The answer is really really simple. The implementation of copy predates >> mutability. When the copy code was written, functions *were* immutable. >> When functions became mutable, the copy code was not changed, and >> nobody noticed or complained. > > Likely scenario, but not true. Interesting. I (clearly) missed that part of the defaultdict discussion (that was a long thread). Regards, Martin From mccredie at gmail.com Thu May 3 10:52:17 2007 From: mccredie at gmail.com (Matimus) Date: 3 May 2007 07:52:17 -0700 Subject: How to replace the last (and only last) character in a string? In-Reply-To: <1178203453.579755.323410@p77g2000hsh.googlegroups.com> References: <1178202464.201578.211150@c35g2000hsg.googlegroups.com> <1178203052.794524.223790@o5g2000hsb.googlegroups.com> <1178203453.579755.323410@p77g2000hsh.googlegroups.com> Message-ID: <1178203937.627182.59950@e65g2000hsc.googlegroups.com> On May 3, 7:44 am, Johny wrote: > On May 3, 4:37 pm, kyoso... at gmail.com wrote: > > > > > On May 3, 9:27 am, Johny wrote: > > > > Let's suppose > > > s='12345 4343 454' > > > How can I replace the last '4' character? > > > I tried > > > string.replace(s,s[len(s)-1],'r') > > > where 'r' should replace the last '4'. > > > But it doesn't work. > > > Can anyone explain why? > > > > Thanks > > > L. > > > I think the reason it's not working is because you're doing it kind of > > backwards. For one thing, the "string" module is deprecated. I would > > do it like this: > > > s = s.replace(s[len(s)-1], 'r') > > > Although that is kind of hard to read. But it works. > > > Mike > > Mike it does NOT work for me.>>> s.replace(s[len(s)-1], 'r') > > '123r5 r3r3 r5r' > > I need only the last character to be replaced Its not working because str.replace: [docstring] Help on method_descriptor: replace(...) S.replace (old, new[, count]) -> string Return a copy of string S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. [/docstring] Notice the "all occurrences of substring" part. Strings are immutable, so there isn't really any replace, either way you are going to be creating a new string. So the best way to do what (I think) you want to do is this... [code] >>> s = '12345 4343 454' >>> s = s[:-1]+'r' >>> s '12345 4343 45r' [/code] From see_below_no_spam at yahoo.es Wed May 16 09:14:40 2007 From: see_below_no_spam at yahoo.es (Javier Bezos) Date: Wed, 16 May 2007 15:14:40 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <7x4pmg716p.fsf@ruckus.brouhaha.com> <4648EC26.8020907@v.loewis.de> Message-ID: "Eric Brunel" escribi? en el mensaje > Funny you talk about Japanese, a language I'm a bit familiar with and for > which I actually know some input methods. The thing is, these only work if > you know the transcription to the latin alphabet of the word you want to > type, which closely match its pronunciation. So if you don't know that ?? > ? is pronounced "uriba" for example, you have absolutely no way of > entering the word. Actually, you can draw the character (in XP, at least) entirely or in part and the system shows a list of them with similar shapes. IIRC, there is a similar tool on Macs. Of course, I'm not saying this allows to enter kanji in a easy and fast way, but certainly it's not impossible at all, even if you don't know the pronunciation. Javier ------------------------------------------- http://www.texytipografia.com From fruels at gmail.com Sun May 6 23:52:18 2007 From: fruels at gmail.com (whitewave) Date: 6 May 2007 20:52:18 -0700 Subject: DiffLib Question In-Reply-To: References: <1178095577.190066.158960@y80g2000hsf.googlegroups.com> <1178097127.286181.216520@y80g2000hsf.googlegroups.com> <1178097973.516943.248720@y80g2000hsf.googlegroups.com> <1178272004.263635.146300@n59g2000hsh.googlegroups.com> Message-ID: <1178509938.636725.154730@w5g2000hsg.googlegroups.com> Hello, I am currently doing the third option. Doing file.read() to both file to be compared then feed the result to the compare function. Let me give you a brief sample of what I want to achieve. Using this code >>> diffline=[] >>> fileDiff = difflib.Differ().compare(f1, f2) >>> diffline = list(fileDiff) >>> finStr = ''.join(diffline) With the following strings for comparison: >>> f1 = ''' The solvable conditions and the Green's functions of linear boundary value ... problems for ordinary differential equations with sufficiently smooth coefficients have been ... investigated in detail by other authors \cite{CR1,CR2,CR3,CR4,CR5}.''' >>> f2 = '''The solvability conditions and the Green's functions of linear boundary value problems for ordinary ... differential equations with sufficiently smooth coefficients have been investigated in detail by many ... authors \cite{CR1,CR2,CR3,CR4,CR5}.''' I get this result: T h e s o l v a b+ i l- e+ i+ t+ y c o n d i t i o n s a n d t h e G r e e n ' s f u n c t i o n s o f l i n e a r b o u n d a r y v a l u e+ + p+ r+ o+ b+ l+ e+ m+ s+ + f+ o+ r+ + o + r+ d+ i+ n+ a+ r+ y + d+ i+ f+ f- p- r- o- b- l e+ r+ e+ n+ t+ i+ a+ l+ + e+ q+ u+ a+ t+ i+ o+ n+ s+ + w+ i+ t+ h+ + s+ u+ f+ f+ i+ c+ i+ e+ n+ t+ l+ y+ + s m- s- - f o- r- o- r- d- i- n- a- r- y- - d- i- f- f- e- r- e- n t- i- a- l- - e- q- u- a- t- i- o- n- s- - w- i- t h - s- u- f- f- i c- i+ o e+ f+ f+ i+ c+ i+ e n t- l- y- s+ + h+ a+ v + e+ + b+ e+ e+ n+ + i+ n+ v+ e+ s+ t+ i+ g+ a+ t+ e+ d+ + i+ n+ + d+ e+ t+ a+ i+ l+ + b+ y+ m- o- o- t- h- - c- o- e- f- f- i- c- i- e- n- t- s- - h a- v- e- - b- e- e n+ y - i- n- v- e- s- t- i- g- a- t- e- d- - i- n- - d- e- t- a- i- l- - b- y- - o- t- h- e- r- a u t h o r s \ c i t e { C R 1 , C R 2 , C R 3 , C R 4 , C R 5 } . Whereas, this is my expected result: T h e s o l v a b+ i l- e+ i+ t+ y c o n d i t i o n s a n d t h e G r e e n ' s f u n c t i o n s o f l i n e a r b o u n d a r y v a l u e- + p r o b l e m s f o r o r d i n a r y- + d i f f e r e n t i a l e q u a t i o n s w i t h s u f f i c i e n t l y s m o o t h c o e f f i c i e n t s h a v e b e e n- + i n v e s t i g a t e d i n d e t a i l b y + m- o- t- h- e- r- a+ n+ y+ + a u t h o r s \ c i t e { C R 1 , C R 2 , C R 3 , C R 4 , C R 5 } . Thanks, Jen From kelvin.you at gmail.com Mon May 28 22:12:16 2007 From: kelvin.you at gmail.com (=?gb2312?B?yMvR1MLkyNXKx8zs0cSjrM37vKvM7NHEsru8+7zS?=) Date: 28 May 2007 19:12:16 -0700 Subject: Issue of redirecting the stdout to both file and screen In-Reply-To: References: <1180343858.903251.182490@x35g2000prf.googlegroups.com> Message-ID: <1180404736.839712.153740@x35g2000prf.googlegroups.com> I see. Many thanks to you! From grante at visi.com Sat May 12 14:45:50 2007 From: grante at visi.com (Grant Edwards) Date: Sat, 12 May 2007 18:45:50 -0000 Subject: Basic question References: <1178986686.510137.195490@p77g2000hsh.googlegroups.com> <1178991933.421386.58500@u30g2000hsc.googlegroups.com> <1178992910.318929.77790@e51g2000hsg.googlegroups.com> Message-ID: <134c2qu80fbgib3@corp.supernews.com> On 2007-05-12, Cesar G. Miguel wrote: > Actually I'm trying to convert a string to a list of float numbers: > str = '53,20,4,2' to L = [53.0, 20.0, 4.0, 2.0] >>> str = '53,20,4,2' >>> [float(w) for w in str.split(',')] [53.0, 20.0, 4.0, 2.0] >>> map(float,str.split(',')) [53.0, 20.0, 4.0, 2.0] -- Grant Edwards grante Yow! I want you to at MEMORIZE the collected visi.com poems of EDNA ST VINCENT MILLAY... BACKWARDS!! From bdesth.quelquechose at free.quelquepart.fr Sun May 20 15:00:33 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 20 May 2007 21:00:33 +0200 Subject: Many-to-many pattern possiable? In-Reply-To: <1179592414.652507.4110@p77g2000hsh.googlegroups.com> References: <1179592414.652507.4110@p77g2000hsh.googlegroups.com> Message-ID: <46509074$0$25104$426a74cc@news.free.fr> Jia Lu a ?crit : > Hi all > > I see dict type can do 1-to-1 pattern, But is there any method to do > 1-to-many, a dict of lists > many-to-1 What's the difference with 1-n ? > and many-to-many pattern ? As usual, using an intermediate dict. > What about using some > Serialized objects? What for ? Anyway, if you're after a relational model, better to use some relational db, possibly with SQLAlchemy on top. From bignose+hates-spam at benfinney.id.au Sun May 27 19:21:03 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 28 May 2007 09:21:03 +1000 Subject: Is PEP-8 a Code or More of a Guideline? References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <87myzqpstb.fsf@benfinney.id.au> <1180282164.427316.51710@p47g2000hsd.googlegroups.com> Message-ID: <873b1hq2e8.fsf@benfinney.id.au> Paul McGuire writes: > It is a bit reassuring that I am not the only one who turns a blind > eye to this part of the PEP, that l_c_w_u bothers others as well. I see similar support for lower_case, and opposition to camelCase. It's nice that we're both reassured by what we see. What now? > We will continue to see std lib code written using l_c_w_u. > Ordinarily, this would little concern me, since I go to read std lib > code about once/year. But it does mean that additions to the > external API to the std lib will contain method calls such as > get_files, send_message, delete_record, etc. I think this just > promotes a perception of Python as "so last century." If clearly-readable code is "so last century", I don't see how that's a negative. > It would also seem we will continue to see 3rd party developers use > whatever their personal taste and/or project coding standards > dictate. So for these users, this part of the PEP is "not really a > code, its more of a guideline."* Many of these libraries have users, and even primary developers, who hope to find the modules added to the standard library one day. I think using lower_case for names is good style in all Python code, for consistency. -- \ "You could augment an earwig to the point where it understood | `\ nuclear physics, but it would still be a very stupid thing to | _o__) do!" -- The Doctor, _The Two Doctors_ | Ben Finney From musiccomposition at gmail.com Sat May 19 22:35:04 2007 From: musiccomposition at gmail.com (Benjamin) Date: 19 May 2007 19:35:04 -0700 Subject: Start In-Reply-To: References: Message-ID: <1179628504.380787.71690@y80g2000hsf.googlegroups.com> On May 19, 10:18 am, Nautilus wrote: > Can anybody halp me start using Python. First you'll need to download Python. You can do that at http://www.python.org. Then download and read the tutorial at http://python.org/doc/. From johnjsal at NOSPAMgmail.com Thu May 10 09:52:32 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 10 May 2007 09:52:32 -0400 Subject: Suggestions for how to approach this problem? In-Reply-To: References: <4640ca5b$0$23392$c3e8da3@news.astraweb.com> <4641ea34$0$6823$c3e8da3@news.astraweb.com> Message-ID: <4643234b$0$11292$c3e8da3@news.astraweb.com> James Stroud wrote: > I included code in my previous post that will parse the entire bib, > making use of the numbering and eliminating the most probable, but still > fairly rare, potential ambiguity. You might want to check out that code, > as my testing it showed that it worked with your example. Thanks. It looked a little involved so I hadn't started to work through it yet, but I'll do that now before I actually try to write something from scratch. :) From thejaswi.puthraya at gmail.com Thu May 31 04:24:36 2007 From: thejaswi.puthraya at gmail.com (theju) Date: 31 May 2007 01:24:36 -0700 Subject: Usage of the __and__ method In-Reply-To: <1180590944.469615.49150@p47g2000hsd.googlegroups.com> References: <1180588305.004419.127680@d30g2000prg.googlegroups.com> <1180590944.469615.49150@p47g2000hsd.googlegroups.com> Message-ID: <1180599876.487437.294820@g37g2000prf.googlegroups.com> Thank you folks for reminding me that the logical AND cannot be over- ridden and that the __and__ method represents the bit-wise AND operation. Thank You Thejaswi Puthraya http://thejuhyd.blogspot.com From tmp123 at menta.net Wed May 2 09:56:31 2007 From: tmp123 at menta.net (tmp123) Date: 2 May 2007 06:56:31 -0700 Subject: pack/unpack zero terminated string Message-ID: <1178114191.580368.59520@c35g2000hsg.googlegroups.com> Hello, Thanks for your time. After review the "struct" documentation, it seems there are no option to pack/unpack zero terminated strings. By example, if the packed data contains: byte + zero terminated string + zero terminated string + byte, it seems no possible to unpack it using "struct". Please, has someone any hint or pointer to another librarian to be used? Thanks. From steve at holdenweb.com Wed May 16 09:26:19 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 16 May 2007 09:26:19 -0400 Subject: Execute commands from file In-Reply-To: <1179320782.594398.67980@u30g2000hsc.googlegroups.com> References: <1179320782.594398.67980@u30g2000hsc.googlegroups.com> Message-ID: tmp123 wrote: > Hello, > > Thanks for your time. > > We have very big files with python commands (more or less, 500000 > commands each file). > Those are BIG programs. Presumably other programs are writing them? > It is possible to execute them command by command, like if the > commands was typed one after the other in a interactive session? > You need to look for "pdb", the interactive Python debugger. This is capable of single-step operations, and supports breakpoints. > ( Better using command flags than with an small script like "while 1: > input()" ) > > Thanks a lot. > You are pretty much going to have to run pdb then trigger your code by calling a pdb method with a function in your code as an argument, if I am remembering correctly how it 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 ------------------ Asciimercial --------------------- Get on the web: Blog, lens and tag your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From mail at microcorp.co.za Fri May 18 02:44:31 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 18 May 2007 08:44:31 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de><1179160242.787344.48060@h2g2000hsg.googlegroups.com> <1179258692.237438.110860@p77g2000hsh.googlegroups.com> <464ad4a2$0$23143$9b4e6d93@newsspool1.arcor-online.net><464C34DB.4010903@v.loewis.de> <008901c79880$0282a260$03000080@hendrik> Message-ID: <00a701c7991b$293ed9a0$03000080@hendrik> "Hendrik van Rooyen" wrote: > > > > > Now look me in the eye and tell me that you find > > > the mix of proper German and English keywords > > > beautiful. > > > > I can't admit that, but I find that using German > > class and method names is beautiful. The rest around > > it (keywords and names from the standard library) > > are not English - they are Python. > > MvL: > > (look me in the eye and tell me that "def" is > > an English word, or that "getattr" is one) > > > HvR: > LOL - true - but a broken down assembler programmer like me > does not use getattr - and def is short for define, and for and while > and in are not German. After an intense session of omphaloscopy, I would like another bite at this cherry. I think my problem is something like this - when I see a line of code like: def frobnitz(): I do not actually see the word "def" - I see something like: define a function with no arguments called frobnitz This "expansion" process is involuntary, and immediate in my mind. And this is immediately followed by an irritated reaction, like: WTF is frobnitz? What is it supposed to do? What Idiot wrote this? Similarly, when I encounter the word "getattr" - it is immediately expanded to "get attribute" and this "expansion" is kind of dependant on another thing, namely that my mind is in "English mode" - I refer here to something that only happens rarely, but with devastating effect, experienced only by people who can read more than one language - I am referring to the phenomenon that you look at an unfamiliar piece of writing on say a signboard, with the wrong language "switch" set in your mind - and you cannot read it, it makes no sense for a second or two - until you kind of step back mentally and have a more deliberate look at it, when it becomes obvious that its not say English, but Afrikaans, or German, or vice versa. So in a sense, I can look you in the eye and assert that "def" and "getattr" are in fact English words... (for me, that is) I suppose that this "one language track" - mindedness of mine is why I find the mix of keywords and German or Afrikaans so abhorrent - I cannot really help it, it feels as if I am eating a sandwich, and that I bite on a stone in the bread. - It just jars. Good luck with your PEP - I don't support it, but it is unlikely that the Python-dev crowd and GvR would be swayed much by the opinions of the egregious HvR. Aesthetics aside, I think that the practical maintenance problems (especially remote maintenance) is the rock on which this ship could founder. - Hendrik -- Philip Larkin (English Poet) : They fuck you up, your mom and dad - They do not mean to, but they do. They fill you with the faults they had, and add some extra, just for you. From flavio.preto at gmail.com Thu May 3 17:02:28 2007 From: flavio.preto at gmail.com (Flavio Preto) Date: Thu, 3 May 2007 18:02:28 -0300 Subject: PyGTK and Window Size Message-ID: <5fb10ac20705031402s315afa04g7a686b2c36d3a22@mail.gmail.com> Hi, Currently i am developing a python script that will be executed in Gnome. This script uses the PyGTK library, however i have a question: How can I make my application to remember the last window size when it was closed? This behavior is natural for the majority of Gnome applications (i think). The trivial solution that i've imagined is to save to a config file the current status of the window, but i wish that PyGTK automatic handled this for me. Thanks, Flavio -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Fri May 25 13:35:46 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 25 May 2007 13:35:46 -0400 Subject: Proxying every function in a module In-Reply-To: <465705DF.8000007@laculine.com> References: <465705DF.8000007@laculine.com> Message-ID: Josh West wrote: > Kind and wise fellows, > [...] Please see my separate reply with the same subject line but in a new thread. That reply explains *why* it's in a new thread. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From duncan.booth at invalid.invalid Tue May 15 15:07:30 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 15 May 2007 19:07:30 GMT Subject: Trying to choose between python and java References: Message-ID: "Hamilton, William " wrote: > > No, they'll work just fine. They just won't work with Python 3. It's > not like the Python Liberation Front is going to hack into your > computer in the middle of the night and delete you 2.x installation. Is that a breakaway group from the PSU? From toby at tobiah.org Wed May 2 18:48:25 2007 From: toby at tobiah.org (Tobiah) Date: Wed, 02 May 2007 15:48:25 -0700 Subject: Slicing Arrays in this way In-Reply-To: <4639043f$0$10194$88260bb3@free.teranews.com> References: <4638fe20$0$16403$88260bb3@free.teranews.com> <1178144265.751484.318830@y80g2000hsf.googlegroups.com> <4639043f$0$10194$88260bb3@free.teranews.com> Message-ID: <463908a8$0$16350$88260bb3@free.teranews.com> I'm a retard. Disregard. -- Posted via a free Usenet account from http://www.teranews.com From arnodel at googlemail.com Sun May 20 16:34:48 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 20 May 2007 13:34:48 -0700 Subject: Translating some Java to Python In-Reply-To: <1179692679.422164.27700@r3g2000prh.googlegroups.com> References: <1179692679.422164.27700@r3g2000prh.googlegroups.com> Message-ID: <1179693288.768882.34200@x18g2000prd.googlegroups.com> On May 20, 9:24 pm, Daniel Gee wrote: > A while ago I wrote a class in Java for all kinds of dice rolling > methods, as many sides as you want, as many dice as you want, only > count values above or below some number in the total, things like > that. Now I'm writing a project in Python that needs to be able to > make use of that kind of a class. > > The Java version has static methods for common roll styles (XdY and XdY > +Z) for classes that just want a result but don't want to bother > keeping an object around for later. > > So the question is, assuming that I wanted to keep the static method > behavior (which I'm not really sure I do), how does one format the > method header on a 'static' method in Python? Is it just something > like: > > class Foo: > def statAdd(self,a): > return a+5 > > or do you drop the 'self' bit and just use a 1 variable parameter list? Do you really want your dice rolling functions to be methods? It seems to me that you would be better off grouping them as functions in a module rather than as methods in a class. A java class full of static methods translates to a python module populated with functions in general. -- Arnaud From ptmcg at austin.rr.com Sat May 19 19:42:53 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 19 May 2007 16:42:53 -0700 Subject: Inverse of id()? Message-ID: <1179618173.280286.284120@n59g2000hsh.googlegroups.com> Is there an inverse function to the builtin 'id'? The poster who asked about 1-to-1, 1-to-n, etc. relationships (presumably in CS terms - I hope I didn't misread some porn spam by mistake), got me thinking about containers and ids, and what kind of a container would implement a many-to-many. I happened to still have my Python interpreter open from noodling about another poster's question, using named arguments and parse-time functions in a regex, so I looked at the 'results' variable that experiment generated (this was a quick way to work with a non-trivial object, so if I reconstructed it from an id, I could test whether I really got back the object): >>> re = Regex("(\d*)").setResultsName("x").setParseAction(lambda t:int(t[0])) >>> results = re.parseString("123") pyparsing results have some special lookup behavior, that if the results name is a Python-friendly identifier, can use the name as if it were an object attribute: >>> results.x 123 So I extracted the id of results, and then started looking for the function that does the inverse of id. Unfortunately, skimming through the docs, I didn't find it, so I brute-force searched the globals() dict: >>> z = id(results) >>> for x in globals().values(): ... if id(x)==z: break ... This gives me a variable x that is indeed another ref to the results variable: >>> x is results True >>> x.x 123 Now is there anything better than this search technique to get back a variable, given its id? -- Paul From erikwickstrom at gmail.com Wed May 23 17:17:12 2007 From: erikwickstrom at gmail.com (erikcw) Date: 23 May 2007 14:17:12 -0700 Subject: Creating Graphs for the Web Message-ID: <1179955032.556481.170260@g4g2000hsf.googlegroups.com> Hi, I'm working on a django powered website, and need to dynamically generate some graphs (bar, pie, and line) from users' data stored in MySQL. Can anyone recommend a good library I can use for this? Thanks! Erik From sjmachin at lexicon.net Sat May 5 19:06:54 2007 From: sjmachin at lexicon.net (John Machin) Date: 5 May 2007 16:06:54 -0700 Subject: change of random state when pyc created?? In-Reply-To: <008%h.379$HR1.364@trnddc01> References: <1178388186.631422.290580@w5g2000hsg.googlegroups.com> <008%h.379$HR1.364@trnddc01> Message-ID: <1178406414.901845.223410@y80g2000hsf.googlegroups.com> On May 6, 9:00 am, "Alan Isaac" wrote: > I have documented this behavior > on two completely different systems > (Win 2000 and Win XP SP2), using Python 2.5.1. You can't say that you have "documented" the behaviour when you haven't published files that exhibit the alleged behaviour. From dwhall256 at gmail.com Wed May 9 09:20:34 2007 From: dwhall256 at gmail.com (dwhall) Date: 9 May 2007 06:20:34 -0700 Subject: Does RETURN_VALUE always result in an empty stack? Message-ID: <1178716834.573994.51210@u30g2000hsc.googlegroups.com> I'm developing PyMite and would like to know a little detail about Python 2.5's design. Is it true that when the RETURN_VALUE executes and pops its argument, that at that point the stack should *always* be empty? I mean just the argument stack for that execution frame. I want to use this knowledge to test if PyMite is working properly. thanks, !!Dean From kelvin.you at gmail.com Mon May 28 05:17:39 2007 From: kelvin.you at gmail.com (=?gb2312?B?yMvR1MLkyNXKx8zs0cSjrM37vKvM7NHEsru8+7zS?=) Date: 28 May 2007 02:17:39 -0700 Subject: Issue of redirecting the stdout to both file and screen Message-ID: <1180343858.903251.182490@x35g2000prf.googlegroups.com> I wanna print the log to both the screen and file, so I simulatered a 'tee' class Tee(file): def __init__(self, name, mode): file.__init__(self, name, mode) self.stdout = sys.stdout sys.stdout = self def __del__(self): sys.stdout = self.stdout self.close() def write(self, data): file.write(self, data) self.stdout.write(data) Tee('logfile', 'w') print >>sys.stdout, 'abcdefg' I found that it only output to the file, nothing to screen. Why? It seems the 'write' function was not called when I *print* something. From slewin at rogers.com Thu May 24 09:48:25 2007 From: slewin at rogers.com (scott) Date: Thu, 24 May 2007 09:48:25 -0400 Subject: A few questions In-Reply-To: References: Message-ID: <465597A9.4030500@rogers.com> JYOUNG79 at kc.rr.com wrote: > Just wanted to send a quick "Thank You!" to everyone who helped answer my questions. This > list is awesome!! I'm finding the same, this list is amazing. There is a more welcome feeling than the C or C++ list I have seen. > I'm currently reading "How to Think Like a Computer Scientist" (thanks Basilisk96) Me too, it is an amazing book and I am loving Python much better than C. I would just like to find some answers to the exercises to make sure I'm doing them correctly. > I still want to take a look at "Dive into Python" as well as the other books you all > mentioned. I put "Dive into Python" on my palm. Is it a good 2nd book to go through? -- Your friend, Scott Sent to you from a Linux computer using Kubuntu Version 7.04 (Feisty Fawn) From grante at visi.com Sat May 12 14:47:07 2007 From: grante at visi.com (Grant Edwards) Date: Sat, 12 May 2007 18:47:07 -0000 Subject: Basic question References: <1178986686.510137.195490@p77g2000hsh.googlegroups.com> <1178991933.421386.58500@u30g2000hsc.googlegroups.com> <1178992910.318929.77790@e51g2000hsg.googlegroups.com> Message-ID: <134c2tb9kof4u01@corp.supernews.com> On 2007-05-12, Dmitry Dzhus wrote: > str="53,20,4,2" > map(lambda s: float(s), str.split(',')) There's no need for the lambda. map(float,str.split(',')) Does exactly the same thing. -- Grant Edwards grante Yow! I feel like I am at sharing a "CORN-DOG" with visi.com NIKITA KHRUSCHEV... From mangabasi at gmail.com Wed May 23 12:58:36 2007 From: mangabasi at gmail.com (Mangabasi) Date: 23 May 2007 09:58:36 -0700 Subject: Inheriting from Python list object(type?) Message-ID: <1179939516.574991.194470@u30g2000hsc.googlegroups.com> Howdy, I would like to create a Point class that lets me use Point instances like the following example. >>> p = Point(3, 4) >>> p.x 3 >>> p.y 4 >>> p.z 1 >>> p[0] 3 >>> p[1] 4 >>> p[1] = 5 >>> p.y 5 >>> other than the x, y, z attributes, these instances should behave like regular Python lists. I have created something like : class Point: def __init__(self, x, y, z = 1): self.list = [x, y, z] def __repr__(self): return str(self.list) def __str__(self): return str(self.list) def __getattr__(self, name): if name == 'x': return self.list[0] elif name == 'y': return self.list[1] elif name == 'z': return self.list[2] else: return self.__dict__[name] def __setattr__(self, name, value): if name == 'x': self.list[0] = value elif name == 'y': self.list[1] = value elif name == 'z': self.list[2] = value else: self.__dict__[name] = value def __getitem__(self, key): return self.list[key] def __setitem__(self, key, value): self.list[key] = value def __getslice__(self, i, j): return self.list[i : j] def __setslice__(self, i, j, s): self.list[i : j] = s def __contains__(self, obj): if obj in self.list: return True else: return False There must be a way to inherit from the list type without having to redefine all the methods and attributes that regular lists have. i.e. class Point(list): ... Can someone provide an example? Thanx in advance From phishboh at gmail.com Sun May 6 08:55:59 2007 From: phishboh at gmail.com (phishboh at gmail.com) Date: 6 May 2007 05:55:59 -0700 Subject: Installation of eyeD3 on Windows (newbie) Message-ID: <1178456159.115779.274630@l77g2000hsb.googlegroups.com> As a Python introduction exercise, I plan to write a script to automatically rename my music files according to the information in the ID3 tag (v2.X), and update the tag if necessary. To read/write ID3 tags, I found the eyeD3 library (http:// eyed3.nicfit.net/). However, I could not find any downloads or installation instructions for Windows, only for other OSs. I downloaded "eyeD3-0.6.13.tar.gz" anyway and unpacked it. Since I couldn't find any installation instructions for Windows, I tried renaming the file "setup.py.in" to "setup.py" to run the command "python setup.py install" from the command window in the directory of "eyeD3-0.6.13". After that, I tried "import eyeD3" and "from eyeD3 import *;", as in the file "eyeD3" in the bin directory without any success: import eyeD3 Traceback (most recent call last): File "", line 1, in File "C:\Program Files\Python\Lib\site-packages\eyeD3-0.6.13\bin \eyeD3.py", line 33, in from eyeD3.tag import *; ImportError: No module named tag I would highly appreciate if someone could help me with how to proceed (step-by-step) to get started and use the eyeD3 library in Windows? Many thanks in advance! From stefan.behnel-n05pAM at web.de Mon May 14 05:18:07 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 14 May 2007 11:18:07 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46477f19$0$19845$426a74cc@news.free.fr> References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> Message-ID: <4648294F.2000704@web.de> Bruno Desthuilliers wrote: > but CS is english-speaking, period. That's a wrong assumption. I understand that people can have this impression when they deal a lot with Open Source code, but I've seen a lot of places where code was produced that was not written to become publicly available (and believe me, it *never* will become Open Source). And the projects made strong use of identifiers with domain specific names. And believe me, those are best expressed in a language your client knows and expresses concepts in. And this is definitely not the language you claim to be the only language in CS. Stefan From jaford at watford53.freeserve.co.uk Tue May 1 15:49:32 2007 From: jaford at watford53.freeserve.co.uk (Jim Ford) Date: Tue, 01 May 2007 19:49:32 GMT Subject: SEO - Search Engine Optimization - Seo Consulting In-Reply-To: References: <1177808356.681710.42980@n76g2000hsh.googlegroups.com> <#O8fXGAjHHA.3700@TK2MSFTNGP06.phx.gbl> Message-ID: Bob Phillips wrote: > That is the oft-quoted, idiotic type of example. The reality is that if we > follow the thread, we know the question, we only want to see the answer, not > wade through a morass of stuff we have already seen. If we haven't seen it, > guess what, we can go and read it. !tuoba no gnignab ruoy tahw aedi on ev'I From aisaac at american.edu Thu May 10 02:00:18 2007 From: aisaac at american.edu (Alan Isaac) Date: Thu, 10 May 2007 06:00:18 GMT Subject: change of random state when pyc created?? References: <5ae25fF2oggbqU1@mid.uni-berlin.de> Message-ID: "Carsten Haese" wrote in message news:mailman.7500.1178771660.32031.python-list at python.org... > I was simply pointing out all the ways in which you made it difficult for the > community to explain your problem. And without that community, I would still not have a clue. Thanks to all! > Please feel free to suggest specific wording changes to make the documentation > more useful. I'm sure my first pass will be flawed, but here goes: http://docs.python.org/lib/typesmapping.html: to footnote (3), add phrase "which may depend on the memory location of the keys" to get: Keys and values are listed in an arbitrary order, which may depend on the memory location of the keys. This order is non-random, varies across Python implementations, and depends on the dictionary's history of insertions and deletions. http://docs.python.org/lib/types-set.html: append a new sentence to 2nd paragraph Iteration over a set returns elements in an arbitrary order, which may depend on the memory location of the elements. fwiw, Alan Isaac From apatheticagnostic at gmail.com Fri May 25 21:07:17 2007 From: apatheticagnostic at gmail.com (kaens) Date: Fri, 25 May 2007 21:07:17 -0400 Subject: conditionally creating functions within a class? In-Reply-To: <163f0ce20705251744j5c728e9fn53585fe0c9250827@mail.gmail.com> References: <163f0ce20705251744j5c728e9fn53585fe0c9250827@mail.gmail.com> Message-ID: <163f0ce20705251807v3f974b79x22db49425c83129f@mail.gmail.com> On 5/25/07, kaens wrote: > > then I try doing this within a function: meant "within a class" here, whoops. From digimotif at gmail.com Thu May 24 12:45:15 2007 From: digimotif at gmail.com (digimotif) Date: 24 May 2007 09:45:15 -0700 Subject: need advice on building core code for python and PHP Message-ID: <1180025115.704410.250890@a35g2000prd.googlegroups.com> All, I'm currently working with a small development company on a PHP application they already have. There are several processing tasks that could be scripted in Python and run in the background to modify a database, instead of the way they have it now, which waits for a webpage to return from processing. There is also the possibility of building client gui applications that work with the database as well, so I'm looking for a way I could create a code base that enables us to use the same functions and objects over and over again while building interfaces in Python, or PHP, or whatever. Is there a way I could code the base (core) code in Python and have PHP call it? I've really liked using SQLAlchemy and there are other great things like Pylons I could integrate for various tasks, but I first have to move some functionality out of PHP and into something more "universal". What would you recommend? Any ideas are appreciated. Brian From john at datavoiceint.com Wed May 9 17:13:18 2007 From: john at datavoiceint.com (HMS Surprise) Date: 9 May 2007 14:13:18 -0700 Subject: File I/O Message-ID: <1178745198.392518.56840@q75g2000hsh.googlegroups.com> If one has a list of lists such as lst = [['a','1'],['b','2']] is there a standard python idiom for writing and reading the pairs to/ from a file? Thanks, jh From i3dmaster at gmail.com Thu May 17 03:30:23 2007 From: i3dmaster at gmail.com (i3dmaster) Date: 17 May 2007 00:30:23 -0700 Subject: Execute commands from file In-Reply-To: References: <1179320782.594398.67980@u30g2000hsc.googlegroups.com> <464b370c$0$3808$5402220f@news.sunrise.ch> Message-ID: <1179387023.005808.60670@o5g2000hsb.googlegroups.com> On May 16, 1:05 pm, Steve Holden wrote: > Martin Blume wrote: > > "tmp123" schrieb > > >> We have very big files with python commands > >> (more or less, 500000 commands each file). > > >> It is possible to execute them command by command, > > > inp = open(cmd_file) > > for line in inp: > > exec line > > > might help. You don't get quite the same feeling as > > "like if the commands was typed one after the other > > in a interactive session", but perhaps this helps. > > > Warning: the code above is without any error checks. > > You might also run into security problems, the example > > above assumes you trust your input. > > > HTH. YMMV. > > Martin > > The problem with this approach is that each line executes without any > connection to the environment created by previous lies. > > Try it on a file that reads something like > > xxx = 42 > print xxx > > and you will see NameError raised because the assignment hasn't affected > the environment for the print statement. > > 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 your way to fame!! > holdenweb.blogspot.com squidoo.com/pythonology > tagged items: del.icio.us/steve.holden/python > All these services currently offer free registration! > -------------- Thank You for Reading ---------------- cat file: x = 100 print x cat file.py: #!/usr/bin/python2.4 import os.path import sys file, ext = os.path.splitext(sys.argv[0]) f = open(file,'rb') for i in f: exec i >./file.py 100 Don't see the problem though. From stefan.sonnenberg at pythonmeister.com Sun May 6 02:53:56 2007 From: stefan.sonnenberg at pythonmeister.com (Stefan Sonnenberg-Carstens) Date: Sun, 06 May 2007 08:53:56 +0200 Subject: Python Binding In-Reply-To: <463D6FFD.2050005@web.de> References: <463D6FFD.2050005@web.de> Message-ID: <463D7B84.80402@pythonmeister.com> Stefan Behnel schrieb: > Georg Grabler wrote: > >> There's a C library which i'd like to have python bindings for. I havn't >> known anything before about how to write python bindings for a C library. >> >> I succeeded now by using distutils to write the first bindings for functions >> and similar. >> >> Now, it seems as something is blocking my brain. For the library, i >> need "custom" types, so types defined in this library (structures), >> including pointers and similar. >> >> I've been thinking about what i will need to represent this lists in python. >> I thought about creating an external python object, providing "information" >> i get from the list in C structures which can be converted. >> >> Basically, it are list of packages, which have several attributes (next, >> prev, etc). But i don't know how to supply a proper list from the binding / >> object written in C. >> >> Any suggestions or hints about this? >> > > Use Pyrex. It's a Python-like language that was designed to write extension > modules in C and it's great for writing wrappers. > > http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/ > > An example wrapper is described here: > > http://ldots.org/pyrex-guide/ > > Hope it helps, > Stefan > Hi, use SWIG. It is a no-brainer for simple libs. wxPython relies heavily on it. I worked with some times and it is really straightforward. See this: http://www.swig.org/Doc1.1/HTML/Python.html Cheers, Stefan From wildemar at freakmail.de Thu May 31 19:27:12 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Fri, 01 Jun 2007 01:27:12 +0200 Subject: call function in console without paranthesis In-Reply-To: <465f3dbc$0$52092$edfadb0f@dread11.news.tele.dk> References: <465f3dbc$0$52092$edfadb0f@dread11.news.tele.dk> Message-ID: <465F59D0.6080006@freakmail.de> Troels Thomsen wrote: > Hello, > > I am wondering if I can write some code, that allows me to call functions in > the console , IDLE, without using the paranthesis notation. Like print. > This will improve "intreractive'ness" > Matlab-like, right? In a nutshell: No, not possible in python *itself*. I'm not a python-guru, but I'm pretty sure that this would require changes to the python sources, because what you ask for would basically be a new language (syntax) feature. But if you really need that, you could try to write your own parser. You would have to think *hard* to get the semantics right, but in principle all you would have to do is translate your "simplified" console-input to valid python code and feed that to the exec() function (I think). At least, that's how I would do it. /W From mtobis at gmail.com Tue May 15 22:25:18 2007 From: mtobis at gmail.com (Michael Tobis) Date: 15 May 2007 19:25:18 -0700 Subject: Python Newbie Suggestions In-Reply-To: <464a50d7$1_4@mk-nntp-2.news.uk.tiscali.com> References: <1179264515.958714.72880@l77g2000hsb.googlegroups.com> <464a50d7$1_4@mk-nntp-2.news.uk.tiscali.com> Message-ID: <1179282318.821090.82840@h2g2000hsg.googlegroups.com> I think http://www.diveintopython.org/ would be very suitable for you. mt From clodoaldo.pinto at gmail.com Thu May 24 05:17:01 2007 From: clodoaldo.pinto at gmail.com (Clodoaldo) Date: 24 May 2007 02:17:01 -0700 Subject: Locale case change not working Message-ID: <1179998221.372699.17600@p77g2000hsh.googlegroups.com> When using unicode the case change works: >>> print u'?'.lower() ? But when using the pt_BR.utf-8 locale it doesn't: >>> locale.setlocale(locale.LC_ALL, 'pt_BR.utf-8') 'pt_BR.utf-8' >>> locale.getlocale() ('pt_BR', 'utf') >>> print '?'.lower() ? What am I missing? I'm in Fedora Core 5 and Python 2.4.3. # cat /etc/sysconfig/i18n LANG="en_US.UTF-8" SYSFONT="latarcyrheb-sun16" Regards, Clodoaldo Pinto Neto From victor.kryukov at gmail.com Wed May 16 17:04:17 2007 From: victor.kryukov at gmail.com (Victor Kryukov) Date: 16 May 2007 14:04:17 -0700 Subject: Python Web Programming - looking for examples of solid high-traffic sites Message-ID: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> Hello list, our team is going to rewrite our existing web-site, which has a lot of dynamic content and was quickly prototyped some time ago. Today, as we get better idea of what we need, we're going to re-write everything from scratch. Python is an obvious candidate for our team: everybody knows it, everybody likes it, it has *real* objects, nice clean syntax etc. Our main requirement for tools we're going to use is rock-solid stability. As one of our team-members puts it, "We want to use tools that are stable, has many developer-years and thousands of user-years behind them, and that we shouldn't worry about their _versions_." The main reason for that is that we want to debug our own bugs, but not the bugs in our tools. Our problem is - we yet have to find any example of high-traffic, scalable web-site written entirely in Python. We know that YouTube is a suspect, but we don't know what specific python web solution was used there. TurboGears, Django and Pylons are all nice, and provides rich features - probably too many for us - but, as far as we understand, they don't satisfy the stability requirement - Pylons and Django hasn't even reached 1.0 version yet. And their provide too thick layer - we want something 'closer to metal', probably similar to web.py - unfortunately, web.py doesn't satisfy the stability requirement either, or so it seems. So the question is: what is a solid way to serve dynamic web pages in python? Our initial though was something like python + mod_python + Apache, but we're told that mod_python is 'scary and doesn't work very well'. And although http://www.python.org/about/quotes/ lists many big names and wonderful examples, be want more details. E.g. our understanding is that Google uses python mostly for internal web-sites, and performance is far from perfect their. YouTube is an interesting example - anybody knows more details about that? Your suggestions and comments are highly welcome! Best Regards, Victor. From steve at holdenweb.com Wed May 16 19:59:17 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 16 May 2007 19:59:17 -0400 Subject: Declaring variables In-Reply-To: <1179359317.494376.259990@n59g2000hsh.googlegroups.com> References: <1179334649.990688.73320@o5g2000hsb.googlegroups.com> <1179359317.494376.259990@n59g2000hsh.googlegroups.com> Message-ID: Matimus wrote: > On May 16, 9:57 am, HMS Surprise wrote: >> I looked in the language but did not find a switch for requiring >> variables to be declared before use. >> >> Is such an option available? >> >> Thanks, >> >> jvh > > You do have to declare a variable before use. You do so by assigning > it a value. You can't use a variable before it has been assigned. In > some ways this is less ambiguous than even C where you can declare a > variable without assigning a value. Also note that this caries the > type information, since the variable is of whatever type was assigned > to it. The only thing it doesn't do is give a unique flag that says > "hey this is where I'm declared", although I suppose you could do that > with a comment. > Strictly, the variable has no type at all (and strictly your "variables" are actually names bound to values in a namespace, and it's the values that are typed). We shouldn't ignore the fact that declarations unambiguously say "the programmer intends to use such-and-such a name for a value of a specific type". Contrast this with a Python program where one path makes an assignment (binding) to a name while another path doesn't, resulting in a later NameError. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From Roka100 at gmail.com Fri May 18 12:28:17 2007 From: Roka100 at gmail.com (Jia Lu) Date: 18 May 2007 09:28:17 -0700 Subject: Why canNOT import from a local directory ? In-Reply-To: <464dcf65$0$3806$5402220f@news.sunrise.ch> References: <1179503376.706409.185930@w5g2000hsg.googlegroups.com> <464dcf65$0$3806$5402220f@news.sunrise.ch> Message-ID: <1179505697.497571.3710@o5g2000hsb.googlegroups.com> > > You need to define a file __init__.py in your newly created lib directory. > Thank you very much :) From ivlenin at gmail.com Thu May 24 15:36:42 2007 From: ivlenin at gmail.com (I V) Date: Thu, 24 May 2007 19:36:42 +0000 (UTC) Subject: CP4E revival References: <1179941107.366354.101860@h2g2000hsg.googlegroups.com> <465562f1$0$14719$afc38c87@news.optusnet.com.au> Message-ID: On Thu, 24 May 2007 20:03:29 +1000, Richard Jones wrote: > Hoop-jumping implemented to prevent just this kind of direct linking (and > thus not saving of the PDF to local disk to view, and thus increasing the > load on the server). I'm not sure I see the connection - if you're serving something as application/pdf, then people are going to download it or view it directly as they see fit (or as their browser is configured), whether or not they got their by clicking a link or pressing two buttons (indeed, using the buttons makes it _harder_ to save the PDF to disk, if that's what you want to enforce, because users can't right-click/save-as; if their browser is set up to open PDFs directly, they can't change that behavior without reconfiguring their browser). From __peter__ at web.de Wed May 16 10:55:50 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 16 May 2007 16:55:50 +0200 Subject: Unusual i/o problems References: <1179325595.708882.289510@e65g2000hsc.googlegroups.com> Message-ID: saif.shakeel at gmail.com wrote: > output_file = open(test_file,"w") ... > input_xml_sec = open(output_file,'r') Can you spot the problem now? To prevent it, use a naming convention that allows you to distinguish between file /names/ and file /objects/. > But i am getting an error on this line > (input_xml_sec = open(output_file,'r')).I have tried to figure out but > not able to debug.Can someone throw some light or anything they feel > could be going wrong somewhere. In the future, to make it as easy as possible to help you, please post the actual traceback which contains valuable hints about the error you encountered even if you cannot make sense of it. Peter From peter.anderson at internode.on.net Sat May 19 22:03:17 2007 From: peter.anderson at internode.on.net (Peter Anderson) Date: Sun, 20 May 2007 12:03:17 +1000 Subject: python shell In-Reply-To: <1179337107.842668.112690@k79g2000hse.googlegroups.com> References: <1179337107.842668.112690@k79g2000hse.googlegroups.com> Message-ID: <134vb3f3olucs28@corp.supernews.com> Krypto wrote: > I have been using python shell to test small parts of the big program. > What other ways can I use the shell effectively. My mentor told me > that you can virtually do anything from testing your program to > anything in the shell. Any incite would be useful. > I'm not sure this will help - but! I use a text editor (EditPlus under Windows) as a mini IDE. Some text editors have a concept of "tools" where you can run the "tool" from within the editor and it calls an external program to run the source code in the editor. With EditPlus the tool looks something like: Menu text: Python Command: C:\Python25\python.exe Argument: "$(FileName)" Initial directory: $(FileDir) Capture output: [X] Output from the program run is captured in an "output window". A full blown IDE it ain't but handy it is. Regards, Peter -- Peter Anderson There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things — Niccolo Machiavelli, "The Prince", ch. 6 From kyosohma at gmail.com Mon May 14 10:55:25 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 14 May 2007 07:55:25 -0700 Subject: A newbie question about FileDialog in wxPython In-Reply-To: References: Message-ID: <1179154525.068790.66490@h2g2000hsg.googlegroups.com> On May 11, 1:24 pm, "OhKyu Yoon" wrote: > Hi! > I am opening files using the wx.FileDialog in wxPython. > I want to modify the FileDialog such that some information about a > highlighted file is displayed before I decide to open the file. > This is what I tried: > > class ModifiedFileDialog(wx.FileDialog): > def __init__(self,parent,message,wildcard,style): > wx.FileDialog(self,parent,message,"","",wildcard,style) > width,height = self.GetSizeTuple() > self.SetSizeWH(width,height+100) > # and so on... > > I get an error when I try to change the size or make other changes. > Could someone tell me how to make this work or direct me to some reference? > Thank you. I don't know the answer either, but the people on the wxPython user's group probably will: http://www.wxpython.org/maillist.php Please post the question there too. Mike From snaury at gmail.com Mon May 21 08:58:38 2007 From: snaury at gmail.com (Alexey Borzenkov) Date: 21 May 2007 05:58:38 -0700 Subject: Python assignment loop In-Reply-To: References: <1179717712.491520.288060@z24g2000prd.googlegroups.com> Message-ID: <1179752317.989986.67010@y2g2000prf.googlegroups.com> On May 21, 8:12 am, "Silver Rock" wrote: > yes, that is the way I a solving the problem. using lists. so it seems > that there is no way around it then.. There's at least one way to do it that I can think of straight away: selfmodule = __import__(__name__, None, None, (None,)) setattr(selfmodule, "varname", value) But I can't say it's anywhere near elegant. From see.signature at no.spam Wed May 16 11:59:46 2007 From: see.signature at no.spam (Eric Brunel) Date: Wed, 16 May 2007 17:59:46 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <7x4pmg716p.fsf@ruckus.brouhaha.com> <4648EC26.8020907@v.loewis.de> Message-ID: On Wed, 16 May 2007 17:14:32 +0200, Gregor Horvath wrote: > Eric Brunel schrieb: > >> Highly improbable in the general context. If I stumble on a source code >> in Chinese, Russian or Hebrew, I wouldn't be able to figure out a >> single sound. > > If you get source code in a programming language that you don't know you > can't figure out a single sound too. > How is that different? What kind of argument is that? If it was carved in stone, I would not be able to enter it in my computer without rewriting it. So what? The point is that today, I have a reasonable chance of being able to read, understand and edit any Python code. With PEP 3131, it will no more be true. That's what bugs me. > If someone decides to make *his* identifiers in Russian he's taking into > account that none-Russian speakers are not going to be able to read the > code. Same question again and again: how does he know that non-Russian speakers will *ever* get in touch with his code and/or need to update it? -- 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 Wed May 2 13:12:19 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 02 May 2007 14:12:19 -0300 Subject: Leaving Python List References: Message-ID: En Wed, 02 May 2007 08:27:43 -0300, Gurpreet Singh escribi?: > This mail is to confirm that i want to leave the > python list. Goodbye! -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Fri May 25 06:39:59 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 25 May 2007 07:39:59 -0300 Subject: Newsgroups and mailing lists (was Re: Slightly OT: Why all the spam?) References: <3bb44c6e0705220008y10f5deb7v86ed82d3f8241761@mail.gmail.com> Message-ID: En Thu, 24 May 2007 21:53:24 -0300, Terry Reedy escribi?: > "Aahz" wrote in message > news:f34qpt$3oh$1 at panix3.panix.com... > | First of all, if you're accessing python-list as comp.lang.python, > you're > | accessing a newsgroup, *not* a mailing list. Secondly, c.l.py is an > | unmoderated group; there is no moderator and no control over who posts. > | However, netnews (Usenet) has a mechanism for cancelling articles, and > | cancelbots send out cancel messages for spam articles. > > This does not address the issue of spam passing thru python-list, which I > believe is supposed to be somewhat moderated (by people who have rejected > my help to catch spam) to gmane, where I read it. I presume this is the > path for stuff injected via google. Or perhaps stuff flows the other > way. I am not sure. Or perhaps it it injected independently in both or > all > three places. Or four or N places; anybody can post using any other nntp server that carries this group (if the server allows him, of course). Mailing lists are easier to control because there is a single entry point; news aren't that way. -- Gabriel Genellina From martin at v.loewis.de Tue May 8 17:14:54 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 08 May 2007 23:14:54 +0200 Subject: Question about file handles and windows handles @ Windows Operating Systems In-Reply-To: <1178658013.349284.94980@n59g2000hsh.googlegroups.com> References: <1178658013.349284.94980@n59g2000hsh.googlegroups.com> Message-ID: <4640E84E.7040802@v.loewis.de> > Are there any function to get windows handle of file which is already > opened with built-in file-function. mscvrt.get_osfhandle HTH, Martin From gagsl-py2 at yahoo.com.ar Thu May 24 16:20:16 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 24 May 2007 17:20:16 -0300 Subject: read file to a dictionary References: <1179962203.201472.104500@q19g2000prn.googlegroups.com> <1179994137.289599.164100@n15g2000prd.googlegroups.com> Message-ID: En Thu, 24 May 2007 05:08:57 -0300, rohit escribi?: > ohh i think i forgot to include intricate details > in dictionary i use the following: > value: name of a file existing on disk > Key : a unique number assigned to each file ,with no. assigned in > increasing order to file appearing earlier in the "english dictionary" So you don't have to read any file at all - just scan all file names. dict(enumerate(os.listdir("."))) -- Gabriel Genellina From deets at nospam.web.de Thu May 10 11:26:52 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 10 May 2007 17:26:52 +0200 Subject: trouble with generators In-Reply-To: References: Message-ID: <5agru2F2ovai8U1@mid.uni-berlin.de> Hans-Peter Jansen schrieb: > Hi Pythonistas, > > I'm stuck in a maze of new style classes and generators. While I love the > concepts, I obviously didn't grok them throughout. > > I'm trying to generate a bunch of similar classes, where some are contained > in list attributes of others, e.g.: All your code below shows that you don't create classes, but _instances_ of classes. So - is that what you mean to do? Or do you really want to create classes? > class A: > def __init__(self): > self.id = 'A1' > self.b = [instances of B] > > class B: > def __init__(self): > self.id = 'B1' > > Here's the test code, I have: > > #!/usr/bin/env python > # -*- coding: utf8 -*- > > class A(object): > "A" > def __init__(self): > self.id = None > self.b = [] > > class B(object): > "B" > def __init__(self): > self.id = None > > class Gen(object): > def records(self, cls): > for i in range(3): > setattr(cls, "id", "%s%s" % (cls.__doc__, i)) > yield cls > > def display(self, rec): > for i in rec.__dict__.keys(): > if not i.startswith("_"): > print "%s: %s: %s" % (rec.__doc__, i, rec.__dict__[i]) > > class GenA(Gen): > def __init__(self): > self.genB = GenB() > > def records(self): > for a in Gen.records(self, A()): Here you pass an instance of A, not the class A. > for b in self.genB.records(): > #self.genB.display(b) > a.b.append(b) > #self.display(a) > yield a > > class GenB(Gen): > def records(self): > return Gen.records(self, B()) Same here - instance of B. > # testing.. > > aRecs = [] > bRecs = [] > > for i, r in enumerate(GenB().records()): > bRecs.append(r) > print i, r.id, r > > for i, r in enumerate(GenA().records()): > aRecs.append(r) > print i, r.id, r > for b in r.b: > print b.id, b > > > Here's the commented output: > # even if I keep a reference to each rec, the object is reused: > 0 B0 <__main__.B object at 0xb7bd0f8c> > 1 B1 <__main__.B object at 0xb7bd0f8c> > 2 B2 <__main__.B object at 0xb7bd0f8c> Sure - because you create one B-instance, and pass that to your generator. That generator then simply sets the succinct id's on that object, and returns it. But it is always the same instance!! In a nutshell, you do this: b = B() res = [] for i in xrange(3): b.id = i res.append(b) Always the same b. What you seem to want is this >>> class B(object): ... pass ... >>> res = [] >>> for i in xrange(3): ... class BSubClass(B): ... pass ... BSubClass.id = i ... res.append(BSubClass) ... >>> print [c.id for c in res] [0, 1, 2] >>> > # same here, with additional quadratic behavior, I do not understand > 0 A0 <__main__.A object at 0xb7bd206c> > B2 <__main__.B object at 0xb7bd210c> > B2 <__main__.B object at 0xb7bd210c> > B2 <__main__.B object at 0xb7bd210c> > 1 A1 <__main__.A object at 0xb7bd206c> > B2 <__main__.B object at 0xb7bd210c> > B2 <__main__.B object at 0xb7bd210c> > B2 <__main__.B object at 0xb7bd210c> > B2 <__main__.B object at 0xb7bd20ec> > B2 <__main__.B object at 0xb7bd20ec> > B2 <__main__.B object at 0xb7bd20ec> > 2 A2 <__main__.A object at 0xb7bd206c> > B2 <__main__.B object at 0xb7bd210c> > B2 <__main__.B object at 0xb7bd210c> > B2 <__main__.B object at 0xb7bd210c> > B2 <__main__.B object at 0xb7bd20ec> > B2 <__main__.B object at 0xb7bd20ec> > B2 <__main__.B object at 0xb7bd20ec> > B2 <__main__.B object at 0xb7bd0f8c> > B2 <__main__.B object at 0xb7bd0f8c> > B2 <__main__.B object at 0xb7bd0f8c> It's not quadratic - you add the same B to a.b in each generator run, so the first run shows 3 times the B, then 6, then 9. And because its always the same instance, printing them yields the same id for all - B2. > I expected to get 3 different class objects from both sections, with each A > containing 3 different Bs in the latter section, but obviously got > something else. > > Could some kind soul help me to distangle my mind twist here? Am I healable? I'm still not sure what you want - do you want instances created, or classes? For the former, you need constructor calls on your classes, and pass the class instead of an instance. Like this: class B(object): pass def g(cls): for i in xrange(3): o = cls() o.id = i yield o list(g(B)) Or you want really different classes (which is somewhat strange then to create that hierarchy of yours with As containing Bs), which you can accomplish using a class-statement in the generator as shown above. There are other ways as well, but less intuitive I'd say. Maybe stepping back and telling us what you want to accomplish here would help Diez From kyosohma at gmail.com Tue May 8 11:38:40 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 8 May 2007 08:38:40 -0700 Subject: Can Python Parse an MS SQL Trace? In-Reply-To: References: <1178544236.856685.288740@y80g2000hsf.googlegroups.com> <1178547517.938939.201490@w5g2000hsg.googlegroups.com> Message-ID: <1178638720.294070.207280@l77g2000hsb.googlegroups.com> On May 8, 5:18 am, Tim Golden wrote: > kyoso... at gmail.com wrote: > > On May 7, 8:34 am, Tim Golden wrote: > >> kyoso... at gmail.com wrote: > >>> Can Python parse a trace file created with MS SQL's profiler? There > >>> are a few thousand lines in the trace file and I need to find the > >>> insert statements and the stored procedures. Unfortunately, I am not > >>> an SQL guru and was hoping Python could help. > >>> Mike > >> Mike, > > >> Can I suggest that, since the answer is more to > >> do with parsing and less to do with MSSQL (which > >> simply generated the output) that you post an example > >> of a trace file to some web location to see if anyone > >> wants to pick up the challenge? > > >> I'm not at work so I don't have access to MSSQL, but > >> I seem to remember that you can output/save as XML, > >> which may make things easier (or at least interest a > >> different group of people in having a look). > > >> I'm quite certain it can by done by Python; I did > >> consider it myself a couple of months back, but my > >> colleague spotted the problem before I'd really got > >> into the code! > > >> TJG > > > Good point. Unfortunately, I think our SQL Server must be too old for > > xml (we have version 8). The only save options I see is Trace > > Template, Trace File, Trace Table and SQL Script. > > Yes, you're right; I have clients installed for SQL 2000 & > 2005 and it's only under 2005 that I have the XML output > option. The .trc file format is pretty much opaque binary, > and the .sql output only gives you the SQL statements > issued - not the events they're associated with. > > One obvious way is to save it to a table and to interrogate > that table. I find that kind of thing a bit cumbersome, but > if XML's not an option, it might be the only way. (FWIW, > I find XML cumbersome too, but that might just be lack > of practice ;) > > Running a standard trace and saving to a table, this is > the structure which resulted: > > CREATE TABLE [trace_output] ( > [RowNumber] [int] IDENTITY (1, 1) NOT NULL , > [EventClass] [int] NULL , > [TextData] [ntext] COLLATE SQL_Latin1_General_CP1_CS_AS NULL , > [NTUserName] [nvarchar] (128) COLLATE > SQL_Latin1_General_CP1_CS_AS NULL , > [ClientProcessID] [int] NULL , > [ApplicationName] [nvarchar] (128) COLLATE > SQL_Latin1_General_CP1_CS_AS NULL , > [LoginName] [nvarchar] (128) COLLATE > SQL_Latin1_General_CP1_CS_AS NULL , > [SPID] [int] NULL , > [Duration] [bigint] NULL , > [StartTime] [datetime] NULL , > [Reads] [bigint] NULL , > [Writes] [bigint] NULL , > [CPU] [int] NULL , > PRIMARY KEY CLUSTERED > ( > [RowNumber] > ) ON [PRIMARY] > ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] > GO > > Seems like you might be able to do something with it. > (Possibly just dumping it straight back out to CSV > or XML if that's easier for you than db querying) > > TJG Thanks for the advice. I did the one that had to be done now by hand. However, I know I'll need to do more of these in the future, so I'll try it then. Mike From mailme.gurpreet at gmail.com Fri May 4 06:02:37 2007 From: mailme.gurpreet at gmail.com (Jaswant) Date: 4 May 2007 03:02:37 -0700 Subject: How to check if a string is empty in python? In-Reply-To: <1178224237.326531.254130@o5g2000hsb.googlegroups.com> References: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> <1178138964.503290.254060@o5g2000hsb.googlegroups.com> <1178139155.260722.153750@n59g2000hsh.googlegroups.com> <463a31c0$0$6845$c3e8da3@news.astraweb.com> <1178224237.326531.254130@o5g2000hsb.googlegroups.com> Message-ID: <1178272957.427279.89350@n76g2000hsh.googlegroups.com> This is a simple way to do it i think s=hello >>> if(len(s)==0): ... print "Empty" ... else: ... print s ... hello From bronger at physik.rwth-aachen.de Fri May 18 05:43:32 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Fri, 18 May 2007 11:43:32 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <4648DC86.8080709@v.loewis.de> Message-ID: <87k5v6piuz.fsf@wilson.homeunix.com> Hall?chen! Martin v. L?wis writes: >> In , Nick Craig-Wood >> wrote: >> >>> My initial reaction is that it would be cool to use all those >>> great symbols. A variable called OHM etc! >> >> This is a nice candidate for homoglyph confusion. There's the >> Greek letter omega (U+03A9) ? and the SI unit symbol (U+2126) ?, >> and I think some omegas in the mathematical symbols area too. > > Under the PEP, identifiers are converted to normal form NFC, and > we have > > py> unicodedata.normalize("NFC", u"\u2126") > u'\u03a9' > > So, OHM SIGN compares equal to GREEK CAPITAL LETTER OMEGA. It can't > be confused with it - it is equal to it by the proposed language > semantics. So different unicode sequences in the source code can denote the same identifier? Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From wgwigw at gmail.com Wed May 30 08:49:49 2007 From: wgwigw at gmail.com (momobear) Date: 30 May 2007 05:49:49 -0700 Subject: How to print this character u'\u20ac' to DOS terminal In-Reply-To: <1180508736.598924.26170@r19g2000prf.googlegroups.com> References: <1180501468.957322.106650@z28g2000prd.googlegroups.com> <465D0A6B.1000203@v.loewis.de> <1180508736.598924.26170@r19g2000prf.googlegroups.com> Message-ID: <1180529389.864527.282690@i13g2000prf.googlegroups.com> On May 30, 3:05 pm, ?????????????????????????????? wrote: > On 5??30??, ????1??23??, "Martin v. Lo"wis" wrote: > > > > > ?????????????????????????????? schrieb: > > > > Who could explain the follow issue ? > > >>>> print u'\u0394' > > > ?? > > >>>> print u'\u20ac' > > > Traceback (most recent call last): > > > File "", line 1, in > > > UnicodeEncodeError: 'gbk' codec can't encode character u'\u20ac' in > > > position 0: > > > illegal multibyte sequence > > > > My terminal is cmd.exe under windows XP. > > > what's the different between the two character ? what can I do if I > > > want to print the u'\u20ac'? > > > The problem is that your terminal uses (some form of) the GBK encoding; > > seehttp://zh.wikipedia.org/wiki/GBKfordetails on GBK. > > > It seems that GBK (or, rather, code page 936) supports the delta > > character, but not the euro sign. > > > To change that, you can use "chcp" in your terminal window. > > For example, if you do "chcp 850", you should be able to > > display the euro sign (but will simultaneously use the ability > > to display the letter delta, and the chinese letters). > > > I don't know whether the terminal supports an UTF-8 code > > page; you can try setting the terminal's code page to > > 65001 (which should be UTF-8). > > > Regards, > > Martin > > Thanks, but it seems not work yet. > > ---------------------------------------------------- > C:\WINDOWS>chcp 850 > Active code page: 850 > > C:\WINDOWS>python > 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.>>> print u'\u20ac' > > Traceback (most recent call last): > File "", line 1, in > File "C:\Python25\lib\encodings\cp850.py", line 12, in encode > return codecs.charmap_encode(input,errors,encoding_map) > UnicodeEncodeError: 'charmap' codec can't encode character u'\u20ac' > in position > 0: character maps to > > C:\WINDOWS>chcp 65001 > Active code page: 65001 > > C:\WINDOWS>python > 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.>>> print u'\u20ac' > > Traceback (most recent call last): > File "", line 1, in > LookupError: unknown encoding: cp65001 > ----------------------------------------------- > I find that the u'\u20ac' related 'mbcs' encode is 0x80, I could print > it directly > > >>> print '\x80' > ? > > But the string contained the u'\u20ac' is get from remote host. Is > there any method to decode it to the local 'mbcs'? forgot to unicode(string) before send it? From MMM at disney.com Tue May 8 15:24:26 2007 From: MMM at disney.com (MMM at disney.com) Date: Tue, 08 May 2007 14:24:26 -0500 Subject: After the Deletion of Google Answers, . U Got Questions Fills the Gap Answering and Asking the Tough Questions References: <1178559951.933883.134750@l77g2000hsb.googlegroups.com> Message-ID: On 7 May 2007 10:45:51 -0700, Leisure.208 at gmail.com wrote: >My friend asked some tough questions http://ugotquestions.blogspot.com/2007_05_01_archive.html >unlike yahoo answers ( Which Generates Content with Answers ) U got >questions picks only the best, Real Person Questions.,yeah so there is >this second book called E.T. and the BOOK OF THE GREEN PLANET... yeah, >what happens in it... i heard he dies, and what happend to elliot.... >this has been bugging me for years...so someone please tell >mehttp://ugotquestions.blogspot.com/2007_04_01_archive.html - i start >my car and shut it off 4 to 5 times it starts fine but when i continue >repeat this procedure for another 2 to 3 times then it dies. it doesnt >start at all. the headlights and all other lights dont go dim so might >not be the battery. then i have to wait for 3 to 5 minutes for it to >start again. it does crank slowly sometime then start. the alternator >was replaced 2 years ago so was the battery. the car has 129000miles >its 01 maxima. automatic. as far as i think it could be the >starter...http://ugotquestions.blogspot.com/2007/05/y-alert-yahoo- >answers_7473.html 1- if you ask anyone in the town that: Are you a >wise human? and he says yes, what you can say about him? 2- tree >mathematicians are talking about their trip to this town: 1st man >says: in my trip to the town, I ask John (a people of the town) are >you a wise human? and with his reply, I could not rcognize what is he. >2nd man says: I also ask John are you a loony human? and with his >reply, I could not recognize what is he too. 3rd man says: I also ask >John are you a wise devil? and with his...http:// >ugotquestions.blogspot.com/2007/05/y-alert-yahoo-answers_7075.html >Which major should I choose before law school if I want to practice >criminal and civil law and I also want in the future be a judge.The >majors that I like are criminal justice,politcal science and >finance.But I don't know which should I choose.I already know the >speech that law schools don't care about your mayor but I want to know >which one of those three could help me more in my goals fo practice >criminal and civil law and be a judge.Thanks a lot....http:// >ugotquestions.blogspot.com/2007/05/y-alert-yahoo-answers_6058.html >Everyday I wake up to my mom yelling about something I did. All she >does is come home from work sit on the couch and watch a movie she >gets from blockbuster everyday while we are suppose to be doing >chores. She dosnt let us watch her movies becuase she pays for them,. >we dont have cable and we havnt gone grocery shopping in two months >becuase she says we dont hav the money.( while she gets take out >everyday at work and a blockbuster movie everyday to. )She told me i >cant wash my clothes for... shaw loves this. Kill the DVD player From Steffen.Oschatz at googlemail.com Thu May 10 06:14:56 2007 From: Steffen.Oschatz at googlemail.com (Steffen Oschatz) Date: 10 May 2007 03:14:56 -0700 Subject: Newbie (but improving) - Passing a function name with parameters as a parameter In-Reply-To: <1178785638.736644.312970@e51g2000hsg.googlegroups.com> References: <1178785638.736644.312970@e51g2000hsg.googlegroups.com> Message-ID: <1178792096.927676.218760@e51g2000hsg.googlegroups.com> On 10 Mai, 10:27, mosscliffe wrote: > I am trying to time a function's execution, Do you know the timeit module ? : Tool for measuring execution time of small code snippets Steffen From Wiseman1024 at gmail.com Fri May 4 20:11:41 2007 From: Wiseman1024 at gmail.com (Wiseman) Date: 4 May 2007 17:11:41 -0700 Subject: Python regular expressions just ain't PCRE Message-ID: <1178323901.381993.47170@e65g2000hsc.googlegroups.com> I'm kind of disappointed with the re regular expressions module. In particular, the lack of support for recursion ( (?R) or (?n) ) is a major drawback to me. There are so many great things that can be accomplished with regular expressions this way, such as validating a mathematical expression or parsing a language with nested parens, quoting or expressions. Another feature I'm missing is once-only subpatterns and possessive quantifiers ( (?>...) and ?+ *+ ++ {...}+ ) which are great to avoid deep recursion and inefficiency in some complex patterns with nested quantifiers. Even java.util.regex supports them. Are there any plans to support these features in re? These would be great features for Python 2.6, they wouldn't clutter anything, and they'd mean one less reason left to use Perl instead of Python. Note: I know there are LALR parser generators/parsers for Python, but the very reason why re exists is to provide a much simpler, more productive way to parse or validate simple languages and process text. (The pyparse/yappy/yapps/ argument could have been used to skip regular expression support in the language, or to deprecate re. Would you want that? And following the same rule, why would we have Python when there's C?) From carsten at uniqsys.com Fri May 25 11:28:38 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 25 May 2007 11:28:38 -0400 Subject: Why isn't this query working in python? In-Reply-To: <6e42ec490705250751i89d3cf3v3a3062690d0284aa@mail.gmail.com> References: <1180103946.552760.239200@p47g2000hsd.googlegroups.com> <6e42ec490705250751i89d3cf3v3a3062690d0284aa@mail.gmail.com> Message-ID: <1180106924.3743.34.camel@dot> On Fri, 2007-05-25 at 09:51 -0500, Dave Borne wrote: > > I'm trying to run the following query: > ... > > member_id=%s AND expire_date > NOW() AND completed=1 AND (product_id > > Shouldn't you be using the bind variable '?' instead of '%s' ? The parameter placeholder for MySQLdb is, indeed and unfortunately, %s. The OP is using parameter substitution correctly, though in an obfuscated fashion. 'sql' is a misnamed tuple containing both the query string *and* the parameters, which is being unpacked with '*' into two arguments to the execute call. The only problem I see is that the parameters should be a sequence, i.e. (self.uid,) instead of just (self.uid). HTH, -- Carsten Haese http://informixdb.sourceforge.net From collver at peak.org Sat May 5 05:16:58 2007 From: collver at peak.org (Ben Collver) Date: Sat, 05 May 2007 02:16:58 -0700 Subject: My Python annoyances In-Reply-To: References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> Message-ID: <9rSdnVecBrAW1qHbnZ2dnUVZ_gWdnZ2d@scnresearch.com> Terry Reedy wrote: > You don't need an invitation to disagree with another person's tracker > comment. I assumed you knew this and took non-response as acquiesence. > That (closing no response by item submitter) is a fairly typical pattern , > by the way. I wish it were otherwise. I (incorrectly) took the comment to support rather than invalidate my report, and did not see anything to challenge. Email is not 100% reliable, but I understand you don't have the time to hound submitters. Do you think it might help to ask a question when you expect a response from the submitter? It might act as a prompt. > That is a different issue. If, for instance, you think the docs could and > should be improved to make people more wary, reopen the item, change the > appropriate field to 'documentation' and please give a suggested addition > or change. I trust the experts to take the appropriate action. It seems equally reasonable to ignore the report for its triviality, or to treat the checksum as a long, since that is what zlib returns. Ben From srikrishnamohan at gmail.com Tue May 8 07:22:03 2007 From: srikrishnamohan at gmail.com (km) Date: Tue, 8 May 2007 16:52:03 +0530 Subject: __getattr__ and __getattribute__ Message-ID: Hi all, i find it difficult to understand the difference between the magic methods __getattr__ and __getattribute__ and so donot know when to use former or later. can someone brief me on it ? regards, KM -------------- next part -------------- An HTML attachment was scrubbed... URL: From jon at ffconsultancy.com Thu May 3 22:06:15 2007 From: jon at ffconsultancy.com (Jon Harrop) Date: Fri, 04 May 2007 03:06:15 +0100 Subject: Why stay with lisp when there are python and perl? References: <1178155239.007219.205020@y5g2000hsa.googlegroups.com> <1178219732.127815.3260@y80g2000hsf.googlegroups.com> Message-ID: <463a9668$0$8719$ed2619ec@ptn-nntp-reader02.plus.net> Nameless wrote: > Why should I keep on learning lisp when there are python and perl? Lisp compilers are much more advanced, for one thing. Xah Lee wrote: > (if there is some demand, i will add a concrept, little programing > example, that shows, how lisp's symbols and macros concepts, set it > apart from new scripting languages) I already did something similar, writing simple programs to simplify symbolic expressions in different languages: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/239715 Also, here is a symbolic derivative example: http://codecodex.com/wiki/index.php?title=Derivative Note that pattern matching (as found in OCaml, F#, Haskell etc.) is very useful for this kind of term rewriting and is not found in Python, Perl or Lisp. > This lisp's symbol concept, as far as i know, does not exist in some > other high-level functional programing languages such as Haskell. Correct. > I'm > not familiar with many functional languages except Lisp and > Mathematica. I'm curious, as to how Haskell, which itself is quite > with capable of symbolic computation i think, deals with it even > though the language doesn't employ the concep of lisp's symbols per > se. In Standard ML, Haskell and F# you must define a sum type that represents a symbolic expression whereas, in Lisp, you can use the built-in s-expressions. The sum type that you define typically includes a "Symbol" that carries its string name. For example, the F# code cited above used: type expr = | Int of int | Add of expr * expr | Mul of expr * expr | Var of string with static member ( + ) (f, g) = Add(f, g) static member ( * ) (f, g) = Mul(f, g) end in this case, "Var" represents a symbol, e.g. the value Var "x" would represent a variable x. However, note that the best Lisp implementation of the symbolic simplifier (by Pascal Constanza) avoids s-expressions, improving performance. In OCaml, you can rely on the compiler inferring the sum type for you by using polymorphic variants. However, this is not generally a good idea because they are slower and harbor some of the disadvantages of dynamic typing. It is worth noting that eager, statically-typed languages like OCaml and F# are many times faster than the other languages at this task. This is precisely the forte of OCaml and F#, manipulating trees and graphs. -- Dr Jon D Harrop, Flying Frog Consultancy The F#.NET Journal http://www.ffconsultancy.com/products/fsharp_journal/?usenet From jorgen.maillist at gmail.com Tue May 8 09:40:58 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Tue, 8 May 2007 15:40:58 +0200 Subject: changing a var by reference of a list In-Reply-To: <5abcj4F2nv0p0U1@mid.uni-berlin.de> References: <5abcj4F2nv0p0U1@mid.uni-berlin.de> Message-ID: <11e49df10705080640pa19e535va4c21e41040b7dcc@mail.gmail.com> Ok thanks, I will try this approach. The idea was that I could give a list to the SQL execute command, so that the results coming back would automatically be assigned to variables. With regards, - Jorgen On 5/8/07, Diez B. Roggisch wrote: > Jorgen Bodde wrote: > > > Hi, > > > > I am trying to simplify my code, and want to automate the assigning of > > variables I get back from a set. I was thinking of putting the > > variables I want changed in a list: > > > > L = [self._varA, self._varB ] > > > > self._varA is a variable I want to change when I pass L to a function. > > I know doing this; > > > > L[0] = 12 > > > > Will replace the entry self._varA with 12, but is there a way to > > indirectly change the value of self._varA, through the list, something > > like a by-reference in C++ or a pointer-pointer? > > No, there isn't. > > But you could do > > L = ['_varA'] > > for v in L: > setattr(self, v, value) > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > From thn at mail.utexas.edu Fri May 4 10:21:49 2007 From: thn at mail.utexas.edu (Thomas Nelson) Date: 4 May 2007 07:21:49 -0700 Subject: How safe is a set of floats? Message-ID: <1178288509.067493.5140@e65g2000hsc.googlegroups.com> I want to generate all the fractions between 1 and limit (with limit>1) in an orderly fashion, without duplicates. def all_ratios(limit): s = set() hi = 1.0 lo = 1.0 while True: if hi/lo not in s: s.add(hi/lo) yield (hi,lo) hi += 1 if hi/lo > limit: lo += 1 hi = lo I use a set to keep from giving duplicates; but is this safe? In C they always tell you not to trust floating point equality comparisons, since they may not work as you expect. My code seems fine for the limited amount I've tested, but I'm curious: is there a gaurantee about sets of floats? Or a warning? Thanks, Tom From apardon at forel.vub.ac.be Thu May 3 04:42:35 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 3 May 2007 08:42:35 GMT Subject: Lazy evaluation: overloading the assignment operator? References: <1178133344.415521.118710@n76g2000hsh.googlegroups.com> Message-ID: On 2007-05-03, Terry Reedy wrote: > > "sturlamolden" wrote in message > news:1178133344.415521.118710 at n76g2000hsh.googlegroups.com... >| >| Python allows the binding behaviour to be defined for descriptors, >| using the __set__ and __get__ methods. I think it would be a major >| advantage if this could be generalized to any object, by allowing the >| assignment operator (=) to be overloaded. > > Conceptually, assignment is *not* an operator. Binary operators take two > values (of the same type) and produce a third (usually of either the input > type or a boolean) that usually depends on both inputs. Assignment does > nothing of the sort. > > In Python, the equal sign is *not* an operator: it is a grammatical symbol. > One use of the operator fiction in C is to enable simple chained > assignment: a=b=2. Python does this directly without the fiction. C's > store-and-test usage can be implemented in Python with a 'purse' class. > >| One particular use for this would be to implement "lazy evaluation". > > Since (in Python, at least) operands are evaluated *before* the > operator/function is called, I do not see how. But they could evaluate to an expression tree instead of the actual result. This tree could then be evaluate at the moment of assignment. This is an idea I have been playing with myself in an other context. You have a class of symbolic names. e.g. First, Last ... You can use the normal operators to these names, the result will be an expression tree. So Last - 2 will evaluate to something like sub / \ Last 2 I want to use this in the context of a table (a list like structure but with arbitrary start index, which can be negative, so tab[-1] can't refer to the last element). So I can use this as follows: el = tab[Last - 2] to access the element two places before the last, because the evaluation of the tree happens in the __getitem__ method. I could even write something like: el = tab[(First + Last) / 2] To get at the midle element. -- Antoon Pardon From http Sat May 5 02:00:59 2007 From: http (Paul Rubin) Date: 04 May 2007 23:00:59 -0700 Subject: Looping over lists References: Message-ID: <7xirb7zu5g.fsf@ruckus.brouhaha.com> Tommy Grav writes: > In C this would be equivalent to: > for(i = 0; i < n; i++) { > for(j=i+1; j < n; j++) { > print a[i], a[j] for i in xrange(n): for j in xrange(i+1, n): print a[i], a[j] From nyamatongwe+thunder at gmail.com Mon May 21 18:53:01 2007 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Mon, 21 May 2007 22:53:01 GMT Subject: List Moderator In-Reply-To: <1353asbpai1gqd6@corp.supernews.com> References: <880dece00705172218n71123b55q531ec0c5e500f208@mail.gmail.com> <880dece00705190012g4f3d3ef6v4e6c87a156708bb0@mail.gmail.com> <880dece00705191305m203bc8ep804d647c17438581@mail.gmail.com> <464F5E42.6090607@holdenweb.com> <880dece00705201305q6944986fj8f77c4b5cac09456@mail.gmail.com> <13524svhtst5dd1@corp.supernews.com> <1353asbpai1gqd6@corp.supernews.com> Message-ID: Grant Edwards: > To quantify things for curiosity's sake, I just scanned through > the last 1000 postings in c.l.p. There was exactly 1 spam > message and two replies to spam messages complaining about > them. Looking at all my cached messages, I saw 9 including replies. Only one reply went through the mail server to reach me as shown by its headers (such as X-BeenThere: python-list at python.org). The most obvious non-reply *appeared* to be injected into usenet from Google Groups and today's "Boobies" was similar. If you are reading through usenet, spam messages are recognised and expired early - I don't know what mechanism is used for this. Neil From nszabolcs at gmail.com Wed May 30 13:00:32 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 30 May 2007 10:00:32 -0700 Subject: Is PEP-8 a Code or More of a Guideline? In-Reply-To: References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <5c1jpkF2tl0ilU1@mid.individual.net> <1180539790.654176.26900@q75g2000hsh.googlegroups.com> Message-ID: <1180544432.736659.16190@h2g2000hsg.googlegroups.com> Joe Riopel wrote: > Using camel case instead of the under_score means less typing. I am lazy. > > fooBar > foo_bar camel case makes source code extremely ugly in weird disturbing way YMMV From sjmachin at lexicon.net Thu May 10 15:45:22 2007 From: sjmachin at lexicon.net (John Machin) Date: 10 May 2007 12:45:22 -0700 Subject: Comparing dates problem In-Reply-To: <1178823142.101246.220660@l77g2000hsb.googlegroups.com> References: <1178746479.776908.319930@p77g2000hsh.googlegroups.com> <1178748764.663230.186570@y80g2000hsf.googlegroups.com> <1178823142.101246.220660@l77g2000hsb.googlegroups.com> Message-ID: <1178826321.961336.66070@q75g2000hsh.googlegroups.com> On May 11, 4:52 am, kyoso... at gmail.com wrote: > On May 9, 5:12 pm, John Machin wrote: > > > > > > > > > On May 10, 7:34 am, kyoso... at gmail.com wrote: > > > > Hi, > > > > I am writing a reminder program for our Zimbra email client. One of > > > the requirements I was given was to automatically increment or > > > decrement the display to show something like the following: > > > > 5 minutes until appointment > > > > or > > > > 10 minutes past your appointment > > > > Either way, as each minute goes by, I need to increment it or > > > decrement it. I am having trouble finding a coherent way to take the > > > same date and compare just the number of minutes between them to find > > > the difference. Like if I have an appointment at 9:30 a.m. and the app > > > is loaded at 8 a.m., I need to know the number of minutes or hours and > > > minutes until the appointment. > > > > I have looked at the dateutils module and it has many comparison > > > methods, but they seem to only return the number of days or seconds. > > > Ermmm ... what's wrong with > > > minutes = seconds / 60.0 > > hours = minutes / 60.0 > > > ? > > I'm sure there is a hack for doing something like what you suggest, > but it would be messy. The problem is that I get a datetime object > returned and division really isn't something you can do to one of > those objects. Besides, if I had seconds returned, I would want to > multiply by 60, not divide. > > Maybe I misunderstand you. > Maybe it's mutual -- hack? messy? multiply? Where I come from, 180 seconds is (180 / 60 = 3) minutes. 180 seconds * 60 is 10800 sixtieths- of-a-second, which appears to be travelling away from a solution to your problem. You have *TWO* datetime objects, (say) appt_dt and now_dt. delta =appt_dt - now_dt # delta is a timedelta object. # calculate difference in minutes mins = delta.days * 24 * 60 + delta.seconds // 60 Have you not read Tim Golden's response? From josiah.carlson at sbcglobal.net Sun May 13 15:58:27 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Sun, 13 May 2007 12:58:27 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <46476081.7080609@web.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476081.7080609@web.de> Message-ID: Stefan Behnel wrote: > Anton Vredegoor wrote: >>> In summary, this PEP proposes to allow non-ASCII letters as >>> identifiers in Python. If the PEP is accepted, the following >>> identifiers would also become valid as class, function, or >>> variable names: L?ffelstiel, chang?, ??????, or ??? >>> (hoping that the latter one means "counter"). >> I am against this PEP for the following reasons: >> >> It will split up the Python user community into different language or >> interest groups without having any benefit as to making the language >> more expressive in an algorithmic way. > > We must distinguish between "identifiers named in a non-english language" and > "identifiers written with non-ASCII characters". [snip] > I do not think non-ASCII characters make this 'problem' any worse. So I must > ask people to restrict their comments to the actual problem that this PEP is > trying to solve. Really? Because when I am reading source code, even if a particular variable *name* is a sequence of characters that I cannot identify as a word that I know, I can at least spell it out using Latin characters, or perhaps even attempt to pronounce it (verbalization of a word, even if it is an incorrect verbalization, I find helps me to remember a variable and use it later). On the other hand, the introduction of some 60k+ valid unicode glyphs into the set of characters that can be seen as a name in Python would make any such attempts by anyone who is not a native speaker (and even native speakers in the case of the more obscure Kanji glyphs) an exercise in futility. As it stands, people who use Python (and the vast majority of other programming languages) learn the 52 upper/lowercase variants of the latin alphabet (and sometimes the 0-9 number characters for some parts of the world). That's it. 62 glyphs at the worst. But a huge portion of these people have already been exposed to these characters through school, the internet, etc., and this isn't likely to change (regardless of the 'impending' Chinese population dominance on the internet). Indeed, the lack of the 60k+ glyphs as valid name characters can make the teaching of Python to groups of people that haven't been exposed to the Latin alphabet more difficult, but those people who are exposed to programming are also typically exposed to the internet, on which Latin alphabets dominate (never mind that html tags are Latin characters, as are just about every daemon configuration file, etc.). Exposure to the Latin alphabet isn't going to go away, and Python is very unlikely to be the first exposure programmers have to the Latin alphabet (except for OLPC, but this PEP is about a year late to the game to change that). And even if Python *is* the first time children or adults are exposed to the Latin alphabet, one would hope that 62 characters to learn to 'speak the language of Python' is a small price to pay to use it. Regarding different characters sharing the same glyphs, it is a problem. Say that you are importing a module written by a mathematician that uses an actual capital Greek alpha for a name. When a user sits down to use it, they could certainly get NameErrors, AttributeErrors, etc., and never understand why it is the case. Their fancy-schmancy unicode enabled terminal will show them what looks like the Latin A, but it will in fact be the Greek ?. Until they copy/paste, check its ord(), etc., they will be baffled. It isn't a problem now because A = ? is a syntax error, but it can and will become a problem if it is allowed to. But this issue isn't limited to different characters sharing glyphs! It's also about being able to type names to use them in your own code (generally very difficult if not impossible for many non-Latin characters), or even be able to display them. And no number of guidelines, suggestions, etc., against distributing libraries with non-Latin identifiers will stop it from happening, and *will* fragment the community as Anton (and others) have stated. - Josiah From bbxx789_05ss at yahoo.com Thu May 31 03:56:01 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 31 May 2007 00:56:01 -0700 Subject: trouble with wxPython intro In-Reply-To: References: <1180581067.908739.252960@a26g2000pre.googlegroups.com> Message-ID: <1180598161.088508.15920@q69g2000hsb.googlegroups.com> On May 30, 11:41 pm, Anthony Irwin wrote: > Daniel Gee wrote: > > I'm trying to learn WxPython with the tutorial: > >http://wiki.wxpython.org/Getting_Started > I'm a wxPython beginner too, but instead of Anthony Irwin's suggestions, I think you should delete these two lines: ID_ABOUT=101 ID_EXIT=110 and use: wx.ID_ABOUT wx.ID_EXIT throughout the body of your program. As far as I can tell, there is no reason for you to be manually setting your own id's (is there ever?). Instead, you can use the ids in the wx module. In addition, I suggest you never use wx.PySimpleApp(). If you create your own app class, you can send the error messages to the console. Instead of always seeing a window that flashes at you briefly and being left with no clue what went wrong, you can at least see an error message and a line number in the console. Here's how you would do that: ----------------- import wx class MyFrame(wx.Frame): def __init__(self, mytitle): wx.Frame.__init__(self, None, title= mytitle) class MyApp(wx.App): def __init__(self): wx.App.__init__(self, redirect=False) app = MyApp() window = MyFrame("Testing") window.Show() app.MainLoop() ------------------ By setting redirect=False in wx.App.__init__(), the errors will be sent to the console. From half.italian at gmail.com Thu May 10 17:21:42 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 10 May 2007 14:21:42 -0700 Subject: Newbie look at Python and OO In-Reply-To: <1178812734.860473.236370@y80g2000hsf.googlegroups.com> References: <1178812734.860473.236370@y80g2000hsf.googlegroups.com> Message-ID: <1178832102.256466.235020@l77g2000hsb.googlegroups.com> walterbyrd wrote: > I learned to program with Pascal, way back when. Went into software > development for a while, then went into systems admin. Have programmed > in several languages, just learning Python. > > Some things I find odd: > > 1) 5/-2 == -3? > > 2) list assignment handling, pointing two vars to the same list: > > With simple data types: > >>> a = 5 > >>> b = a > >>> a = 3 > >>> a,b > (3, 5) > > Which is what I'd expect, since I have changed a, but not b. > > But with lists: > >>> a = list("1234") > >>> b = a > >>> a.append("5") > >>> a,b > (['1', '2', '3', '4', '5'], ['1', '2', '3', '4', '5']) > > b changes even though I have not touched b. I know why, but this is > not what I would ordinarilly expect, it does not seem intuitive. And, > IMO, it gets worse: > > >>> a = list("1234") > >>> b = a > >>> a = a + ['5'] > >>> a,b > (['1', '2', '3', '4', '5'], ['1', '2', '3', '4']) > > Sometimes changing a changes b, and sometimes not. You also have to > remember that subseqent changes to a will not change b - after some > operation but not others. To those who think in Python, I'm sure this > all seems normal. But, having programmed in about one dozen other > language, this seems downright bizare to me. I know why it works like > this, but it seems like an odd way to do things. > > 3) ambiguous use of the form: this.that() > > Sometimes, this.that() means module.funcion() as in: > > >>> os.dirlist(".") > > Other times, "this" is sort of like a parameter to the "that" > function: > > >>> a = list("1234") > >>> "_".join(a) > '1_2_3_4_5' > > And still other times, is seems that "this" is an object, acted upon > by "that" : > > >>> a = list("1234") > >>> b = "_".join(a) > >>> b.split("_") > ['1', '2', '3', '4', '5'] > > BTW: it seems a bit odd to that the positions of the string, and the > delimitor, are reversed between the complementory functions join(), > and split(). I suppose if it weren't for OO, we have something > terribly complicated, like: > > split(str, "_") > join(str, "_") > > Again, those who think in Python, will understand right away that: > > math.count(x) > > is counting the substring "x" in the "math" string. But can you see > where that might be confused to be a function called count() in the > math module? > > I'm not complaining. Python is a great language in many respects. But, > I would take some issue with those claiming Python is intuitive and > easy. IMO: there seems to be many ambiguous, unintuitve, and > confusing, aspects to Python. These conversations are funny to me. I use Python every day and I have never actually thought about the implications of binding objects to names, or two names pointing to the same object. Problems of this sort just never come up in actual programming for me. It just works. Python was my virgin language, so maybe that just makes it natural to me, but it seems like people coming from other languages get hung up on testing out the differences and theories rather than just programming in it. Alas, maybe I have yet to get deep enough to run into these kinds of problems. The question of what math is in math.count(x) makes sense, but this one never comes up either (or rarely). I usually know what the object is that I'm working with. ~Sean From tom at finland.com Sun May 13 02:31:11 2007 From: tom at finland.com (tom at finland.com) Date: Sun, 13 May 2007 06:31:11 GMT Subject: keyword checker - keyword.kwlist In-Reply-To: References: <5UK0i.237$Hb2.206@read3.inet.fi> Message-ID: tom at finland.com kirjoitti: > Gabriel Genellina kirjoitti: >> En Thu, 10 May 2007 17:03:13 -0300, escribi?: >> my_input = raw_input("...").strip() >> >> as Peter Otten suggested before >> >> --Gabriel Genellina >> > Ok, it seems to work with strip(). Thanks for your help. > > Do you guys have any clue why mine previous code doesn't work? Oh, repr() function revealed the issue. Thank you all! From stefan.behnel-n05pAM at web.de Mon May 14 05:04:36 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 14 May 2007 11:04:36 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1hy2qg3.iqfvwnrvr9kjN%aleax@mac.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1hy2qg3.iqfvwnrvr9kjN%aleax@mac.com> Message-ID: <46482624.6050507@web.de> Alex Martelli schrieb: > Aldo Cortesi wrote: > >> Thus spake Steven D'Aprano (steven at REMOVE.THIS.cybersource.com.au): >> >>> If you're relying on cursory visual inspection to recognize harmful code, >>> you're already vulnerable to trojans. >> What a daft thing to say. How do YOU recognize harmful code in a patch >> submission? Perhaps you blindly apply patches, and then run your test suite on >> a quarantined system, with an instrumented operating system to allow you to >> trace process execution, and then perform a few weeks worth of analysis on the >> data? >> >> Me, I try to understand a patch by reading it. Call me old-fashioned. > > I concur, Aldo. Indeed, if I _can't_ be sure I understand a patch, I > don't accept it -- I ask the submitter to make it clearer. > > Homoglyphs would ensure I could _never_ be sure I understand a patch, > without at least running it through some transliteration tool. I don't > think the world of open source needs this extra hurdle in its path. But then, where's the problem? Just stick to accepting only patches that are plain ASCII *for your particular project*. And if you want to be sure, put an ASCII encoding header in all source files (which you want to do anyway, to prevent the same problem with string constants). The PEP is only arguing to support this decision at a per-project level rather than forbidding it at the language level. This makes sense as it moves the power into the hands of those people who actually use it, not those who designed the language. Stefan From walterbyrd at iname.com Thu May 3 10:53:31 2007 From: walterbyrd at iname.com (walterbyrd) Date: 3 May 2007 07:53:31 -0700 Subject: Can I use Python instead of Joomla? In-Reply-To: <4639173e$0$2415$426a74cc@news.free.fr> References: <1178138925.498663.252920@o5g2000hsb.googlegroups.com> <4639173e$0$2415$426a74cc@news.free.fr> Message-ID: <1178204011.101042.81880@l77g2000hsb.googlegroups.com> On May 2, 5:38 pm, Bruno Desthuilliers wrote: > You're mixing apples, fishes, and cars here. Joomla is a content > management system, Django a framework and Python a language. Yes, I know, but they are all ways to create a website. If I wanted a site which included galleries, forums, etc. and I didn't want to re- invent the wheel, I could: 1) Use joomla or drupal, and possible end up "fighting the framework" to get just what I want. 2) Cooble together a web-site with various scripts, either developed by others, or myself. I would like to work with django, and include some python stuff. But, the PHP environments seem to have a much richer assortment of pre- written scripts. If I want to include my own applications, I could develop those apps with a popular PHP MVC called "CakePHP" and include those into joomla or drupal. I don't know if there is anything like that with Python development. From JHoover at fbi.gov Mon May 28 23:02:31 2007 From: JHoover at fbi.gov (Gordon Airporte) Date: Mon, 28 May 2007 23:02:31 -0400 Subject: itertools.groupby In-Reply-To: <7xveecr5xx.fsf@ruckus.brouhaha.com> References: <1180286272.100790.131670@q75g2000hsh.googlegroups.com> <7xveecr5xx.fsf@ruckus.brouhaha.com> Message-ID: <6Y6dnb0mTLsaCsbbnZ2dnUVZ_hCdnZ2d@comcast.com> Paul Rubin wrote: > It chops up the iterable into a bunch of smaller ones, but the total > size ends up the same. "Telescope", "compact", "collapse" etc. make > it sound like the output is going to end up smaller than the input. Good point... I guess I was thinking in terms of the number of iterators being returned being smaller than the length of the input, and ordered relative to the input - not about the fact that the iterators contain all of the objects. > There is also a dirty secret involved , which is that the > itertools functions (including groupby) are mostly patterned after > similarly named functions in the Haskell Prelude, which do about the > same thing. They are aimed at helping a similar style of programming, > so staying with similar names IMO is a good thing. Ah - those horrible, intolerant Functionalists. I dig ;-). > But that is what groupby does, except its notion of uniqueness is > limited to contiguous runs of elements having the same key. "itertools.groupby_except_the_notion_of_uniqueness_is_limited_to- _contiguous_runs_of_elements_having_the_same_key()" doesn't have much of a ring to it. I guess this gets back to documentation problems, because the help string says nothing about this limitation: ''' class groupby(__builtin__.object) | groupby(iterable[, keyfunc]) -> create an iterator which returns | (key, sub-iterator) grouped by each value of key(value). | ''' "Each" seems to imply uniqueness here. From bj_666 at gmx.net Tue May 15 09:33:45 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 15 May 2007 15:33:45 +0200 Subject: Storing and searching nodes of a tree References: <1179233407.473173.259110@h2g2000hsg.googlegroups.com> Message-ID: In <1179233407.473173.259110 at h2g2000hsg.googlegroups.com>, jm.suresh at no.spam.gmail.com wrote: > I use these names as keys in a dictionary, and store node's data. > Now given a name like "abc", I want to find the key with the following > rule: > If the key exists return the value > If the key does not exist, return the value of the leaf node whose > name is in the given name. For, "abc", it is "ab" . For, "ad", it is > "a". > > I suppose there must be a simpler solution to this problem. I > implemented it like this: > d = {'a':0, 'aa':12, 'ab':43, 'aaa':22, 'aab':343, 'ac':33} > name = 'abc' > key = max( [ x for x in d.iterkeys() if x in name] ) > value = d[key] > > I can change the data structure from dictinory to tuple of key,value > pairs or any thing, and afford to keep them in a particular order. Is > there any way I can speed up this as I have to do this for around 4000 > times with tree size being ~5000. What about this: def search(tree, path): while path: result = tree.get(path) if result is not None: return result path = path[:-1] raise KeyError('path not on tree') Ciao, Marc 'BlackJack' Rintsch From steven at REMOVE.THIS.cybersource.com.au Tue May 15 04:52:10 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 15 May 2007 08:52:10 GMT Subject: removing spaces between 2 names References: <1179208842.114189.233060@e65g2000hsc.googlegroups.com> Message-ID: On Mon, 14 May 2007 23:14:23 -0700, Steven Howe wrote: > saif.shakeel at gmail.com wrote: >> Hi, >> Suppose i have a string stored in variable,how do i remove the >> space between them,like if i have the name: "USDT request" in a >> variable.i need "USDTrequest",without any space . >> Thanks >> >> > from string import replace > st = 'abcd acdfg xtit' > st.replace(' ','') > 'abcdacdfgxtit' The line "from string import replace" is redundant. -- Steven. From revuesbio at gmail.com Wed May 9 04:34:19 2007 From: revuesbio at gmail.com (revuesbio) Date: 9 May 2007 01:34:19 -0700 Subject: msbin to ieee In-Reply-To: <1178663401.061610.296340@e51g2000hsg.googlegroups.com> References: <1178487847.671199.108140@h2g2000hsg.googlegroups.com> <1178502738.104124.3840@h2g2000hsg.googlegroups.com> <1178525916.145819.264070@n59g2000hsh.googlegroups.com> <1178536910.566119.6650@o5g2000hsb.googlegroups.com> <1178539202.316506.199940@p77g2000hsh.googlegroups.com> <1178542593.668743.71500@u30g2000hsc.googlegroups.com> <1178545075.530201.180120@u30g2000hsc.googlegroups.com> <1178573895.164509.82270@u30g2000hsc.googlegroups.com> <1178619341.882665.245470@e51g2000hsg.googlegroups.com> <1178663401.061610.296340@e51g2000hsg.googlegroups.com> Message-ID: <1178699659.339627.185050@e51g2000hsg.googlegroups.com> Hi, I found something interresting. First, MBF Files come from metastock software but i use another one (MLDownloader) to get quotes and convert them to MBF format probably using functions you've just described (C, borland,...). In final, all my files are created by mldownloader. 2nd, I've tried to modify quotes directly in metastock. And when you read bytes corresponding to "zero" ... : '\x00\x00\x00\x00' ! cheers, Antoine From stefan.behnel-n05pAM at web.de Mon May 14 05:00:29 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 14 May 2007 11:00:29 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <464762B6.701@web.de> Message-ID: <4648252D.5020704@web.de> Eric Brunel wrote: > On Sun, 13 May 2007 21:10:46 +0200, Stefan Behnel > wrote: > [snip] >> Now, I am not a strong supporter (most public code will use English >> identifiers anyway) > > How will you guarantee that? I'm quite convinced that most of the public > code today started its life as private code earlier... Ok, so we're back to my original example: the problem here is not the non-ASCII encoding but the non-english identifiers. If we move the problem to a pure unicode naming problem: How likely is it that it's *you* (lacking a native, say, kanji keyboard) who ends up with code that uses identifiers written in kanji? And that you are the only person who is now left to do the switch to an ASCII transliteration? Any chance there are still kanji-enabled programmes around that were not hit by the bomb in this scenario? They might still be able to help you get the code "public". Stefan From noagbodjivictor at gmail.com Sun May 6 17:05:21 2007 From: noagbodjivictor at gmail.com (noagbodjivictor at gmail.com) Date: 6 May 2007 14:05:21 -0700 Subject: using boost to extend python with c++ In-Reply-To: References: Message-ID: <1178485521.882275.34740@l77g2000hsb.googlegroups.com> On May 6, 4:12 pm, "mr_gees100_peas" wrote: > Hi, > > I've been trying for days to make either boost.python or swig to > work for me. The one I have gotten the closest to is boost. Note that > this is for windows XP. I'm not much of an unix person besides doing > simple ls and copy paste. > > What I have done is to download the boost library: C:\boost_1_34_0 > I downloaded the bjam library: C:\boost-jam-3.1.14-1-ntx86 > > I then set up the path so that I could do bjam from anywhere suing the > coomand prompt. Did the same for python and g++. I'm using the g++ > that came with bloodshed DevC++ compiler. > > So, I navigated myself to the tutorial example in the boost library. > C:\boost_1_34_0\libs\python\example\tutorial > > In the command prompt I typed bjam and I got the following error message. > > C:\boost_1_34_0\libs\python\example\tutorial>bjam > Jamroot:17: in modules.load > rule python-extension unknown in module > Jamfile. > C:/boost_1_34_0/tools/build/v2/build\project.jam:312: in load-jamfile > C:/boost_1_34_0/tools/build/v2/build\project.jam:68: in load > C:/boost_1_34_0/tools/build/v2/build\project.jam:170: in project.find > C:/boost_1_34_0/tools/build/v2\build-system.jam:237: in load > C:\boost_1_34_0\libs\python\example\..\..\..\tools\build\v2/kernel\modules.jam:261: > in import > C:\boost_1_34_0\libs\python\example\..\..\..\tools\build\v2/kernel/bootstrap.jam:132: > in boost-build > C:\boost_1_34_0\libs\python\example\boost-build.jam:7: in module scope > > I've have been trying desperately for 3 days. I also tried swig with > similar results but I feel I'm closer to solving the issue with boost > than with swig. I'm at a total lost here. I have tried the tutorials > in the boost web page but I just don't get anywhere. > > http://www.boost.org/libs/python/doc/tutorial/doc/html/python/hello.html I think your paste is incomplete. From steve at holdenweb.com Fri May 25 13:30:40 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 25 May 2007 13:30:40 -0400 Subject: Proxying every function in a module Message-ID: > Kind and wise fellows, > > I've got a web application with the following structure: > > 1) module of 100 functions corresponding to user actions (e.g. > "update_profile()", "organisations_list()") > 2) a wsgi callable which maps urls to functions eg > /organisations/list/?sort=date_created is mapped to > organisations_list("dateCreated") > 3) mapping is performed using inspect.getargspec() > 4) a bunch of html generating templates > > In the templates I want to generate urls by referencing the function to > which they map, rather than the url, e.g. > > Sort By Date Created > > In other words, I want to always refer to functions, rather than mixing > up function calls and urls > > I would like a class that proxies all the 100 functions in the user > actions module. When a proxied function is called via this class it > should return the url to which it is mapped rather than executing the > user action function. > > Sort By Date > Created > > should produce: > > Sort By Date Created > > Obviously, I don't want to write and maintain copies of these 100 > functions in another class. > > My question is therefore: what is the best way to proxy these 100 functions? > > Thanks > First off, don't attempt to start a new thread by replying to a previous one. Many newsreaders will merge the two, confusing the hell out of everyone and generally not helping. Second, what makes you think you need a module? I'd have thought an instance of some user-defined class would have been better, as that way you can redefine the __getattr__() method to return appropriate functions. This seems to work, though I haven't tested it extensively (i.e. I have called one instance precisely once ;-) >>> import re >>> pat = re.compile("([a-z]+)(.+)") >>> class myRewriter: ... def srt(self, s): ... m = pat.match(s) ... if not m: raise ValueError(s) ... return m.group(1), m.group(2).lower() ... def __getattr__(self, name): ... n1, n2 = name.split("_") ... def f(val): ... s1, s2 = self.srt(val) ... return "/%s/%s/?sort=%s_%s" % \ ... (n1, n2, s1, s2) ... return f ... >>> r = myRewriter() >>> r.organisations_list('dateCreated') '/organisations/list/?sort=date_created' >>> 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From stefan.behnel-n05pAM at web.de Mon May 14 08:51:49 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 14 May 2007 14:51:49 +0200 Subject: multi threaded SimpleXMLRPCServer In-Reply-To: References: Message-ID: <46485B65.2010605@web.de> Vyacheslav Maslov wrote: > I need multi threaded version of SimpleXMLRPCServer. Does python library > already have implementation of this one? Or i need to implement multi > threading by myself? > > Which way is the simpliest? Twisted has XML-RPC support: http://twistedmatrix.com/trac/ Stefan From _karlo_ at _mosor.net Sat May 12 12:57:06 2007 From: _karlo_ at _mosor.net (Karlo Lozovina) Date: Sat, 12 May 2007 18:57:06 +0200 Subject: Dynamic subclassing ? In-Reply-To: <1178976888.443891.116090@y80g2000hsf.googlegroups.com> References: <1178976888.443891.116090@y80g2000hsf.googlegroups.com> Message-ID: manatlan wrote: > I can't find the trick, but i'm pretty sure it's possible in an easy > way. It's somewhat easy, boot looks ugly to me. Maybe someone has a more elegant solution: In [6]: import new In [13]: class Button: ....: def buttonFunc(self): ....: pass In [14]: class ExtensionClass: ....: def extendedMethod(self): ....: pass In [15]: hybrid = new.instance(Button, Button.__dict__.update(ExtensionClass.__dict__)) In [17]: dir(hybrid) Out[17]: ['__doc__', '__module__', 'buttonFunc', 'extendedMethod'] Seems to do what you want it to do. HTH, Karlo. From johnsto at gmail.com Thu May 3 08:15:52 2007 From: johnsto at gmail.com (Dave Johnston) Date: 3 May 2007 05:15:52 -0700 Subject: Comparing bitmap images for differences? In-Reply-To: <1178098566.836135.193430@o5g2000hsb.googlegroups.com> References: <1178024505.768505.262270@h2g2000hsg.googlegroups.com> <59p1unF2lje91U1@mid.uni-berlin.de> <1178098566.836135.193430@o5g2000hsb.googlegroups.com> Message-ID: <1178194552.178212.67540@y80g2000hsf.googlegroups.com> On May 2, 10:36 am, "lanwrang... at gmail.com" wrote: > Thanks for the tip for an algorithm - I can see how that could work > really nicely (and it gives me some ideas for other things, too!) > Thanks also for the link to the OpenCV bindings. I'll give 'em a try > and see what happens. I did similar stuff for a project at Uni, but for tracking pedestrians... in (eurgh) Java. Tad boring, but might help a little bit: http://uni.johnsto.co.uk/crowd/ Unfortunately it only got tested on pre-recorded feeds, not live ones. The background removal was fun. I think I ended up getting the background by converting every 5th frame to grayscale, and calculating the median for each pixel position across the sample. A couple filters to remove tiny 1 or 2 pixel specks of noise, and then went onto blob detection for identifying people and tracking their movement across the entire video. The same filtering in numpy should be really quite fast indeed! From aisaac at american.edu Sat May 19 09:19:44 2007 From: aisaac at american.edu (Alan Isaac) Date: Sat, 19 May 2007 13:19:44 GMT Subject: docs patch: dicts and sets References: Message-ID: I submitted the language based on Bill and Carsten's proposals: https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1721372&group_id=5470 That language has been rejected. You many want to read the discussion and see if acceptible language still seems discoverable. Alan Isaac From rajb at rice.edu Wed May 30 10:13:47 2007 From: rajb at rice.edu (Raj B) Date: Wed, 30 May 2007 09:13:47 -0500 Subject: New-style classes and special methods Message-ID: <6B8D80D7-8967-443C-B89C-D6C9D2491A49@rice.edu> Hi My question is about how special methods are stored internally in Python objects. Consider a new-style class which implements special methods such as __call__ and __new__ class C(type): def __call__(...): class B: __metaclass__ = C b= B() The type of C is 'type', that of B is 'C'. When B is instantiated, the __call__ method of C is first invoked, since C is the metaclass for B. Internally, when a Python callable object 'obj' is called, the actual function called seems to be 'obj->ob_type->tp_call'. Does this that somehow the '__call__' method defined in C above is assigned to the 'tp_call' slot in the object representing the class C, instead of it just being stored in the dictionary like a normal attribute? Where and how does this magic happen exactly? I'd appreciate any level of detail. Thanks! Raj From jorgen.maillist at gmail.com Mon May 21 13:26:52 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Mon, 21 May 2007 19:26:52 +0200 Subject: managed lists? Message-ID: <11e49df10705211026s3e8f15b8nee32e0aa94b55ee6@mail.gmail.com> Hi all, I have been slowly progressing with my application written in wxPython. I love the freedom, speed and lack of the compiling run. I still have to get used to the lack of (strong) types, and it sometimes frustates me to no end that a wrongly given argument explodes somewhere deep inside my application without giving any clue why it blew up in the first place.. Right now i have a list in a class that I export as a member variable to the outside world, it is a standard list (e.g. [] ) but I wish to have a stronger type checking when adding objects, that only some objects are allowed and others are not. It was quite easy to create it, but I wonder if there is already a standard solution for lists that carry only objects of a single type? I solved it now, by using isinstance() and giving the class name as argument to the list (thank god that everything in Python is an object ;-) ) where I check against when adding, but re-inventing the wheel is silly ofcourse - Jorgen From hafeliel at yahoo.com Sat May 19 09:46:05 2007 From: hafeliel at yahoo.com (Gre7g Luterman) Date: Sat, 19 May 2007 07:46:05 -0600 Subject: Writelines() a bit confusing References: <1179578195.565952.244110@u30g2000hsc.googlegroups.com> Message-ID: "aiwarrior" wrote in message news:1179578195.565952.244110 at u30g2000hsc.googlegroups.com... > If file.WriteLines( seq ) accepts a list and it says it writes lines, > why does it write the whole list in a single line. Be cause of that > the reverse of file.writelines(seq) is not file.readlines(). > Are the assumptions i made correct? If yes why is this so? readlines() and writelines() are complimentary. readlines() leaves the line terminators intact. It does not strip them off. writelines() does not add in carriage returns for the same reason. For example: >>> D=open("temp.txt").readlines() >>> D ['the quick\n', 'brown fox\n', 'jumps over\n', 'the lazy dog.'] >>> open("temp2.txt","w").writelines(D) will create temp2.txt to be identical to temp.txt. From nogradi at gmail.com Wed May 16 17:43:05 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Wed, 16 May 2007 23:43:05 +0200 Subject: How do I count the number of spaces at the left end of a string? In-Reply-To: <1179351367.714864.47190@l77g2000hsb.googlegroups.com> References: <1179351367.714864.47190@l77g2000hsb.googlegroups.com> Message-ID: <5f56302b0705161443w77731850t774ef879b5c08800@mail.gmail.com> > I don't know exactly what the first non-space character is. I know the > first non-space character will be * or an alphanumeric character. How about: >>> mystring = ' ksjfkfjkfjds ' >>> print len( mystring ) - len( mystring.lstrip( ) ) 4 HTH, Daniel From nogradi at gmail.com Wed May 23 03:31:38 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Wed, 23 May 2007 09:31:38 +0200 Subject: model browser In-Reply-To: <46521edd$0$16328$88260bb3@free.teranews.com> References: <46521edd$0$16328$88260bb3@free.teranews.com> Message-ID: <5f56302b0705230031l19a2bc49jdb2492a6bdf382fb@mail.gmail.com> > > Are there other options I overlooked? > > > > Daniel > > There is a CRUD template for TG: > http://docs.turbogears.org/1.0/CRUDTemplate > > Might be what you're looking for. I was looking for something that is not based on a framework such as django or tg (and not on sqlalchemy either, but on sqlobject). It seems actually that catwalk is quite easy to decouple from tg and thus can be turned into a stand alone model browser that only depends on sqlobject. From larry.bates at websafe.com Fri May 18 11:51:54 2007 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 18 May 2007 10:51:54 -0500 Subject: progress indicator in a mod_python script In-Reply-To: <1179413183.860119.264040@q23g2000hsg.googlegroups.com> References: <1179413183.860119.264040@q23g2000hsg.googlegroups.com> Message-ID: <1eudnQCSzaIKVtDbnZ2dnUVZ_rLinZ2d@comcast.com> Rajarshi wrote: > Hi, I have a web application built using mod_python.Currently it > behaves like a standard CGI - gets data from a form, performs a query > on a backend database and presents a HTML page. > > However the query can sometimes take a bit of time and I'd like to > show the user some form of indeterminate progress indicator (spinning > dashes etc). My searching seems to indicate that this is based on some > form of asynchronous calls (AJAX) and I'm not sure how I can achieve > this effect in my mod_python app. > > Any pointers to achieve this would be very appreciated. > > Thanks, > If you want "real" progress than you must do it with some asynchronous communications via XMLRPC or sockets. You can "simulate" progress by doing a little client-side javascript and include a progressive GIF. There are a bunch of them available here: http://www.ajaxload.info/ -Larry From jm.suresh at gmail.com Fri May 25 02:31:50 2007 From: jm.suresh at gmail.com (jm.suresh@no.spam.gmail.com) Date: 24 May 2007 23:31:50 -0700 Subject: Find the closest relative Message-ID: <1180074710.011260.276830@n15g2000prd.googlegroups.com> Hi I have three objects, all of them are instances of classes derived from a base class. Now, given one of the instance, I want to find the closest relative of the other two. How can I do this? This is how I implemented; I guess there must be elegant way to do this... def find_closest_relative(a,b,c): c1 = b.__class__ c2 = b.__class__ while True: if isinstance(a, c1): return b if isinstance(a, c2): return c c1 = c1.__base__ c2 = c1.__base__ - Suresh From rrr at ronadam.com Wed May 9 11:32:05 2007 From: rrr at ronadam.com (Ron Adam) Date: Wed, 09 May 2007 10:32:05 -0500 Subject: Sorting attributes by catagory Message-ID: This is for a new version of pydoc if I can get the class attributes sorted out. The module level attributes aren't too difficult to categorize. (I might be just too tired to see the obvious.) The original pydoc did this a somewhat round about way, so I would like to find a more direct method if possible. Where dir(obj) is used to get all attributes of a module or class. And they are then sorted into categories depending on what they are. (In order of precedence.) For modules: - imported_items (defined in another module, or is another module) - classes - functions - other_objects (everything else) For classes: - from_else_where (object created someplace else) - inherited_attributes (from parents classes or type) - static_methods_here - class_methods_here - other_methods - properties - getset_descriptors - other_descriptors - other_attributes (everything else) A single function that accepts an object and can return one of the above (or equivalent) strings would be ideal. Finer grained categorizing is ok as long as they don't overlap more than one group. It seems I can get some of these fairly easy with the inspect module, but others I need to test in multiple ways. Any ideas? Cheers, Ron From tkapoor at wscm.net Thu May 17 16:39:19 2007 From: tkapoor at wscm.net (Tarun Kapoor) Date: Thu, 17 May 2007 15:39:19 -0500 Subject: Error on FTP Upload .. No such file or directory Message-ID: <9E0CC1A9D55BE54CAD39E562649F1716038DA37F@wscmmail.wscm.corp> By the way... test.txt does exist Disclaimer This e-mail and any attachments is confidential and intended solely for the use of the individual(s) to whom it is addressed. Any views or opinions presented are solely those of the author and do not necessarily represent those of Waterstone Capital Management, L.P and affiliates. If you are not the intended recipient, be advised that you have received this e-mail in error and that any use, dissemination, printing, forwarding or copying of this email is strictly prohibited. Please contact the sender if you have received this e-mail in error. You should also be aware that e-mails are susceptible to interference and you should not assume that the contents of this e-mail originated from the sender above or that they have been accurately reproduced in their original form. Waterstone Capital Management, L.P. and affiliates accepts no responsibility for information, or errors or omissions in this e-mail or use or misuse thereof. If in doubt, please verify the authenticity with the sender. From aleax at mac.com Wed May 30 22:47:30 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 30 May 2007 19:47:30 -0700 Subject: New-style classes and special methods References: Message-ID: <1hyxyq1.ksj6xxiu6ncrN%aleax@mac.com> Raj B wrote: > > Yes, special methods populate the slots in the structures which > Python > > uses to represent types. Objects/typeobject.c in the Python source > > distribution does the hard work, particularly in function type_new > > > > Thanks for that quick response. I am quite comfortable with C code > and am trying to understand exactly what happens when a new-style > class is created, and then instantiated. > > I have been reading typeobject.c and type_new() inside it in detail, > and there are a few issues I am trying to figure out. > > I can see a lot of *SLOT() macros in the file that seem to set the > slots to appropriate values. What I am having trouble figuring out is > the connection i.e. at what point during construction of the class > object in type_new() are those slots allotted? Is it the tp_alloc() > function which does this? I believe there are different times -- one for the fundamental struct that represents all types, others for secondary structs that represent e.g. numerical/arithmetic methods, sequence methods, etc, each of which is present only if necessary for a given type. > Is there some kind of descriptor or other mechanism connecting > special method names with their slots in the object representation? > (e.g. "__call__" with type->tp_call) The online docs for the C/API interface do some effort at explaining the type-struct and auxiliary ones, and I spent a couple of pages on that same subject in "Python in a Nutshell", though nowhere close to doing it justice (such docs normally address people who want to write C-coded extensions, rather than ones whose goal is to understand the existing Python runtime -- though many of the issues are identical). > Also, what happens when a class inherits from multiple classes with > their own __call__ methods? Where and how is it decided which > __call__ goes into the tp_call slot? The MRO is used (that stands for Method Resolution Order, and is also implemented in the same C file, and documented there AND in a strong essay by M. Simionato whose URL is, I believe, also in a comment in that file) to find the relevant implementation. > I'm sure I'll eventually figure it out if I stare at the code hard > enough, but would totally appreciate any help I can get :) > > Thanks again! You're welcome, but I hope somebody else will also step up to offer useful comments, because (what between my talk at Google Developer's Day tomorrow, and traveling next week to speak in Krakow and then at the first Italian conference on Python in Florence) I'm rather overwhelmed these days;-). Alex From mail at microcorp.co.za Mon May 14 02:21:05 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 14 May 2007 08:21:05 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> Message-ID: <015101c795f3$a683de40$03000080@hendrik> "Bruno Desthuilliers" wrote: >Martin v. L?wis a ?crit : >> So, please provide feedback, e.g. perhaps by answering these >> questions: >> - should non-ASCII identifiers be supported? > >No. Agreed - I also do not think it is a good idea > >> why? > >Because it will definitivly make code-sharing impossible. Live with it >or else, but CS is english-speaking, period. I just can't understand >code with spanish or german (two languages I have notions of) >identifiers, so let's not talk about other alphabets... > The understanding aside, it seems to me that the maintenance nightmare is more irritating, as you are faced with stuff you can't type on your keyboard, without resorting to look up tables and ... sequences. And then you could still be wrong, as has been pointed out for capital A and Greek alpha. Then one should consider the effects of this on the whole issue of shared open source python programs, as Bruno points out, before we argue that I should not be "allowed" access to Greek, or French and German code with umlauts and other diacritic marks, as someone else has done. I think it is best to say nothing of Saint Cyril's script. I think that to allow identifiers to be "native", while the rest of the reserved words in the language remains ASCII English kind of defeats the object of making the python language "language friendly". It would need something like macros to enable the definition of native language terms for things like "while", "for", "in", etc... And we have been through the Macro thingy here, and the consensus seemed to be that we don't want people to write their own dialects. I think that the same arguments apply here. >NB : I'm *not* a native english speaker, I do *not* live in an english >speaking country, and my mother's language requires non-ascii encoding. >And I don't have special sympathy for the USA. And yes, I do write my >code - including comments - in english. > My case is similar, except that we are supposed to have eleven official languages. - When my ancestors fought the English at Spion Kop*, we could not even spell our names - and here I am defending the use of this disease that masquerades as a language, in the interests of standardisation of communication and ease of sharing and maintenance. BTW - Afrikaans also has stuff like umlauts - my keyboard cannot type them and I rarely miss it, because most of my communication is done in English. - Hendrik * Spion Kop is one of the few battles in history that went contrary to the common usage whereby both sides claim victory. In this case, both sides claimed defeat. "We have suffered a small reverse..." - Sir Redvers Buller, who was known afterwards as Sir Reverse Buller, or the Ferryman of the Tugela. To be fair, it was the first war with trenches in it, and nobody knew how to handle them. From castironpi at gmail.com Tue May 8 00:42:43 2007 From: castironpi at gmail.com (castironpi at gmail.com) Date: 7 May 2007 21:42:43 -0700 Subject: interesting exercise In-Reply-To: <1178598876.913274.184850@p77g2000hsh.googlegroups.com> References: <1178595952.641173.76540@y80g2000hsf.googlegroups.com> <1178598876.913274.184850@p77g2000hsh.googlegroups.com> Message-ID: <1178599363.051648.235280@w5g2000hsg.googlegroups.com> On May 7, 11:34 pm, castiro... at gmail.com wrote: > On May 7, 10:45 pm, Michael Tobis wrote: > > > > > I want a list of all ordered permutations of a given length of a set > > of tokens. Each token is a single character, and for convenience, they > > are passed as a string in ascending ASCII order. > > > For example > > > permute("abc",2) > > > should return ["aa","ab","ac","ba","bb","bc","ca","cb","cc"] > > > and permute("13579",3) should return a list of 125 elements > > ["111","113", ... ,"997","999"] > > > permute("axc",N) or permute("2446",N) should raise ValueError as the > > alphabet is not strictly sorted. > > > I have a reasonably elegant solution but it's a bit verbose (a couple > > dozen lines which I'll post later if there is interest). Is there some > > clever Pythonism I didn't spot? > > > thanks > > mt > > Post yours. Oh well, as I'm not the first. def p(a,b): if list( a ) != sorted( list( a ) ): raise ValueError, "String not ordered." if not b: return [''] a = sorted( set( a ) ) return [i+j for i in a for j in p(a,b-1)] p('abc',3) #fb: ['aaa', 'aab', 'aac', 'aba', 'abb', 'abc', 'aca', 'acb', 'acc', 'baa', 'bab', 'bac', 'bba', 'bbb', 'bbc', 'bca', 'bcb', 'bcc', 'caa', 'cab', 'cac', 'cba', 'cbb', 'cbc', 'cca', 'ccb', 'ccc'] p('abc',2) #fb: ['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc'] len(p("13579",3)) #fb: 125 edit() From kw at codebykevin.com Mon May 21 14:19:01 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Mon, 21 May 2007 14:19:01 -0400 Subject: Python and GUI In-Reply-To: <1179761984.704369.116310@b40g2000prd.googlegroups.com> References: <1179761984.704369.116310@b40g2000prd.googlegroups.com> Message-ID: <38a37$4651e295$4275d90a$15861@FUSE.NET> sdoty044 at gmail.com wrote: > Ultimately, is it worth downloading and learning some of the packages > avaiable for Python, or should I just stick to the Tkinter stuff that > is included. It depends. Are you selling your application commercially/closed-source or is it freeware/open-source? Are you deploying on several platforms, or just one? Here are a few things to consider: 1. Tkinter is simple to code and easy to deploy. It's a bit bare-bones without additional packages. 2. wxPython is big, harder to learn than Tkinter, but looks good on Mac, Windows, and *Nix. It will require users to install a lot of extra stuff (or you'll have to bundle the extra stuff). 3. PyQt is also nice, and works well on Mac/Windows/*Nix but the free version requires your app to be released under the GPL. That may or may not be an issue for you. PyQt is also a large package to install. 4. PyGTK is popular on*Nix and works OK on Windows. But it doesn't run natively on the Mac. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From steve at holdenweb.com Fri May 18 16:40:06 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 18 May 2007 16:40:06 -0400 Subject: namespace question In-Reply-To: <%fm3i.726$u56.355@newssvr22.news.prodigy.net> References: <%fm3i.726$u56.355@newssvr22.news.prodigy.net> Message-ID: T. Crane wrote: > "Robert Kern" wrote in message > news:mailman.7868.1179512371.32031.python-list at python.org... >> T. Crane wrote: >>> Hi, >>> >>> If I define a class like so: >>> >>> class myClass: >>> import numpy >>> a = 1 >>> b = 2 >>> c = 3 >>> >>> def myFun(self): >>> print a,b,c >>> return numpy.sin(a) >>> >>> >>> I get the error that the global names a,b,c,numpy are not defined. >>> Fairly >>> straightforward. But if I am going to be writing several methods that >>> keep >>> calling the same variables or using the same functions/classes from >>> numpy, >>> for example, do I have to declare and import those things in each method >>> definition? Is there a better way of doing this? >> Put your imports at the module level. I'm not sure what you intended with >> a, b, >> c so let's also put them at the top level. > > If you put them at the top level, and suppose you saved it all in a file > called test.py, then when you type > > ln [1]: from test import myClass > > does it still load a,b,c and numpy into the namespace? > Why does it need to? The functions in module "test" will access that module's namespace, not that of the calling module. >> import numpy >> a = 1 >> b = 2 >> c = 4 >> >> class myClass: >> def myFun(self): >> print a, b, c >> return numpy.sin(a) >> >> >> OTOH, if a, b, c were supposed to be attached to the class so they could >> be >> overridden in subclasses, or be default values for instances, you can >> leave them >> in the class definition, but access them through "self" or "myClass" >> directly. > > Yeah, they don't need to be accessed anywhere other than within the class > itself and I won't need to overwrite them, so I'll try just putting them in > the top level. > That should work 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From tenax.raccoon at gmail.com Wed May 9 15:09:52 2007 From: tenax.raccoon at gmail.com (Jason) Date: 9 May 2007 12:09:52 -0700 Subject: Inheritance problem In-Reply-To: <1178734168.255175.248800@e51g2000hsg.googlegroups.com> References: <1178734168.255175.248800@e51g2000hsg.googlegroups.com> Message-ID: <1178737792.032917.191110@e65g2000hsc.googlegroups.com> On May 9, 12:09 pm, amidzic.bra... at gmail.com wrote: > I'm trying to solve a problem using inheritance and polymorphism in > python 2.4.2 > > I think it's easier to explain the problem using simple example: > > class shortList: > > def __init__(self): > > self.setList() > > def setList(self): > > a = [1,2,3] > > print a > > class longList(shortList): > > def __init__(self): > > shortList.setList() > > self.setList() > > def setList(self): > > a.extend([4,5,6]) > > print a > > def main(): > > a = raw_input('Do you want short or long list? (s/l)') > > if a.upper() == 'S': > > lst = shortList() > > else: > > lst = longList() > > lst.setList() > > if __name__ == '__main__': > > main() > > After that I'm getting a message: > > TypeError: unbound method setList() must be called with shortList > instance as first argument (got nothing instead) > > Where is the problem? > > Thanks in advance... As Neil indicated, you use the self object to access the current object's class members. The first parameter to a Python method is the object that the method is operating on. For a silly example: >>> class SayHi(object): ... def __init__(self, name): ... self.name = name # Save the name for later ... def Talk(self): ... print "Hi,", self.name ... >>> helloWorld = SayHi("World") >>> helloWorld.Talk() Hi, World >>> As you can see, the __init__ special method saves the name by "self.name = name". Similarly, the name is accessed in the Talk method via "self.name". Please note that the first parameter is called "self" by convention. Python doesn't care what you call the first parameter to a method. However, most of the Python world uses "self", so it is highly recommended to follow this convention. Now for the problem specific to the error message that you're getting: As above, the first parameter to a Python method is the object being operated on. Python uses a little bit of "syntactic sugar" to make calling methods easier. You can explicitly call a class method directly and pass the object in as the first parameter yourself. >>> helloWorld.Talk() # This is the normal way of calling Talk Hi, World >>> SayHi.Talk(helloWorld) # This works, too! Hi, World To easily call a superclass method, you can explicitly use the baseclass. You're attempting to do so, but you forgot one important ingrediant: the object being operated on! In C++, the object is implicit. In Python, you must explicitly send it to the superclass: >>> class SayHello(SayHi): ... def __init__(self, name): ... SayHi.__init__(self, name) # Call the superclass's init ... def Talk(self): ... print "Hello,", self.name ... >>> moreTalk = SayHello("World") >>> moreTalk.Talk() Hello, World Basically, you need to: 1. Assign your lists in setList to "self.a" instead of the local variable "a". 2. Pass the object to the superclass method in setList ("shortList.setList(self)") There are other things that may be improved with your design. Keep plugging at it! --Jason From DustanGroups at gmail.com Sat May 5 14:03:06 2007 From: DustanGroups at gmail.com (Dustan) Date: 5 May 2007 11:03:06 -0700 Subject: change of random state when pyc created?? In-Reply-To: References: Message-ID: <1178388186.631422.290580@w5g2000hsg.googlegroups.com> On May 4, 10:48 pm, "Alan Isaac" wrote: > This may seem very strange, but it is true. > If I delete a .pyc file, my program executes with a different state! > > In a single directory I have > module1 and module2. > > module1 imports random and MyClass from module2. > module2 does not import random. > > module1 sets a seed like this:: > > if __name__ == "__main__": > random.seed(314) > main() > > I execute module1.py from the (Windows) shell. > I get a result, let's call it result1. > I execute it again. I get another result, say result2. > Running it again and again, I get result2. > > Now I delete module2.pyc. > I execute module1.py from the shell. > I get result1. > I execute it again; I get result2. > From then on I get result2, > unless I delete module.pyc again, > in which case I once again get result1. > > Can someone explain this to me? > > Thank you, > Alan Isaac I can't imagine why that would be, and I was unable to reproduce that behavior, using Microsoft Windows XP and Python 2.5: import module2 import random def main(): for i in range(10): print module2.aRandom() if __name__ == '__main__': random.seed(314) main() import random print "module2 imported" def aRandom(): return random.randrange(1000000) C:\Documents and Settings\DUSTAN\Desktop\apackage>module1.py module2 imported 196431 111465 2638 628136 234231 207699 546775 449804 633844 179171 C:\Documents and Settings\DUSTAN\Desktop\apackage>module1.py module2 imported 196431 111465 2638 628136 234231 207699 546775 449804 633844 179171 C:\Documents and Settings\DUSTAN\Desktop\apackage>module1.py module2 imported 196431 111465 2638 628136 234231 207699 546775 449804 633844 179171 C:\Documents and Settings\DUSTAN\Desktop\apackage>module1.py module2 imported 196431 111465 2638 628136 234231 207699 546775 449804 633844 179171 I deleted module2.pyc right before that last call. From carsten at uniqsys.com Sat May 12 21:10:54 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 12 May 2007 21:10:54 -0400 Subject: Interesting list Validity (True/False) In-Reply-To: <1179017740.656323.209590@e51g2000hsg.googlegroups.com> References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> <1178914190.166662.285410@p77g2000hsh.googlegroups.com> <1178915791.584216.293130@l77g2000hsb.googlegroups.com> <1178918808.091358.233740@o5g2000hsb.googlegroups.com> <1179017740.656323.209590@e51g2000hsg.googlegroups.com> Message-ID: <1179018654.3252.4.camel@localhost.localdomain> On Sat, 2007-05-12 at 17:55 -0700, mensanator at aol.com wrote: > On May 12, 12:56?pm, Carsten Haese wrote: > > On Fri, 2007-05-11 at 14:26 -0700, mensana... at aol.com wrote: > > > if arg==True: > > > > > tests the type property (whether a list is a boolean). > > > > That sounds nonsensical and incorrect. Please explain what you mean. > > > Sec 2.2.3: > Objects of different types, except different numeric types and > different string types, never compare equal; > That doesn't explain what you mean. How does "if arg==True" test whether "a list is a boolean"? -- Carsten Haese http://informixdb.sourceforge.net From gagsl-py2 at yahoo.com.ar Mon May 14 22:51:33 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 14 May 2007 23:51:33 -0300 Subject: multi-line input? References: <1179179435.410251.303530@u30g2000hsc.googlegroups.com> Message-ID: En Mon, 14 May 2007 18:50:35 -0300, escribi?: > I'm writing a C++ application with an embedded Python interpreter. > Command text is captured and passed to the interpreter a single line > at a time. My question is this: is there a simple way of determining > whether a given input line of text will cause the prompt to change > from the regular ">>>" to the multi-line "..." before sending the text > to the interpreter? I suppose the completely correct solution would be > tokenize and parse the entire string and then examine all the > constituent parts, but that seems like a lot more work than I really > want to do. There is an emulation of the read-eval-print loop written in Python itself, see the code module. In particular, compile_command tries to determine whether the entered text is a complete Python statement, contains a syntax error, or requires more input. If you want to stay with C code, you could use Py_CompileString and see if the already entered code can be compiled or not - but I'm not sure if you will actually be able to distinguish a SyntaxError from an incomplete statement. > As far as I can tell, there are only a few ways to trigger the multi- > line input prompt: > > - if-statement, for-loop, function or class definition > - line continuation (\) > - block quote (""" or ''') - Any expression involving an open group of () [] {} -- Gabriel Genellina From collver at peak.org Fri May 4 10:43:33 2007 From: collver at peak.org (Ben Collver) Date: Fri, 04 May 2007 07:43:33 -0700 Subject: My Python annoyances In-Reply-To: References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> <1178202431.147195.249790@u30g2000hsc.googlegroups.com> Message-ID: Chris Mellon wrote: > You should "check" for the methods by calling them. If the object > doesn't support the method in question, you will get a runtime > exception. Premature inspection of an object is rarely useful and > often outright harmful. That makes sense, thank you for the response. What about the case where I have an array of objects that represent some particular binary file format. If the object is a file, then I want to copy its contents. If the object is a string, then I want to write the string. And so forth. Should I assume that an object is file-like if it has a read method, and that I can call the read method without unexpected side effects? Ben From igouy at yahoo.com Sun May 6 22:13:28 2007 From: igouy at yahoo.com (Isaac Gouy) Date: 6 May 2007 19:13:28 -0700 Subject: My newbie annoyances so far In-Reply-To: References: <1177688082.758043.133920@r30g2000prh.googlegroups.com> <_9pYh.1787$uJ6.894@newssvr17.news.prodigy.net> <1178400807.051103.95690@q75g2000hsh.googlegroups.com> <1hxp15f.1bvtgo11ydx3cvN%aleax@mac.com> Message-ID: <1178504008.035594.216920@o5g2000hsb.googlegroups.com> On May 6, 6:09 pm, John Nagle wrote: > Alex Martelli wrote: > > John Nagle wrote: > > >>igo... at yahoo.com wrote: > > >>>On Apr 27, 9:07 am, John Nagle wrote: > > >>>>The CPython implementation is unreasonably slow compared > >>>>to good implementations of other dynamic languages such > >>>>as LISP and JavaScript. > > >>>Why do you say CPython is slower than JavaScript? Please provide > >>>examples. > > >> See > > >> http://www.mozilla.org/projects/tamarin/faq.html > > >>Tamarin is a just-in-time compiler for Javascript. > > > ...and is not yet released, as far as I can tell; this makes it kind of > > diffcult to verify any kinds of claims about its speed. > > Tamarind is inside the current implementation of Flash, but it's > not into Firefox yet, apparently. The current SpiderMonkey implementation > is nothing to get excited about in terms of performance. It was my impression that the "current SpiderMonkey implementation is nothing to get excited about in terms of performance" which made your unfavourable comparison to CPython so puzzling (and does the tamarin website actually show any performance comparisons with CPython?) > My point is that there are optimizing hard-code compiler implementations > of many dynamic languages, including LISP, Self, and Smalltalk, but not Python. I guess Lisp is a safe-ish example but I don't think Self really made it out of the lab, and it really depends which Smalltalk implementation you have in mind and what you think about Pysco. From joel.hedlund at gmail.com Wed May 23 10:26:07 2007 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Wed, 23 May 2007 16:26:07 +0200 Subject: Slightly OT: Why all the spam? In-Reply-To: References: <3bb44c6e0705220008y10f5deb7v86ed82d3f8241761@mail.gmail.com> Message-ID: > Thus you may want to consider reading c.l.p via nntp when at work. I'm doing that using Thunderbird 1.5.0, and I still get the spam. Googling for a bit shows me that people have been having issues with Thunderbird not removing expired articles all the way since 2003. Does anyone have a suggestion on how I can make thunderbird remove expired articles? Or should I perhaps use another news reader? /Joel From slava.maslov at gmail.com Sun May 6 21:17:44 2007 From: slava.maslov at gmail.com (Vyacheslav Maslov) Date: Mon, 7 May 2007 08:17:44 +0700 Subject: default test method name in unittest framework Message-ID: <271115400705061817u3c8ee950u3c7b0ec7ddcf6576@mail.gmail.com> Hi, all! i have question related to python's unit testing framework. Take a look at unittest.TestCase class. The main method which contains all code related to test case execution have name "run". But in the same time constructor of unittest.TestCase class have param methodName with default value "runTest", not "run"! Why? This leads to AttributeError exception if i do not explicitly set methodName to "run" during TestCase initialization. -------------- next part -------------- An HTML attachment was scrubbed... URL: From groups at theyoungfamily.co.uk Wed May 16 04:57:19 2007 From: groups at theyoungfamily.co.uk (Ben) Date: 16 May 2007 01:57:19 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464A3354.4060205@web.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649dd55$0$23144$9b4e6d93@newsspool1.arcor-online.net> <464a25e9$0$10188$9b4e6d93@newsspool4.arcor-online.net> <464A3354.4060205@web.de> Message-ID: <1179305839.190121.177990@e65g2000hsc.googlegroups.com> On May 15, 11:25 pm, Stefan Behnel wrote: > Ren? Fleschenberg wrote: > > Javier Bezos schrieb: > >>> But having, for example, things like open() from the stdlib in your code > >>> and then ?ffnen() as a name for functions/methods written by yourself is > >>> just plain silly. It makes the code inconsistent and ugly without > >>> significantly improving the readability for someone who speaks German > >>> but not English. > >> Agreed. I always use English names (more or > >> less :-)), but this is not the PEP is about. > > > We all know what the PEP is about (we can read). The point is: If we do > > not *need* non-English/ASCII identifiers, we do not need the PEP. If the > > PEP does not solve an actual *problem* and still introduces some > > potential for *new* problems, it should be rejected. So far, the > > "problem" seems to just not exist. The burden of proof is on those who > > support the PEP. > > The main problem here seems to be proving the need of something to people who > do not need it themselves. So, if a simple "but I need it because a, b, c" is > not enough, what good is any further prove? > > Stefan For what it's worth, I can only speak English (bad English schooling!) and I'm definitely +1 on the PEP. Anyone using tools from the last 5 years can handle UTF-8 Cheers, Ben From martin at v.loewis.de Wed May 9 00:17:09 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 09 May 2007 06:17:09 +0200 Subject: psycopg2 error In-Reply-To: References: Message-ID: <46414b46$0$9746$9b622d9e@news.freenet.de> > ImportError: libpq.so.5: cannot open shared object file: No such file or > directory > > libpq files are readable by the world: root at lince pgsql # ll lib/ -d > drwxr-xr-x 3 postgres postgres 1528 2007-05-07 23:25 lib/ Don't try this as the root user, but as the one for whom it is failing: What does "file /usr/local/psql/lib/libpq.so.5" say? > The postgreSQL lib is in ld.so.conf and ldconfig has been run: > > What is wrong? So what does "/sbin/ldconfig -p" say, when run as the user for whom it is failing? Regards, Martin From rene at korteklippe.de Wed May 16 04:20:29 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Wed, 16 May 2007 10:20:29 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464ABA99.8080208@web.de> References: <46473267$0$31532$9b622d9e@news.freenet.de> <464ab2f9$0$23146$9b4e6d93@newsspool1.arcor-online.net> <464ABA99.8080208@web.de> Message-ID: <464abecb$0$6403$9b4e6d93@newsspool2.arcor-online.net> Stefan Behnel schrieb: > Then get tools that match your working environment. Integration with existing tools *is* something that a PEP should consider. This one does not do that sufficiently, IMO. -- Ren? From robert.kern at gmail.com Fri May 25 18:54:14 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 25 May 2007 17:54:14 -0500 Subject: printing list, is this a bug? In-Reply-To: <1180126524.884163.234040@k79g2000hse.googlegroups.com> References: <1180126524.884163.234040@k79g2000hse.googlegroups.com> Message-ID: William Chang wrote: > Is the different behavior between __repr__ and __str__ intentional > when it comes to printing lists? Basically I want to print out a list > with elements of my own class, but when I overwrite __str__, __str__ > doesn't get called but if I overwrite __repr__, __repr__ will get > called. Is this a bug? No, it's deliberate design. The string representation of a list object, either list.__str__() or list.__repr__(), uses the __repr__() of its contained objects. -- 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 dalcolmo at vh-s.de Mon May 7 13:26:21 2007 From: dalcolmo at vh-s.de (Josef Dalcolmo) Date: Mon, 07 May 2007 19:26:21 +0200 Subject: getmtime differs between Py2.5 and Py2.4 Message-ID: I tried this on Windows only: In Python 2.4 os.path.getmtime returned the local time, in Python 2.5 it seems to return GMT: import os, time print ctime.time(os.path.getmtime(foo)) differs on Python 2.4 and Python 2.5 by the timezone. Now, the implementation of the two stat calls differs on Windows between the two versions. I actually like the new behaviour better, because I believe the reported time of a file should not depend on the timezone or other local settings, however the old behaviour is the time also Windows shows - and there is an incompatibility. Is this a bug? - Josef From warren at muse.com Wed May 30 18:37:59 2007 From: warren at muse.com (Warren Stringer) Date: Wed, 30 May 2007 15:37:59 -0700 Subject: c[:]() In-Reply-To: <465DF3DE.40404@cc.umanitoba.ca> References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com><1180504773.374529.161740@q66g2000hsg.googlegroups.com><002801c7a2eb$288a8750$240110ac@Muse> <1180554872.3356.30.camel@dot.uniqsys.com><003601c7a301$dfcff0b0$240110ac@Muse> <465DF3DE.40404@cc.umanitoba.ca> Message-ID: <004001c7a30b$2d3dc8a0$240110ac@Muse> Hey many thanks for the replies! Ah, so is seems that c[:][:][:][:][:][:][:][:][:][:][:][0]() also work ... Ah well, can't have everything. Guess I was inspired by the alphabetically adjacent message "Call for Ruby Champion". Would have been nice for it work - a more elegant iterator would be hard to come by. A PEP, perhaps? Maybe not; am still a bit new - am probably missing something obvious why this isn't an easy fix. Pretty cool that I can override the list class. Cheers, \~/ > -----Original Message----- > From: python-list-bounces+warren=muse.com at python.org [mailto:python-list- > bounces+warren=muse.com at python.org] On Behalf Of Brian van den Broek > Sent: Wednesday, May 30, 2007 3:00 PM > To: python-list at python.org > Subject: Re: c[:]() > > Warren Stringer said unto the world upon 05/30/2007 05:31 PM: > > Hmmm, this is for neither programmer nor computer; this is for a user. > If I > > wanted to write code for the benefit for the computer, I'd still be > flipping > > switches on a PDP-8. ;-) > > > > This is inconsistent: > > > > why does c[:][0]() work but c[:]() does not? > > c[:][0]() says take a copy of the list c, find its first element, and > call it. Since c is a list of functions, that calls a function. > > c[:]() says take a copy of the list c and call it. Since lists are not > callable, that doesn't work. > > > Why does c[0]() has exactly the same results as c[:][0]() ? > > Because c[0] is equal to c[:][0]. > > > Moreover, c[:][0]() implies that a slice was invoked > > Yes, but the complete slice. > > > So, tell me, for scheduling a lot of asynchronous events, what would be > more > > readable than this: > > > > bidders = [local_members] + [callin_members] > > bidders[:].sign_in(roster) > > ... > > for bidder in [local_members] + [callin_members]: > bidder.sign_in(roster) > > Best, > > Brian vdB > > > \~/ > > > >> -----Original Message----- > >> From: python-list-bounces+warren=muse.com at python.org [mailto:python- > list- > >> bounces+warren=muse.com at python.org] On Behalf Of Carsten Haese > >> Sent: Wednesday, May 30, 2007 12:55 PM > >> To: python-list at python.org > >> Subject: Re: c[:]() > >> > >> On Wed, 2007-05-30 at 11:48 -0700, Warren Stringer wrote: > >>> I want to call every object in a tupple, like so: > >>> > >>> #------------------------------------------ > >>> def a: print 'a' > >>> def b: print 'b' > >>> c = (a,b) > >>> > >>>>>> c[:]() # i wanna > >>> [...] > >>> Is there something obvious that I'm missing? > >> Yes: Python is not Perl. > >> > >> Python is based on the principle that programmers don't write computer > >> code for the benefit of the computer, but for the benefit of any > >> programmer who has to read their code in the future. Terseness is not a > >> virtue. To call every function in a tuple, do the obvious: > >> > >> for func in funcs: func() > >> > >> HTH, > >> > >> -- > >> Carsten Haese > >> http://informixdb.sourceforge.net > >> > >> > >> -- > >> http://mail.python.org/mailman/listinfo/python-list > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list From arjunajay_ajay at rediffmail.com Sun May 20 01:01:09 2007 From: arjunajay_ajay at rediffmail.com (Arjun Narayanan) Date: 19 May 2007 22:01:09 -0700 Subject: Can't embed python in C++(Mingw[3.*] compiler) In-Reply-To: References: <1179591280.469302.289010@p77g2000hsh.googlegroups.com> Message-ID: <1179637269.471339.307050@w5g2000hsg.googlegroups.com> On May 20, 1:28 am, "Gabriel Genellina" wrote: > En Sat, 19 May 2007 13:14:40 -0300, Arjun Narayanan > escribi?: > > > For thr program, > > #include "E:\Python25\include\Python.h" > > #include > > Configure your environment so using: > > #include > > works (you may need to add E:\Python25\include to some list of searched > directories, maybe an INCLUDE environment variable). > > -- > Gabriel Genellina That AND I didn't use the american spelling Py_Initiali >>> Z <<< e(); From nufuhsus at gmail.com Wed May 9 15:37:06 2007 From: nufuhsus at gmail.com (nufuhsus at gmail.com) Date: 9 May 2007 12:37:06 -0700 Subject: preferred windows text editor? In-Reply-To: References: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> <1178738724.695273.191930@n59g2000hsh.googlegroups.com> Message-ID: <1178739425.943249.104880@o5g2000hsb.googlegroups.com> On May 9, 3:30 pm, Trent Mick wrote: > There is an ActivePython 2.5.1 now:http://www.activestate.com/products/activepython/ > > You should give Komodo Edit a try too:http://www.activestate.com/products/komodo_edit/ Thanks for the heads up Trent. From f.braennstroem at gmx.de Mon May 14 16:56:20 2007 From: f.braennstroem at gmx.de (Fabian Braennstroem) Date: Mon, 14 May 2007 20:56:20 +0000 Subject: track cpu usage of linux application Message-ID: Hi, I would like to track the cpu usage of a couple of programs using python. Maybe it works somehow with piping 'top' to python read the cpu load for a greped application and clocking the the first and last appearence. Is that a good approach or does anyone have a more elegant way to do that? Greetings! Fabian From ranaeng at hotmail.com Mon May 7 02:13:15 2007 From: ranaeng at hotmail.com (majeed rana) Date: Sun, 6 May 2007 23:13:15 -0700 Subject: PChess 0.9 Message-ID: I want pchess 0.9 -------------- next part -------------- An HTML attachment was scrubbed... URL: From simon at brunningonline.net Thu May 17 08:51:19 2007 From: simon at brunningonline.net (Simon Brunning) Date: Thu, 17 May 2007 18:21:19 +0530 Subject: Sending a JavaScript array to Python script? In-Reply-To: <1179405295.865954.241740@e65g2000hsc.googlegroups.com> References: <1179405295.865954.241740@e65g2000hsc.googlegroups.com> Message-ID: <8c7f10c60705170551k34d819p6c43402910785adb@mail.gmail.com> On 17 May 2007 05:34:55 -0700, placid wrote: > Just wondering if there is any way of sending a JavaScript array to a > Python cgi script? A quick Google search didn't turn up anything > useful. JSON might be worth a look: http://www.json.org/ -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues From collver at peak.org Fri May 4 11:07:41 2007 From: collver at peak.org (Ben Collver) Date: Fri, 04 May 2007 08:07:41 -0700 Subject: My Python annoyances In-Reply-To: <1hxkwj0.12jtj1v3b522bN%aleax@mac.com> References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> <1178202431.147195.249790@u30g2000hsc.googlegroups.com> <1hxkwj0.12jtj1v3b522bN%aleax@mac.com> Message-ID: <2omdnf0u9vqj0abbnZ2dnUVZ_u3inZ2d@scnresearch.com> Alex Martelli wrote: > "Type-switching" in this way is a rather dubious practice in any > language (it can't respect the "open-closed" principle). Can't you have > those objects wrapped in suitable wrappers with a "copyorwrite" method > that knows what to do? For example, StringIO.StringIO is a standard > library wrapper type that makes a string look like a file. That is very reasonable. Thanks again, Ben From john at datavoiceint.com Tue May 15 13:24:26 2007 From: john at datavoiceint.com (HMS Surprise) Date: 15 May 2007 10:24:26 -0700 Subject: File record separators. In-Reply-To: References: <1179241525.667682.112220@y80g2000hsf.googlegroups.com> Message-ID: <1179249866.369812.167590@u30g2000hsc.googlegroups.com> Thanks folks. Was unaware of enumerate , still have a lot to learn about python. Sorry for the poorly phrased request, but you gathered the gist of it. My wonderment is how to write the following 2 lines and make sure they are saved as separate records or lines so that I pull in only one at a time with readline(?). ['a', 'b'], ['c','d']] [['a', 'b'], ['c','d'], ['e','f']] Would like to use pickle but it is apparently unavailable in the package I am using, Jython 2.2. From snewman18 at gmail.com Wed May 30 20:56:58 2007 From: snewman18 at gmail.com (snewman18 at gmail.com) Date: 30 May 2007 17:56:58 -0700 Subject: How to parse usenet urls? Message-ID: <1180573018.786188.220260@h2g2000hsg.googlegroups.com> I'm trying to parse newsgroup messages, and I need to follow URLs in this format: news://some.server. I can past them into a newsreader with no problem, but I want to do it programatically. I can't figure out how to follow these links - anyone have any ideas? From claird at lairds.us Wed May 16 14:01:02 2007 From: claird at lairds.us (Cameron Laird) Date: Wed, 16 May 2007 18:01:02 +0000 Subject: Trying to choose between python and java References: Message-ID: In article , Terry Reedy wrote: > >"Anthony Irwin" wrote in message >news:f2bghg$4q0$1 at news-01.bur.connect.com.au... . . . >| #5 someone said that they used to use python but stopped because the >| language changed or made stuff depreciated (I can fully remember >| which) and old code stopped working. Is code written today likely to >| still work in 5+ years or do they depreciate stuff and you have to >update? > >Most versions of Python are still available. You are free to use and >distribute your copies indefinitely. Several older versions are still in >use. > >Recent releases have added features but removed very little except bugs. >Unfortunately, bug removal sometimes breaks code. And feature additions >occasionally introduce bugs or otherwise break code, but that is why there >are alpha, beta, and candidate releases before a final release. > >Python3 will remove many things at once. A conversion tool is being >written. And there is no expectation that production code should be >immediately converted, if ever. . . . I'll answer even more aggressively: Python's record of backward compatibility is *better* than Java's. From martin at v.loewis.de Tue May 29 03:05:14 2007 From: martin at v.loewis.de (=?GB2312?B?Ik1hcnRpbiB2LiBMbyJ3aXMi?=) Date: Tue, 29 May 2007 09:05:14 +0200 Subject: how to print the GREEK CAPITAL LETTER delta under utf-8 encoding In-Reply-To: <1180421212.151587.118020@r19g2000prf.googlegroups.com> References: <1180414659.066482.236370@i38g2000prf.googlegroups.com> <465BBB49.6000803@v.loewis.de> <1180421212.151587.118020@r19g2000prf.googlegroups.com> Message-ID: <465BD0AA.9080805@v.loewis.de> > yes, it could print to the terminal(cmd.exe), but when I write these > string to file. I got the follow error: > > File "E:\Tools\filegen\filegen.py", line 212, in write > self.file.write(data) > UnicodeEncodeError: 'ascii' codec can't encode character u'\u0394' in > position 0 > : ordinal not in range(128) Yes, when writing to a file, you need to define an encoding, e.g. self.file.write(data.encode("utf-8")) You can use codecs.open() instead of open(), so that you can just use self.file.write(data) Alternatively, you can find out what sys.stdout.encoding is, and use that when encoding data for the terminal (falling back to "utf-8" when .encoding is not available on the file). > but other text, in which include "chinese characters" got from > os.listdir(...), are written to the file OK. why? Your version of Windows uses a code page that supports Chinese characters in the byte-oriented character set. These are normally encoded using the "mbcs" encoding (except that the terminal likely uses a different encoding). So if you use "mbcs" instead of "utf-8", you might be able to read the text as well. Regards, Martin From ivoras at __fer.hr__ Sat May 12 20:20:15 2007 From: ivoras at __fer.hr__ (Ivan Voras) Date: Sun, 13 May 2007 02:20:15 +0200 Subject: __dict__ for instances? Message-ID: While using PyGTK, I want to try and define signal handlers automagically, without explicitly writing the long dictionary (i.e. I want to use signal_autoconnect()). To do this, I need something that will inspect the current "self" and return a dictionary that looks like: { "method_name" : self.method_name } Class.__dict__ does something very similar, but when I use it, either I'm doing something wrong or it doesn't return methods bound to "self", and python complains a wrong number of arguments is being passed to the methods (one instead of two). instance.__dict__ on the other hand returns an empty dictionary. This looks like it should be easy, but I can't find the solution :( -- (\__/) (O.o) (> < ) This is Bunny. Copy Bunny into your signature to help him on his way to world domination! -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 258 bytes Desc: OpenPGP digital signature URL: From kyosohma at gmail.com Wed May 9 14:20:34 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 9 May 2007 11:20:34 -0700 Subject: preferred windows text editor? In-Reply-To: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> References: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> Message-ID: <1178734834.673234.73010@h2g2000hsg.googlegroups.com> On May 9, 1:06 pm, "T. Crane" wrote: > Right now I'm using Notepad++. What are other people using? > > trevis For Python, I still prefer IDLE or PythonWin. For other things like cmd, ini, and other text files, I use either Notepad++ or UltraEdit. Mike From f.braennstroem at gmx.de Tue May 15 18:39:19 2007 From: f.braennstroem at gmx.de (Fabian Braennstroem) Date: Tue, 15 May 2007 22:39:19 +0000 Subject: track cpu usage of linux application References: <1179177471.235450@smirk> Message-ID: Hi, thanks to both! I will take a look at the proc files! * James T. Dennis wrote: > Fabian Braennstroem wrote: >> Hi, > >> I would like to track the cpu usage of a couple of >> programs using python. Maybe it works somehow with >> piping 'top' to python read the cpu load for a greped >> application and clocking the the first and last >> appearence. Is that a good approach or does anyone have >> a more elegant way to do that? > >> Greetings! >> Fabian > > If you're on a Linux system you might be far better accessing > the /proc/$PID/stat files directly. The values you'd find therein > are documented: > > http://www.die.net/doc/linux/man/man5/proc.5.html > > (among other places). > > Of course you could write you code to look for file and fall back > to use the 'ps' command if it fails. In addition you can supply > arguments to the 'ps' command to limit it to reporting just on the > process(es) in which you are interested ... and to eliminate the > header line and irrelevant columns of output. Greetings! Fabian From horpner at yahoo.com Wed May 23 08:34:14 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 23 May 2007 12:34:14 GMT Subject: converting text and spans to an ElementTree References: Message-ID: On 2007-05-22, Steven Bethard wrote: > Thanks a lot! This put me on the right track (though the > devil's definitely in the details). It's working now:: > > > >>> tree = xmltools.text_and_spans_to_etree('aaa aaa aaaccc cccaaa', [ > ... (etree.Element('a'), 0, 21), > ... (etree.Element('b'), 11, 11), > ... (etree.Element('c'), 11, 18), > ... ]) > >>> etree.tostring(tree) > 'aaa aaa aaaccc cccaaa' > >>> tree = xmltools.text_and_spans_to_etree('bbb\naaaccc\ncccaaa', [ > ... (etree.Element('a'), 0, 17), > ... (etree.Element('b'), 0, 4), > ... (etree.Element('c'), 7, 14), > ... (etree.Element('b'), 14, 14), > ... ]) > >>> etree.tostring(tree) > 'bbb\naaaccc\ncccaaa' > >>> tree = xmltools.text_and_spans_to_etree('abc', [ > ... (etree.Element('a'), 0, 3), > ... (etree.Element('b'), 0, 3), > ... (etree.Element('c'), 0, 3), > ... ]) > >>> etree.tostring(tree) > 'abc' > > > And for the sake of any poor soul who runs into a similar > problem, here's the code I wrote using Gabriel's hints above:: When I saw you manually keeping a stack, I called Captain Recursion on my Red-Alert Recursion Phone. (I'm sorry he left out the Element stuff, which he doesn't know or use yet. The Captain's get_tree just returns the string) def get_tree(text, spans): """ >>> text = 'aaa aaa aaabbb bbbaaa' >>> spans = [ ... ('a', 0, 21), ... ('b', 11, 18), ... ('c', 18, 18), ... ] I'd like to produce the corresponding ElementTree. So I want to write a get_tree() function that works like:: >>> get_tree(text, spans) 'aaa aaa aaabbb bbbaaa' """ if not spans: return '' else: head, tail = spans[0], spans[1:] elem, start, end = head if tail: _, follow_start, follow_end = tail[0] else: follow_start, follow_end = (end, end) if end > start: return ("<%s>%s%s%s" % (elem, text[start:follow_start], get_tree(text, tail), text[follow_end:end], elem)) else: return "<%s />%s" % (elem, get_tree(text, tail)) -- Neil Cerutti From __peter__ at web.de Sat May 19 11:38:05 2007 From: __peter__ at web.de (Peter Otten) Date: Sat, 19 May 2007 17:38:05 +0200 Subject: RFC - n-puzzle.py References: <1179530104.645902.135250@p77g2000hsh.googlegroups.com> <1179566627.583978.304810@n59g2000hsh.googlegroups.com> <1179578316.956894.164140@y80g2000hsf.googlegroups.com> Message-ID: Steve Holden wrote: > Phoe6 wrote: >> On May 19, 2:23 pm, Raymond Hettinger wrote: >>> Instead of: >>> short_path = mdists[0] >>> if mdists.count(short_path) > 1: >>> write: >>> short_path = mdists[0] >>> if short_path in mdists[1:]: >> >> I would like to understand the difference between the two if >> statements. >> I had used count method, to signify the meaning that, if the least >> distance occurs more then proceed with block. >> How is 'in' with list[1:] an advantage? If it is. > > Because it can stop as soon as short_path is found, whereas the count > method must examine all elements to determine whether they should > increment the count beyond one. It's a trade-off. You check only half (on average) of the items in the original list, but in exchange copy all but one into a new list. The idiom Raymond recommended only makes sense because comparison is "slow" and slicing is "fast" in Python. If the original list were large in comparison to the available RAM the following idiom might be preferrable: it = iter(mdists) short_path = it.next() if short_path in it: # ... Peter From kensmith at rahul.net Fri May 4 09:43:53 2007 From: kensmith at rahul.net (MooseFET) Date: 4 May 2007 06:43:53 -0700 Subject: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before? In-Reply-To: <08qk33t594ih0ulmjmev90d22lkfnotgoe@4ax.com> References: <1178161523.615688.256120@y80g2000hsf.googlegroups.com> <08qk33t594ih0ulmjmev90d22lkfnotgoe@4ax.com> Message-ID: <1178286233.899362.160630@q75g2000hsh.googlegroups.com> On May 3, 4:08 pm, quasi wrote: > On Fri, 04 May 2007 09:37:37 +1200, Gib Bogle > > wrote: > >Ah, so the firefighters were in on the conspiracy! > > No, but the firefighters are very much aware that there is more to > 9/11 than has been officially revealed. > > This is even more true at Pentagon. The firefighters there brought > dogs trained to search for survivors and/or remains and found nothing. Thats because nobody works at the Pentagon. Like the CIA headquarters it is actually a show run by Disney corp on a special contract. It is just to keep the voters from asking where all that money really goes. From steve at holdenweb.com Thu May 17 17:46:55 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 17 May 2007 17:46:55 -0400 Subject: Execute commands from file In-Reply-To: <464c7e99$0$3814$5402220f@news.sunrise.ch> References: <1179320782.594398.67980@u30g2000hsc.googlegroups.com> <464b370c$0$3808$5402220f@news.sunrise.ch> <1179387023.005808.60670@o5g2000hsb.googlegroups.com> <464c7e99$0$3814$5402220f@news.sunrise.ch> Message-ID: Martin Blume wrote: > "Steve Holden" schrieb >>>> Try it on a file that reads something like >>>> >>>> xxx = 42 >>>> print xxx >>>> >>>> and you will see NameError raised because the assignment >>>> hasn't affected the environment for the print statement. >>>> >>> [...] >>> >> No, because there isn't one. Now try adding a function >> definition and see how well it works. >> > C:\temp>more question.py > xxx=42 > print xxx > def sowhat(): > print xxx > > print xxx > > > C:\temp>c:\programme\python\python > Python 2.4 (#60, Nov 30 2004, 11:49:19) > [MSC v.1310 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" > for more information. >>>> exec open("question.py").read() > 42 > 42 >>>> sowhat() > 42 >>>> xxx > 42 > > > Seems to work great to me. > > OTOH, this doesn't: >>>> inp=open("question.py") >>>> for l in inp: > ... exec l > ... > 42 > Traceback (most recent call last): > File "", line 2, in ? > File "", line 1 > def sowhat(): > ^ > SyntaxError: unexpected EOF while parsing > > > So it seems to depend on the way the file is read. > It depends on the way the lines of the file are executed, not how they are read. And you may remember the original poster was proposing this: inp = open(cmd_file) > for line in inp: > exec line As for your first example, why not just use execfile() ? 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From sjmachin at lexicon.net Fri May 4 18:06:57 2007 From: sjmachin at lexicon.net (John Machin) Date: 4 May 2007 15:06:57 -0700 Subject: Getting some element from sets.Set In-Reply-To: <1178267029.258868.219800@h2g2000hsg.googlegroups.com> References: <1178258913.095438.173020@h2g2000hsg.googlegroups.com> <1178267029.258868.219800@h2g2000hsg.googlegroups.com> Message-ID: <1178316417.371855.63170@p77g2000hsh.googlegroups.com> On May 4, 6:23 pm, "jm.sur... at no.spam.gmail.com" wrote: > On May 4, 11:34 am, Peter Otten <__pete... at web.de> wrote: > > > > > jm.sur... at no.spam.gmail.com wrote: > > > It is not possible to index set objects. That is OK. > > > But, what if I want to find some element from the Set. > > > > from sets import Set > > > s = Set( range(12 ) > > > > if I do pop, that particular element gets removed. > > > I do not want to remove the element, but get some element > > > from the Set. > > > > s.some_element() # Is not available > > > > Is there a way to do this. I am doing it like this: > > > > for x in s: break > > > > Now x is /some_element/ from s. > > > A set is probably not the appropriate container then. What is your use case? > > > Peter > > Peter, I need to do a lot of union and intersection operations on > these elements. So, set is a must for me in this case. Errmm, union and intersection operations each apply to two (or more) sets, not to the elements of a set. > > In the particular case, I have to read an attribute from any one of > the elements, which one doesn't matter because this attribute value is > same across all elements in the set. > Well, I'm not so easily convinced as some people :-) You say the rule is that each element in a set has element.someattribute == somevalue. You have n sets set0, set1, .... Let u be the number of unique somevalues (1 <= u <= n) If u > 1, then after setn = union(set0, set1), setn may not conform to the rule -- does this matter? You have a rather redundant data structure, and perhaps should consider refactoring it. A physical analogy: somebody has packed fruit into boxes, all the bananas in one box, the oranges in a second box, the apples in a third box, etc, without writing labels on the boxes. The somebody has however laboriously pasted a label ("banana", "orange", etc) on each piece of fruit. You now need to grab an object from each box, presumably to identify the box contents. How close is this analogy to your scenario? Cheers, John From lyoshaM at gmail.com Fri May 18 03:45:08 2007 From: lyoshaM at gmail.com (Lyosha) Date: 18 May 2007 00:45:08 -0700 Subject: How to convert a number to binary? In-Reply-To: References: <1179444832.775573.55830@y80g2000hsf.googlegroups.com> <1179445546.307017.275850@p77g2000hsh.googlegroups.com> Message-ID: <1179474308.939323.74720@p77g2000hsh.googlegroups.com> On May 17, 11:04 pm, Stargaming wrote: [...] > >>>Is there an *easy* way to convert a number to binary? [...] > > Wrote this a few moons ago:: > > dec2bin = lambda x: (dec2bin(x/2) + str(x%2)) if x else '' This is awesome. Exactly what I was looking for. Works for other bases too. I guess the reason I couldn't come up with something like this was being brainwashed that lambda is a no-no. And python2.5 funky ?: expression comes in handy! Thanks a lot! From ruoyu0088 at gmail.com Tue May 15 09:46:45 2007 From: ruoyu0088 at gmail.com (HYRY) Date: 15 May 2007 06:46:45 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179226183.215907.140450@q75g2000hsh.googlegroups.com> Message-ID: <1179236805.066552.277950@e65g2000hsc.googlegroups.com> > The other thing is trying to teach them formal operational logic when > they are not yet ready for it. In that case it would be better to wait > until they are ready, but unfortunately there are large variations in > the age at which children become ready. Please do not confuse the two > very different matters of language acquisition and formal operational > logic. Language is learned at an early age while formal logic starts at > about the age of eleven (but with very large variation among children). I think programming language such as Logo, or project such as RUR-PLE are used to teach children programming. So, I think there is no problem to teach a 12 years old child for programming. The real problem is they must remeber many English words before programming logic, and it's not funny at all. > Why not use IronPython? But anyway you are actually making things worse > by *not* teaching them the language now that they will need later on and > by *teaching* them formal operational logic at an age when they just get > disappointed and frustrated by not yet being able to understand it. > Better go easy on them and teach them lots of English computing terms > and only introduce logic when they show they are ready. > IronPython is wonderful, I will search for some easy and powerful IDE for it, and switch to IronPython. Learning English is an other subject, my object is to teach them some basic programming logic, not English, not even Python. I don't think English is the necessary condition for formal operational logic. From showell30 at yahoo.com Tue May 29 18:09:49 2007 From: showell30 at yahoo.com (Steve Howell) Date: Tue, 29 May 2007 15:09:49 -0700 (PDT) Subject: Periodic tasks. In-Reply-To: <1180446987.562753.238450@j4g2000prf.googlegroups.com> Message-ID: <234051.24252.qm@web33503.mail.mud.yahoo.com> --- vasudevram wrote: > On May 29, 4:39 pm, Steve Holden > wrote: > > > Alternatively, the user could make use of the > already-existing "sched" > > module from the standard library. With a little > threading that would do > > the job fine. > > Yes. Also, there's an example in the Python Cookbook > (print edition) > which is exactly about this - using sched. The > recipe before that also > shows how to do it without using the sched library. > Both those recipes > are purely in Python. Thanks. Here are two links, not sure those are exactly what are being referenced here, but look in the ballpark: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413137 http://docs.python.org/lib/module-sched.html ____________________________________________________________________________________Looking for a deal? Find great prices on flights and hotels with Yahoo! FareChase. http://farechase.yahoo.com/ From howe.steven at gmail.com Thu May 17 11:08:41 2007 From: howe.steven at gmail.com (Steven Howe) Date: Thu, 17 May 2007 08:08:41 -0700 Subject: how do I count spaces at the beginning of a string? In-Reply-To: <1179405818.432742.146600@k79g2000hse.googlegroups.com> References: <1179367338.906430.97420@k79g2000hse.googlegroups.com> <1179405818.432742.146600@k79g2000hse.googlegroups.com> Message-ID: <464C6FF9.4010601@gmail.com> Paul McGuire wrote: On May 16, 9:02 pm, walterbyrd wrote: > The strings start with whitespace, and have a '*' or an alphanumeric > character. I need to know how many whitespace characters exist at the > beginning of the string. > using buitlin function len() and lstrip() ax = ' asdfjlwese asdfasl ' len( ax ) - len( ax.lstrip() ) sph -- HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Sun May 13 12:13:02 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 13 May 2007 18:13:02 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <20070513160046.GC29172@v.igoro.us> References: <46473267$0$31532$9b622d9e@news.freenet.de> <20070513160046.GC29172@v.igoro.us> Message-ID: <4647390E.4040801@v.loewis.de> > The only objection that comes to mind is that adding such support may > make some distinct identifiers visually indistinguishable. IIRC the DNS > system has had this problem, leading to much phishing abuse. This is a commonly-raised objection, but I don't understand why people see it as a problem. The phishing issue surely won't apply, as you normally don't "click" on identifiers, but rather type them. In a phishing case, it is normally difficult to type the fake character (because the phishing relies on you mistaking the character for another one, so you would type the wrong identifier). People have mentioned that this could be used to obscure your code - but there are so many ways to write obscure code that I don't see a problem in adding yet another way. People also mentioned that they might mistake identifiers in a regular, non-phishing, non-joking scenario, because they can't tell whether the second letter of MAXLINESIZE is a Latin A or Greek Alpha. I find that hard to believe - if the rest of the identifier is Latin, the A surely also is Latin, and if the rest is Greek, it's likely an Alpha. The issue is only with single-letter identifiers, and those are most common as local variables. Then, it's an Alpha if there is also a Beta and a Gamma as a local variable - if you have B and C also, it's likely A. > I don't necessarily think that the objection is strong enough to reject > the idea -- programmers using non-ASCII symbols would be responsible for > the consequences of their character choice. Indeed. Martin From joel.hedlund at gmail.com Tue May 22 02:50:24 2007 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Tue, 22 May 2007 08:50:24 +0200 Subject: Slightly OT: Why all the spam? Message-ID: Does anyone know why we get so much spam to this group? It's starting to get embarrasing to read at work and that's just not how it should be. Cheers! /Joel From theller at ctypes.org Tue May 15 15:29:07 2007 From: theller at ctypes.org (Thomas Heller) Date: Tue, 15 May 2007 21:29:07 +0200 Subject: ctypes-1.0.2 for 64-bit Windows Message-ID: <464A0A03.9030406@ctypes.org> For the brave enough to run a 64-bit Python under a 64-bit Windows installation, I have added a first version of ctypes for win64 in the sourceforge download area. It does NOT use the same sourcecode as the 'official' version, the code has been patched by merging selected commits from the Python SVN trunk. This release is not too much tested; in fact even one unittest still fails. The failure only occurs when compiled for Python 2.5 with the MS SDK compiler, not with Visual Studio 2008. If you try to use ctypes-win64, be sure to use the proper argtypes and restypes attributes for dll-functions; integers (which ctypes assumes by default) and pointers have different sizes on 64-bit Windows. Apart from that, enjoy. Thomas From jeff_barish at earthlink.net Tue May 15 15:23:29 2007 From: jeff_barish at earthlink.net (Jeffrey Barish) Date: Tue, 15 May 2007 13:23:29 -0600 Subject: Moving class used in pickle Message-ID: I have a class derived from string that is used in a pickle. In the new version of my program, I moved the module containing the definition of the class. Now the unpickle fails because it doesn't find the module. I was thinking that I could make the unpickle work by putting a copy of the module in the original location and then redefine the class by sticking a __setstate__ in the class thusly: def __setstate__(self, state): self.__dict__.update(state) self.__class__ = NewClassName My plan was to specify the new location of the module in NewClassName. However, when I do this I get the message "'class' object layout differs from 'class'". I don't think that they do as the new module is a copy of the old one. I suspect that I am not allowed to make the class assignment because my class is derived from string. What is the best way to update the pickle? The only thought I have is to read all the data with the old class module, store the data in some nonpickle format, and then, with another program, read the nonpickle-format file and rewrite the pickle with the class module in the new location. -- Jeffrey Barish From showell30 at yahoo.com Sun May 27 10:06:11 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 27 May 2007 07:06:11 -0700 (PDT) Subject: Is PEP-8 a Code or More of a Guideline? In-Reply-To: <1180272049.3157.2.camel@localhost.localdomain> Message-ID: <316098.9123.qm@web33510.mail.mud.yahoo.com> --- Carsten Haese wrote: > On Sun, 2007-05-27 at 07:30 +0000, OKB (not > okblacke) wrote: > > Underscores are harder to type than any > alphanumeric character. > > This is a discussion about underscores versus > capital letters denoting > the word boundaries in identifiers. How is an > underscore harder to type > than a capital letter? > longer reach with the pinkie on American keyboards Slowly type the following two keywords, you'll see what I mean: hop_count hopCount Also note the number of characters. ____________________________________________________________________________________Take the Internet to Go: Yahoo!Go puts the Internet in your pocket: mail, news, photos & more. http://mobile.yahoo.com/go?refer=1GNXIC From tenax.raccoon at gmail.com Fri May 11 15:18:42 2007 From: tenax.raccoon at gmail.com (Jason) Date: 11 May 2007 12:18:42 -0700 Subject: File writing success In-Reply-To: <1178907719.896993.299910@h2g2000hsg.googlegroups.com> References: <1178907719.896993.299910@h2g2000hsg.googlegroups.com> Message-ID: <1178911122.904699.281200@o5g2000hsb.googlegroups.com> On May 11, 12:21 pm, HMS Surprise wrote: > If file writing has no return value (http://docs.python.org/lib/bltin- > file-objects.html), how do you know if the write was successful? > Should one assume that if the open was successful then write are also? > > Thanks, > > jvh In Python, errors are not usually indicated by a return code. Instead, an exception should be raised for error conditions. The Python file semantics follows this. If the function returns instead of raising an exception, you may assume that the write completed successfully. Please note that the file objects may use buffers, so a call to the flush method may be needed to ensure that everything is on disk. K:\temp>dir Volume in drive K is LEXAR MEDIA Volume Serial Number is 0000-0000 Directory of K:\temp 05/11/2007 01:14 PM . 05/11/2007 01:14 PM .. 0 File(s) 0 bytes 2 Dir(s) 75,071,488 bytes free K:\temp>python Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> out = file("test.txt", "wb") >>> out.write( "Hi!" * 80000000 ) Traceback (most recent call last): File "", line 1, in IOError: [Errno 28] No space left on device >>> From john at datavoiceint.com Fri May 11 11:35:02 2007 From: john at datavoiceint.com (HMS Surprise) Date: 11 May 2007 08:35:02 -0700 Subject: Better way to isolate string In-Reply-To: <1178896888.721679.207240@n59g2000hsh.googlegroups.com> References: <1178896888.721679.207240@n59g2000hsh.googlegroups.com> Message-ID: <1178897702.872729.72050@y5g2000hsa.googlegroups.com> I suppose a one liner would look better, but I am alway leery of these things 'breaking'. t = s.split('">')[-1].split('<')[0] s ='G132153' jh From paul at boddie.org.uk Tue May 8 12:29:38 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 8 May 2007 09:29:38 -0700 Subject: Towards faster Python implementations - theory In-Reply-To: <1210i.7468$2v1.2505@newssvr14.news.prodigy.net> References: <1210i.7468$2v1.2505@newssvr14.news.prodigy.net> Message-ID: <1178641778.266569.13290@p77g2000hsh.googlegroups.com> On 8th May, 17:53, John Nagle wrote: > Some faster Python implementations are under development. > JPython Ahem: Jython! > has been around for a while, and PyPy and ShedSkin > continue to move forward. It's worth thinking about what slows > down Python implementations. It's the dynamicity! ;-) But things like clever memory allocation can pay dividends, too, and I wouldn't be surprised if this explained Python's better-than-expected showing when compared to other languages - such as that comparison you provoked with those claims of superior JavaScript performance. ;-) > It isn't the dynamism, really. In theory, no, but in practice CPython doesn't optimise away the dynamism. Recent experiments with method caches seem to have shown modest performance improvements, and I'd guess that such things are fairly established in other dynamic language implementations. > As others have pointed out > in the Python literature, most of the time, the more elaborate > dynamic features aren't being used for any given variable or > object. If code has something like "x = 1.0", the odds are that > "x" is going to stay a floating point number, and not suddenly turn > into a list or an object reference. The type inference of Shed Skin > builds on that assumption, adding some restrictions about changing of > variable types. The problem here, amongst many others, is knowing for sure whether the more elaborate features have been avoided. Approaches which attempt to avoid knowing such things include just-in-time compilation (you avoid knowing in advance) and type declarations (you give up thinking about whether it's possible and have the programmer do all the work). > The Shed Skin effort indicates that explicit typing, via 'decorators' > or otherwise, isn't really necessary. What's necessary is the avoidance > of "surprises" in the language. In this context, a "surprise" is > the use of a dynamic feature in a way that can't be seen at compile time. I concur with your assessment of the supposed necessity of explicit typing. However, you might be surprised as to what constitutes a "surprise" in Python... > A typical "surprise" would be the use of "setattr" on an object from > outside the compilation unit that defines the object. Within a module, > "setattr" on an object in that module is no problem; the compiler can see > it and generate the extra machinery needed to make an object dynamically > alterable at run time. But if an object doesn't need that extra machinery > and associated dictionary, it's a big win to discard the excess baggage > and use a simpler fixed-size representation, comparable to a C struct, > for the object. You don't even need to bring out setattr to make the inference activity a difficult one. Even straightforward attribute access needs to be repeatedly checked to see if the target of a normal attribute assignment or query has changed. Traditionally, people have shown some trivial function in isolation... def f(x): return x.a ...and said, "We don't know anything! It's all impossible!" But context is everything, as you know, and whole program analysis is the only way to go with the aforementioned goals in mind. What if the parameter to the above itself comes from attribute access? def g(y): return f(y.b) You can descend into some fairly demanding situations with respect to keeping track of all the possibilities. > On the typing front, the neatest way to express typing is via > initialization. With the Shed Skin restrictions, if all variables are > initialized before use (preferably in __init__), there's no need to > maintain an "undefined" flag for a variable. And, of course, if > the type of a varaible is simple and can't change, it doesn't have to > be "boxed", (enclosed in an object) which is a big win. I'm fairly sure, although my intuition unfortunately doesn't provide a ready example right now, that typing via initialisation, whilst an important tool, may either impose unacceptable restrictions if enforced too rigidly or limit the precision that one might desire in determining type information in the resulting system. But it is a worthwhile objective to identify fixed-size structures and unboxed values, in my opinion. > The point here is that we don't need language changes or declarations > to make Python much faster. All we need are a few restrictions that > insure that, when you're doing something unusual, the compiler can > tell. Agreed. And I don't buy into the negative "lesser Python" labelling of such work, either. People seem to have forgotten how to use older, conservative Python features, preferring to show off with metaclasses and closures even for problems that could be solved using simple classes and objects. If that's "greater Python" then call me a minimalist! Paul From rene at korteklippe.de Wed May 16 05:39:00 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Wed, 16 May 2007 11:39:00 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476081.7080609@web.de> <46476F6B.2000501@web.de> <4649844b$0$6402$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <464ad132$0$10187$9b4e6d93@newsspool4.arcor-online.net> Steven D'Aprano schrieb: >> Unless you are 150% sure that there will *never* be the need for a >> person who does not know your language of choice to be able to read or >> modify your code, the language that "fits the environment best" is >> English. > > Just a touch of hyperbole perhaps? > > You know, it may come to a surprise to some people that English is not > the only common language. In fact, it only ranks third, behind Mandarin > and Spanish, and just above Arabic. Although the exact number of speakers > vary according to the source you consult, the rankings are quite stable: > Mandarin, Spanish, then English. Any of those languages could equally > have claim to be the world's lingua franca. For a language to be a (or the) lingua franca, the sheer number of people who speak it is actually not as important as you seem to think. Its use as an international exchange language is the decisive criterion -- definitely not true for Mandarin, and for Spanish not nearly as much as for English. Also, there can be different "linguae francae" for different fields. English definitely is the lingua franca of programming. But that is actually off topic. Programming languages are not the same as natural languages. I was talking about program code, not about works of literature. -- Ren? From http Mon May 21 01:50:36 2007 From: http (Paul Rubin) Date: 20 May 2007 22:50:36 -0700 Subject: What is deployment? References: <68m4i4-9a4.ln1@lairds.us> <7x4pm8tf6v.fsf@ruckus.brouhaha.com> <87646o3yrb.fsf@benfinney.id.au> <7x8xbkjc6c.fsf@ruckus.brouhaha.com> <1179726190.740400.272740@u36g2000prd.googlegroups.com> Message-ID: <7xlkfik9n7.fsf@ruckus.brouhaha.com> Maria R writes: > I would suggest a somewhat more limited view. > That is, deployment is the process after development is finished (or > the product system is purchased) up until it is in full operation > (including establishing support organisation etc). > The exact point of time is, of course, not very clear cut. > Upgrading the product, adding more users, extending the use etc. is > not, as I see it, *deployment*. Hmm, ok. Putting the mechanisms into place to make all that stuff happen is part of deployment. Actually having them happen is operations. From larry.bates at websafe.com Fri May 4 16:09:05 2007 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 04 May 2007 15:09:05 -0500 Subject: How to check if a string is empty in python? In-Reply-To: <1hxia6q.18rflwk1mez8vhN%aleax@mac.com> References: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> <1178154290.811928.208900@h2g2000hsg.googlegroups.com> <1hxia6q.18rflwk1mez8vhN%aleax@mac.com> Message-ID: Alex Martelli wrote: > Steven D'Aprano wrote: > >> On Wed, 02 May 2007 21:19:54 -0400, Roy Smith wrote: >> >>> for c in s: >>> raise "it's not empty" >> String exceptions are depreciated and shouldn't be used. >> >> http://docs.python.org/api/node16.html > > They're actually deprecated, not depreciated. > > Searching define:deprecated -- first hit: > > In computer software standards and documentation, deprecation is the > gradual phasing-out of a software or programming language feature. > en.wikipedia.org/wiki/Deprecated > > and the other four hits are fine too. > > Searching define:depreciated , we move almost entirely into accounting > and finance, except: > > http://en.wikipedia.org/wiki/Depreciated > """ > Depreciated is often confused or used as a stand-in for "deprecated"; > see deprecation for the use of depreciation in computer software > """ > > > Alex Isn't deprecated like depreciated but not quite to zero yet? -Larry From mikeminer53 at hotmail.com Wed May 23 12:45:12 2007 From: mikeminer53 at hotmail.com (mkPyVS) Date: 23 May 2007 09:45:12 -0700 Subject: Resizing listbook's listview pane In-Reply-To: <1179932659.180278.72990@w5g2000hsg.googlegroups.com> Message-ID: <1179938712.477533.46920@m36g2000hse.googlegroups.com> On May 23, 9:04 am, kyoso... at gmail.com wrote: > Which Python gui toolkit are you using? Tkinter, wxPython, pyQT? Are > you wanting the resize to happen programmatically, when the user > changes the app's size, both or what? > > More details would be helpful. > > Mike Sorry, copied from wxpython submit as well.. I'm using wxpython 2.8... Primariy I want the resize to happen programatically during object creation/post creation... I can worry about app size changes later. Thanks, From steven.bethard at gmail.com Sun May 27 13:08:43 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 27 May 2007 11:08:43 -0600 Subject: ten small Python programs In-Reply-To: References: Message-ID: Steve Howell wrote: > --- Steven Bethard wrote: >> Very cool! Do you mind putting this up on the Wiki >> somewhere so that we >> can link to it more easily? Maybe something like: >> >> http://wiki.python.org/moin/SimplePrograms >> > > Done. I think I would rewrite the current unit-testing example to use the standard library unittest module:: # Let's write reusable code, and unit test it. def add_money(amounts): # do arithmetic in pennies so as not to accumulate float errors pennies = sum([round(int(amount * 100)) for amount in amounts]) return float(pennies / 100.0) import unittest class TestAddMoney(unittest.TestCase): def test_float_errors(self): self.failUnlessEqual(add_money([0.13, 0.02]), 0.15) self.failUnlessEqual(add_money([100.01, 99.99]), 200) self.failUnlessEqual(add_money([0, -13.00, 13.00]), 0) if __name__ == '__main__': unittest.main() I believe I've still kept it to 13 lines. STeVe P.S. The "right" way to add money is using the decimal module, but I couldn't think of a better example. From nogradi at gmail.com Wed May 2 06:48:13 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Wed, 2 May 2007 12:48:13 +0200 Subject: What do people use for code analysis. In-Reply-To: References: Message-ID: <5f56302b0705020348w1898b1faxa4aa59223f8b6ef1@mail.gmail.com> > Lots of code, calls to, calls by, inheritance, multiple tasks, etc. > > What do people use to figure out what's happening? This is a pretty cool project just for that: http://codeinvestigator.googlepages.com/codeinvestigator HTH, Daniel From sturlamolden at yahoo.no Wed May 2 20:19:34 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 2 May 2007 17:19:34 -0700 Subject: Microsoft's Dynamic Languages Runtime (DLR) In-Reply-To: <1178151313.421106.43130@o5g2000hsb.googlegroups.com> References: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> <1178151313.421106.43130@o5g2000hsb.googlegroups.com> Message-ID: <1178151574.302703.205560@l77g2000hsb.googlegroups.com> On May 3, 2:15 am, Kaz Kylheku wrote: > Kindly refrain from creating any more off-topic, cross-posted threads. > Thanks. The only off-topic posting in this thread is your own (and now this one). Begone. S.M. From QncyMI at netscape.net Thu May 3 01:32:13 2007 From: QncyMI at netscape.net (Major Quaternion Dirt Quantum) Date: 2 May 2007 22:32:13 -0700 Subject: Video: Professor of Physics Phd at Cal Tech says: 911 Inside Job In-Reply-To: <1178161673.787120.277250@n59g2000hsh.googlegroups.com> References: <1177467203.719625.93920@u32g2000prd.googlegroups.com> <1177780530.539758.275660@c35g2000hsg.googlegroups.com> <1177792809.503415.182480@o5g2000hsb.googlegroups.com> <1177793419.474675.156860@y80g2000hsf.googlegroups.com> <1178161673.787120.277250@n59g2000hsh.googlegroups.com> Message-ID: <1178170333.908225.301470@o5g2000hsb.googlegroups.com> can you puhlease reply to my questions? nothing is ever 100%, if only because of Heisenberg -- that dirty little physicist! > I suppose you never seen this footage of WTC7 before have you? Its > 100% evidence that WTC7 was controlled demolition:http://www.youtube.com/watch?v=YNN6apj5B2U- thus: maybe, "pulled" is just a firefighteresque synonym for gravity doing its thing -- still not subsumed in the Standard Model of physicists, so, There. y'know, sort of like, how it is, pilots refer to going "out" and "in," instead of up & down. Zogby clientlist, cool; what great organizations I will assume them to be -- if any one else wants to look at it & report back.... lies, polls, statistics; how they, for instance, leveraged the Governeurateur, during the Recall, by the art of dysmissing "less likely voters" that they had interviewed, because they were a) Democrats, and b) were removed by some other signal processing techniques; what it is?... thank gawd for Zogby et al ad vomitorium; with over 40% electronic voting, how *else* will you know? I know, you were not suggesting that (--with the rather obvious burning on the other side, that was away from most of your videos, and after teh catastrophic collapse and/or demolition of both, huge towers into the gigantic subway--) the commanding officers should have kept them inside the evacuated building, til it fell. thus: if you can't prove that all Fermat numbers are pairwise coprime, again! Darfur 'Mini-Summit' http://www.larouchepub.com/other/1998/rice_2546.html thus: uh yeah; Borat wants you in Sudan, why, Baby?... Harry Potter wants you in Iran -- yeah, Baby; shag'US with a spoon? --DARFURIA CONSISTS OF ARABs & nonARABs; NEWS-ITEM: we are marching to Darfuria, Darfuria, Darfuria! Harry Potter IIX, ?Ordeal @ Oxford//Sudan ^ Aircraft Carrier! http://larouchepub.com/other/2007/3410caymans_hedges.html ALgoreTHEmovieFORpresident.COM: http://larouchepub.com/eirtoc/site_packages/2007/al_gore.html From wildemar at freakmail.de Wed May 23 08:47:29 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Wed, 23 May 2007 14:47:29 +0200 Subject: Module listing in order. In-Reply-To: <1179905562.541601.264400@m36g2000hse.googlegroups.com> References: <1179905562.541601.264400@m36g2000hse.googlegroups.com> Message-ID: <465437E1.2000505@freakmail.de> Ramashish Baranwal wrote: > I want a way to get the contents in the order of their declaration, > i.e. [B, A, D]. Does anyone know a way to get it? > My suggestion would be to actually parse the text of the module. "Brute force" is what it's called ;). But doing so with, say, pyparsing shouldn't be *very* difficult. Just out of curiosity: Why do you need the order? W From __peter__ at web.de Sat May 5 02:12:49 2007 From: __peter__ at web.de (Peter Otten) Date: Sat, 05 May 2007 08:12:49 +0200 Subject: Do I have to quit python to load a module? References: Message-ID: wang frank wrote: > When I edit a module, I have to quit python and then restart python and > then import the module. Are there any way to avoid quit python to load an > updated module? When I am debugging a module code, I need to constantly > make changes. It is not convenient to quit and reload. There is the reload() function, but it has pitfalls. Objects referenced from without the module are not updated: >>> open("tmp.py", "w").write(""" ... def f(): print "version one" ... """) >>> import tmp >>> tmp.f() version one >>> g = tmp.f >>> open("tmp.py", "w").write(""" ... def f(): print "version two" ... """) >>> reload(tmp) >>> tmp.f() version two >>> g() version one Peter From bbxx789_05ss at yahoo.com Wed May 9 11:13:15 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 9 May 2007 08:13:15 -0700 Subject: which is more pythonic/faster append or +=[] In-Reply-To: <1hxtelz.7f6rvnw4cyxmN%aleax@mac.com> References: <1hxtelz.7f6rvnw4cyxmN%aleax@mac.com> Message-ID: <1178723595.516379.18180@u30g2000hsc.googlegroups.com> On May 8, 11:05 pm, a... at mac.com (Alex Martelli) wrote: > alf wrote: > > two ways of achieving the same effect > > > l+=[n] > > > or > > > l.append(n) > > > so which is more pythonic/faster? > > .append - easy to measure, too: > > brain:~ alex$ python -mtimeit 'L=range(3); n=23' 'x=L[:]; x.append(n)' > 1000000 loops, best of 3: 1.31 usec per loop > > brain:~ alex$ python -mtimeit 'L=range(3); n=23' 'x=L[:]; x+=[n]' > 1000000 loops, best of 3: 1.52 usec per loop > > Alex Why is it necessary to copy L? From michele.simionato at gmail.com Tue May 8 00:17:16 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 7 May 2007 21:17:16 -0700 Subject: how do you implement a reactor without a select? In-Reply-To: <1178559374.393874.113460@l77g2000hsb.googlegroups.com> References: <1178543812.260333.39280@w5g2000hsg.googlegroups.com> <1178559374.393874.113460@l77g2000hsb.googlegroups.com> Message-ID: <1178597836.223030.233510@u30g2000hsc.googlegroups.com> On May 7, 7:36 pm, "sjdevn... at yahoo.com" wrote: > > Busy-looping like that is ugly and inefficient, even with the sleep > thrown in. > > Most GUI main loops _do_ use either select() or poll(). When Xt/GTK/ > Qt/etc have function like "gtk_add_input" which takes an fd that > you'll get notified about if it's written to while you're in the main > loop, that's just adding another fd to the select() loop. > > There are other ways to wait for events on an fd, but they tend to be > less portable. Depending on your Unix flavor, epoll, /dev/poll, > kqueues, kevent, queued realtime signals, or something else might be > available from the OS (but probably not from Python without futzing > with ctypes or writing an extension). If you want details, check outhttp://www.kegel.com/c10k.html > > The alternatives usually aren't really faster unless you have hundreds > of connections, though--select/poll have major portability advantages, > so go with them unless you have a compelling reason. I see where you are coming from. In a GUI or in a Web server most of the time is spent waiting from input, so a busy loop design would be a terrible design indeed. But I had another use case in mind. The code I posted is extracted from a batch script I have, called 'dbexplorer'. The script performs lots of queries in a database and find out "bad" data according to some criterium. So at each iteration there is a default action which is nontrivial; it becomes a time.sleep only at the end, when the batch has finished its job and it is waiting for input.In normal conditions most of the time is spent doing something, not waiting, so the busy loop design here is not so bad. Still I wanted to know what my alternatives were. And from this thread I gather the impression that actually the only portable alternative is using some kind of select, unless I want to use threads, and in that case the scheduler approach could be viable. Anyway, that C10K page is really an interesting resource, thanks for pointing it out! Michele Simionato From howe.steven at gmail.com Tue May 15 03:07:34 2007 From: howe.steven at gmail.com (Steven Howe) Date: Tue, 15 May 2007 00:07:34 -0700 Subject: Trying to choose between python and java In-Reply-To: References: Message-ID: <46495C36.8010406@gmail.com> Anthony Irwin wrote: > Hi All, > > I am currently trying to decide between using python or java and have > a few quick questions about python that you may be able to help with. > > #1 Does python have something like javas .jar packages. A jar file > contains all the program files and you can execute the program with > java -jar program.jar > > I am sort of hoping python has something like this because I feel it > makes it easier to distribute between platforms e.g. linux, mac > windows etc. > > #2 What database do people recommend for using with python that is > easy to distribute across linux, mac, windows. > > #3 Is there any equivalent to jfreechart and jfreereport > (http://www.jfree.org for details) in python. > > #4 If I write a program a test it with python-wxgtk2.6 under linux are > the program windows likely to look right under windows and mac? > > #5 someone said that they used to use python but stopped because the > language changed or made stuff depreciated (I can fully remember > which) and old code stopped working. Is code written today likely to > still work in 5+ years or do they depreciate stuff and you have to update? > > Anyway hopefully someone can help me out with these last few questions > I have. > > Also does anyone else have any useful comments about python vs java > without starting a flame war. > > > Flame war? Here amongst all the reasonable adults programmers? It never happens. 1) I always thought jar files were weird. Change the run mode on you python script and just run it, over and over. chmod u+x program.py ./program.py No doubt you are (shudder) a Windows user (and beat yourself in the closet at night as well). No doubt Windows has a feature to set the privilege on a file to make it executable. With any luck, I'll never know. 2) Python interfaces with with damn near every database I've ever seen, regardless if the database is on the same system or remote. At worst case, it seems to have ODBC connection (yes I know, C and connect are the same thing, like an American saying Mount Fujiyama, which is of course, Mount Fuji Mount) feature. Not as precise as a targeted connector, but it works. There are even multiple ways to 'see' the database. As strings, lists, objects, rows, tables and dictionaries. It's all quite a powerful tool. Image, getting to choose how you 'see' the database. Who'd have thunk! 3) No idea about jfree. Perhaps a few keyword searchs on Google or Sourceforge would give you an answer. 6) Never programmed wx. But it seems to be very stable on the programs I've downloaded. Anyway mapping one GUI to another is always an imprecise effort (especially when you have 235 patents on the product that you dare not tell anyone about). No two mindset ever really meet, especially when money is involved. 5) All languages grow. Get over it. But, if you keep the older interpreter around, you can still run your old scripts. At NCR I had to support 6 different version of Perl because the programmers wouldn't fix/update their code. Seem they had better things to do and you can always expect the Sysadmin to save your bacon. But if you haven't got to that point (six version to support) yet, during pre-upgrade tests, you might run the program and note the features that are going to be decrepit. Generally you have a few minor version releases (year or more) before the decrepit feature is dropped. Then you can decide if upgrading/fix or running multiple version of python is the right path for you. Using the PYTHONPATH environment variable is a good way to redirect your older scripts to use decrepit feature via an older interpreter. The (6) you didn't ask. As a Sysadmin, I hate Java. It's a resource hog. Little tasks take hundreds of megabytes of RAM. What can one expect. It's a virtual machine inside your computer. Hog it must be! Python is a bit slimmer on the memory footprint and I think a hell of a lot easier to debug. Even strace can be used on python programs. Never got strace to work on Java scripts. The (7) you didn't ask. Last month there was a full flame war about java/python on the python-list. It petered out after about 15 days. You might review the archives to get a sense for yourself (so we don't have repeat the war, just for you). sph -- HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 From bbxx789_05ss at yahoo.com Fri May 25 18:05:03 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 25 May 2007 15:05:03 -0700 Subject: problem with eval while using PythonCard In-Reply-To: <1180130097.439585.308510@g4g2000hsf.googlegroups.com> References: <1180130097.439585.308510@g4g2000hsf.googlegroups.com> Message-ID: <1180130703.577624.167360@u30g2000hsc.googlegroups.com> Here's a complete example: ################### #create object 's': class S(object):pass class X(object):pass class Y(object):pass s = S() s.components = X() s.components.d1 = Y() s.components.d2 = Y() s.components.d3 = Y() ###################### ###################### set some initial values: for i in range(1, 4): obj = getattr(s.components, "d" + str(i)) obj.text = "hello world" ##################### ##################### #change the values: for i in range(1, 4): getattr(s.components, "d" + str(i)).text = "goodybe" ##################### ##################### #print out the new values: for i in range(1, 4): print getattr(s.components, "d" + str(i)).text ##################### From mccredie at gmail.com Tue May 15 14:24:19 2007 From: mccredie at gmail.com (Matimus) Date: 15 May 2007 11:24:19 -0700 Subject: Trying to choose between python and java In-Reply-To: References: Message-ID: <1179253459.772362.245710@n59g2000hsh.googlegroups.com> > #3 Is there any equivalent to jfreechart and jfreereport > (http://www.jfree.orgfor details) in python. I haven't used either extensively but you might check out ReportLab for report generation (http://www.reportlab.org). And MatPlotLib for creating plots, charts and graphs (http://matplotlib.sourceforge.net). There may be alternatives available. Matt From duncan.booth at invalid.invalid Thu May 10 13:28:58 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 May 2007 17:28:58 GMT Subject: append References: <1178816546.689849.255070@y5g2000hsa.googlegroups.com> Message-ID: HMS Surprise wrote: > Trying not to be a whiner but I sure have trouble finding syntax in > the reference material. I want to know about list operations such as > append. Is there a pop type function? I looked in tutorial, language > reference, and lib for list, append, sequence. Is there a place where > us doofi ( who may not have our heads out in the sunlight) may find > all related syntax grouped together? > Do you really mean syntax? Anyway, try google: python list methods The second result is: http://docs.python.org/lib/typesseq-mutable.html From rtw at freenet.co.uk Thu May 17 15:50:22 2007 From: rtw at freenet.co.uk (Rob Williscroft) Date: Thu, 17 May 2007 14:50:22 -0500 Subject: Is wsgi ready for prime time? References: Message-ID: Ron Garret wrote in news:rNOSPAMon-B77D6B.12263417052007 @news.gha.chartermi.net in comp.lang.python: >> PACKAGE CONTENTS >> handlers >> headers >> simple_server >> util >> validate >> >> Reading the documentation can be useful sometimes. Recommending >> http://docs.python.org/lib/module-wsgiref.html, too. > > I did read the documentation, but the documentation does not seem to > reflect reality, e.g.: > >>>> wsgiref.util > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'module' object has no attribute 'util' > IDLE 1.2 >>> import wsgiref.util >>> wsgiref.util >>> Rob. -- http://www.victim-prime.dsl.pipex.com/ From half.italian at gmail.com Sun May 27 17:03:34 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 27 May 2007 14:03:34 -0700 Subject: Can python create a dictionary from a list comprehension? In-Reply-To: <1180299312.207986.4340@k79g2000hse.googlegroups.com> References: <1180299312.207986.4340@k79g2000hse.googlegroups.com> Message-ID: <1180299814.129770.93220@o11g2000prd.googlegroups.com> On May 27, 1:55 pm, erikcw wrote: > Hi, > > I'm trying to turn o list of objects into a dictionary using a list > comprehension. > > Something like > > entries = {} > [entries[int(d.date.strftime('%m'))] = d.id] for d in links] > > I keep getting errors when I try to do it. Is it possible? Do > dictionary objects have a method equivalent to [].append? Maybe a > lambda? > > Thanks for your help! > Erik try... [entries.__setitem__(int(d.date.strftime('%m'))], d.id) for d in links] btw...I was curious of this too. I used 'dir(dict)' and looked for a method that might do what we wanted and bingo! ~Sean From claird at lairds.us Sat May 19 21:07:32 2007 From: claird at lairds.us (Cameron Laird) Date: Sun, 20 May 2007 01:07:32 +0000 Subject: How to convert a number to binary? References: <1179444832.775573.55830@y80g2000hsf.googlegroups.com> <1179445546.307017.275850@p77g2000hsh.googlegroups.com> <87lkfm64ry.fsf@benfinney.id.au> <1179474720.810650.10510@l77g2000hsb.googlegroups.com> Message-ID: In article <1179474720.810650.10510 at l77g2000hsb.googlegroups.com>, Lyosha wrote: . . . >While I agree with this general statement, I think remembering a >particular one-liner to convert a number to a binary is more valuable >to my brain than remembering where I placed the module that contains >this function. > >I needed the one-liner not to save disk space or screen lines. It's >to save time, should I need to convert to binary when doing silly >little experiments. I would spend more time getting the module >wherever it is I stored it (and rewriting it if it got lost). > >It's fun, too. I know the feeling. In fact, there's a point here that's deep enough to deserve a follow-up. Various people, including, I think, the timbot, have said that the distinction of a good high-level language is code NON-re-use; that is, in the positive aspect, a language like Python is so expressive and productive that it makes it generally easier to re-use *ideas* than code. From Roka100 at gmail.com Mon May 28 09:45:47 2007 From: Roka100 at gmail.com (Jia Lu) Date: 28 May 2007 06:45:47 -0700 Subject: Can string be callable as a method ? Message-ID: <1180359947.660314.26320@n15g2000prd.googlegroups.com> Hi all I tried to scan a directory and __import__ all modules , imported module: help imported module: __init__ imported module: hi imported module: thanks and I scaned all methods in them, and put them to a list like: [['f_chelp', 'f_help'], [], ['f_exclaim', 'f_hi', 'random'], ['f_thanks', 'random']] But how can I call them from that list?? Thank you. Jia Lu From Green.Horn.000 at gmail.com Thu May 17 10:17:09 2007 From: Green.Horn.000 at gmail.com (GreenH) Date: 17 May 2007 07:17:09 -0700 Subject: An expression that rebinds a variable? Message-ID: <1179411429.536764.5620@q75g2000hsh.googlegroups.com> Can I know what kind of expressions rebind variables, of course unlike in C, assignments are not expressions (for a good reason) So, eval(expr) should bring about a change in either my global or local namespace, where 'expr' is the expression From arnoreg at gmail.com Wed May 30 09:27:37 2007 From: arnoreg at gmail.com (Arno Stienen) Date: Wed, 30 May 2007 15:27:37 +0200 Subject: xmlrpclib hangs execution In-Reply-To: <465A9DC7.2010708@gmail.com> References: <45AC0631.8080601@ctw.utwente.nl> <465890FB.4030405@utwente.nl> <465A9DC7.2010708@gmail.com> Message-ID: <465D7BC9.3040900@gmail.com> I'm sorry to keep bumping my request, but I've been working on this problem for several months now and am stuck. Perhaps you do not have a direct answer, but know someone or someforum where I could ask these XML-RPC or TCP/IP package questions. Thanks, Arno. Arno Stienen wrote: > Perhaps I should be a bit more specific. When using this code to connect > to a remote XML-RPC server (C++, xmlrpc++0.7 library): > > import xmlrpclib > server = xmlrpclib.Server("http://10.10.101.62:29500") > print server.Connection_Request("roberto") > > the Python command line 'hangs' until I kill the server. Then, the > correct output is suddenly displayed: > > {'state': 0, 'id_session': '2Z3EUSLJFA13', 'port': 29501, > 'str': 'Connection accepted. Session attached.'} > > Yet a slightly simpler call works flawlessly: > > import xmlrpclib > server = xmlrpclib.Server("http://10.10.101.62:29500") > print server.Info_RT('Master') > > {'state': 0, 'str': 'Info_RT'} > > Looking at the TCP packages (using Wireshark), the first > Connection_Request flow as follows (c=python client,s= xml-rpcserver): > > 1 c>s SYN > 2 s>c SYN,ACK > 3 c>s ACK > 4 c>s PSH,ACK (setting content-type: text/xml) > 5 s>c ACK > 6 c>s PSH,ACK (xml-rpc request) > 7 s>c ACK > 8 s>c PSH,ACK (xml-rpc results, correct) > 9 c>s ACK > > At this point, Python 'hangs' until I kill (-9) the server (28 seconds > later), and then these last packages are send: > > 10 s>c FIN,ACK > 11 c>s FIN,ACk > 12 s>c ACK > > After which Python continues and prints the xml-rpc results on the > screen. Strangely, before Python hangs, it has already received the > package with the results, but doesn't do anything with it. > > For comparison, this is the package flow for the Info_RT method, which > returns within a second with the correct result on the Python command line: > > 1 c>s SYN > 2 s>c SYN,ACK > 3 c>s ACK > 4 c>s PSH,ACK (setting content-type: text/xml) > 5 s>c ACK > 6 c>s PSH,ACK (xml-rpc request) > 7 s>c ACK > 8 s>c PSH,ACK (xml-rpc results, correct) > 9 s>c FIN,ACK > 10 c>s ACK > 11 c>s FIN,ACk > 12 s>c ACK > > Notice the reverse order of packages 9 and 10. Could this be it? Is > Python waiting until the server sends a FIN package? But if so, why? > > Looking at the Python trace, this might be it. A diff between the trace > of the killed Connection_Request and the Info_RT resulted only in > expected differences (due to different length of parameters). But when > diffing the traces of the killed and non-killed Connection_Request, > something else is visible. The killed Connection_Request ends with: > > [...] > string:318: return sep.join(words) > xmlrpclib:866: self._type = "params" > xmlrpclib:769: try: > xmlrpclib:770: f = self.dispatch[tag] > xmlrpclib:771: except KeyError: > xmlrpclib:772: pass # unknown tag ? > xmlrpclib:1273: if sock: > xmlrpclib:1274: response = sock.recv(1024) > xmlrpclib:1277: if not response: > xmlrpclib:1278: break > xmlrpclib:1283: file.close() > socket:218: try: > socket:219: if self._sock: > socket:220: self.flush() > socket:232: if self._wbuf: > socket:222: self._sock = None > xmlrpclib:1284: p.close() > xmlrpclib:530: self._parser.Parse("", 1) # end of data > xmlrpclib:531: del self._target, self._parser # get rid of > circular references > xmlrpclib:1286: return u.close() > xmlrpclib:741: if self._type is None or self._marks: > xmlrpclib:743: if self._type == "fault": > xmlrpclib:745: return tuple(self._stack) > socket:225: try: > socket:226: self.close() > socket:218: try: > socket:219: if self._sock: > socket:222: self._sock = None > xmlrpclib:1386: if len(response) == 1: > xmlrpclib:1387: response = response[0] > xmlrpclib:1389: return response > __main__:26: print result > {'state': 0, 'id_session': 'QDLY3GP9FBM5', 'port': 29501, 'str': > 'Connection accepted. Session attached.'} > > But the non-killed Connection_Request looks like: > > [...] > return sep.join(words) > xmlrpclib:866: self._type = "params" > xmlrpclib:769: try: > xmlrpclib:770: f = self.dispatch[tag] > xmlrpclib:771: except KeyError: > xmlrpclib:772: pass # unknown tag ? > xmlrpclib:1273: if sock: > xmlrpclib:1274: response = sock.recv(1024) > socket:225: try: > socket:226: self.close() > socket:218: try: > socket:219: if self._sock: > socket:220: self.flush() > socket:232: if self._wbuf: > socket:222: self._sock = None > > (In the diff there is a gap between the xmlrpclib:1274 and socket:225 > lines, as compared to the killed Connection_Request; perhaps Ctrl+C > still executes the "socket try close" lines?) > > If you want to do your own 'diff' on the Python traces, or look at the > TCP packages in more details with Wireshark, here are the files for the > correctly working Info_RT and faulty Connection_Request methods: > > http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-infort-python.ws > http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-infort-python-ws.txt > http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-infort-trace.txt > > http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-conreq-python.ws > http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-conreq-python-ws.txt > http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-conreq-trace.txt > http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-conreq-trace-hardbreak.txt > > (The first three ConReq files all include killing the server after ~28 > seconds, thus resulting in the correct output. In the fourth files, > tracing is stopped before the server is killed. It is therefor the trace > up to the 'hanging point'. Note that the first two Wireshark packages > are not TCP, but ARP, thus the file has a total of 14 packages, not 12 > as above.) > > Really, any help here is appreciated! > > Kind regards, > Arno. > > Arno Stienen wrote: >> Hello all, >> >> It has been a while, but I finally found the time to further investigate >> my problems with connecting Python to a RTAI-XML server. As I cannot >> tell if the problems I'm facing are caused by RTAI-XML (or more >> precisely, the xmlrpc++0.7 library) or Python (xmlrpclib), I'm posting >> this message on both the RTAI as the Python mailing list. >> >> Just to recap, here are the symptoms I described earlier. >> >> I am using two computers. One is running the RTAI-patched real-time >> linux kernel, and this computer controls my robotic hardware. On this >> RTAI computer I installed the RTAI-XML server, which uses incoming >> XML-RPC calls to control real-time processes on the server. RTAI-XML is >> programmed in C++, using the xmlrpc++0.7 library. >> >> The second is a desktop machine (Windows XP or Ubuntu), from which a >> XML-RPC connection can be made to the RTAI computer. Although in theory >> it should make no difference if I use C, C++, Java or Python to make the >> connection, in practise I can get the Java connection running, but have >> problems using Python. And I really like to use Python to quickly create >> interfaces! >> >> When connecting with Python on the desktop computer to the RTAI-XML >> server running on my RTAI machine, I used the following code. >> >> import xmlrpclib >> server = xmlrpclib.Server("http://10.10.101.62:29500") >> print server.Info_RT('Master') >> >> This results in the correct output: >> >> {'state': 0, 'str': 'Info_RT'} >> >> Yet, this is only an information call. The really interesting part >> should comes when I ask the server to open a connection: >> >> import xmlrpclib >> server = xmlrpclib.Server("http://10.10.101.62:29500") >> print server.Connection_Request("roberto") >> >> But then nothing happens. Python just hangs and is unresponsive. Until, >> I kill the RTAI-XML server on the RTAI computer! And then suddenly the >> correct output appears on the desktop command line: >> >> {'state': 0, 'id_session': '2Z3EUSLJFA13', 'port': 29501, >> 'str': 'Connection accepted. Session attached.'} >> >> (Using an alternative Python XML-RPC library '#import pyxmlrpclib as >> xmlrpclib' makes no difference to the result.) >> >> So what happens? I did some experiments. I did some package sniffing >> with Wireshark and I did Python tracing. I stored the sniffing results >> in both the Wireshark as plain text format. The files for the first >> Info_RT examples are here: >> >> http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-infort-python.ws >> http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-infort-python-ws.txt >> http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-infort-trace.txt >> >> The files for the second, not correctly working example are here: >> >> http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-conreq-python.ws >> http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-conreq-python-ws.txt >> http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-conreq-trace.txt >> http://ctw-bw008.ctw.utwente.nl/~arno/rtaixml/roberto-conreq-trace-hardbreak.txt >> >> The first three files all include killing the server after ~30 seconds, >> thus resulting in the correct output. In the fourth files, tracing is >> stopped before the server is killed. It is therefor the trace up to the >> 'hanging point'. >> >> Any, really any, suggestions are appreciated! >> >> Kind regards, >> Arno Stienen. > From steve at holdenweb.com Thu May 17 21:52:51 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 17 May 2007 21:52:51 -0400 Subject: Python-URL! - weekly Python news and links (May 16) In-Reply-To: References: <1179408898.460231.292340@k79g2000hse.googlegroups.com> Message-ID: Steve Holden wrote: > Beliavsky wrote: >> On May 16, 2:45 pm, "Cameron Laird" wrote: >>> QOTW: "Sometimes you just have to take the path of least distaste". - Grant >>> Edwards >>> >>> "I want to choose my words carefully here, so I'm not misunderstood. >> >> >> I think Cameron Laird does a good job with the Python digest but >> blundered here. Why did he highlight a foul comment having nothing to >> do with Python? >> > In fact it *is* peripherally related, since Gartner are currently doing > a "survey" on dynamic languages, and there was a considerable effort > exerted just to make sure that most of the questions actually allowed > sensible comparisons between the various languages. > Please accept my apology: it's Forrester who are currently undertaking the study on dynamic languages. Anyone interested in helping might look at http://python-advocacy.blogspot.com/2007/05/need-help-in-preparing-for-study-of.html and (now the study is underway) http://python-advocacy.blogspot.com/2007/05/seeking-four-code-samples-for-forrester.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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From C.delete_this.Sanders at BoM.GOv.AU Thu May 10 04:59:48 2007 From: C.delete_this.Sanders at BoM.GOv.AU (Charles Sanders) Date: Thu, 10 May 2007 18:59:48 +1000 Subject: preferred windows text editor? In-Reply-To: <1178783872.463067.297280@o5g2000hsb.googlegroups.com> References: <05o0i.2142$zj3.1887@newssvr23.news.prodigy.net> <1178749301.768963.278070@w5g2000hsg.googlegroups.com> <1178783872.463067.297280@o5g2000hsb.googlegroups.com> Message-ID: <4642df05$0$83110$c30e37c6@lon-reader.news.telstra.net> Ant wrote: > > What method of executing code snippets in a Python shell do other Vim > users use? Other than just copy/paste? > Not vim, but good old vi so should work in vim 1. Mark the start of the fragment, for exampls ms (to mark with label s). Labels a through z are available. 2. Move to the end of the fragment. 3. :'s,.w !python to send the fragment to the python interpreter Worked for me when I tried it a few minutes ago. I had never bothered before - just copied/pasted. Obviously, you can also mark the end, move to the start and do something like :.,'ew !python or mark both the start and the end, or use line numbers, or labels plus offsets, or searches, eg :/def/;+5w !python to search forward to the next occurrence of "def" and send that line plus the next five to the interpreter. Whatever works for you. The abbreviate and map commands can be used to reduce the typing if you are fanatical. Charles From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed May 9 10:34:26 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 09 May 2007 16:34:26 +0200 Subject: Simulating simple electric circuits References: <5a9838F2nlbanU1@mid.individual.net> <1178565381.136800.250100@o5g2000hsb.googlegroups.com> Message-ID: <5ae4fiF2ku9rtU2@mid.individual.net> Arnaud Delobelle wrote: > When you turn a switch off, it would send a message to the paths > that depend on it (maybe via the controller?) so that they would > be > deactivated. In turn the lightbulbs on these paths would be > informed that they are no longer active. > > When you turn a switch on, it would send a message to the paths > that depend on it so that those who do not have another off switch > would be > activated. In turn the lightbulbs on these paths would be > informed that they have a new power source. Wow, as I read your reply again, this is exactly the approach I thought of yesterday. :) As mentioned in an adjacent posting, I'll try it out. Thanks to all for comments. This list is great. :) Regards, Bj?rn -- BOFH excuse #133: It's not plugged in. From nogradi at gmail.com Tue May 8 18:18:45 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Wed, 9 May 2007 00:18:45 +0200 Subject: __getattr__ and __getattribute__ In-Reply-To: References: Message-ID: <5f56302b0705081518s8434011i6622a6c9f95046c7@mail.gmail.com> > i find it difficult to understand the difference between the magic methods > __getattr__ and __getattribute__ > and so donot know when to use former or later. >From the docs: __getattr__(self, name) Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). __getattribute__(self, name) Called unconditionally to implement attribute accesses for instances of the class. Please see http://docs.python.org/ref/new-style-attribute-access.html and http://docs.python.org/ref/attribute-access.html HTH, Daniel From openopt at ukr.net Tue May 15 07:29:56 2007 From: openopt at ukr.net (dmitrey) Date: 15 May 2007 04:29:56 -0700 Subject: howto get function from module, known by string names? Message-ID: <1179228596.349933.168610@l77g2000hsb.googlegroups.com> hi all, can anyone explain howto get function from module, known by string names? I.e. something like def myfunc(module_string1, func_string2, *args): eval('from ' + module_string1 + 'import ' + func_string2') return func_string2(*args) or, if it's impossible, suppose I have some modules module1 module2 module3 ... etc each module has it own funcs 'alfa', 'beta' and class module1, module2,... with same string name as module name. can I somehow pass module as function param and then import function 'alfa' from (for example) module8? and/or import class moduleN from moduleN? something like def myfunc(moduleK, *args): return moduleK.moduleK(*args) or return moduleK.alfa(*args) Thx, D From bjourne at gmail.com Wed May 30 12:43:32 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Wed, 30 May 2007 18:43:32 +0200 Subject: Creating a distro of python... What would you include in it? In-Reply-To: <1180538748.448426.182820@g4g2000hsf.googlegroups.com> References: <1180538748.448426.182820@g4g2000hsf.googlegroups.com> Message-ID: <740c3aec0705300943o1d42c32eje6ab054b7dd7977a@mail.gmail.com> On 30 May 2007 08:25:48 -0700, farksimmons at yahoo.com wrote: > I am creating a distro of Python to be licensed as GPL.... am > wondering, what would anyone suggest as to 3rd party modules being put > into it (non-commercial of course!)? I know I'd put MySQLdb into it at > the very least. Any suggestions? If your distro is to be GPL-licensed, does that mean that you want your components to be GPL too? If so, the number of components you can select is reduced drastically. I'd like a distro with a good IDE, GUI toolkit (PyGTK for example), Django and PyGame. Something you could point a newbie to and they would be able to create "real" applications with, without needing to download hundreds of dependencies. -- mvh Bj?rn From rohitsethidce at gmail.com Mon May 7 15:51:37 2007 From: rohitsethidce at gmail.com (rohit) Date: 7 May 2007 12:51:37 -0700 Subject: randomly write to a file Message-ID: <1178567497.042096.82940@w5g2000hsg.googlegroups.com> hi, i am developing a desktop search.For the index of the files i have developed an algorithm with which i should be able to read and write to a line if i know its line number. i can read a specified line by using the module linecache but i am struck as to how to implement writing to the n(th) line in a file EFFICIENTLY which means i don't want to traverse the file sequentially to reach the n(th) line Please help. Regards Rohit From jmazzonelli at gmail.com Thu May 24 09:53:52 2007 From: jmazzonelli at gmail.com (Jorge Mazzonelli) Date: Thu, 24 May 2007 10:53:52 -0300 Subject: (Modular-)Application Framework / Rich-Client-Platform in Python In-Reply-To: <464D5BD0.6080902@freakmail.de> References: <464D5BD0.6080902@freakmail.de> Message-ID: <138a70320705240653k559c107dxa91a3189cbb37506@mail.gmail.com> Maybe I'm missing the point but the mozilla platform doesn't meet you're needs? I know it's not a pure python solution but there's work in progress to use python as a scripting language instead of javascript to develop the components. I did not made anything on the python + XUL side but tested 2 years ago in javascript and it was neat. The book Creating Applicatin with Mozilla was very helpfull (BTW, if I'm not wrong thunderbird and firefox are both build using the mozilla platform/XPCOM/XUL) you can find the python reference in mozilla here: http://developer.mozilla.org/en/docs/Python and the book on mozilla platform: http://books.mozdev.org/html cheers Jorge -------------- next part -------------- An HTML attachment was scrubbed... URL: From Dave.Baum at motorola.com Mon May 21 11:46:17 2007 From: Dave.Baum at motorola.com (Dave Baum) Date: Mon, 21 May 2007 10:46:17 -0500 Subject: A few questions References: Message-ID: In article , jay wrote: > Hi, > > I'm totally new to Python and was hoping someone might be able to > answer a few questions for me: > > 1. What are your views about Python vs Perl? Do you see one as > better than the other? I introduced Python into my group at work and it has for the most part supplanted Perl. For short scripts Python tends to be a lot more readable than Perl. Python also scales better, allowing us to tackle some larger projects with Python than we would have attempted with Perl. However, a lot of this depends on your current skill with the languages and the kind of project you will be working on. A Perl guru is going to be more productive with Perl than with Python. Text processing programs are likely to be more concise in Perl than Python. However, as a general purpose programming language I think Python is an excellent choice. > 2. Is there a good book to start with while learning Python? I'm > currently reading 'Python Essential Reference' by David M. Beazley. > So far it looks like a pretty good book, but would like more > tutorials to work with (I've also been reading through the tutorials > at 'python.org' which has some excellent stuff!). "Learning Python" is a good book for getting started, although it is a bit dated by now. It might not be quite what you are looking for with respect to tutorials, so I'd recommend looking at a copy before buying it. > 3. Currently, I write most of my code with Xcode (on the Mac > platform) using Applescript. This gives me GUI capabilities. Is > there anything you'd recommend that I could use for Python that would > give me a GUI interface? I'd like this to be able to work for both > the Mac and Windows platforms. I've been reading a little about > 'Claro Graphics Toolkit' and 'PyGUI'... would you recommend either of > those? I'll be writing code on a Mac so I need something that will > run on that system. Tkinter is the easiest way to get started with Python GUI programming because it is part of the default python distribution. However, I prefer wxPython for GUI development. You'll have to install a few extra pieces, but in the end wxPython does a better job of being "pythonic" for the programmer, and resulting in native look and feel for the user. "wxPython in Action" is an excellent book for learning about wxPython. Dave From mail at microcorp.co.za Thu May 24 05:56:49 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 24 May 2007 11:56:49 +0200 Subject: Shared Memory Space - Accross Apps & Network References: <1179913683.260600.283420@q69g2000hsb.googlegroups.com> Message-ID: <000301c79eb1$2973bf80$03000080@hendrik> From: "D.Hering" wrote: > On May 23, 4:04 am, Tim Golden wrote: > > Robert Rawlins - Think Blue wrote: > > I did not see the original post either :-( ... > > > I've got an application that runs on an embedded system, the application > > > uses a whole bunch or dicts and other data types to store state and other > > > important information. > > > I'm looking to build a small network of these embedded systems, and I'd love > > > to have them all share the same set or data. Is it possible to share the > > > applications variables across multiple applications, so certain lists are > > > like a 'pool' written to by the different systems? I'm sure I could cobble > > > something together by writing the lists to shared files instead of keeping > > > them in RAM, but that feels a little inefficient. I'd like to try and > > > configure some form of master/slave relationship between my applications if > > > possible. What kind of "embedded" platform are you using? - sounds like a cut down PC. I have just spent a lot of time solving similar problems on *very* small processors, and ended up designing a very simple language and a kind of distributed OS, that can do nothing more than putting voltages on wires, but both locally and remotely... The human interface part runs on PC's and is written in Python. The embedded controllers are written in a mix of C and assembler and implement an assembler like reverse polish notation multi tasking language running on a virtual risc machine. The "compiler" is also written in Python. Can probably only share some of the pain with you to make your journey less painful... > > > > I was really surprised you hadn't received a whole > > slew of answers for this (even if they were: search > > the newsgroup for the last time this was asked!) But > > then I noticed that the post hadn't appeared on Google > > Groups, at least. I read things via the mailing list; > > is it possible your post hasn't made it across to > > Usenet either? > > > > Just to get the ball rolling, I'd suggest two things: > > > > Pyro -http://pyro.sf.net This is good advice, if you have the power to run it. > > > > This is actively maintained and has been going for a while. > > We use it here (on a fairly small scale) and I know that > > others use it elsewhere for bigger things. It's based on > > a threaded socket server so whenever someone starts to say: > > "I know; I'll roll my own threaded socket server", I'm > > inclined to say: "Don't reinvent the wheel; try Pyro". > > > > PyLinda -http://www-users.cs.york.ac.uk/~aw/pylinda/ When I looked at this, it looked very nice too, but different from pyro. > > > > This implements the tuplespace paradigm. It's great > > fun to use, but as far as I know this implementation > > was a PhD project and lacks the robustness and wide > > use of other things. That said, it works perfectly > > well within its remit and might be a good match for > > what you're trying to do. > > > > No doubt other people can chime in with suggestions > > > > TJG > > Possibly, IPython's new interactive parallel environment is what you > are looking for: http://ipython.scipy.org/moin/Parallel_Computing Unqualified to comment on this - Hendrik From afrojas at gmail.com Sun May 27 20:00:06 2007 From: afrojas at gmail.com (Andres Francisco Rojas) Date: Sun, 27 May 2007 17:00:06 -0700 Subject: CGI + appscript newbie question/problem Message-ID: Hey everyone. So I'm more or less new to Python, just wanted to say that right up front so please excuse any silly questions. Generally what I'm trying to do is control a Mac OS X application through a website via Python and appscript. I have successfully got Apache running and configured to run Python scripts, basic modules like os and cgi work and I can do silly form processing and stuff like that, so I know Python itself is good to go, along with the web server. I can execute AppleScript commands, and control applications, successfully using appscript when using Python via Terminal (and following along with the examples), but when I try to import appscript into the script run as cgi I get an 500 Internal Server Error. I know it's the import call because I can comment it out and the script runs, but I can't do any AppleScripting (obviously). Is there a limitation to running appscript when in cgi on Apache? Is there an Apache setting I'm missing? Everything is local, by the way, running off the machine I'm writing this message on. Below is the code that Apache runs: #!/usr/bin/python import cgi from appscript import * print "Content-Type: text/html\n\n" # Define function to generate HTML form. def generate_form(): print "\n" print "\n" print "\tInfo Form\n" print "\n" print "\n" print "\t
    \n" print "\t\n" print "\t\n" print "\n" print "\n" # Define main function. def main(): form = cgi.FieldStorage() if (form.has_key("action")): if (form["action"].value == "launch"): print "COUNTDOWN!" texteditGUI = app('System Events').processes['TextEdit'] app('TextEdit').activate() mref = texteditGUI.menu_bars[1].menus mref['File'].menu_items['New'].click() mref['Edit'].menu_items['Paste'].click() mref['Window'].menu_items['Zoom Window'].click() else: generate_form() # Call main function. main() I tried using both 'from appscript import *' and 'import appscript' and it doesn't make a difference. 'from appscript import *' is the way it successfully works when using the command line interpreter. Thanks for any help on this! -Andr?s Rojas -------------- next part -------------- An HTML attachment was scrubbed... URL: From gh at gregor-horvath.com Thu May 17 23:51:19 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Fri, 18 May 2007 05:51:19 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <1179441050.656539.277900@o5g2000hsb.googlegroups.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <464C5382.6080403@v.loewis.de> <1179423799.254286.294930@w5g2000hsg.googlegroups.com> <1179441050.656539.277900@o5g2000hsb.googlegroups.com> Message-ID: sjdevnull at yahoo.com schrieb: > With the second one, all my standard tools would work fine. My user's > setups will work with it. And there's a much higher chance that all > the intervening systems will work with it. > Please fix your setup. This is the 21st Century. Unicode is the default in Python 3000. Wake up before it is too late for you. Gregor From john at datavoiceint.com Wed May 9 10:15:35 2007 From: john at datavoiceint.com (HMS Surprise) Date: 9 May 2007 07:15:35 -0700 Subject: String parsing In-Reply-To: References: <1178672992.522463.228620@l77g2000hsb.googlegroups.com> Message-ID: <1178720135.613295.81720@e51g2000hsg.googlegroups.com> > This looks to be simple HTML (and I'm presuming that's a type on > that ?> ending). A quick glance at the Python library reference (you do > have a copy, don't you) reveals at least two HTML parsing modules... > No that is not a typo and bears investigation. Thanks for the find. I found HTMLParser but had trouble setting it up. > About five minutes work gave me this: > My effort has been orders of magnitude greater in time..... Thanks all for all the excellent suggestions. jh From howe.steven at gmail.com Sat May 5 14:07:27 2007 From: howe.steven at gmail.com (Steven Howe) Date: Sat, 05 May 2007 11:07:27 -0700 Subject: File names and file objects [was Re: My Python annoyances] In-Reply-To: References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> <1178202431.147195.249790@u30g2000hsc.googlegroups.com> <1hxkwj0.12jtj1v3b522bN%aleax@mac.com> Message-ID: <463CC7DF.3040307@gmail.com> An HTML attachment was scrubbed... URL: From kw at codebykevin.com Sat May 26 20:51:17 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Sat, 26 May 2007 20:51:17 -0400 Subject: Tix and OS X In-Reply-To: <1180218876.623283.174680@p77g2000hsh.googlegroups.com> References: <1180218876.623283.174680@p77g2000hsh.googlegroups.com> Message-ID: Jeff Reavis wrote: > Does python not ship with Tix for OS X? I know there was an issue with > 2.5.0 and Tix on Windows, and upgrading to 2.5.1 fixed it. > Unfortunately, I seem to have the same issue with OS X and 2.5.1. The > error I get is: > > self.tk.eval('package require Tix') > _tkinter.TclError: can't find package Tix > > I did find tkinter.so (Tkinter seems to work), but nothing matching > tix.so. > Is this a known issue? I haven't found any information about it on the > web or in this group. > > Thanks in advance. > > This is an Intel Mac, btw. > > -jjr > You have to have the Tcl Tix package installed--the Python module just wraps it. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From amitsoni.605 at gmail.com Thu May 3 05:35:42 2007 From: amitsoni.605 at gmail.com (amit soni) Date: Thu, 3 May 2007 02:35:42 -0700 Subject: Using Bessel Functions Message-ID: <7a9982ec0705030235h23035156w4f0726e6cef52f@mail.gmail.com> Hi, I want to use Bessel functions in Python. I found on internet that package Scipy has a function jn(x), but I'm not able to use it. I am importing scipy and numpy for using it. But i'm getting an error "NameError: name 'j1' is not defined". Can anyone tell me what is the exact syntax for to use it. Thank you, Amit -------------- next part -------------- An HTML attachment was scrubbed... URL: From Graham.Dumpleton at gmail.com Tue May 1 02:16:54 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: 30 Apr 2007 23:16:54 -0700 Subject: re-importing modules In-Reply-To: <7xejm1w0pw.fsf@ruckus.brouhaha.com> References: <8%pZh.18192$Kd3.76@newssvr27.news.prodigy.net> <1177962288.575008.48490@q75g2000hsh.googlegroups.com> <1177967919.968338.3300@l77g2000hsb.googlegroups.com> <1177997329.701861.143290@e65g2000hsc.googlegroups.com> <7xejm1w0pw.fsf@ruckus.brouhaha.com> Message-ID: <1178000214.802269.267260@n76g2000hsh.googlegroups.com> On May 1, 3:51 pm, Paul Rubin wrote: > Graham Dumpleton writes: > > That it doesn't reload a parent when a child changes may be fine in an > > interactive debugger, but can cause problems if not done where > > automatic reloading is being done in a long running web application > > where you want to avoid server restarts. > > Oh that sounds horrid. If you really have to do something like that, > it's time to consider adding serious hot-patching capability as I > believe Erlang has done. Better is to start a new server process and > transfer the live session data and active connections to it through > IPC mechanisms. I've had an open RFE for many years (#814689) about > ancillary messages on AF_UNIX sockets, which let you pass file > descriptors (such as those attached to open TCP connections) between > processes. It actually came up in conversation with someone about > something I'm currently working on, so maybe I'll have reason to try > coding it sometime soon (that's not at all definite though). It may sound horrible but mod_python's original module importer had lots of problems because of things not being reloaded when they should have in a consistent manner. People weren't going to want to give up the reload feature altogether as restarting Apache all the time is viewed as a worse solution, so the only practical solution was at least make it reliable and this is one of the things that was required to do it. The number of complaints against mod_python module importing and reloading problems has basically vanished now with mod_python 3.3 and the whole thing is so much more stable now. Do note that this reloading mechanism isn't applied across all Python modules, only mod_python handler and associated modules which are used within the context of URL/document space of your web server. Thus it is quite specialised and has quite specific use case scenarios which are well understood. In that context the whole mechanism works fine. Thus, please try not to pass judgment on it without full understanding the problem space it operates in and how it internally works. :-) Graham From steven at REMOVE.THIS.cybersource.com.au Tue May 15 20:47:57 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 16 May 2007 00:47:57 GMT Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> <4648294F.2000704@web.de> <46487a6c$0$2400$426a74cc@news.free.fr> <464977D3.6010703@web.de> <464993e7$0$23148$9b4e6d93@newsspool1.arcor-online.net> Message-ID: On Tue, 15 May 2007 13:05:12 +0200, Ren? Fleschenberg wrote: > Any program that uses non-English identifiers in Python is bound to > become gibberish, since it *will* be cluttered with English identifiers > all over the place anyway, wether you like it or not. It won't be gibberish to the people who speak the language. -- Steven. From sjdevnull at yahoo.com Sat May 5 17:06:37 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 5 May 2007 14:06:37 -0700 Subject: Python regular expressions just ain't PCRE In-Reply-To: <1178323901.381993.47170@e65g2000hsc.googlegroups.com> References: <1178323901.381993.47170@e65g2000hsc.googlegroups.com> Message-ID: <1178399197.942689.69390@e65g2000hsc.googlegroups.com> Wiseman wrote: > I'm kind of disappointed with the re regular expressions module. In > particular, the lack of support for recursion ( (?R) or (?n) ) is a > major drawback to me. There are so many great things that can be > accomplished with regular expressions this way, such as validating a > mathematical expression or parsing a language with nested parens, > quoting or expressions. -1 on this from me. In the past 10 years as a professional programmer, I've used the wierd extended "regex" features maybe 5 times total, whether it be in Perl or Python. In contrast, I've had to work around the slowness of PCRE-style engines by forking off a grep() or something similar practically every other month. I think it'd be far more valuable for most programmers if Python moved toward dropping the extended semantics so that something one of the efficient regex libraries (linked in a recent thread here on comp.lang.python) could work with, and then added a parsing library to the standard library for more complex jobs. Alternatively, if the additional memory used isn't huge we could consider having more intelligence in the re compiler and having it choose between a smarter PCRE engine or a faster regex engine based on the input. The latter is something I'm playing with a patch for that I hope to get into a useful state for discussion soon. But regexes are one area where speed very often makes the difference between whether they're usable or not, and that's far more often been a limitation for me--and I'd think for most programmers--than any lack in their current Python semantics. So I'd rather see that attacked first. From hniksic at xemacs.org Wed May 9 05:00:14 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 09 May 2007 11:00:14 +0200 Subject: Multiple regex match idiom Message-ID: <87r6pqxtgh.fsf@busola.homelinux.net> I often have the need to match multiple regexes against a single string, typically a line of input, like this: if (matchobj = re1.match(line)): ... re1 matched; do something with matchobj ... elif (matchobj = re2.match(line)): ... re2 matched; do something with matchobj ... elif (matchobj = re3.match(line)): .... Of course, that doesn't work as written because Python's assignments are statements rather than expressions. The obvious rewrite results in deeply nested if's: matchobj = re1.match(line) if matchobj: ... re1 matched; do something with matchobj ... else: matchobj = re2.match(line) if matchobj: ... re2 matched; do something with matchobj ... else: matchobj = re3.match(line) if matchobj: ... Normally I have nothing against nested ifs, but in this case the deep nesting unnecessarily complicates the code without providing additional value -- the logic is still exactly equivalent to the if/elif/elif/... shown above. There are ways to work around the problem, for example by writing a utility predicate that passes the match object as a side effect, but that feels somewhat non-standard. I'd like to know if there is a Python idiom that I'm missing. What would be the Pythonic way to write the above code? From gregory.lielens at gmail.com Thu May 3 05:02:58 2007 From: gregory.lielens at gmail.com (gregory.lielens at gmail.com) Date: 3 May 2007 02:02:58 -0700 Subject: assigning to __class__ for an extension type: Is it still possible? Message-ID: <1178182978.525197.130690@u30g2000hsc.googlegroups.com> Hello, We are currently writing python bindings to an existing C++ library, and we encountered a problem that some of you may have solved (or that has found unsolvable :( ): A C++ class (let's call it CClass) is binded using classical Python extension API to _PClass, which is accesible through python without any problem. The problem is that I want this class to be extended/ extensible in python, and expose the python-extended version (PClass) to library users (_PClass should never be used directly nor be retruned by any function). The aim is to leave only performance critical methods in C++ so that the binding work is minimal, and develop the other methods in python so that they are easier to maintain/extend. We thus have something like this class PClass(_PClass): def overide_method(self,...): ... def new_method(self,...): ... and I can define a=PClass() and use my new or overiden method a.overide_method() a.new_method() as intended... So far, so good, trouble begin when I have a method from another class PClass2 derived from _PClass2 which bind the C++ class CClass2, that should return objects of type PClass: Let call this method troublesome_method: b=_PClass2() c=b.troublesome_method() type(c) gives _PClass. Now I want to define a python class PClass2 for extending methods of _PClass2 like I have done for _PClass, in particular I want that PClass2 troublesome_method return objects of type PClass instead of _PClass... To this end I try something like this class PClass2(_PClass2): ... def troubelsome_method(self): base=_PClass2.troublesome_method(self) base.__class__=PClass and I have python complaining about TypeError: __class__ assignment: only for heap types... We have then added the Py_TPFLAGS_HEAPTYPE tp_flag, which turn _PClass into a heap class and should make this class assignment possible...or so I though: When the _PClass is turned into a heaptype, assignent to __class__trigger a test in python's typeobject.c on tp_dealloc/tp_free witch raise an exception TypeError: __class__ assignment: '_PClass' deallocator differs from 'PClass' I have commented out this test, just to check what happen, and just got an error later on TypeError: __class__ assignment: '_PClass' object layout differs from 'PClass' It seems thus that this approach is not possible, but problem is that delegation ( embedding a _PClass instance in PClass (lets say as _base attribute) and automatically forwarding all methods calls/setattr/getattr to ._base) is far from ideal... Indeed, we would have to change all other methods that accepted _PClass, to give them PClass._base, this means wrapping a large number of methods (from our c++ bindings) for argument-processing... This is particularly frustrating cause I also have the impression that want we want to do was at one time possible in python, let say in 2002-2003, when __class__ was already assignable but before various safety checks were implemented (assignmenent only for heaptypes, check on tp_free/tp_dealloc, layout check,...) Any hint on this problem? In particular, a list of condition type A and B have to fullfull so that a=A(); a.__class__=B is possible would be very nice, especially when A is an extension type (I think the correct term is static type) while B is defined by a class statement (dynamic type)...This is something that is not easy to find in the docs, and seems to have changed quite a lot between revisions 2.2/2.3/2.4/2.5... Thanks, Greg. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri May 18 08:48:42 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 18 May 2007 14:48:42 +0200 Subject: Python Web Programming - looking for examples of solid high-traffic sites In-Reply-To: References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> Message-ID: <464da0a9$0$25891$426a74cc@news.free.fr> John Nagle a ?crit : > Victor Kryukov wrote: >> Hello list, >> >> our team is going to rewrite our existing web-site, which has a lot of >> dynamic content and was quickly prototyped some time ago. > ... >> Our main requirement for tools we're going to use is rock-solid >> stability. As one of our team-members puts it, "We want to use tools >> that are stable, has many developer-years and thousands of user-years >> behind them, and that we shouldn't worry about their _versions_." The >> main reason for that is that we want to debug our own bugs, but not >> the bugs in our tools. > > You may not be happy with Python, then. John, I'm really getting tired of your systemic and totally unconstructive criticism. If *you* are not happy with Python, by all means use another language. From jstroud at mbi.ucla.edu Tue May 8 17:34:05 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 08 May 2007 14:34:05 -0700 Subject: Suggestions for how to approach this problem? In-Reply-To: <4640d69b$0$31446$c3e8da3@news.astraweb.com> References: <4640ca5b$0$23392$c3e8da3@news.astraweb.com> <4640d69b$0$31446$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: > Marc 'BlackJack' Rintsch wrote: > Here's what it looks like now: > > 1. Levy, S.B. (1964) Isologous interference with ultraviolet and X-ray > irradiated > bacteriophage T2. J. Bacteriol. 87:1330-1338. > 2. Levy, S.B. and T. Watanabe (1966) Mepacrine and transfer of R > factor. Lancet 2:1138. > 3. Takano, I., S. Sato, S.B. Levy and T. Watanabe (1966) Episomic > resistance factors in > Enterobacteriaceae. 34. The specific effects of the inhibitors of DNA > synthesis on the > transfer of R factor and F factor. Med. Biol. (Tokyo) 73:79-83. > 4. Levy, S.B. (1967) Blood safari into Kenya. The New Physician > 16:50-54. > 5. Levy, S.B., W.T. Fitts and J.B. Leach (1967) Surgical treatment of > diverticular disease of the > colon: Evaluation of an eleven-year period. Annals Surg. 166:947-955. > > As you can see, any single citation is broken over several lines as a > result of a line break. I want it to look like this: > > 1. Levy, S.B. (1964) Isologous interference with ultraviolet and X-ray > irradiated bacteriophage T2. J. Bacteriol. 87:1330-1338. > 2. Levy, S.B. and T. Watanabe (1966) Mepacrine and transfer of R > factor. Lancet 2:1138. > 3. Takano, I., S. Sato, S.B. Levy and T. Watanabe (1966) Episomic > resistance factors in Enterobacteriaceae. 34. The specific effects > of the inhibitors of DNA synthesis on the > transfer of R factor and F factor. Med. Biol. (Tokyo) 73:79-83. > 4. Levy, S.B. (1967) Blood safari into Kenya. The New Physician > 16:50-54. > 5. Levy, S.B., W.T. Fitts and J.B. Leach (1967) Surgical treatment of > diverticular disease of the colon: Evaluation of an eleven-year > period. Annals Surg. 166:947-955. > > Now, since this is pasted, it might not even look good to you. But in > the second example, the numbers are meant to be bullets and so the > indentation would happen automatically (in Word). But for now they are > just typed. If you can count on the person not skipping any numbers in the citations, you can take an "AI" approach to hopefully weed out the rare circumstance that a number followed by a period starts a line in the middle of the citation. This is not failsafe, say if you were on citation 33 and it was in chapter 34 and that 34 happend to start a new line. But, then again, even a human would take a little time to figure that one out--and probably wouldn't be 100% accurate either. I'm sure there is an AI word for the type of parser that could parse something like this unambiguously and I'm sure that it has been proven to be impossible to create: import re records = [] record = None counter = 1 regex = re.compile(r'^(\d+)\. (.*)') for aline in lines: m = regex.search(aline) if m is not None: recnum, aline = m.groups() if int(recnum) == counter: if record is not None: records.append(record) record = [aline.strip()] counter += 1 continue record.append(aline.strip()) if record is not None: records.append(record) records = [" ".join(r) for r in records] py> import re py> records = [] py> record = None py> counter = 1 py> regex = re.compile(r'^(\d+)\. (.*)') py> for aline in lines: ... m = regex.search(aline) ... if m is not None: ... recnum, aline = m.groups() ... if int(recnum) == counter: ... if record is not None: ... records.append(record) ... record = [aline.strip()] ... counter += 1 ... continue ... record.append(aline.strip()) ... py> if record is not None: ... records.append(record) ... py> records = [" ".join(r) for r in records] py> records ['Levy, S.B. (1964) Isologous interference with ultraviolet and X-ray irradiated bacteriophage T2. J. Bacteriol. 87:1330-1338.', 'Levy, S.B. and T. Watanabe (1966) Mepacrine and transfer of R factor. Lancet 2:1138.', 'Takano, I., S. Sato, S.B. Levy and T. Watanabe (1966) Episomic resistance factors in Enterobacteriaceae. 34. The specific effects of the inhibitors of DNA synthesis on the transfer of R factor and F factor. Med. Biol. (Tokyo) 73:79-83.', 'Levy, S.B. (1967) Blood safari into Kenya. The New Physician 16:50-54.', 'Levy, S.B., W.T. Fitts and J.B. Leach (1967) Surgical treatment of diverticular disease of the colon: Evaluation of an eleven-year period. Annals Surg. 166:947-955.'] James From mccredie at gmail.com Tue May 1 18:09:24 2007 From: mccredie at gmail.com (Matimus) Date: 1 May 2007 15:09:24 -0700 Subject: Python user group in Portland, OR? In-Reply-To: <1178054753.732189.137230@h2g2000hsg.googlegroups.com> References: <1178054753.732189.137230@h2g2000hsg.googlegroups.com> Message-ID: <1178057364.942127.203200@n76g2000hsh.googlegroups.com> Python.org lists PORPIG (PORtland Python Intrest Group) but the site that it points to no longer seems to represent that. Also, when I looked into going to a meeting a while back, the last one listed was some time in 2004. I will put this out there though, if someone wants to start a PIG back up for Portland I would certainly be interested. I am at least one Python developer living in the Portland area. The web contains evidence of others as well. In general there is a fairly large software development presence in Portland, especially around Open Source. From robert.kern at gmail.com Thu May 17 18:15:07 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 17 May 2007 17:15:07 -0500 Subject: FreeType In-Reply-To: <464CCDA5.4030505@holdenweb.com> References: <1179422948.600593.117310@p77g2000hsh.googlegroups.com> <1179431247.954420.219690@q75g2000hsh.googlegroups.com> <397DF4A1-A882-4B90-ADE1-8D3F3BC408F6@jedimindworks.com> <464CCDA5.4030505@holdenweb.com> Message-ID: Steve Holden wrote: > Alternatively use the Python Imaging Library (PIL), which I believe > includes freetype support. The OP seems to be trying to build matplotlib, which actually does require the FreeType library. The PIL, lovely though it is, is not a substitute. -- 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 jon+usenet at unequivocal.co.uk Fri May 11 15:18:58 2007 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 11 May 2007 19:18:58 GMT Subject: File writing success References: <1178907719.896993.299910@h2g2000hsg.googlegroups.com> Message-ID: On 2007-05-11, HMS Surprise wrote: > If file writing has no return value (http://docs.python.org/lib/bltin- > file-objects.html), how do you know if the write was successful? Because no exception was thrown? Although bear in mind that some errors might not become apparent until you close or flush the file. From warren at muse.com Thu May 31 10:59:35 2007 From: warren at muse.com (Warren Stringer) Date: Thu, 31 May 2007 07:59:35 -0700 Subject: c[:]() In-Reply-To: References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com><1180554872.3356.30.camel@dot.uniqsys.com><465DF3DE.40404@cc.umanitoba.ca><1180566831.239580.199300@m36g2000hse.googlegroups.com><005401c7a31a$136f7fe0$240110ac@Muse> Message-ID: <001d01c7a394$4d8704d0$240110ac@Muse> Hey Marc, > > [d() for d in c] > > If you are using the list comprehension just for the side effect of > calling `d` then consider this bad style. You are building a list of > `None` objects just to have a "cool" one liner then. Yep, you're right > for func in funcs: > func() > > Because it is explicit and readable and matches the english description > "for every function in functions: call that function" very closely while a > list comprehension or your "perlish" line noise is much more magic to > explain and harder to remember. Hmmmm... the reason what I use the list comprehension was the description "call that thing for every thing in those things" The first time I something saw this I though, in my C befuddled head 'huh? that's backwards!' But, then the more I thought about it I recall that this is how some people speak. Still I prefer funcs[:]() Because, I can describe it in English as "call everything that funcs has" (BTW, I have yet to write my first line of Perl. It that good thing or a bad thing?) From pc at p-cos.net Wed May 2 15:20:42 2007 From: pc at p-cos.net (Pascal Costanza) Date: Wed, 02 May 2007 21:20:42 +0200 Subject: Microsoft's Dynamic Languages Runtime (DLR) In-Reply-To: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> References: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> Message-ID: <59s6kbF2kq8uoU1@mid.individual.net> sturlamolden wrote: > On Monday Microsoft announced a new runtime for dynamic languages, > which they call "DLR". It sits on top of the conventional .NET runtime > (CLR) and provides services for dynamically typed languages like > Python or Lisp (thus the cross-posting). Apparently is is distributed > under a BSD-like open-source license. > > I am curious to know how it performs in comparison to CPython and an > efficient compiled Lisp like CMUCL. Speed is a major problem with > CPython but not with .NET or CMUCL, so it will be interesting to see > how the DLR performs in comparison. It would be great to finally see a > Python that runs on steroids, but knowing M$ bloatware my expectations > are not too high. > > Has anyone looked at the DLR yet? What are your impression? So far, there is not a lot of information available. The only statement about the technology I have read so far is that the DLR is a thin layer on top of the CLR. This doesn't say a lot. So it's hard to tell whether this is a (good) marketing stunt or whether there are actual substantial improvement to the infrastructure. Pascal -- My website: http://p-cos.net Common Lisp Document Repository: http://cdr.eurolisp.org Closer to MOP & ContextL: http://common-lisp.net/project/closer/ From mailmaverick666 at gmail.com Thu May 3 02:10:16 2007 From: mailmaverick666 at gmail.com (rishi pathak) Date: Thu, 3 May 2007 11:40:16 +0530 Subject: FInd files with .so extension In-Reply-To: <1178168321.581307.284750@y5g2000hsa.googlegroups.com> References: <1178168321.581307.284750@y5g2000hsa.googlegroups.com> Message-ID: <180b672e0705022310i3ad709f8w6590e6aaffd884cc@mail.gmail.com> May be this would work import os grep="so" dir="." lst = os.listdir(dir) filelst=[] for i in lst: if i.split(".")[len(i.split("."))-1] == grep: lst.append(i) print lst On 2 May 2007 21:58:41 -0700, pradeep nair wrote: > > HI, > > > How do i find files with .so extension using python . > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Regards-- Rishi Pathak National PARAM Supercomputing Facility Center for Development of Advanced Computing(C-DAC) Pune University Campus,Ganesh Khind Road Pune-Maharastra -------------- next part -------------- An HTML attachment was scrubbed... URL: From john at datavoiceint.com Tue May 8 11:35:40 2007 From: john at datavoiceint.com (HMS Surprise) Date: 8 May 2007 08:35:40 -0700 Subject: sys.path Message-ID: <1178638540.056691.161750@e65g2000hsc.googlegroups.com> Is sys.path setup differnently in jython vs python? I have environment variables pythonpath and jythonpath set to include C:\python22 but the initial printout indicates it is being ignored. Also when I used sys.path.extend, the added pathname shows up as a series of single characters. Have I misused .extend? Thanks, jh import sys print sys.path sys.path.extend("c:\python22") print sys.path import urllib ['.', 'C:\\maxq\\lib\\Lib', 'C:\\maxq\\jython'] ['.', 'C:\\maxq\\lib\\Lib', 'C:\\maxq\\jython', 'c', ':', '\\', 'p', 'y', 't', 'h', 'o', 'n', '2', '2'] Traceback (innermost last): File "", line 9, in ? ImportError: no module named urllib From silverfrequent at gmail.com Mon May 21 00:12:05 2007 From: silverfrequent at gmail.com (Silver Rock) Date: Mon, 21 May 2007 01:12:05 -0300 Subject: Python assignment loop In-Reply-To: <1179717712.491520.288060@z24g2000prd.googlegroups.com> References: <1179717712.491520.288060@z24g2000prd.googlegroups.com> Message-ID: On 20 May 2007 20:21:52 -0700, George Sakkis wrote: > On May 20, 10:33 pm, "Silver Rock" wrote: > > i need to do something like this: > > > > ### > > import wx > > x=number > > for i in range(500): > > "var"+str(i)=ClassXYZ(...,x+i,...) > > > > #.... code > > y=number > > for i in range(y): > > ClassAAAA(object_called_by_the_string("var"+str(i)),...) > > > > ### > > i can't figure out how to do this, and could not find it on the web. > > c. > > Whenever you are tempted to create dynamically variables names, 99% of > the time what you really want is a data structure, typically a dict or > a list. In your example, a list will do: > > x=number > xyz_objects = [ClassXYZ(...,x+i,...) for i in xrange(500)] > #.... code > y=number > aaaa_objects = [ClassAAAA(object_called_by_the_string(xyz,...) > for xyz in xyz_objects[:y]] > > If you can't figure out what this does, lookup for "list > comprehensions". By the way, I hope these were shortened examples and > you're not actually using names such as 'ClassAAAA' or 'ClassXYZ' in > your actual code... > > George > > -- > http://mail.python.org/mailman/listinfo/python-list > hi George, thanks for your help. yes, that is the way I a solving the problem. using lists. so it seems that there is no way around it then.. cheers, i am not using ClassAAAA or ClassXYZ in my code :-) From manatlan at gmail.com Sun May 13 04:46:16 2007 From: manatlan at gmail.com (manatlan) Date: 13 May 2007 01:46:16 -0700 Subject: Dynamic subclassing ? In-Reply-To: <1179043443.193791.255510@p77g2000hsh.googlegroups.com> References: <1178976888.443891.116090@y80g2000hsf.googlegroups.com> <1179043443.193791.255510@p77g2000hsh.googlegroups.com> Message-ID: <1179045976.502995.20990@e51g2000hsg.googlegroups.com> On 13 mai, 10:04, manatlan wrote: > On 12 mai, 18:57, Karlo Lozovina <_karlo_ at _mosor.net> wrote: > > > > > manatlan wrote: > > > I can't find the trick, but i'm pretty sure it's possible in an easy > > > way. > > > It's somewhat easy, boot looks ugly to me. Maybe someone has a more > > elegant solution: > > > In [6]: import new > > > In [13]: class Button: > > ....: def buttonFunc(self): > > ....: pass > > > In [14]: class ExtensionClass: > > ....: def extendedMethod(self): > > ....: pass > > > In [15]: hybrid = new.instance(Button, > > Button.__dict__.update(ExtensionClass.__dict__)) > > > In [17]: dir(hybrid) > > Out[17]: ['__doc__', '__module__', 'buttonFunc', 'extendedMethod'] > > > Seems to do what you want it to do. > > > HTH, > > Karlo. > > yes, i think it's the only solution ... it's weird > but it seems to be the only one ... > i will try that ... in fact, the "new" solution adds methods to all "gtk.Button" and not a specific instance ... it's not good for me but thanks (i always forget the use of the "new" module for this kind of things) From jstroud at mbi.ucla.edu Mon May 14 19:59:48 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 14 May 2007 16:59:48 -0700 Subject: tkinter button state = DISABLED In-Reply-To: <1179163831.016938.79840@w5g2000hsg.googlegroups.com> References: <1179163831.016938.79840@w5g2000hsg.googlegroups.com> Message-ID: rahulnag22 at yahoo.com wrote: > I have created a button widget with a button click binding. The button > initially has a state=disabled. I can see the greyed out version of > the button in the GUI. But If I click on the button it still invokes > the callback/binding function. > > Any suggestions as to why the callback is being invoked even though > the button has a disabled state. It looks like- > > b=Button(frame, text = "Button", state = 'disabled') > > b.bind("", > lambda > event : > function() > ) > > Thanks > Rahul > DISABLED refers to the whether the function supplied in the "command" parameter is called when the button is pressed, other bindings are irrelevant, so you will need code to re-bind any events you have bound when the button is "disabled". So its better to just use the "command" parameter rather than binding mouse events. An exception is Checkbutton, where you might want to bind and then query the button's state (or the state of an IntVar associated with it) to make a decision--if you want a GUI to respond real-time to user events. James From aleax at mac.com Thu May 3 00:59:56 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 2 May 2007 21:59:56 -0700 Subject: How to check if a string is empty in python? References: <1178138147.029830.304130@p77g2000hsh.googlegroups.com> <1178154290.811928.208900@h2g2000hsg.googlegroups.com> Message-ID: <1hxia6q.18rflwk1mez8vhN%aleax@mac.com> Steven D'Aprano wrote: > On Wed, 02 May 2007 21:19:54 -0400, Roy Smith wrote: > > > for c in s: > > raise "it's not empty" > > String exceptions are depreciated and shouldn't be used. > > http://docs.python.org/api/node16.html They're actually deprecated, not depreciated. Searching define:deprecated -- first hit: In computer software standards and documentation, deprecation is the gradual phasing-out of a software or programming language feature. en.wikipedia.org/wiki/Deprecated and the other four hits are fine too. Searching define:depreciated , we move almost entirely into accounting and finance, except: http://en.wikipedia.org/wiki/Depreciated """ Depreciated is often confused or used as a stand-in for "deprecated"; see deprecation for the use of depreciation in computer software """ Alex From mensanator at aol.com Sun May 13 00:50:12 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 12 May 2007 21:50:12 -0700 Subject: Interesting list Validity (True/False) In-Reply-To: References: <1178911704.529457.292280@e51g2000hsg.googlegroups.com> <1178914190.166662.285410@p77g2000hsh.googlegroups.com> <1178915791.584216.293130@l77g2000hsb.googlegroups.com> <1178918808.091358.233740@o5g2000hsb.googlegroups.com> <1179017740.656323.209590@e51g2000hsg.googlegroups.com> <1179020634.130689.171960@o5g2000hsb.googlegroups.com> Message-ID: <1179031812.090768.248750@l77g2000hsb.googlegroups.com> On May 12, 11:02???pm, Steven D'Aprano wrote: > On Sat, 12 May 2007 18:43:54 -0700, mensana... at aol.com wrote: > > On May 12, 8:10?pm, Carsten Haese wrote: > >> On Sat, 2007-05-12 at 17:55 -0700, mensana... at aol.com wrote: > >> > On May 12, 12:56?pm, Carsten Haese wrote: > >> > > On Fri, 2007-05-11 at 14:26 -0700, mensana... at aol.com wrote: > >> > > > if arg==True: > > >> > > > tests the type property (whether a list is a boolean). > > >> > > That sounds nonsensical and incorrect. Please explain what you mean. > > >> > > >> > Sec 2.2.3: > >> > Objects of different types, except different numeric types and > >> > different string types, never compare equal; > >> > > > I should point out that only applies to built-in types, not custom classes. > > >> That doesn't explain what you mean. How does "if arg==True" test whether > >> "a list is a boolean"? > > >>>> type(sys.argv) > > > >>>> type(True) > > > > That still doesn't make sense. However, using my incredible psychic > ability to read between the lines, I think what Mensanator is trying (but > failing) to say is that "if arg==True" first tests whether arg is of type > bool, and if it is not, it knows they can't be equal. That's not actually > correct. We can check this: > > >>> import dis > >>> def test(arg): > > ... ? ? return arg == True > ...>>> dis.dis(test) > > ? 2 ? ? ? ? ? 0 LOAD_FAST ? ? ? ? ? ? ? ?0 (arg) > ? ? ? ? ? ? ? 3 LOAD_GLOBAL ? ? ? ? ? ? ?0 (True) > ? ? ? ? ? ? ? 6 COMPARE_OP ? ? ? ? ? ? ? 2 (==) > ? ? ? ? ? ? ? 9 RETURN_VALUE > > As you can see, there is no explicit type test. (There may or may not be > an _implicit_ type test, buried deep in the Python implementation of the > COMPARE_OP operation, but that is neither here nor there.) > > Also, since bool is a subclass of int, we can do this: > > >>> 1.0+0j == ?True > > True > > > Actually, it's this statement that's non-sensical. > > > > > "if arg==True" tests whether the object known as arg is equal to the > > object known as True. > > > > Not at all, it makes perfect sense. X == Y always tests whether the > argument X is equal to the object Y regardless of what X and Y are. Except for the exceptions, that's why the statement is wrong. > > > None of these four examples are "equal" to any other. > > That's actually wrong, as you show further down. No, it's not, as I show further down. > > > > > > >>>> a = 1 > >>>> b = (1,) > >>>> c = [1] > >>>> d = gmpy.mpz(1) > > >>>> type(a) > > > >>>> type(b) > > > >>>> type(c) > > > >>>> type(d) > > > >>>> a==b > > False > >>>> b==c > > False > >>>> a==d > > True > > See, a and d are equal. No, they are not "equal". Ints and mpzs should NEVER be used together in loops, even though it's legal. The ints ALWAYS have to be coerced to mpzs to perform arithmetic and this takes time...LOTS of it. The absolute stupidest thing you can do (assuming n is an mpz) is: while n >1: if n % 2 == 0: n = n/2 else: n = 3*n + 1 You should ALWAYS do: ZED = gmpy.mpz(0) ONE = gmpy.mpz(1) TWO = gmpy.mpz(2) TWE = gmpy.mpz(3) while n >ONE: if n % TWO == ZED: n = n/TWO else: n = TWE*n + ONE This way, no coercion is performed. > > > And yet a==d returns True. So why doesn't b==c > > also return True, they both have a 1 at index position 0? > > Why should they return true just because the contents are the same? Why should the int 1 return True when compared to mpz(1)? a = [1] b = [1] returns True for a==b? After all, it returns false if b is [2], so it looks at the content in this case. So for numerics, it's the value that matters, not the type. And this creates a false sense of "equality" when a==d returns True. > A bag > of shoes is not the same as a box of shoes, even if they are the same > shoes. Exactly. For the very reason I show above. The fact that the int has the same shoes as the mpz doesn't mean the int should be used, it has to be coerced. > Since both lists and tuples are containers, neither are strings or > numeric types, so the earlier rule applies: they are different types, so > they can't be equal. But you can't trust a==d returning True to mean a and d are "equal". To say the comparison means the two objects are equal is misleading, in other words, wrong. It only takes one turd to spoil the whole punchbowl. > > gmpy.mpz(1) on the other hand, is both a numeric type and a custom class. > It is free to define equal any way that makes sense, and it treats itself > as a numeric type and therefore says that it is equal to 1, just like 1.0 > and 1+0j are equal to 1. They are equal in the mathematical sense, but not otherwise. And to think that makes no difference is to be naive. > > -- > Steven From george.sakkis at gmail.com Wed May 23 17:08:38 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 23 May 2007 14:08:38 -0700 Subject: Parallel/distributed generator In-Reply-To: <1179948932.314833.34930@a35g2000prd.googlegroups.com> Message-ID: <1179954518.028501.159760@o5g2000hsb.googlegroups.com> On May 23, 3:35 pm, half.ital... at gmail.com wrote: > On May 23, 11:00 am, George Sakkis wrote: > > > > > I'm looking for any existing packages or ideas on how to implement the > > equivalent of a generator (in the Python sense, i.e.http://www.python.org/dev/peps/pep-0255/) in a parallel/distributed > > way. As a use case, imagine a function that generates a range of > > primes. I'd like to be able to do something along the following lines: > > > def iterprimes(start=1, end=None): > > # ... > > yield prime > > > # rpc-related initialization > > ... > > rpc_proxy = some_rpc_lib(iterprimes, start=1e6, end=1e12) > > for prime in proxy: > > print prime > > > Is there any module out there that does anything close to this ? > > > George > > Parellel Python? > > http://www.parallelpython.com/content/view/17/31/#SUM_PRIMES > > I've never used it, but looks like it does what you are looking for. Looked promising, until I saw that it requires you to pass explicitly the dependent functions and the modules to be imported for the callable to work. I guess this has to be done recursively for all the dependent functions/modules, which is impractical for anything but toy examples. George From john at datavoiceint.com Tue May 8 17:38:41 2007 From: john at datavoiceint.com (HMS Surprise) Date: 8 May 2007 14:38:41 -0700 Subject: Another easy pair of questions In-Reply-To: <4640E7A1.7000902@v.loewis.de> References: <1178655556.202998.241870@e65g2000hsc.googlegroups.com> <4640E7A1.7000902@v.loewis.de> Message-ID: <1178660320.967603.160860@y80g2000hsf.googlegroups.com> > Press the cursor-up key. > > Martin Should have mentioned that I tried that hunting around earlier and it did not work. jh From aleax at mac.com Sun May 13 14:56:34 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 13 May 2007 11:56:34 -0700 Subject: Dynamic subclassing ? References: <1178976888.443891.116090@y80g2000hsf.googlegroups.com> <1hy0dfh.1d8mafv1fwburaN%aleax@mac.com> <1179043374.090262.50880@h2g2000hsg.googlegroups.com> Message-ID: <1hy1vnf.1ksfv5v1oj2vc1N%aleax@mac.com> manatlan wrote: ... > > def addaclass(aninst, onemoreclass): > > aninst.__class__ = type(aninst.__aclass__.__name__, > > (aninst.__aclass__, onemoreclass), {}) ... > b=gtk.Button("the_label") > addaclass(b,MoreMethods) ... > "TypeError: __class__ assignment: only for heap types" > on the last line ... Ah, yes, a type can be coded in such a way that you simply can't reassign the __class__ of its instances, and apparently gtk.Button is coded that way. If you're keen on __class__ reassigning, you'll have to wrap such classes before instance creation time, e.g.: class weirdGtkButton(gtk.Button): pass and use b = weirdGtkButton("the label") to generate the instances. That, of course, assumes that gtk.Button isn't ALSO coded in ways that impede subclassing (as for all I know it might be -- I don't have GTK around to check), in which case instead of subclassing it you need a trickier wrap-and-hold approach (and you can never pass isinstance checks, which subclassing would let you pass). Alex From wise.of.clean789 at gmail.com Fri May 11 17:57:21 2007 From: wise.of.clean789 at gmail.com (wise.of.clean789 at gmail.com) Date: 11 May 2007 14:57:21 -0700 Subject: OMG BRITNEYS AT IT AGAIN AGAIN!!!!!! Message-ID: <1178920641.280005.221690@p77g2000hsh.googlegroups.com> http://britneyboobs.blogspot.com/2007/05/britney-spears-slips-up-again-exposes.html - Exclusive pics of Britney Spears...... From paul at boddie.org.uk Fri May 4 21:15:17 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 4 May 2007 18:15:17 -0700 Subject: Microsoft's Dynamic Languages Runtime (DLR) In-Reply-To: <1178318039.527265.197770@e65g2000hsc.googlegroups.com> References: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> <1178151313.421106.43130@o5g2000hsb.googlegroups.com> <1178151574.302703.205560@l77g2000hsb.googlegroups.com> <1178296035.993859.183720@n59g2000hsh.googlegroups.com> <1178313159.059210.97560@y80g2000hsf.googlegroups.com> <1178315641.763473.168290@h2g2000hsg.googlegroups.com> <1178317722.669477.260070@y80g2000hsf.googlegroups.com> <1178318039.527265.197770@e65g2000hsc.googlegroups.com> Message-ID: <1178327717.762994.243660@y80g2000hsf.googlegroups.com> Fuzzyman wrote: > On May 4, 11:28 pm, Paul Boddie wrote: > > Despite the permissive licences - it'd be hard to slap a > > bad EULA on IronPython now - the whole thing demonstrates Microsoft's > > disdain for open standards as usual, > > How do you work that out? It seems like a very positive move from > them. Well, I don't think the W3C have been *particularly* effective in defining updated but still relevant standards and bringing them to my particular part of the big developer table of late, but I think the different open standards (XHTML, CSS, SVG and so on) have some mileage in them yet. I'd rather see moderately slow improvement to those standards than have some break-out group of vested interests (eg. WHATWG, Microsoft, Adobe) define some pseudo-standard that is even more tightly bound to their pet implementations than some of the stuff that gets a W3C blessing (which is how some people could perceive the W3C standards process). A permissive licence on the DLR technologies may be positive, but a cursory inspection of Microsoft's site doesn't reveal much in a similar vein for the Silverlight technologies. At least technologies like XUL (which is itself "standards-polluting" if used to deliver Web applications to the wider public) are the product of an open development process and have first-class open source implementations. Still, I'm a cynic about a lot of add-ons to the Web, and I think Sean McGrath makes a valid point: http://seanmcgrath.blogspot.com/2007_04_29_seanmcgrath_archive.html#9180786898079500068 Usability isn't always about duplicating the desktop paradigm in a browser window or encouraging the proliferation of "cool" but closed technologies which may reveal the glory of an application's "rich" user experience to those with the latest Microsoft updates, but which excludes other users for no good reason. > As for SilverLight, there will probably be a fully open implementation > by the end of the year. We'll see. It may depend on how well the Mono people can play catch-up with Microsoft, but given the sprinkling of potentially optional but undoubtedly patented technologies (WMA, MP3, and various others, I imagine), I doubt that "fully open" will ever really apply to any implementation. Paul From harvey.thomas at informa.com Tue May 22 11:23:56 2007 From: harvey.thomas at informa.com (harvey.thomas at informa.com) Date: 22 May 2007 08:23:56 -0700 Subject: xml.dom.minidom: how to preserve CRLF's inside CDATA? In-Reply-To: <1179841504.782279.86490@u36g2000prd.googlegroups.com> References: <1179841504.782279.86490@u36g2000prd.googlegroups.com> Message-ID: <1179847436.108684.195390@y2g2000prf.googlegroups.com> On May 22, 2:45 pm, "sim.sim" wrote: > Hi all. > i'm faced to trouble using minidom: > > #i have a string (xml) within CDATA section, and the section includes > "\r\n": > iInStr = '\n \nEND:VCALENDAR\r\n]]>\n' > > #After i create DOM-object, i get the value of "Data" without "\r\n" > > from xml.dom import minidom > iDoc = minidom.parseString(iInStr) > iDoc.childNodes[0].childNodes[0].data # it gives u'BEGIN:VCALENDAR > \nEND:VCALENDAR\n' > > according tohttp://www.w3.org/TR/REC-xml/#sec-line-ends > > it looks normal, but another part of the documentation says that "only > the CDEnd string is recognized as markup":http://www.w3.org/TR/REC-xml/#sec-cdata-sect > > so parser must (IMHO) give the value of CDATA-section "as is" (neither > both of parts of the document do not contradicts to each other). > > How to get the value of CDATA-section with preserved all symbols > within? (perhaps use another parser - which one?) > > Many thanks for any help. You will lose the \r characters. From the document you referred to """ This section defines some symbols used widely in the grammar. S (white space) consists of one or more space (#x20) characters, carriage returns, line feeds, or tabs. White Space [3] S ::= (#x20 | #x9 | #xD | #xA)+ Note: The presence of #xD in the above production is maintained purely for backward compatibility with the First Edition. As explained in 2.11 End-of-Line Handling, all #xD characters literally present in an XML document are either removed or replaced by #xA characters before any other processing is done. The only way to get a #xD character to match this production is to use a character reference in an entity value literal. """ From fred at adventistcare.org Mon May 21 15:46:47 2007 From: fred at adventistcare.org (Sells, Fred) Date: Mon, 21 May 2007 15:46:47 -0400 Subject: Python Web Programming - looking for examples of solidhigh-tr affic sites Message-ID: I just started using flex (flex.org) from Adobe for the front end and am quite amazed at what it can do. Good docs. Clean client/server api if you like xml. It's relatively new so you still have to turn over some rocks and kiss some frogs to figure out how to get exactly the behavior you want in some cases. of couse the end result is that you're running flash on the client, but if you don't use the extensive special effects, you may be ok. If flash is politically correct, you don't have to worry about server variants. Still use python on the server side. I might even consider writing python classes to generate their Message-ID: In <4640ca5b$0$23392$c3e8da3 at news.astraweb.com>, John Salerno wrote: > I have a large list of publication citations that are numbered. The > numbers are simply typed in with the rest of the text. What I want to do > is remove the numbers and then put bullets instead. Now, this alone > would be easy enough, with a little Python and a little work by hand, > but the real issue is that because of the way these citations were > typed, there are often line breaks at the end of each line -- in other > words, the person didn't just let the line flow to the next line, they > manually pressed Enter. So inserting bullets at this point would put a > bullet at each line break. > > So I need to remove the line breaks too, but of course not *all* of them > because each reference still needs a line break between it. So I'm > hoping I could get an idea or two for approaching this. I figure regular > expressions will be needed, and maybe it would be good to remove the > line breaks first and *not* remove a line break that comes before the > numbers (because that would be the proper place for one), and then > finally remove the numbers. I think I have vague idea how the input looks like, but it would be helpful if you show some example input and wanted output. Ciao, Marc 'BlackJack' Rintsch From insights123 at yahoo.com Tue May 8 19:04:14 2007 From: insights123 at yahoo.com (ralph lewis) Date: Tue, 8 May 2007 16:04:14 -0700 (PDT) Subject: USA VISA USA STUDENT VISA USA H1B VISA Jobs With VISA Sponsorship, USA VISA immigration, USA VISA Sponsorship, USA VISA Message-ID: <349025.15415.qm@web30902.mail.mud.yahoo.com> Feel free to add to your list: Seeking a USA Job? Do you want to know which USA employers/companies sponsor H1B work visa applicants? Download more than 65,000 new H1B visa employer/sponsor listings at http://www.insights123.com/visa.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From erikwickstrom at gmail.com Wed May 30 15:05:38 2007 From: erikwickstrom at gmail.com (erikcw) Date: 30 May 2007 12:05:38 -0700 Subject: Trying to render a pie chart Message-ID: <1180551938.887170.26950@q66g2000hsg.googlegroups.com> HI all, I'm trying to use Matplotlib to render a pie chart for a django site I'm working on. I can't figure out how to get rid of the grey background, or make the dimensions square (it's getting stretched). Here is the code: def oldchart(request): from PIL import Image as PILImage from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure from StringIO import StringIO fig = Figure() canvas = FigureCanvas(fig) ax = fig.add_subplot(111) #ax.plot([1,2,3]) labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' fracs = [15,30,45, 10] ax.pie(fracs, labels=labels) #ax.set_title('hi mom') ax.grid(True) #ax.set_xlabel('time') #ax.set_ylabel('volts') canvas.draw() size = canvas.get_renderer().get_canvas_width_height() buf=canvas.tostring_rgb() im=PILImage.fromstring('RGB', size, buf, 'raw', 'RGB', 0, 1) imdata=StringIO() im.save(imdata, format='JPEG') response = HttpResponse(imdata.getvalue(), mimetype='image/jpeg') return response Thanks for your help! Erik From malaclypse2 at gmail.com Fri May 11 09:12:34 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 11 May 2007 09:12:34 -0400 Subject: module error for elementtree In-Reply-To: <1178867119.666923.204000@h2g2000hsg.googlegroups.com> References: <1178867119.666923.204000@h2g2000hsg.googlegroups.com> Message-ID: <16651e80705110612h299308d9q508d7d88a01d6a24@mail.gmail.com> On 11 May 2007 00:05:19 -0700, saif.shakeel at gmail.com wrote: > For the above code to work elementtree is > imported in first line ,but when running it says : > ImportError: No module named elementtree.ElementTree > Does thie module exists as default or a patch is needed? That depends on which version of Python you are running. Starting with 2.5, ElementTree was moved into the standard library, as part of the xml package. If you're using an older version of python, I think you'll need to download and install the elementtree package from http://effbot.org/zone/element-index.htm Assuming you're using python 2.5, you probably want something like this: from xml.etree.ElementTree import ElementTree as et -- Jerry From NikitaTheSpider at gmail.com Wed May 30 23:09:56 2007 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Wed, 30 May 2007 23:09:56 -0400 Subject: calling Postgresql stored procedure References: <1180516688.022056.70220@q69g2000hsb.googlegroups.com> Message-ID: In article <1180516688.022056.70220 at q69g2000hsb.googlegroups.com>, Alchemist wrote: > I am using Python 2.4 and Postgresql 8.2 database server. > > On the database I have created a stored function, example, > CREATE OR REPLACE FUNCTION calculateaverage() > > I created a new python script and would like to call my database > stored function. > > How can I call a database stored function/procedure in python? You need a layer in between Python and Postgres so that they can talk to one another. If you don't have one, try this one (use version 2, not version 1.x): http://www.initd.org/tracker/psycopg Good luck -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From warren at muse.com Thu May 31 21:39:06 2007 From: warren at muse.com (Warren Stringer) Date: Thu, 31 May 2007 18:39:06 -0700 Subject: c[:]() In-Reply-To: References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> <135tobve86qj808@corp.supernews.com> <135tru124pie2b3@corp.supernews.com> <135tv1bjqgbmsc9@corp.supernews.com> <003301c7a3ab$f2bdf960$240110ac@Muse> <001801c7a3cc$e9f0b270$240110ac@Muse> Message-ID: <001a01c7a3ed$a49c93d0$240110ac@Muse> > > What?!? I started this thread. > > > No you didn't. Your original post was a reply to a message whose subject > line was 'Re: "is" and ==', and included the header > > In-Reply-To: <1180504773.374529.161740 at q66g2000hsg.googlegroups.com> You're right, thanks. > >> I think the fundamental mistake you have made is to convince yourself > that > >> > >> c[:]() > >> > >> is legal Python. It isn't, it never has been. In my opinion, it is better to ask me directly what I think than to assume what I am thinking. Describing a situation in second person -- using "you" -- tends to have more interpretation than fact. When the interpretation is wrong, the person who is at the receiving end of that "you" may be compelled to reply. Sometimes that correction includes another "you"; interpretation spawns interpretation -- soon, facts are replaced by projectiles. > > > > In summation: > > I started this thread asking why c[:]() wouldn't work > > I did not hijack another thread > > I posted working examples (with one typo, not quoted here) > > I am extremely annoyed by this post > > > > Tis best not to assume what other people are thinking > > > Probably best not to try to help them too, if this is the response. I do appreciate your help. Responding on topic helps. Negative feedback regarding typos helps. And, your statement: > Perhaps you didn't express yourself too clearly. makes me feel all warm and fuzzy like ... why thank you! > Next > time you want assistance try to ensure that you copy and paste your > examples instead of trying to duplicate them from memory. Agreed. Fortunately, others got the gist of what I was saying. Oddly enough, as annoying as it was, your post helped my form, while other posters have helped my content. I bet you'd make a good editor. Cheers, \~/ From gagsl-py2 at yahoo.com.ar Thu May 3 23:25:30 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 04 May 2007 00:25:30 -0300 Subject: adding methods at runtime and lambda References: <1178221975.149008.192410@y5g2000hsa.googlegroups.com> Message-ID: En Thu, 03 May 2007 16:52:55 -0300, Mike escribi?: > I was messing around with adding methods to a class instance at > runtime and saw the usual code one finds online for this. All the > examples I saw say, of course, to make sure that for your method that > you have 'self' as the first parameter. I got to thinking and thought > "I have a lot of arbitrary methods in several utility files that I > might like to add to things. How would I do that?" And this is what I > came up with: I don't see the reason to do that. If you have a function that does not use its "self" argument, what do you get from making it an instance method? If -for whatever strange reason- you want it to actually be a method, use a static method: py> def foo(x): ... print "I like %r" % x ... py> class A(object): pass ... py> a = A() py> A.foo = staticmethod(foo) py> a.foo() Traceback (most recent call last): File "", line 1, in TypeError: foo() takes exactly 1 argument (0 given) py> a.foo("coffee") I like 'coffee' py> A.foo("tea") I like 'tea' -- Gabriel Genellina From steve at holdenweb.com Wed May 16 16:05:03 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 16 May 2007 16:05:03 -0400 Subject: Execute commands from file In-Reply-To: <464b370c$0$3808$5402220f@news.sunrise.ch> References: <1179320782.594398.67980@u30g2000hsc.googlegroups.com> <464b370c$0$3808$5402220f@news.sunrise.ch> Message-ID: Martin Blume wrote: > "tmp123" schrieb > >> We have very big files with python commands >> (more or less, 500000 commands each file). >> >> It is possible to execute them command by command, > > inp = open(cmd_file) > for line in inp: > exec line > > might help. You don't get quite the same feeling as > "like if the commands was typed one after the other > in a interactive session", but perhaps this helps. > > Warning: the code above is without any error checks. > You might also run into security problems, the example > above assumes you trust your input. > > HTH. YMMV. > Martin > The problem with this approach is that each line executes without any connection to the environment created by previous lies. Try it on a file that reads something like xxx = 42 print xxx and you will see NameError raised because the assignment hasn't affected the environment for the print statement. 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From ceball at gmail.com Wed May 9 03:25:35 2007 From: ceball at gmail.com (Chris) Date: 9 May 2007 00:25:35 -0700 Subject: Strange terminal behavior after quitting Tkinter application In-Reply-To: References: <1178440794.659370.47230@y5g2000hsa.googlegroups.com> Message-ID: <1178695535.804766.175430@e65g2000hsc.googlegroups.com> On May 7, 10:02 pm, "Hamilton, William " wrote: > > From: Chris > > > I'll admit to being surprised at seeing a claim that atkinter > > > application, started within an interactive session, without a > mainloop, > > > even runs... I could see it maybe happening from Idle, since Idle is > > > running atkintermainloop, so the application bindings may have > just > > > become "added widgets" to the Idle loop (but of course, a second > > > mainloop would conflict heavily). > > > You can try by building a workingTkinterGUI interactively from the > > standard Python interpreter, and see that the GUI works (i.e. > > processes events) at the same time. > > If you build it as a class (such as the code in Chris's original post) > it works; if you do it all directly, nothing happens until you run > mainloop(). It works, but I'm not sure that it was intended to work > that way. I think your problem is related to that difference. Do you have any idea where I should go to find out the differences between using mainloop() and not using it? So far I have found this quitting problem (which does not occur on all platforms), and the need to call update() or update_idletasks() after some operations, but no others. > You'll probably be better off creating a new interpreter window as part > of your program, if you really need access to the interpreter alongside > your GUI. You may be able to extract IDLE's interpreter window and use > it directly. I really do need access to the interpreter alongside the GUI in my real program*, since the GUI cannot really offer all the functionality of the command line (or is a long way from doing so...). I do offer simple access to the interpreter in my gui (via code.InteractiveConsole and a text widget, but I agree with the author of the comp.lang.python posting "Has anybody made a Tkinter text widget into a terminal emulator?" (http://groups.google.com/group/ comp.lang.python/browse_thread/thread/a3f223f563205156/ fc729e1de51ca2dc): it's a shame to force people to use a particular editor. I don't know if she found a solution; I haven't found anything reasonable yet. Thanks * Actually it's not my program, it's an open-source software package for modelling neural maps: topographica.org. The GUI code is being reorganized. From kyosohma at gmail.com Wed May 9 09:03:07 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 9 May 2007 06:03:07 -0700 Subject: Specification for win32com.client package In-Reply-To: References: <23617.87850.qm@web63415.mail.re1.yahoo.com> Message-ID: <1178715787.220103.245060@e65g2000hsc.googlegroups.com> On May 8, 7:34 am, Tim Golden wrote: > Peter Fischer wrote: > > Hello Tim, > > > thank you for your answer and sorry for the multiple e-mails. Thank you also for > > the hint on the book. I already read into it in our local library. Its good, but a > > little outdated (Jan. 2000) as I mentioned in > > >http://mail.python.org/pipermail/python-list/2007-May/438800.html > > Ah, yes. Didn't spot that. Although the book is outdated, > so is COM! It's been around in pretty much its present > format for wasily as long as that. > > > Do you know, whether something has changed, since the book was written, in > > the use of the dcomcnfg tool? > > I wouldn't know, but I doubt it; it looks pretty > old-fashioned to me. Worth checking some microsoft newsgroups. > > > I am not clear what steps are necessary under today's WinXP Professional > > to get DCOM run. But it is said that it shouldn't be difficult. > > Certainly I've got no problem running simple stuff. My main > area of expertise - WMI - uses it under the covers and it > only gives me problems when there's security involved. > > > One short question back to the documentation: I read that 'makepy' could be > > helpful to generate documentation to the package? > > AFAIK, makepy's got nothing to do with the pywin32 docs. It > can be used to generate a proxy Python module for an > existing COM package, eg: > > > from win32com.client import gencache > xl = gencache.EnsureDispatch ("Excel.Application") > > # > # Behind the scenes this has called makepy to generate > # a module which on my machine is under > # c:\python24\lib\site-packages\win32com\gen_py > # > > help (xl.__class__) > > > > Sorry I can't be more help. I know Mark Hammond follows > the python-win32 list; I don't know if he follows the > main Python list, so it might be worth posting to > python-win32. > > TJG The win32com module seems to get short shrift, which I could say about a lot of the win32 modules and other 3rd party modules in general. However, I have found the following pages helpful for Python and COM: http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/pywin32/html/com/win32com/HTML/docindex.html http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/pywin32/html/win32/help/process_info.html#pythoncom And this is good for just general info on win32: http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/pywin32/win32_modules.html The wiki idea sounds like a good one. I was thinking about doing some kind of Python site about the modules and I think the popular 3rd party ones would be a good place to start, maybe starting with win32. How much information do you think would need to be on a site like this to start out with? Mike From showell30 at yahoo.com Sun May 27 11:04:21 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 27 May 2007 08:04:21 -0700 (PDT) Subject: Is PEP-8 a Code or More of a Guideline? In-Reply-To: Message-ID: <236537.94503.qm@web33503.mail.mud.yahoo.com> --- Gabriel Genellina wrote: > > Underscores are not always easily available on non > us-layout keyboards, > like \ and @ and many other "special" characters. A > language that requires > more symbols than the 26 english letters has to make > room somewhere - > keyboards usually have "only" 102 keys (or 105 > nowadays). > Back to the style, I think that mixedCaseIsEnough to > Regarding the US keyboard, if you like chess: 1) The right pinkie normally sits on the semicolon, and if you shift it, you get a colon. 2) Typing the "P" character is like moving a pawn up one square (while shifting with the left). 3) Typing the "[" and "{" is like capturing with the pawn (one up, one over). 4) Typing the "_" is like moving the knight (two up, one over), as are typing the "]" an "}" (one up, two over). ____________________________________________________________________________________ No need to miss a message. Get email on-the-go with Yahoo! Mail for Mobile. Get started. http://mobile.yahoo.com/mail From james.b.looney at lmco.com Tue May 8 18:43:21 2007 From: james.b.looney at lmco.com (Looney, James B) Date: Tue, 08 May 2007 16:43:21 -0600 Subject: Using os.popen and os.chdir together In-Reply-To: References: Message-ID: ok, nevermind. My coworker pointed out part of what's wrong. Guess I'll need to do more spelunking in my script to figure out what I'm messing up. -JB ________________________________ From: python-list-bounces+james.b.looney=lmco.com at python.org [mailto:python-list-bounces+james.b.looney=lmco.com at python.org] On Behalf Of Looney, James B Sent: Tuesday, May 08, 2007 4:17 PM To: python-list at python.org Subject: Using os.popen and os.chdir together Within a script on a *nix machine, I use os.chdir then os.popen, and it appears to me as though the os.chdir had no effect so far as the os.popen is concerned. Why's that? Here's what I'm doing: >>> import os >>> os.path.realpath( os.curdir ) '/home/jlooney' >>> print os.popen( "echo $PWD" ).readlines() ['/home/jlooney\n'] >>> >>> os.chdir( "/tmp" ) >>> os.path.realpath( os.curdir ) '/tmp' >>> print os.popen( "echo $PWD" ).readlines() ['/home/jlooney\n'] >>> You'll notice that initially, the current paths are the same, and correct. After I call os.chdir, and try os.popen, it's not in the new directory. When I do other things like creating new files, the chdir did exactly what I expected. What I don't understand is why os.popen appears to be special? How do I change directories within a script and have popen see that change? -JB -------------- next part -------------- An HTML attachment was scrubbed... URL: From mike4ty4 at yahoo.com Fri May 4 04:29:19 2007 From: mike4ty4 at yahoo.com (mike3) Date: 4 May 2007 01:29:19 -0700 Subject: Firefighters at the site of WTC7 "Move away the building is going to blow up, get back the building is going to blow up." In-Reply-To: <1178207619.155007.129860@o5g2000hsb.googlegroups.com> References: <1178161820.731367.264500@y80g2000hsf.googlegroups.com> <1178163974.007362.13870@c35g2000hsg.googlegroups.com> <1178172877.755445.101340@q75g2000hsh.googlegroups.com> <1178173090.238547.62190@o5g2000hsb.googlegroups.com> <1178207619.155007.129860@o5g2000hsb.googlegroups.com> Message-ID: <1178267359.630392.252740@l77g2000hsb.googlegroups.com> On May 3, 9:53 am, malibu wrote: > On May 3, 12:18 am, Eric Gisse wrote: > > > > > > > On May 2, 10:14 pm, malibu wrote: > > > > On May 2, 9:46 pm, Eric Gisse wrote: > > > > > On May 2, 7:10 pm, Midex wrote: > > > > > [...] > > > > > I guess the explanation that people were looking at the building and > > > > watching its' structure deform is too rational. > > > > Also, that was a Larry Silverstein impostor who > > > said they were going to 'pull it'. > > > ...maybe if you read the context, it would make a little more rational > > sense. Fucking nutter. > > > > And the only reason he took out huge amounts > > > of extra insurance on the buildings two months > > > before this happened was because of global > > > warming, because we all know a little bit of heat > > > will bring down steel buildings. > > > A little heat and major structural damage. > > > > John > > Gee, I'll bet all those explosions in the > subfloors of WTC1 + WTC2 did some > structural damage also! > > Come to think of it. > > When the firefighters got there, all the glass > on the street floors was blown out. > > Shock wave from the plane hitting > 80 floors up? > > Janitors and such coming up from the basement levels > bleeding and dazed. > > Jet fuel trickling down the elevator shafts being ignited > by someone's roach? And exploding? > Severing the three-foot thick steel columns? > All 5 dozen of them? > (That's mighty fine primo, pardner!) > > Your brain got structural damage? > Dropped on your head as a kid? > > Don't put that fire iron too close > to the flames, honey. It'll melt > and deform! > Never mind that the irons in the WTC were IN the fire, amongst the coals no less! From shirishag75 at gmail.com Tue May 1 03:16:37 2007 From: shirishag75 at gmail.com (shirish) Date: 1 May 2007 00:16:37 -0700 Subject: Python+Pygame+PyopenGL all in one package? Message-ID: <1178003796.998338.57140@y5g2000hsa.googlegroups.com> Hi all, Is it possible to have Python+Pygame+PyOpenGL in one compact package so people can play the games released at pyweek.org . I have been having a hard time getting the whole thing on windows as well as linux (Ubuntu 7.04) . Strangely, my pleas for the same on pyopengl have gone unanswered. http://sourceforge.net/mailarchive/forum.php?thread_name=511f47f50704260036y2888db21p5cf650a7e472559b%40mail.gmail.com&forum_name=pyopengl-users as well as http://sourceforge.net/mailarchive/forum.php?thread_name=511f47f50704260243i2b05d595rc7fc0496531f5871%40mail.gmail.com&forum_name=pyopengl-users Even wikipedia doesn't know much about PyOpenGL except for the fact it is a package which allows the 3D redering using python. I'm an end-user hence would like to know from some experienced people if they see any way forward or not. Cheers ! From jstroud at mbi.ucla.edu Wed May 16 21:33:02 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 16 May 2007 18:33:02 -0700 Subject: remove all elements in a list with a particular value In-Reply-To: <1179330068.785878.181980@n59g2000hsh.googlegroups.com> References: <1179328873.105705.95580@l77g2000hsb.googlegroups.com> <1179330068.785878.181980@n59g2000hsh.googlegroups.com> Message-ID: John Zenger wrote: >>>>print [x for x in items if x != ''] > > ['SRCPARAM', '1', '6.35e-07', '15.00', '340.00', '1.10', '3.0'] > This can be shortened to [x for x in items if x] James From Bulkan at gmail.com Thu May 17 08:34:55 2007 From: Bulkan at gmail.com (placid) Date: 17 May 2007 05:34:55 -0700 Subject: Sending a JavaScript array to Python script? Message-ID: <1179405295.865954.241740@e65g2000hsc.googlegroups.com> Hi All, Just wondering if there is any way of sending a JavaScript array to a Python cgi script? A quick Google search didn't turn up anything useful. Any help appreciated. Cheers From steve at holdenweb.com Thu May 17 20:39:44 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 17 May 2007 20:39:44 -0400 Subject: Error on FTP Upload .. No such file or directory In-Reply-To: <9E0CC1A9D55BE54CAD39E562649F1716038DA37F@wscmmail.wscm.corp> References: <9E0CC1A9D55BE54CAD39E562649F1716038DA37F@wscmmail.wscm.corp> Message-ID: Tarun Kapoor wrote: > By the way... > > test.txt does exist > > Disclaimer > > This e-mail and any attachments is confidential and intended solely for the use of the individual(s) to whom it is addressed. Any views or opinions presented are solely those of the author and do not necessarily represent those of Waterstone Capital Management, L.P and affiliates. If you are not the intended recipient, be advised that you have received this e-mail in error and that any use, dissemination, printing, forwarding or copying of this email is strictly prohibited. Please contact the sender if you have received this e-mail in error. You should also be aware that e-mails are susceptible to interference and you should not assume that the contents of this e-mail originated from the sender above or that they have been accurately reproduced in their original form. Waterstone Capital Management, L.P. and affiliates accepts no responsibility for information, or errors or omissions in t > his e-mail or use or misuse thereof. If in doubt, please verify the authenticity with the! > sender. > > It looks like a permissions error from the message (I haven't dug into the library code, which you can do relatively easily - the Python is there if you want to read it, and the traceback tells you which file to look in). Maybe there's a non-deletable test.txt on the server already? 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 your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From timr at probo.com Thu May 24 02:06:10 2007 From: timr at probo.com (Tim Roberts) Date: Thu, 24 May 2007 06:06:10 GMT Subject: Lists vs tuples (newbie) References: Message-ID: Neil Cerutti wrote: > >I use tuples simply because of their mellifluous appellation. +1 QOTW. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From stefan.behnel-n05pAM at web.de Wed May 16 04:36:01 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 16 May 2007 10:36:01 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649BC4C.10200@web.de> <4649D32F.4010209@web.de> Message-ID: <464AC271.5090304@web.de> Eric Brunel wrote: > reason why non-ASCII identifiers should be supported. I just wish I'll > get a '--ascii-only' switch on my Python interpreter (or any other means > to forbid non-ASCII identifiers and/or strings and/or comments). I could certainly live with that as it would be the right way around. Support Unicode by default, but allow those who require the lowest common denominator to enforce it. Stefan From arnodel at googlemail.com Sat May 12 12:48:50 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 12 May 2007 09:48:50 -0700 Subject: Basic question In-Reply-To: <1178986686.510137.195490@p77g2000hsh.googlegroups.com> References: <1178986686.510137.195490@p77g2000hsh.googlegroups.com> Message-ID: <1178988530.815766.261700@e51g2000hsg.googlegroups.com> On May 12, 5:18 pm, "Cesar G. Miguel" wrote: > I've been studying python for 2 weeks now and got stucked in the > following problem: > > for j in range(10): > print j > if(True): > j=j+2 > print 'interno',j > > What happens is that "j=j+2" inside IF does not change the loop > counter ("j") as it would in C or Java, for example. > > Am I missing something? Yes you are :) "for j in range(10):..." means: 1. Build a list [0,1,2,3,4,5,6,7,8,9] 2. For element in this list (0, then 1, then 2,...), set j to that value then execute the code inside the loop body To simulate "for(; ; ) " you have to use while in Python: while : Of course in most case it would not be the "pythonic" way of doing it :) -- Arnaud From researchbase at gmail.com Mon May 7 13:08:21 2007 From: researchbase at gmail.com (krishnakant Mane) Date: Mon, 7 May 2007 22:38:21 +0530 Subject: Latest errors on pickled objects and blob datatypes in mysql Message-ID: hello, finally the errors for my sql query have changed so I have even changed the thread subject because I feel now that this is not doable in mysql and this seams to be a bug, ither in python or the MySQLdb module or perhaps both. my table is called testobj and the blob field is called obj. now following is my query with the cursor named CSRInsert. CSRInsert.execute("insert into testobj (obj) values (?);",(pickled_object)) the error is, "type error, not all arguments formatted during string formatting ". can some one now figure out what could be the problem? From nagle at animats.com Fri May 18 14:21:04 2007 From: nagle at animats.com (John Nagle) Date: Fri, 18 May 2007 11:21:04 -0700 Subject: Python Web Programming - looking for examples of solid high-traffic sites In-Reply-To: References: <1179349457.448713.62860@q75g2000hsh.googlegroups.com> <1hy9yf9.1nnsttj139za6bN%aleax@mac.com> <1hyarxo.iqtdo1v9qpivN%aleax@mac.com> Message-ID: John Nagle wrote: > YouTube's home page is PHP. Try "www.youtube.com/index.php". > That works, while the obvious alternatives don't. > If you look at the page HTML, you'll see things like > > onclick="_hbLink('LogIn','UtilityLinks');">Log In > > So there's definitely PHP inside YouTube. Not sure; that "next" field is just the URL of the page you're on, inserted into the output HTML. It's "index.php" because the page was "index.php". But it's an Apache server, with all the usual Apache messages. John Nagle From jstroud at mbi.ucla.edu Wed May 23 20:21:47 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 23 May 2007 17:21:47 -0700 Subject: Call script which accepts com. line par. from another script and error control In-Reply-To: References: Message-ID: Karim Ali wrote: > def MAIN(expression2parse) <----- add a main so can > call from other script Of course you don't mean you want another python interpreter to fire up and run the other script? Here is an example of the way to do what you are suggesting: # mod1.py def doit(param): if not param % 37: raise ValueError, 'Why u want to do dat?' else: print 'All right!' return 'Value is: %s' % param # end of mod1.py # mod2.py import mod1 print mod1.doit(20) print print mod1.doit(30) print try: print mod1.doit(37) except ValueError: print 'Gracefully handling 37....' print print mod1.doit(37) # end of mod2 James From jstroud at mbi.ucla.edu Wed May 16 18:08:07 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 16 May 2007 15:08:07 -0700 Subject: How do I tell the difference between the end of a text file, and an empty line in a text file? In-Reply-To: <134mvk7r3e7k55@corp.supernews.com> References: <1179352021.803070.200780@k79g2000hse.googlegroups.com> <134mvk7r3e7k55@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2007-05-16, walterbyrd wrote: > > >>Python's lack of an EOF character is giving me a hard time. > > > No it isn't. > > >>s = f.readline() >>while s: >>. >>. >>s = f.readline() > > > > >>s = f.readline() >>while s != '' >>. >>. >>s = f.readline() > > > > Neither one of your examples is legal Python. Please post real > code. > > >>In both cases, the loop ends as soon it encounters an empty line in >>the file, i.e. > > > No, it doesn't. Not if you've done something reasonable like > this: > > f = open('testdata','r') > while True: > s = f.readline() > if not s: break > print repr(s) > > or this: > > f = open('testdata','r') > s = f.readline() > while s: > print repr(s) > s = f.readline() > > Please post real, runnable code. You've done something wrong > and we've no way to guess what it was if you won't show us your > code. > I'm guessing it was runnable when he pasted it into google groups. James From rampeters at gmail.com Mon May 7 22:07:09 2007 From: rampeters at gmail.com (johnny) Date: 7 May 2007 19:07:09 -0700 Subject: How to make Python poll a PYTHON METHOD Message-ID: <1178590029.225298.195430@y80g2000hsf.googlegroups.com> Is there a way to call a function on a specified interval(seconds, milliseconds) every time, like polling user defined method? Thanks. From zzbunker at netscape.net Tue May 1 00:00:04 2007 From: zzbunker at netscape.net (zzbunker at netscape.net) Date: 30 Apr 2007 21:00:04 -0700 Subject: Video: Professor of Physics Phd at Cal Tech says: 911 Inside Job In-Reply-To: <1177467203.719625.93920@u32g2000prd.googlegroups.com> References: <1177467203.719625.93920@u32g2000prd.googlegroups.com> Message-ID: <1177992004.066809.266280@o5g2000hsb.googlegroups.com> On Apr 24, 10:13 pm, stj... at rock.com wrote: > Cal Tech is the ELITE of ELITE in physics. > > If Feynman were alive, he would point his finger straight at the 911 > criminal operators, the yank bastards themselves ....... If Feynmann alive were he would be wrighting review crap for PBS.. Since it's quite obvious to even the most causal observer that the only thing he had the foggiet clue concerning engineering is Cal-Tech Shleppers and nano-ons. > > http://www.911blogger.com/node/8101 > > No self-respecting scientist should keep his mouth shut. Its a > fundamental challenge to the method of science, a detective work most > demanding of INTELLECTUAL HONESTY. From gagsl-py2 at yahoo.com.ar Tue May 15 00:55:59 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 15 May 2007 01:55:59 -0300 Subject: Generators in C code Message-ID: Hi I'd like to write a generator in C, callable from Python. The only way to create a generator object I can see, is using PyGen_New(frame) - and a frame object implies Python code, right? holding global state and local variables and stack and a lot of stuff, so perhaps there is no (easy) way I could write that in C code. Or perhaps some way to execute a yield statement inside a C function? Being able to resume execution at the same point later? I feel I'm out of luck, but if someone could point some way to write a generator in C, I'be very grateful! -- Gabriel Genellina From rplzqx402 at sneakemail.com Sun May 6 22:16:17 2007 From: rplzqx402 at sneakemail.com (rplzqx402 at sneakemail.com) Date: 6 May 2007 19:16:17 -0700 Subject: import conflict Message-ID: <1178504177.697440.23740@p77g2000hsh.googlegroups.com> Hello, I have a problem where I need to set up two separate Python projects that each live under the same package. Once they are distributed, they will live under the same filesystem path, but during development, they are separated. For example: proj1/lib/pkg/foo/mod1.py proj2/lib/pkg/bar/mod2.py Furthermore, proj1 is dependent on proj2, so I want to be able to say things like this, from within proj1: import pkg.foo.mod1 import pkg.bar.mod2 Of course this doesn't work, even with a PYTHONPATH configured to see both projects, because it will find 'pkg' in proj1/lib and so pkg.bar will be hidden from view. Any suggestions? Thanks! From kyosohma at gmail.com Wed May 23 11:04:19 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 23 May 2007 08:04:19 -0700 Subject: Resizing listbook's listview pane In-Reply-To: <1179859779.588679.9220@h2g2000hsg.googlegroups.com> References: <1179859779.588679.9220@h2g2000hsg.googlegroups.com> Message-ID: <1179932659.180278.72990@w5g2000hsg.googlegroups.com> On May 22, 1:49 pm, mkPyVS wrote: > I'm having an issue I need help with. I want to resize the listview > control in a listbook but have been unsuccessfull through setting the > columnWidth of the 0'th column and trying to retrieve the listbooks > sizer return's None.... Ideas? > > Thanks, Which Python gui toolkit are you using? Tkinter, wxPython, pyQT? Are you wanting the resize to happen programmatically, when the user changes the app's size, both or what? More details would be helpful. Mike From paddy3118 at googlemail.com Sat May 19 01:14:40 2007 From: paddy3118 at googlemail.com (Paddy) Date: 18 May 2007 22:14:40 -0700 Subject: converting strings to most their efficient types '1' --> 1, 'A' ---> 'A', '1.2'---> 1.2 In-Reply-To: <1179529661.555196.13070@k79g2000hse.googlegroups.com> References: <1179529661.555196.13070@k79g2000hse.googlegroups.com> Message-ID: <1179551680.283157.19000@y80g2000hsf.googlegroups.com> On May 19, 12:07 am, py_genetic wrote: > Hello, > > I'm importing large text files of data using csv. I would like to add > some more auto sensing abilities. I'm considing sampling the data > file and doing some fuzzy logic scoring on the attributes (colls in a > data base/ csv file, eg. height weight income etc.) to determine the > most efficient 'type' to convert the attribute coll into for further > processing and efficient storage... > > Example row from sampled file data: [ ['8','2.33', 'A', 'BB', 'hello > there' '100,000,000,000'], [next row...] ....] > > Aside from a missing attribute designator, we can assume that the same > type of data continues through a coll. For example, a string, int8, > int16, float etc. > > 1. What is the most efficient way in python to test weather a string > can be converted into a given numeric type, or left alone if its > really a string like 'A' or 'hello'? Speed is key? Any thoughts? > > 2. Is there anything out there already which deals with this issue? > > Thanks, > Conor You might try investigating what can generate your data. With luck, it could turn out that the data generator is methodical and column data-types are consistent and easily determined by testing the first or second row. At worst, you will get to know how much you must check for human errors. - Paddy. From mikeminer53 at hotmail.com Wed May 23 12:42:56 2007 From: mikeminer53 at hotmail.com (mkPyVS) Date: 23 May 2007 09:42:56 -0700 Subject: Resizing listbook's listview pane In-Reply-To: <1179932659.180278.72990@w5g2000hsg.googlegroups.com> Message-ID: <1179938576.662712.138820@p47g2000hsd.googlegroups.com> Sorry, copied from wxpython submit as well.. I'm using wxpython 2.8... Primariy I want the resize to happen programatically during object creation/post creation... I can worry about app size changes later. Thanks, Mike From deets at nospam.web.de Tue May 8 10:52:26 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 08 May 2007 16:52:26 +0200 Subject: Gui thread and async jobs. References: <1178627450.408287.139070@p77g2000hsh.googlegroups.com> <5abajlF2nk767U1@mid.uni-berlin.de> <1178632508.635902.187030@e65g2000hsc.googlegroups.com> Message-ID: <5abh5aF2lth8jU1@mid.uni-berlin.de> >> It depends on the toolkit you use. Qt has thread-safe custom events in >> 3.x, and afaik signal/slots (and thus events) are generally thread-safe >> in 4.x. So, no problems there. >> >> Diez > > Aha...So you do not use polling there (in Qt), correct ? You don't need to, no. Diez From claird at lairds.us Thu May 24 11:10:20 2007 From: claird at lairds.us (Cameron Laird) Date: Thu, 24 May 2007 15:10:20 +0000 Subject: Shared Memory Space - Accross Apps & Network References: <003a01c79b8a$8f1f8c30$ad5ea490$@rawlins@thinkbluemedia.co.uk> Message-ID: In article , Tim Golden wrote: . . . >PyLinda - http://www-users.cs.york.ac.uk/~aw/pylinda/ > >This implements the tuplespace paradigm. It's great >fun to use, but as far as I know this implementation >was a PhD project and lacks the robustness and wide >use of other things. That said, it works perfectly >well within its remit and might be a good match for >what you're trying to do. . . . Amen; part of Linda's charm is that it's pleasingly effective even with a simple, unmaintained implementation . From john at datavoiceint.com Wed May 9 17:43:10 2007 From: john at datavoiceint.com (HMS Surprise) Date: 9 May 2007 14:43:10 -0700 Subject: File I/O In-Reply-To: <1178746525.499358.179550@w5g2000hsg.googlegroups.com> References: <1178745198.392518.56840@q75g2000hsh.googlegroups.com> <1178746525.499358.179550@w5g2000hsg.googlegroups.com> Message-ID: <1178746990.587898.122080@y80g2000hsf.googlegroups.com> > [lst.append(list(line.split())) for line in file] Thanks, this is the direction I wanted to go, BUT I must use v2.2 so the line above gives me the error: AttributeError: __getitem__ But the write format will be helpful. Thanks again, jh From lyoshaM at gmail.com Wed May 23 15:21:29 2007 From: lyoshaM at gmail.com (Lyosha) Date: 23 May 2007 12:21:29 -0700 Subject: Inheriting from Python list object(type?) In-Reply-To: <1179947267.368622.92350@m36g2000hse.googlegroups.com> Message-ID: <1179948089.005199.37400@a26g2000pre.googlegroups.com> On May 23, 12:07 pm, Mangabasi wrote: > On May 23, 1:43 pm, "Jerry Hill" wrote: > > > > > On 23 May 2007 11:31:56 -0700, Mangabasi wrote: > > > > When I modified this to: > > > > class Point(list): > > > def __init__(self,x,y): > > > super(Point, self).__init__([x, y]) > > > self.x = x > > > self.y = y > > > > It worked. > > > Are you sure? > > > >>> p = Point(10, 20) > > >>> p > > [10, 20] > > >>> p.x > > 10 > > >>> p.x = 15 > > >>> p > > [10, 20] > > >>> p[0] > > 10 > > >>> p.x > > 15 > > > That doesn't look like what you were asking for in the original post. > > I'm afraid I don't know anything about numpy arrays or what special > > attributes an object may need to be put into a numpy array though. > > > -- > > Jerry > > This is the winner: > > class Point(list): > def __init__(self, x, y, z = 1): > super(Point, self).__init__([x, y, z]) > self.x = x > self.y = y > self.z = z [...] http://docs.python.org/dev/whatsnew/node3.html announces named tuples in python2.6. This is not what you want since tuples are immutable, but you might get some inspiration from their implementation. Or maybe not. From thorsten at thorstenkampe.de Tue May 15 09:15:07 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 15 May 2007 14:15:07 +0100 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <46477f19$0$19845$426a74cc@news.free.fr> <4648294F.2000704@web.de> <46487a6c$0$2400$426a74cc@news.free.fr> <4649a1b6$0$23131$9b4e6d93@newsspool1.arcor-online.net> <4649af35$0$10195$9b4e6d93@newsspool4.arcor-online.net> Message-ID: * Ren? Fleschenberg (Tue, 15 May 2007 15:01:42 +0200) > Thorsten Kampe schrieb: > > * Ren? Fleschenberg (Tue, 15 May 2007 14:04:07 +0200) > >> Thorsten Kampe schrieb: > >>> Because keywords are not meant meant to extended or manipulated or > >>> something similar by the programmers. Keywords are well known and only > >>> a limited set of words. That's why you can't use keywords as > >>> identifiers. > >> This is true for keywords, but not for the stdlib. Are you suggesting > >> that the stdlib should be "internationalized"? > > > > No, because it's the /Standard/ Library to be used by everyone. And > > the lowest common denominator is ASCII and English. > > This makes the argument that this PEP would allow people to write > "Chinese only" Python code invalid (unless they do not use the stdlib). It has nothing to do with that. It simply allows people to write their own identifier names with their native character set without using dodgy transcriptions (that might not even exist). There is no sense in making people write "ueber" instead of "?ber". That's 20th century thinking and archaic. From alan.franzoni_invalid at geemail.invalid Thu May 31 05:55:34 2007 From: alan.franzoni_invalid at geemail.invalid (Alan Franzoni) Date: Thu, 31 May 2007 11:55:34 +0200 Subject: c[:]() References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180504773.374529.161740@q66g2000hsg.googlegroups.com> Message-ID: <1uu1dq8fob7hp.rzbtemioe8qe$.dlg@40tude.net> Il Wed, 30 May 2007 11:48:47 -0700, Warren Stringer ha scritto: [cut] >>> c[:] is c True BTW, I couldn't understand your concern. Are you sure you really need many functions, and not just one function with different parametrs? In such a case you could just use the builtin func map() to achieve the very same result. Or you could define a function of your own like: def call_elems(iterable): for elem in iterable: elem() and just do call_elems(c) when needed. -- Alan Franzoni - Togli .xyz dalla mia email per contattarmi. Remove .xyz from my address in order to contact me. - GPG Key Fingerprint (Key ID = FE068F3E): 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From flyzone at technologist.com Fri May 11 05:19:33 2007 From: flyzone at technologist.com (Flyzone) Date: 11 May 2007 02:19:33 -0700 Subject: checking if hour is between two hours Message-ID: <1178875173.605061.205120@y5g2000hsa.googlegroups.com> Hi all, i'm again working on my script of parsing logfiles :) I putted a new function to disable the rule of error between a certain hours, cause i want to use it as a monitoring script that run every 5 minutes and to disable error in hours of maintenance. But i have some "problems" to check it. In the rule-file i have HHMM(start) and HHMM(stop) ----- 0 0 to disable hours check (i can't check the timestamp in logfile cause not all the logfiles that i need to check have a timestamp in it). In the script i wrote: Actualtime=datetime.datetime.today().strftime("%H%M") if (start>end): if (Actualtime>start): end=int(Hcheck)+1 else: if (int(Actualtime)int(end)) or ((start=="0") and (end=="0")) ): rule=error ...blablabla.... else: rule=skip ....blablabla.... Why i don't use the complete date with YYMMDDHHMM? Think about a rule that need to be disabled from hours 20:00 to 04:00. If i use also yymmdd, in the rule file i need to write a 2000 and 0400+1, the +1 to tell the script that the end is in the day after, to add a day. But it will work just till the 0000, hour in witch the day will change. The script work, but is not so "clean"....i just would like some advice to make it more clean, if possible. Like always, thanks in advance for the helps :) From cam.ac.uk at mh391.invalid Wed May 2 09:59:53 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 02 May 2007 14:59:53 +0100 Subject: While we're talking about annoyances In-Reply-To: References: <1177837565.317999.244420@c35g2000hsg.googlegroups.com> <8oag339eh56tnpbl8mk3lqlf6avkmusvdm@4ax.com> Message-ID: Steven D'Aprano wrote: > On Wed, 02 May 2007 06:10:54 +0000, Tim Roberts wrote: >> I've tended to favor the "Schwarzian transform" (decorate-sort-undecorate) >> because of that. > > That's what the key= argument does. cmp= is slow because the comparison > function is called for EVERY comparison. The key= function is only called > once per element. Right. Using sort(key=keyfunc) is supposed to be faster than decorate-sort-undecorate. And I think it is clearer too. -- Michael Hoffman From memracom at yahoo.com Thu May 17 14:44:32 2007 From: memracom at yahoo.com (memracom at yahoo.com) Date: 17 May 2007 11:44:32 -0700 Subject: Python-URL! - weekly Python news and links (May 16) In-Reply-To: References: Message-ID: <1179427472.766442.252900@w5g2000hsg.googlegroups.com> > PythonWare complements the digest you're reading with the > marvelous daily python url > http://www.pythonware.com/daily Ha, ha, ha... That is a good joke! From carsten at uniqsys.com Sat May 26 19:07:41 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 26 May 2007 19:07:41 -0400 Subject: Why isn't this query working in python? In-Reply-To: <1180207521.072958.322770@p47g2000hsd.googlegroups.com> References: <1180103946.552760.239200@p47g2000hsd.googlegroups.com> <6e42ec490705250751i89d3cf3v3a3062690d0284aa@mail.gmail.com> <1180207521.072958.322770@p47g2000hsd.googlegroups.com> Message-ID: <1180220861.3158.5.camel@localhost.localdomain> On Sat, 2007-05-26 at 12:25 -0700, erikcw wrote: > I tried adding the comma to make it a sequence - but now change. > > ('SELECT payment_id FROM amember_payments WHERE member_id=%s AND > expire_date > NOW() AND completed=1 AND (product_id >11 AND product_id > <21)', (1608L,)) > () > > What else could it be? We won't know until you post more information. Show us the create table statement for amember_payments, show us the query you're running manually and the results you're getting from running the query manually. Maybe that'll give us a clue. (Include the member_id, expire_date, completed, and product_id columns in your manual query, please.) -- Carsten Haese http://informixdb.sourceforge.net From sjdevnull at yahoo.com Wed May 16 05:29:36 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 16 May 2007 02:29:36 -0700 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <464abd12$0$23364$426a34cc@news.free.fr> References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179289167.723990.223890@u30g2000hsc.googlegroups.com> <464abd12$0$23364$426a34cc@news.free.fr> Message-ID: <1179307776.953405.207680@l77g2000hsb.googlegroups.com> Christophe wrote: > sjdevnull at yahoo.com a ecrit : > > Steven D'Aprano wrote: > >> I would find it useful to be able to use non-ASCII characters for heavily > >> mathematical programs. There would be a closer correspondence between the > >> code and the mathematical equations if one could write D(u*p) instead of > >> delta(mu*pi). > > > > Just as one risk here: > > When reading the above on Google groups, it showed up as "if one could > > write ?(u*p)..." > > When quoting it for response, it showed up as "could write D(u*p)". > > > > I'm sure that the symbol you used was neither a capital letter d nor a > > question mark. > > > > Using identifiers that are so prone to corruption when posting in a > > rather popular forum seems dangerous to me--and I'd guess that a lot > > of source code highlighters, email lists, etc have similar problems. > > I'd even be surprised if some programming tools didn't have similar > > problems. > > So, it was google groups that continuously corrupted the good UTF-8 > posts by force converting them to ISO-8859-1? > > Of course, there's also the possibility that it is a problem on *your* > side Well, that's part of the point isn't it? It seems incredibly naive to me to think that you could use whatever symbol was intended and have it show up, and the "well fix your machine!" argument doesn't fly. A lot of the time programmers have to look at stack traces on end-user's machines (whatever they may be) to help debug. They have to look at code on the (GUI-less) production servers over a terminal link. They have to use all kinds of environments where they can't install the latest and greatest fonts. Promoting code that becomes very hard to read and debug in real situations seems like a sound negative to me. From tijs_news at artsoftonline.com Wed May 30 12:25:36 2007 From: tijs_news at artsoftonline.com (Tijs) Date: Wed, 30 May 2007 18:25:36 +0200 Subject: Anyone else has seen "forrtl: error (200) ..." References: Message-ID: <465da580$0$329$e4fe514c@news.xs4all.nl> Alexander Eisenhuth wrote: > Hello, > > Ctrl+C is not passed to the interpreter (i guess it) while I'm executing a > script. Instead i get: > forrtl: error (200): program aborting due to control-C event > I don't know what forrtl is, but I think it is hijacking your SIGINT signal handler. Python installs an OS-level signal handler that raises the KeyboardInterrupt in the main thread. If a library installs its own handler, Python won't catch it. -- Regards, Tijs From mcPas.De.Spam at mclaveauPas.De.Spam.com Mon May 14 14:19:42 2007 From: mcPas.De.Spam at mclaveauPas.De.Spam.com (Michel Claveau) Date: Mon, 14 May 2007 20:19:42 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> Message-ID: And Il1 O0 ? -- @-salutations Michel Claveau From Glich.Glich at googlemail.com Thu May 17 13:29:08 2007 From: Glich.Glich at googlemail.com (Glich) Date: 17 May 2007 10:29:08 -0700 Subject: FreeType Message-ID: <1179422948.600593.117310@p77g2000hsh.googlegroups.com> Hi, where can I download freetype (>= 2.1.7)? I need it to use matplotlib. I have search a lot but still can not find it. Thanks! From joshua at eeinternet.com Thu May 3 19:59:11 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Thu, 03 May 2007 15:59:11 -0800 Subject: 32 OS on 64-bit machine References: <1178183424.548438.303170@y80g2000hsf.googlegroups.com> Message-ID: <463a6af1$0$16396$88260bb3@free.teranews.com> On Thursday 03 May 2007 01:10, SamG wrote: > If anyone has a x86_64 machine and is running a 32bit OS on top of > that.... could you tell me what output would you get for the following > program > > #====================== > import platform > print platform.processor() > print platform.architecture() > #====================== > > Thanks in advance > : )~ >>> import platform >>> print platform.processor() >>> print platform.architecture() ('32bit', '') >>> $ cat /proc/cpuinfo processor : 0 vendor_id : AuthenticAMD cpu family : 15 model : 44 model name : AMD Sempron(tm) Processor 3100+ $ uname -a Linux djibouti 2.6.15-28-k7 #1 SMP PREEMPT Thu Feb 1 16:36:09 UTC 2007 i686 GNU/Linux -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE -- Posted via a free Usenet account from http://www.teranews.com From manstey at csu.edu.au Sun May 20 20:43:49 2007 From: manstey at csu.edu.au (manstey) Date: 20 May 2007 17:43:49 -0700 Subject: subclassing list question Message-ID: <1179708228.916741.26270@y18g2000prd.googlegroups.com> Hi, I have a simple class that subclasses list: class CaListOfObj(list): """ subclass of list """ def __init__(self, *args, **kwargs): list.__init__(self, *args, **kwargs) a = CaListOfObj([1,2,3]) I want an instance method to be run EVERY time a is modified. Is this possible? Thanks, Matthew From mail at microcorp.co.za Thu May 17 02:54:15 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 17 May 2007 08:54:15 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de><1179258692.237438.110860@p77g2000hsh.googlegroups.com> <+Yl*xeSKr@news.chiark.greenend.org.uk> Message-ID: <019601c79856$85c2e420$03000080@hendrik> "Sion Arrowsmith" wrote: >Hendrik van Rooyen wrote: > >>I still don't like the thought of the horrible mix of "foreign" >>identifiers and English keywords, coupled with the English >>sentence construction. > >How do you think you'd feel if Python had less in the way of >(conventionally used) English keywords/builtins. Like, say, Perl? Would not like it at all, for the same reason I don't like re's - It looks like random samples out of alphabet soup to me. - Hendrik From bdesth.quelquechose at free.quelquepart.fr Tue May 15 17:04:14 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 15 May 2007 23:04:14 +0200 Subject: Distributing programs depending on third party modules. In-Reply-To: <53357$4649c4a6$4275d90a$20775@FUSE.NET> References: <53357$4649c4a6$4275d90a$20775@FUSE.NET> Message-ID: <464a1617$0$14328$426a74cc@news.free.fr> Kevin Walzer a ?crit : > Tina I wrote: > >> Hi list, >> >> Is there a preferred way to distribute programs that depends on third >> party modules like PyQt, Beautifulsoup etc? I have used setuptools and >> just having the setup script check for the existence of the required >> modules. If they're not found I have it exit with a message that it >> need this or that installed. >> >> But this is not very convenient for the end user and I have got a few >> complaints about it. Am I missing something in setuptools or is there >> a better way to do it (except for bundling the modules in the package >> which seem like a rather nasty workaround)? >> >> Thanks >> Tina > > > What platform are you doing this on? On the Linux platform, "dependency > hell" of this sort is pretty much unavoidable, Yes it is. EasyInstall works just fine. > because there are so many > different packaging systems (apt, rpm, and so on): it's standard to let > the package manager handle these dependencies. And yes, it is > frustrating for end users. I'm a happy user of Gentoo and Ubuntu. I don't have any frustration feeling. From martin at v.loewis.de Tue May 15 01:29:26 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 15 May 2007 07:29:26 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: <7x4pmg716p.fsf@ruckus.brouhaha.com> References: <46473267$0$31532$9b622d9e@news.freenet.de> <7x4pmg716p.fsf@ruckus.brouhaha.com> Message-ID: <46494536$0$14096$9b622d9e@news.freenet.de> Paul Rubin schrieb: >> Plenty of programming languages already support unicode identifiers, > > Could you name a few? Thanks. The GNU assembler also supports non-ASCII symbol names on object file formats that support it; this includes at least ELF (not sure about PE32). Higher-level programming languages can use that to encode symbols in UTF-8. Regards, Martin From martin at v.loewis.de Mon May 14 19:09:26 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 15 May 2007 01:09:26 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <7x4pmg716p.fsf@ruckus.brouhaha.com> Message-ID: <4648EC26.8020907@v.loewis.de> Neil Hodgson schrieb: > Paul Rubin wrote: >>> Plenty of programming languages already support unicode identifiers, >> >> Could you name a few? Thanks. > > C#, Java, Ecmascript, Visual Basic. Specification-wise, C99 and C++98 also support Unicode identifiers, although many compilers still don't. For dynamic languages, Groovy also supports it. Regards, Martin From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed May 9 10:49:30 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 09 May 2007 16:49:30 +0200 Subject: Newbie prob: How to write a file with 3 threads? References: <1178440537.257526.40980@y5g2000hsa.googlegroups.com> <1178485944.755068.321740@y5g2000hsa.googlegroups.com> <1178522026.763041.319940@e65g2000hsc.googlegroups.com> <_lJ%h.12611$3P3.10440@newsread3.news.pas.earthlink.net> <1178587327.571785.156800@w5g2000hsg.googlegroups.com> <1178621787.113730.63080@e51g2000hsg.googlegroups.com> Message-ID: <5ae5bqF2oave3U1@mid.individual.net> est wrote: > I'd like to say VERY VERY VERY thank you for your detailed > information, that's a lot encourage for a beginner. In fact I am > writing a multi thread download ultility, and I found that very > hard for me. You don't need any system threads for multiple download threads. Since network connections are buffered and much slower than CPU cycles, you can also use event based mechanisms. (I've written 30+ connection servers like this already.) The general pseudocode strategy is while True: waitForEvents() event = getEvent() processEvent(event) # in here, you inspect the event, # e. g. from which connection it is, # and get or write data The only drawback to event based programming is that processor cycle "rationing" is decided in your code and not by the OS, which can make difficulties with really long calculations. But if these problems arise you usually spawn a seperate worker thread :) > Can you recommand any sample code where I can start > with? If you choose event based programming, definitely have a look at Twisted. It lets you create multiple connection clients and servers in few code lines without synchronisation hassle. http://twistedmatrix.com/projects/core/documentation/howto/ http://twistedmatrix.com/projects/core/documentation/howto/clients.html (BTW, don't get scared by "Deferred"s, I never explicitly used them in my code ... though they often work in the background) Regards, Bj?rn -- BOFH excuse #376: Budget cuts forced us to sell all the power cords for the servers. From bjornkri at gmail.com Tue May 22 04:02:31 2007 From: bjornkri at gmail.com (beertje) Date: 22 May 2007 01:02:31 -0700 Subject: Printing dots in sequence ('...') Message-ID: <1179820951.288587.142670@h2g2000hsg.googlegroups.com> This is a very newbie question for my first post, perhaps appropriately. I want to print '....' gradually, as a progress indicator. I have a for-loop that every 10 steps executes: print '.', This results in something like 'Loading. . . .', whereas I want 'Loading....' A pet peeve, I can't for the life of me figure out how to get this desired output. How do I print dots - or anything for that matter - in sequence without a space being inserted in between? Thanks. Bj?rn From maksim.kasimov at gmail.com Fri May 25 12:03:44 2007 From: maksim.kasimov at gmail.com (Maksim Kasimov) Date: Fri, 25 May 2007 19:03:44 +0300 Subject: just a bug (done) In-Reply-To: References: <1179841504.782279.86490@u36g2000prd.googlegroups.com> <1180082137.329142.45350@p77g2000hsh.googlegroups.com> Message-ID: Carsten Haese: > If you want to convey an arbitrary sequence of bytes as if they were > characters, you need to pick a character encoding that can handle an > arbitrary sequence of bytes. utf-8 can not do that. ISO-8859-1 can, but > you need to specify the encoding explicitly. Observe what happens if I > take your example and insert an encoding specification: > >>>> iMessage = '\n\n > \xd0\xbe\xd0\xbf\xd1\x83\xd0\xbb\xd1\x8f\xd1\x80\xd0\xbd\xd1\x8b\xd1\x85 > \xd0\xb7\xd0\xb0\xd0\xbf\xd1\x80\xd0\xbe\xd1\x81\xd0\xbe\xd0\xb2 \xd0 > \xbc\xd0\xbe\xd0\xb6\xd0\xbd\xd0\xbe \xd1\x83\xd1\x87\xd0\xb8\xd1\x82 > \xd1\x8b\xd0\xb2\xd0\xb0\xd1\x82\xd1\x8c \xd0\xbf\xd1\x80\xd0\xb8 \xd1 > \x81\xd0\xbe\xd0\xb1\xd1\x81\xd1\x82\xd0\xb2\xd0\xb5\xd0\xbd\xd0\xbd\xd1 > \x8b\xd1\x85 \xd1\x80\xd0\xb5\xd0\xba\xd0\xbb\xd0\xb0\xd0\xbc\xd0\xbd > \xd1]]>\n\n\n' >>>> minidom.parseString(iMessage) > > > Of course, when you extract your CDATA, it will come out as a unicode > string which you'll have to encode with ISO-8859-1 to turn it into a > sequence of bytes. Then you add the sequence of bytes from the next > message, and in the end that should yield a valid utf-8-encoded string > once you've collected and assembled all fragments. > > Hope this helps, > Hi Carsten! Thanks for your suggestion - it is possible to fix the problem in that way. BTW: i've found an "xmlproc" and use to try to parse with commandline tool xpcmd.py it gives me "Parse complete, 0 error(s) and 0 warning(s)" I did not pick a character encoding "ISO-8859-1" (but using the lib it is another problem: to recode/retest/redoc/re* a lot of things) the project homepage: http://www.garshol.priv.no/download/software/xmlproc/ and another thing: I've open my xml-message in Mozilla again, in pop-up menu select "Page info" item, it shows me: Content-Type: text/xml Encoding: UTF-8 Many thank for your attention and patience! -- Maksim Kasimov From tbrkic at yahoo.com Tue May 29 11:52:51 2007 From: tbrkic at yahoo.com (glomde) Date: 29 May 2007 08:52:51 -0700 Subject: How to set a class inheritance at instance creation? Message-ID: <1180453971.556244.91370@q69g2000hsb.googlegroups.com> Hi I wonder if you can set what subclass a class should have at instance creation. The problem is that I have something like: class CoreLang(): def AssignVar(self, var, value): pass class Lang1(CoreLang): def AssignVar(self, var, value): return var, "=", value class Lang2(CoreLang): def AssignVar(self, var, value): return var, "<=", value class WriteStruct(): def Generate(self, vars): for var in vars: print self.AssignVar() The problem is that I want WriteStruct to sometimes be a subclass of Lang1 and sometimes of Lang2. In the above example I could but the Generate Method in CoreLang. But in my real example I also want to able to subclass WriteStruct to be able to easy customize WriteStruct. Which I wouldnt be able to do if it was a method in CoreLang. So in code I would like to write something like: WriteStruct(Lang1).Generate(vars) Even better would be that if I in the Lang1 class could just do WriteStruct().Generate(vars) and Lang1 class would magically make WriteStruct a subclass of itself. Cheers, /T From ed at leafe.com Sat May 26 15:36:54 2007 From: ed at leafe.com (Ed Leafe) Date: Sat, 26 May 2007 15:36:54 -0400 Subject: Python and GUI In-Reply-To: References: Message-ID: <75443C5B-BA47-4570-A114-EF3A2FCA6610@leafe.com> On May 26, 2007, at 3:17 PM, rzed wrote: > If there were a standard Python GUI API (call it the PGA, > say) that be the target for app developers, they wouldn't have to > worry about the back end. The PGA would have to be flexible enough > to handle incompatibilities among the various approaches to > displaying widgets and text. FWIW, this has been a design goal of Dabo from Day One. While we currently wrap only wxPython, the ui module is not tied to it. We have standardized on a syntax for control names, property names, etc., that is independent of wxPython, and then is implemented in the ui.uiwx module. Throughout Dabo, the only place where you will ever see "import wx" is in the ui.uiwx module; when you write Dabo UI code, you never need to import wx; instead, you write to the Dabo uiapi. The same will be true when we get around to wrapping Tkinter, Qt, etc. -- Ed Leafe -- http://leafe.com -- http://dabodev.com From bscrivener42 at gmail.com Mon May 28 19:14:39 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: 28 May 2007 16:14:39 -0700 Subject: Tkinter error In-Reply-To: References: <1180388107.105473.203510@h2g2000hsg.googlegroups.com> Message-ID: <1180394079.101504.67650@m36g2000hse.googlegroups.com> On May 28, 4:57 pm, Peter Otten <__pete... at web.de> wrote: > >>> b1 = Button(win,text="One") > >>> b2 = Button(win,text="Two") That worked. Thank you. Rick From mcl.office at googlemail.com Fri May 4 14:15:55 2007 From: mcl.office at googlemail.com (mosscliffe) Date: 4 May 2007 11:15:55 -0700 Subject: Newbie and Page Re-Loading In-Reply-To: <463b6678$0$10433$426a34cc@news.free.fr> References: <1178275290.158007.248180@h2g2000hsg.googlegroups.com> <463b6678$0$10433$426a34cc@news.free.fr> Message-ID: <1178302555.479739.227920@o5g2000hsb.googlegroups.com> Bruno, Many thanks for your very helpful reply. I am trying WingIDE Personal as an editor, up to now it seems OK. My ISP is running Python 2.4.3 and does not know about mod_python. I do not want to run a framework yet. I would like to understand python at script level, before adding more aspects to learn, like frameworks. I think I get your idea about hidden fields and how to alter them. My single page script should work something like this DisplayHTMLHeaderandBodyHeader Check if this is a Re-Load (HiddenField would not exist first time I am assuming) Display SearchSection with previous SearchRequest If SearchRequest is True: Get and Display Results Display TrailerHTMLandTrailerBody ......... Wait for NewSearch or NextPage Does the above make sense or is there a better way ? How do I get the directory of my modules into the Python Path Is there a lightweight Https Server I could run locally (WINXP), which would run .py scripts, without lots of installation modifications ? Thanks Richard On 4 May, 18:00, Bruno Desthuilliers wrote: > mosscliffe a ?crit : > > > I am very new to this python world, but I do like the look of the > > language / syntax, though I have had some problems with indenting > > using a text editor. > > There's no shortage of smart code editor having a decent support for > Python. > > > > > I have managed to get my ISP to execute .py files on their server. > > Great. > > > I have created a .py file and it does in fact do the various little > > tasks I have asked it to do. > > > Now i need to get a bit more serious. > > > I wish to have a web page with a search form at the top and on > > processing the form re-load my current page, but with the various > > search results. > > > Do I just add my script name to the Action part of the Form > > your script's url would actually be better. > > > and how > > can I pass variables, other than form variables to each execution of > > the script. If I have to use hidden form variables, how would I alter > > them for each page. > > Since you're talking about redisplaying the page with results added, I > assume this page is dynamically created by another python script. If so, > you can put the form's generation in a function that will take > page-specific params and put them in the appropriate hidden fields. Then > just call that function from the script generating your web page. > > > I suppose I am looking for some sort of session management, > > Depends... But if it's just to know which page called the script, you > don't need sessions here. > > > but I have > > not been able to track one down as yet. > > I'm suppose your doing CGI scripts. I've seen some basic session > management for CGI somewhere, but that's mostly old stuff. > > > I am running on an ISP, with > > no knowledge of python, so asking about getting packages loaded will > > not be an option. > > You can install packages in your own space - you'll just have to make > sure that there in your python path. > > > I have 'Python in a Nutshell', but it is a bit sparse on everyday web > > page examples. > > "everyday web pages examples" in Python usually imply a more > sophisticated framework and a long running process (think Zope, Django, > CherryPy, Pylons, mod_python, wsgi, fcgi etc...) From knipknap at gmail.com Tue May 22 07:58:20 2007 From: knipknap at gmail.com (Samuel) Date: 22 May 2007 04:58:20 -0700 Subject: omniORBpy: Error 0x41540002 Message-ID: <1179833439.210564.191810@x18g2000prd.googlegroups.com> Hi, I am trying to get the files from this tutorial to work: http://www.grisby.org/presentations/py10code.html Direct link to the files: http://www.grisby.org/presentations/py10code/adder.idl http://www.grisby.org/presentations/py10code/adderServer.py It produces the following error: $ omniidl -bpython adder.idl && python adderServer.py Traceback (most recent call last): File "adderServer.py", line 23, in nameRoot = nameRoot._narrow(CosNaming.NamingContext) File "/usr/lib/python2.5/site-packages/omniORB/CORBA.py", line 667, in _narrow return _omnipy.narrow(self, dest._NP_RepositoryId) omniORB.CORBA.TRANSIENT: Minor: 0x41540002, COMPLETED_NO. According to Google this might mean "Connect failed", however, I don't understand why the server would open a connection. I expected it to simply listen on a socket, but I probably just don't understand how it works. Can anyone please explain this? -Samuel From arnodel at googlemail.com Sun May 20 23:58:10 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 20 May 2007 20:58:10 -0700 Subject: Getting the member of a singleton set In-Reply-To: References: <1179692840.158236.198150@z24g2000prd.googlegroups.com> Message-ID: <1179719890.358441.166910@x18g2000prd.googlegroups.com> On May 21, 12:52 am, "Gabriel Genellina" wrote: [...] > Yes, something like peek() or any() would be useful. But you're not > restricted by the builtin methods, you could write your own: > > def peek(iterable): > return iter(iterable).next() Yes, but that's not getting rid of the ugliness, just tucking away from sight :) *I* would know it's still there. IMHO a 'peek' method in these container types (maybe not all iterables because in some cases iter(it).next() changes the state of it, eg when it is an iterator itself). -- Arnaud From http Mon May 28 18:49:35 2007 From: http (Paul Rubin) Date: 28 May 2007 15:49:35 -0700 Subject: itertools.groupby References: <1180373388.112182.225700@i13g2000prf.googlegroups.com> <1180382532.846606.265100@q19g2000prn.googlegroups.com> Message-ID: <7xzm3o36o0.fsf@ruckus.brouhaha.com> Raymond Hettinger writes: > I think the OP would have been better-off with plain > vanilla Python such as: > > See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/259173 But that recipe generates the groups in a random order depending on the dict hashing, instead of keeping them in the original sequence's order, which the OP's application might well require. itertools.groupby really is the right thing. I agree that itertools is not the easiest module in the world for beginning programmers to understand, but every serious Python user should spend some time figuring it out sooner or later. Iterators and itertools really turn Python into a higher-level language than it was before, giving powerful and streamlined general-purpose mechanisms that replace a lot of special-purpose hand-coding that usually ends up being a lot more work to debug in addition to bloating the user's code. Itertools should by no means be thought of as just a performance hack. It makes programs smaller and sharper. It quickly becomes the One Obvious Way To Do It. In my past few kloc of Python, I think I've written just one or two "class" statements. I used to use class instances all the time, to maintain little bits of state that had to be held between different operations in a program. Using itertools means I now tend to organize entire programs as iterator pipelines so that all the data runs "through the goose" exactly once and there is almost no need to maintain any state anywhere outside the scope of simple function invocations. There are just fewer user-written moving parts when a program is written that way, and therefore fewer ways for the program to go wrong. Messy edge cases that used to take a lot of thought to handle correctly now need no attention at all--they just handle themselves. Also I think it's generally better to use a documented standard library routine than a purpose-written routine or even a downloaded recipe, since the stdlib routine will stay easily available from one project to another and as the user gains experience with it, it will become more and more powerful in his or her hands. Also, these days I think I'd write that recipe with a defaultdict instead of setdefault, but that's new with Python 2.5. From rw at smsnet.pl Sat May 26 05:33:19 2007 From: rw at smsnet.pl (Rob Wolfe) Date: Sat, 26 May 2007 11:33:19 +0200 Subject: Removing NS in ElementTree References: Message-ID: <873b1k9bfk.fsf@merkury.smsnet.pl> "Sebastian Bassi" writes: > I would like to remove the namespace information from my elements and > have just the tag without this information. This > "{http://uniprot.org/uniprot}" is preapended into all my output. > I understand that the solution is related with "_namespace_map" but I > don't know much more. > > >>>> for x in eleroot[0]: > print x.tag > print x.text Try this: NS = "{http://uniprot.org/uniprot}" for x in eleroot[0]: x.tag = x.tag[len(NS):] print x.tag -- HTH, Rob From robert.kern at gmail.com Tue May 15 15:07:22 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 15 May 2007 14:07:22 -0500 Subject: Trying to choose between python and java In-Reply-To: <1179254366.023180.69400@e65g2000hsc.googlegroups.com> References: <1179250163.596672.321480@o5g2000hsb.googlegroups.com> <1179254366.023180.69400@e65g2000hsc.googlegroups.com> Message-ID: sturlamolden wrote: > On May 15, 7:29 pm, Beliavsky wrote: > >> print "Hello, world." >> >> a substantial fraction of Python programs in existence, including all >> of my programs, will be broken. Draw your own conclusions. > > In the vent that your Python 2.x install will be fubar and suddenly > stop working the day Python 3k is released: how difficult will it be > it to make a Python 3k script that corrects your code? It's worth mentioning that providing such a script is of high priority for the Python 3.0 team. They've already implemented the translation for print statements, too: http://svn.python.org/view/sandbox/trunk/2to3/ http://svn.python.org/view/sandbox/trunk/2to3/fixes/fix_print.py?rev=54501&view=auto -- 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 larry.bates at websafe.com Tue May 15 11:29:50 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 15 May 2007 10:29:50 -0500 Subject: File record separators. In-Reply-To: <1179241525.667682.112220@y80g2000hsf.googlegroups.com> References: <1179241525.667682.112220@y80g2000hsf.googlegroups.com> Message-ID: HMS Surprise wrote: > I need to write 2 member lists to a file. For each record the number > of these lists can be different. I think a good way to handle that may > be to make each record a list of lists. I am restricted to using > version 2.2. That being the case what is a good standard record > separator to use to ensure that I read in one record (list of lists) > at a time, '\n'? I want to try to stay with what is considered > standard python idioms. > > > Thanks, > > jvh > You really haven't given us quite enough info, but here goes: If I control this file I might just write out a list of lists on each line and eval it (not tested): [['a', 'b'], ['c','d']] [['a', 'b'], ['c','d'], ['e','f']] fp=open(filename, 'r') lists=[] for n, line in enumerate(fp): try: l=eval(line) except SyntaxError: print "SyntaxError on line=%i" % (n+1) lists.append(l) If you want something different, I might use a tab between lists and commas between values. -Larry From gagsl-py2 at yahoo.com.ar Sat May 5 20:42:44 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 05 May 2007 21:42:44 -0300 Subject: Problem with inspect.getfile References: <1178041715.206440.134530@y80g2000hsf.googlegroups.com> <1178085235.386994.258310@e65g2000hsc.googlegroups.com> <1178117189.070192.318610@o5g2000hsb.googlegroups.com> Message-ID: En Wed, 02 May 2007 11:46:29 -0300, elventear escribi?: > On May 2, 1:12 am, "Gabriel Genellina" wrote: >> En Wed, 02 May 2007 02:53:55 -0300, elventear >> escribi?: >> >> > Found the offending code. I was importing between files that were at >> > the same level of the hierarchy without using absolute references. >> > Coded worked fine, but inspect didn't. Was this gaffe on my part? Or >> > was inspect supposed to handle it? >> >> Could you provide an example? > > Simple example > > My PYTHONPATH points to /python > > I have the following: > > /python/packages > __init.py__ > /containers > __init.py__ > module1.py > module2.py > > So basically module2 depends on module1. So within module2.py I was I > was doing "import module1" instead of import > "packages.containers.module1". My code ran ok, but the functions in > the inspect module weren't able to handle it (getfile was the source > of the problem). I tried it with Python 2.5 on Windows XP and couldn't make it fail. Perhaps it is specific to the Mac, or perhaps it depends on other details like __init__.py contents, order of imports, or how specifically you import things. -- Gabriel Genellina From joel.hedlund at gmail.com Wed May 23 11:31:06 2007 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Wed, 23 May 2007 17:31:06 +0200 Subject: Slightly OT: Why all the spam? In-Reply-To: <1358lu17h16a96e@corp.supernews.com> References: <3bb44c6e0705220008y10f5deb7v86ed82d3f8241761@mail.gmail.com> <1358lu17h16a96e@corp.supernews.com> Message-ID: > Expired articles are removed on the server by the server. > ... > maybe Thunderbird is doing something weird (caching headers?). I can see the spam headers and also read the actual articles, and there are lots of them for the last 5 days. Nothing much before that, though. /Joel From fsckedagain at gmail.com Thu May 10 15:45:30 2007 From: fsckedagain at gmail.com (fscked) Date: 10 May 2007 12:45:30 -0700 Subject: path stuff In-Reply-To: <1178818879.239014.152210@e65g2000hsc.googlegroups.com> References: <1178734266.858048.311740@y5g2000hsa.googlegroups.com> <1178818879.239014.152210@e65g2000hsc.googlegroups.com> Message-ID: <1178826330.282268.132350@p77g2000hsh.googlegroups.com> On May 10, 10:41 am, fscked wrote: > On May 9, 7:02 pm, "Gabriel Genellina" wrote: > > > > > > > En Wed, 09 May 2007 15:11:06 -0300, fscked > > escribi?: > > > > I am walking some directories looking for a certain filename pattern. > > > This part works fine, but what if I want to exclude results from a > > > certain directory being printed? > > > Using os.walk you can skip undesired directories entirely: > > > for dirpath, dirnames, filenames in os.walk(starting_dir): > > if "archived" in dirnames: > > dirnames.remove("archived") > > # process filenames, typically: > > for filename in filenames: > > fullfn = os.path.join(dirpath, filename) > > ... > > > -- > > Gabriel Genellina > > OK, this is on Winbloze and it keeps giving me "The directory name is > invalid: u"blahblahblah" with double backslashies everywhere. I am > currently trying to figure out how to make those go away. I shall > check back in a bit. > > thanks for all the help so far. :)- Hide quoted text - > > - Show quoted text - ok, got the backslashies fixed, not I want it to print just a single line for each matching filename and dirpath, but it prints 3... hmm... From __peter__ at web.de Fri May 4 04:48:29 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 04 May 2007 10:48:29 +0200 Subject: Getting some element from sets.Set References: <1178258913.095438.173020@h2g2000hsg.googlegroups.com> <1178267029.258868.219800@h2g2000hsg.googlegroups.com> Message-ID: jm.suresh at no.spam.gmail.com wrote: > On May 4, 11:34 am, Peter Otten <__pete... at web.de> wrote: >> A set is probably not the appropriate container then. What is your use >> case? > Peter, I need to do a lot of union and intersection operations on > these elements. So, set is a must for me in this case. > > In the particular case, I have to read an attribute from any one of > the elements, which one doesn't matter because this attribute value is > same across all elements in the set. Convinced -- I lacked the imagination for this scenario :-) Peter From johnzenger at gmail.com Wed May 16 11:41:08 2007 From: johnzenger at gmail.com (John Zenger) Date: 16 May 2007 08:41:08 -0700 Subject: remove all elements in a list with a particular value In-Reply-To: <1179328873.105705.95580@l77g2000hsb.googlegroups.com> References: <1179328873.105705.95580@l77g2000hsb.googlegroups.com> Message-ID: <1179330068.785878.181980@n59g2000hsh.googlegroups.com> On May 16, 11:21 am, Lisa wrote: > I am reading in data from a text file. I want to enter each value on > the line into a list and retain the order of the elements. The number > of elements and spacing between them varies, but a typical line looks > like: > > ' SRCPARAM 1 6.35e-07 15.00 340.00 1.10 3.0 ' > > Why does the following not work: > > line = ' SRCPARAM 1 6.35e-07 15.00 340.00 1.10 3.0 ' > li = line.split(' ') > for j,i in enumerate(li): > if i == '': > li.remove(i) > > After the original split I get: > ['', '', '', 'SRCPARAM', '', '', '1', '6.35e-07', '15.00', '', > '340.00', '', '', '1.10', '', '', '', '', '', '3.0', '', '', ''] > > And after the for loop I get: > ['SRCPARAM', '1', '6.35e-07', '15.00', '340.00', '1.10', '', '', '', > '3.0', '', '', ''] > > It doesn't remove all of the empty elements. Is there a better way to > split the original string? Or a way to catch all of the empty > elements? > > Thanks As explained elsewhere, this is not the best way to do a split. But if in the future you run into the problem of how to remove all elements in a list with a particular value, here are two popular approaches: >>> items = ['', '', '', 'SRCPARAM', '', '', '1', '6.35e-07', '15.00', '', '340.00', '', '', '1.10', '', '', '', '', '', '3.0', '', '', ''] >>> print filter(lambda i: i != '', items) ['SRCPARAM', '1', '6.35e-07', '15.00', '340.00', '1.10', '3.0'] >>> print [x for x in items if x != ''] ['SRCPARAM', '1', '6.35e-07', '15.00', '340.00', '1.10', '3.0'] From sdoty044 at gmail.com Wed May 9 15:36:02 2007 From: sdoty044 at gmail.com (sdoty044 at gmail.com) Date: 9 May 2007 12:36:02 -0700 Subject: Unzip then Zip help Message-ID: <1178739362.137264.251600@e65g2000hsc.googlegroups.com> I am a true n00b... and I just using Python to complete some very small uneventful task, but need help with one last thing. Basically, this I what I am trying to do. make a temp directory (this part I can do) Need help with: ***unzip a JAR file with the complete list of subdirectories w/ files**** modify the a set of XML files (this part I can do) Need help with: ***then zip the entire contents of the temp directory with sub directories*** The only thing I am having trouble with is the whole directory stuff, if this was just straight files, no problem. Any help would be appreciated From S.Mientki-nospam at mailbox.kun.nl Mon May 14 17:38:51 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Mon, 14 May 2007 23:38:51 +0200 Subject: os.listdir() doesn't work ?? In-Reply-To: References: <1179173881.163830.54930@n59g2000hsh.googlegroups.com> Message-ID: Michel Claveau wrote: > Hi! > > >> You want the glob module > > Warning: glob has "unix like behavior"; just a little different with > windows's DIR Don't know the details of "Unix" but I thought "unix" was case-sensitive, and glob.glob doesn't seem to be, at least not on windows systems ;-) cheers, Stef Mientki From malaclypse2 at gmail.com Thu May 31 09:34:51 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Thu, 31 May 2007 09:34:51 -0400 Subject: Parsing Rdf (Rewrite) In-Reply-To: <465e60a8.30f4919a.5746.3e3f@mx.google.com> References: <465e60a8.30f4919a.5746.3e3f@mx.google.com> Message-ID: <16651e80705310634v61b746d8q220ba305c250923d@mail.gmail.com> On 5/31/07, Brandon McGinty wrote: > I would think that I could do: > etexts=tree.findall('pgterms:etext') > (or something like that), Which would pull out each etext record in the > file. > I could then do: > for book in etexts: > print book.get('id') > This isn't yielding anything for me, no matter how I write it. > Any thoughts on this? I know very little about ElementTree, but a bit of experimentation shows that the following seems to work: import xml.etree.cElementTree as et tree = et.parse("C:/temp/catalog.rdf") root = tree.getroot() etexts = tree.findall("{http://www.gutenberg.org/rdfterms/}etext") for book in etexts: print book.get("{http://www.w3.org/1999/02/22-rdf-syntax-ns#}ID") I see some comments on namespace issues here: http://effbot.org/zone/element.htm#xml-namespaces if that helps. -- Jerry From mail at microcorp.co.za Wed May 16 02:07:02 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 16 May 2007 08:07:02 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <005701c7965a$97244c70$0d7d12ac@kearfott.com> Message-ID: <03f401c7979e$820f0d80$03000080@hendrik> "Michael Yanowitz" wrote; > Let me guess - the next step will be to restrict the identifiers > to be at most 6 characters long. No that is way too restrictive - you need at least eight, but they must be from the first 80 in the ASCII set - i.e. - capitals only Caps lock on, start coding - lovely names like VAR001, VAR002, etc... Hey come to think of it - maybe 6 is good enough... ; - ) - Hendrik From malkarouri at gmail.com Sat May 5 07:57:31 2007 From: malkarouri at gmail.com (malkarouri at gmail.com) Date: 5 May 2007 04:57:31 -0700 Subject: Problem with Closing TCP connection In-Reply-To: <1178363905.984741.124810@u30g2000hsc.googlegroups.com> References: <1178363905.984741.124810@u30g2000hsc.googlegroups.com> Message-ID: <1178366251.195109.217170@q75g2000hsh.googlegroups.com> On 5 May, 12:18, Madhur wrote: [...] > as a sink to pump TCP messages. During which i have observed that the > TCP close interface provided by Python is not closing the connection. > This i confirmed by looking at the ethereal logs, which show proper 3 > way FIN ACK Handshake. But the netstat reports TIME_WAIT state for the > TCP connection, which is hindering the messages to be pumped later. I > would like to know whether the problem exists Python close and is > there is turnaround? to the mentioned problem. IIRC, this is normal operation of TCP connections. A very short explanation is here (http://www.unixguide.net/network/socketfaq/ 2.7.shtml). So it is not a problem of Python. I don't know exactly what you want to do, but I suggest you look at one of the following options: - Either get IP messages and filter them, same way as ethereal. Probably complicated coding. - Depending on your problem, you may try opening the TCP socket in Python using the SO_REUSEADDR option. Regards, k From steven at REMOVE.THIS.cybersource.com.au Tue May 15 20:16:46 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 16 May 2007 00:16:46 GMT Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <46476081.7080609@web.de> <46498514$0$6402$9b4e6d93@newsspool2.arcor-online.net> Message-ID: On Tue, 15 May 2007 12:01:57 +0200, Ren? Fleschenberg wrote: > Marc 'BlackJack' Rintsch schrieb: >> You find it in the sources by the line number from the traceback and >> the letters can be copy'n'pasted if you don't know how to input them >> with your keymap or keyboard layout. > > Typing them is not the only problem. They might not even *display* > correctly if you don't happen to use a font that supports them. Then maybe you should catch up to the 21st century and install some fonts and a modern editor. -- Steven. From sdoty044 at gmail.com Thu May 10 15:33:13 2007 From: sdoty044 at gmail.com (sdoty044 at gmail.com) Date: 10 May 2007 12:33:13 -0700 Subject: Unzip then Zip help In-Reply-To: <87lkfxsnyj.fsf@merkury.smsnet.pl> References: <1178739362.137264.251600@e65g2000hsc.googlegroups.com> <87lkfxsnyj.fsf@merkury.smsnet.pl> Message-ID: <1178825593.446671.94240@p77g2000hsh.googlegroups.com> On May 9, 5:10 pm, Rob Wolfe wrote: > sdoty... at gmail.com writes: > > I am a true n00b... and I just using Python to complete some very > > small uneventful task, but need help with one last thing. > > > Basically, this I what I am trying to do. > > > make a temp directory (this part I can do) > > > Need help with: > > ***unzipa JAR file with the complete list of subdirectories w/ > > files**** > > > modify the a set of XML files (this part I can do) > > > Need help with: > > ***then zip the entire contents of the temp directory with sub > > directories*** > > > The only thing I am having trouble with is the whole directory stuff, > > if this was just straight files, no problem. > > > Any help would be appreciated > > Try this: > > > import os > from os.path import dirname, exists, splitext, join > from zipfile import ZipFile, ZIP_DEFLATED > > def unpack(archname): > arch = ZipFile(archname, 'r') > for path in arch.namelist(): > print path > dname = dirname(path) > if not exists(dname): os.makedirs(dname) > if splitext(path)[1]: > f = open(path, 'wb') > f.write(arch.read(path)) > f.close() > arch.close() > > def pack(archname, paths): > arch = ZipFile(archname, 'w', ZIP_DEFLATED) > for path in paths: > for root, dirs, files in os.walk(path): > for fname in files: > fname = join(root, fname) > print fname > arch.write(fname) > arch.close() > > unpack('test.jar') > pack('test2.jar', ['com', 'META-INF']) > > > -- > HTH, > Rob- Hide quoted text - > > - Show quoted text - Awsome, Thanks !! Ran into one or 2 issues with the unpack and pack methods (related to the JAR files I was using), but it was nothing I could not work out on my own!! From danb_83 at yahoo.com Mon May 21 19:22:06 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: 21 May 2007 16:22:06 -0700 Subject: A newbie question In-Reply-To: References: Message-ID: <1179789726.619470.223710@36g2000prm.googlegroups.com> On May 21, 6:04 pm, "wang frank" wrote: > Hi, > > I am trying to write a python class with a new data type such as: > class Cc14: > def __init__(self, realpart, imagpart): > self.r=realart > self.i=imagpart > > def __add__(self,x): > return self.r+x,r, self.i+x.i > > If I have > x=Cc14(4,5) > y=Cc14(4,5) > z=x+y > > z will be a tuple instead of Cc14. How can I return a Cc14 class? return Cc14(self.r+x,r, self.i+x.i) FYI, Python has a built-in "complex" type. From gur.tom at gmail.com Tue May 15 09:06:53 2007 From: gur.tom at gmail.com (Tom Gur) Date: 15 May 2007 06:06:53 -0700 Subject: Get a control over a window Message-ID: <1179234413.915336.263660@n59g2000hsh.googlegroups.com> Hi, I was wondering how do I get control over a window (Win32). to be more specific, I need to find a handle to a window of a certain program and minimize the window. From hazelnusse at gmail.com Mon May 28 04:44:59 2007 From: hazelnusse at gmail.com (Luke) Date: 28 May 2007 01:44:59 -0700 Subject: Sci.linalg.lu permuation error Message-ID: <1180341898.971618.104760@q19g2000prn.googlegroups.com> I'm trying to use Scipy's LU factorization. Here is what I've got: from numpy import * import scipy as Sci import scipy.linalg A=array([[3., -2., 1., 0., 0.],[-1., 1., 0., 1., 0.],[4., 1., 0., 0., 1.]]) p,l,u=Sci.linalg.lu(A,permute_l = 0) now, according to the documentation: ************************************************** Definition: Sci.linalg.lu(a, permute_l=0, overwrite_a=0) Docstring: Return LU decompostion of a matrix. Inputs: a -- An M x N matrix. permute_l -- Perform matrix multiplication p * l [disabled]. Outputs: p,l,u -- LU decomposition matrices of a [permute_l=0] pl,u -- LU decomposition matrices of a [permute_l=1] Definitions: a = p * l * u [permute_l=0] a = pl * u [permute_l=1] p - An M x M permutation matrix l - An M x K lower triangular or trapezoidal matrix with unit-diagonal u - An K x N upper triangular or trapezoidal matrix K = min(M,N) ********************************************* So it would seem that from my above commands, I should have: A == dot(p,dot(l,u)) but instead, this results in: In [21]: dot(p,dot(l,u)) Out[21]: array([[-1., 1., 0., 1., 0.], [ 4., 1., 0., 0., 1.], [ 3., -2., 1., 0., 0.]]) Which isn't equal to A!!! In [23]: A Out[23]: array([[ 3., -2., 1., 0., 0.], [-1., 1., 0., 1., 0.], [ 4., 1., 0., 0., 1.]]) However, if I do use p.T instead of p: In [22]: dot(p.T,dot(l,u)) Out[22]: array([[ 3., -2., 1., 0., 0.], [-1., 1., 0., 1., 0.], [ 4., 1., 0., 0., 1.]]) I get the correct answer. Either the documentation is wrong, or somehow Scipy is returning the wrong permutation matrix... anybody have any experience with this or tell me how to submit a bug report? Thanks. ~Luke From laxmikiran.bachu at gmail.com Thu May 24 07:45:46 2007 From: laxmikiran.bachu at gmail.com (laxmikiran.bachu at gmail.com) Date: 24 May 2007 04:45:46 -0700 Subject: Changing Unicode object to Tuple Type Message-ID: <1180007144.514744.188090@q75g2000hsh.googlegroups.com> Can we have change a unicode string Type object to a Tuple type object.. If so how ???? From jstroud at mbi.ucla.edu Mon May 21 18:57:17 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 21 May 2007 15:57:17 -0700 Subject: converting strings to most their efficient types '1' --> 1, 'A' ---> 'A', '1.2'---> 1.2 In-Reply-To: <1179766118.332466.251870@r3g2000prh.googlegroups.com> References: <1179529661.555196.13070@k79g2000hse.googlegroups.com> <1179551680.283157.19000@y80g2000hsf.googlegroups.com> <464FA156.2070704@lexicon.net> <1179766118.332466.251870@r3g2000prh.googlegroups.com> Message-ID: py_genetic wrote: > Using a baysian method were my inital thoughts as well. The key to > this method, I feel is getting a solid random sample of the entire > file without having to load the whole beast into memory. If you feel only the first 1000 rows are representative, then you can take a random sample from the first 200-1000 rows depending on how good you think the typing was. At 10,000 bytes per row, you are only reading in a 10MB file if you read 1000 rows. I just timed reading a 28MB file (source tgz file of Open Office 2.0.1) from a local drive at about 1s. As I hope I have demonstrated, you will need only a small random sample from this 200-1000 for testing (maybe 5-15 depending on quality and priors). > What are your thoughts on other techniques? For example training a > neural net and feeding it a sample, this might be nice and very fast > since after training (we would have to create a good global training > set) we could just do a quick transform on a coll sample and ave the > probabilities of the output units (one output unit for each type). > The question here would encoding, any ideas? A bin rep of the vars? > Furthermore, niave bayes decision trees etc? I think these latter ideas require more characterization of your input than is necessary, especially with judicious ordering of simple converter tests. What properties, aside from passing and failing certain converter tests, would you use for the data types? For example, you might use fraction of the string that are integer digits as a property to classify integers. But how many CPU cycles would you spend counting these digits and calculating the fractions for your sample? Do you expect that your data quality is poor enough to warrant expending CPU cycles to quantify the several properties that might characterize each type? However, you might need some advanced learning tools if you want to automatically decide whether a column is a last name or a first name. I'm guessing this is not required and you would only want to know whether to make such a column an int or a string, in which case the testing is pretty straightforward and quick (number of tests per column < 10). I've never converted tables from organizations on a routine basis, but I have a feeling that the quality of these tables are not as poor as one might fear, especially given reasonable foreknowledge of how data types are typically encoded. James From larry.bates at websafe.com Wed May 23 19:47:53 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 23 May 2007 18:47:53 -0500 Subject: read file to a dictionary In-Reply-To: <1179962203.201472.104500@q19g2000prn.googlegroups.com> References: <1179962203.201472.104500@q19g2000prn.googlegroups.com> Message-ID: rohit wrote: > i want to implement a dictionary in python > the query is : > without explicitly doing the following steps > 1. reading from file to list > 2. processing list to dictionary > is there a module or a built in function that helps me "read" a file > directly into a dictionary > or any module that implements the above 2 steps > > thanks > rohit > csv module will read individual lines into a dictionary with keys being the field names. You can then do something with that. It is unclear what the keys, values are for your dictionary when read from a file. More info will be required to help more. -Larry From nospam at noemailhere.nowhere Mon May 21 00:37:33 2007 From: nospam at noemailhere.nowhere (Anthony Irwin) Date: Mon, 21 May 2007 14:37:33 +1000 Subject: A few questions In-Reply-To: References: Message-ID: jay wrote: > Hi, > > I'm totally new to Python and was hoping someone might be able to answer > a few questions for me: > > 1. What are your views about Python vs Perl? Do you see one as better > than the other? I have written some scripts in both perl and python and to me python feels more like a modern programming language then perl does. As I am learning both languages I can also say that I was writing useful python code as I was learning python but had to do more reading with perl to write similar levels of code but maybe thats just me. > > 3. Currently, I write most of my code with Xcode (on the Mac platform) > using Applescript. This gives me GUI capabilities. Is there anything > you'd recommend that I could use for Python that would give me a GUI > interface? I'd like this to be able to work for both the Mac and > Windows platforms. I've been reading a little about 'Claro Graphics > Toolkit' and 'PyGUI'... would you recommend either of those? I'll be > writing code on a Mac so I need something that will run on that system. I have used wxpython and did the tutorial listed in their wiki and ran it on linux and mac and they looked like native applications in both and the same is meant to happen in windows but I don't have windows so have not tried it myself. To do this on the mac I installed the universal python 2.4 from the python site and the wxpython mac install and just double clicked a python file with a .pyw and it executed like a normal app. Originally I had a .py file extension but that does not execute the python script. -- Kind Regards, Anthony Irwin http://www.irwinresources.com http://www.makehomebusiness.com email: anthony at above domains, - www. From not at valid.com Mon May 21 14:36:05 2007 From: not at valid.com (yomgui) Date: Mon, 21 May 2007 11:36:05 -0700 Subject: alternative to eclipse [ python ide AND cvs ] In-Reply-To: References: Message-ID: as you said, I re-installed java properly and it solved the problem. thanks. thanks for everybody else for responding yomgui Nathan Harmston wrote: > I have had very few problems with eclipse on ubuntu with pydev > installed. Is it still running under the gnu jvm, not the sun one? It > was crashing on me until I changed them around, detials about changing > it around on ubuntu anyway > > http://ubuntuguide.org/wiki/Ubuntu_Edgy#How_to_install_Java_Integrated_Development_Environment_.28Eclipse.29 > > > Hope this helps, > > Nathan From mccredie at gmail.com Wed May 2 13:59:13 2007 From: mccredie at gmail.com (Matimus) Date: 2 May 2007 10:59:13 -0700 Subject: Time functions In-Reply-To: <1178126501.245493.210150@y80g2000hsf.googlegroups.com> References: <1178125256.640115.26480@o5g2000hsb.googlegroups.com> <1178126501.245493.210150@y80g2000hsf.googlegroups.com> Message-ID: <1178128753.140811.228620@u30g2000hsc.googlegroups.com> On May 2, 10:21 am, HMS Surprise wrote: > On May 2, 12:03 pm, Marc 'BlackJack' Rintsch wrote: > > > In <1178125256.640115.26... at o5g2000hsb.googlegroups.com>, HMS Surprise > > wrote: > > > > I wish to generate a datetime string that has the following format. > > > '05/02/2007 12:46'. The leading zeros are required. > > > > I found '14.2 time' in the library reference and have pulled in > > > localtime. Are there any formatting functions available or do I need > > > to make my own? Perhaps there is something similar to C's printf > > > formatting. > > > You mean like `time.strftime()`!? :-) > > > Ciao, > > Marc 'BlackJack' Rintsch > > Thanks for posting. > > I think I have an import misconception. > > I use > import from time localtime, strftime > t = strftime('%m/%d/%Y %H:%M', localtime()) > > This works. How would one use it with the module name pre-pended? > > thanx, > jvh I would think that what you have written there shouldn't work at all... it would need to be: [code] from time import localtime, strftime [/code] to use the prepended module name just do this instead: [code] import time t = time.strftime('%m/%d/%Y %H:%M', time.localtime()) [/code] From michele.simionato at gmail.com Wed May 2 05:12:07 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 2 May 2007 02:12:07 -0700 Subject: DiffLib Question In-Reply-To: <1178095577.190066.158960@y80g2000hsf.googlegroups.com> References: <1178095577.190066.158960@y80g2000hsf.googlegroups.com> Message-ID: <1178097127.286181.216520@y80g2000hsf.googlegroups.com> On May 2, 10:46 am, whitewave wrote: > Is there a way for me to disregard > the newlines and spaces? > > Python 2.3 > WINXP > > Thanks. > Jen HTH: >> help(difflib.Differ.__init__) Help on method __init__ in module difflib: __init__(self, linejunk=None, charjunk=None) unbound difflib.Differ method Construct a text differencer, with optional filters. The two optional keyword parameters are for filter functions: - `linejunk`: A function that should accept a single string argument, and return true iff the string is junk. The module-level function `IS_LINE_JUNK` may be used to filter out lines without visible characters, except for at most one splat ('#'). It is recommended to leave linejunk None; as of Python 2.3, the underlying SequenceMatcher class has grown an adaptive notion of "noise" lines that's better than any static definition the author has ever been able to craft. - `charjunk`: A function that should accept a string of length 1. The module-level function `IS_CHARACTER_JUNK` may be used to filter out whitespace characters (a blank or tab; **note**: bad idea to include newline in this!). Use of IS_CHARACTER_JUNK is recommended. Michele Simionato From warren at muse.com Wed May 30 20:24:38 2007 From: warren at muse.com (Warren Stringer) Date: Wed, 30 May 2007 17:24:38 -0700 Subject: c[:]() In-Reply-To: <1180566831.239580.199300@m36g2000hse.googlegroups.com> References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com><1180554872.3356.30.camel@dot.uniqsys.com><465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> Message-ID: <005401c7a31a$136f7fe0$240110ac@Muse> Hey Dustan, very cool! The first hit on "python is not java" turns up the dirtsimple blog, which kicked my asp -- so, to speak (reptile not server pages - mon dieu, I'm explain a pun, how wretched) ... Dirtsimple mentions shallow versus deep. Damn! First off, I love dots. They're easy to type. I like to go deep. Yet have been finding that a.b.c.d.e.f() tends to suck __getattr__ The dirtsimple blog also mentions using hash-trees as a switch statement...hmmmm .... I wonder which is faster: a.b.c.d.e.f() # or h['a.b.c.d.e.f']() # doh! I still want my executable container though. Would love to so this h[search('a//f')]() # where a//f is like an Xpath // search for leaves Believe me, this is incredibly useful for executing an ontology, which happens to be what I'm working on during every waking moment, when not on the python list. Cheers, \~/ > -----Original Message----- > From: python-list-bounces+warren=muse.com at python.org [mailto:python-list- > bounces+warren=muse.com at python.org] On Behalf Of Dustan > Sent: Wednesday, May 30, 2007 4:14 PM > To: python-list at python.org > Subject: Re: c[:]() > > On May 30, 5:37 pm, "Warren Stringer" wrote: > > Hey many thanks for the replies! > > > > Ah, so is seems that c[:][:][:][:][:][:][:][:][:][:][:][0]() > > also work ... > > > > Ah well, can't have everything. Guess I was inspired by the > alphabetically > > adjacent message "Call for Ruby Champion". Would have been nice for it > work > > - a more elegant iterator would be hard to come by. A PEP, perhaps? > Maybe > > not; am still a bit new - am probably missing something obvious why this > > isn't an easy fix. > > > > Pretty cool that I can override the list class. > > > > Cheers, > > Do a search on "python is not java" (words to live by). You can also > plug in another language you know (like Ruby), but you won't get as > many results. > > -- > http://mail.python.org/mailman/listinfo/python-list From lesande at gmail.com Thu May 31 08:26:14 2007 From: lesande at gmail.com (Lee Sander) Date: 31 May 2007 05:26:14 -0700 Subject: file reading by record separator (not line by line) Message-ID: <1180614374.027569.235540@g4g2000hsf.googlegroups.com> Dear all, I would like to read a really huge file that looks like this: > name1.... line_11 line_12 line_13 ... >name2 ... line_21 line_22 ... etc where line_ij is just a free form text on that line. how can i read file so that every time i do a "read()" i get exactly one record up to the next ">" many thanks Lee From showell30 at yahoo.com Mon May 28 11:14:24 2007 From: showell30 at yahoo.com (Steve Howell) Date: Mon, 28 May 2007 08:14:24 -0700 (PDT) Subject: itertools.groupby In-Reply-To: <7xveed1mnk.fsf@ruckus.brouhaha.com> Message-ID: <598969.40596.qm@web33507.mail.mud.yahoo.com> --- Paul Rubin <"http://phr.cx"@NOSPAM.invalid> wrote: > [...] > Here's yet another example that came up in something > I was working on: > you are indexing a book and you want to print a list > of page numbers > for pages that refer to George Washington. If > Washington occurs on > several consecutive pages you want to print those > numbers as a > hyphenated range, e.g. > > Washington, George: 5, 19, 37-45, 82-91, 103 > > This is easy with groupby (this version not tested > but it's pretty close > to what I wrote in the real program). Again it > works by Bates numbering, > but a little more subtly (enumerate generates the > Bates numbers): > > snd = operator.itemgetter(1) # as before > > def page_ranges(): > pages = sorted(filter(contains_washington, > all_page_numbers)) > for d,g in groupby(enumerate(pages), lambda > (i,p): i-p): > h = map(snd, g) > if len(h) > 1: > yield '%d-%d'% (h[0], h[-1]) > else: > yield '%d'% h[0] > print ', '.join(page_ranges()) > > [...] Cool. Here's another variation on itertools.groupby, which wraps text from paragraphs: import itertools lines = [line.strip() for line in ''' This is the first paragraph. This is the second. '''.split('\n')] for has_chars, frags in itertools.groupby(lines, lambda x: len(x) > 0): if has_chars: print ' '.join(list(frags)) # prints this: # # This is the first paragraph. # This is the second. I put the above example here: http://wiki.python.org/moin/SimplePrograms ____________________________________________________________________________________ Park yourself in front of a world of choices in alternative vehicles. Visit the Yahoo! Auto Green Center. http://autos.yahoo.com/green_center/ From C.delete_this.Sanders at BoM.GOv.AU Wed May 9 02:13:06 2007 From: C.delete_this.Sanders at BoM.GOv.AU (Charles Sanders) Date: Wed, 09 May 2007 16:13:06 +1000 Subject: interesting exercise In-Reply-To: <1178670691.209680.119330@o5g2000hsb.googlegroups.com> References: <1178595952.641173.76540@y80g2000hsf.googlegroups.com> <1178601624.812907.23550@u30g2000hsc.googlegroups.com> <1178661305.063868.130730@e65g2000hsc.googlegroups.com> <1178661851.606885.104330@p77g2000hsh.googlegroups.com> <1178670691.209680.119330@o5g2000hsb.googlegroups.com> Message-ID: <46416674$0$83110$c30e37c6@lon-reader.news.telstra.net> Michael Tobis wrote: > Here is the bloated mess I came up with. I did see that it had to be > recursive, and was proud of myself for getting it pretty much on the > first try, but the thing still reeks of my sorry old fortran-addled > mentality. Recursion is not necessary, but is much, much clearer. Here is one non-recursive version from another aging fortran programmer. I agree it is less clear than most of the recursive alternatives. No checks for sorted input etc, these are left as an exercise for the reader. def permute( s, n ): def _perm( m, n ): ilist = [0]*n while True: yield ilist i = n-1 while i >= 0 and ilist[i]>=m-1: i = i - 1 if i >= 0: ilist = ilist[0:i] + [ilist[i]+1] + [0]*(n-i-1) else: return return [ ''.join([s[i] for i in ilist]) for ilist in _perm(len(s),n) ] print "permute('abc',2) = ", permute('abc',2) print "len(permute('13579',3)) = ", len(permute('13579',3)) permute('abc',2) = ['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc'] len(permute('13579',3)) = 125 or even this monstrosity ... def permute2( s, n ): return [ ''.join([ s[int(i/len(s)**j)%len(s)] for j in range(n-1,-1,-1)]) for i in range(len(s)**n) ] print "permute2('abc',2) =", permute2('abc',2) print "len(permute2('13579',3)) =", len(permute2('13579',3)) permute2('abc',2) = ['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc'] len(permute2('13579',3)) = 125 Charles From nis at superlativ.dk Tue May 22 12:43:45 2007 From: nis at superlativ.dk (=?ISO-8859-1?Q?Nis_J=F8rgensen?=) Date: Tue, 22 May 2007 18:43:45 +0200 Subject: Create an XML document In-Reply-To: <1179846012.972391.160800@z28g2000prd.googlegroups.com> References: <1179846012.972391.160800@z28g2000prd.googlegroups.com> Message-ID: <46531dcb$0$90273$14726298@news.sunsite.dk> kyosohma at gmail.com skrev: > Hi all, > > I am attempting to create an XML document dynamically with Python. It > needs the following format: > > > > 1179775800 > 1800 > > > > I tried using minidom with the following code: > > > > from xml.dom.minidom import Document > > doc = Document() > > zappt = doc.createElement('zAppointments') > zappt.setAttribute('reminder', '15') > doc.appendChild(zappt) > > appt = doc.createElement('appointment') > zappt.appendChild(appt) > > begin = doc.createElement('begin') > appt.appendChild(begin) > f = file(r'path\to\file.xml', 'w') > f.write(doc.toprettyxml(indent=' ')) > f.close() > > > How do I get Python to put values into the elements by tag name? I can > parse my documents just fine, but now I need to edit them and write > them out to a file for an application I am working on. I am sure I am > missing something obvious. >From http://wiki.python.org/moin/MiniDom Add an Element with Text Inside Create & add an XML element to an XML document, the element has text inside. ex: hello, world! from xml.dom.minidom import parse dom = parse("bar.xml") x = dom.createElement("foo") # creates txt = dom.createTextNode("hello, world!") # creates "hello, world!" x.appendChild(txt) # results in hello, world! dom.childNodes[1].appendChild(x) # appends at end of 1st child's \ children print dom.toxml() From claird at lairds.us Fri May 4 12:54:22 2007 From: claird at lairds.us (Cameron Laird) Date: Fri, 4 May 2007 16:54:22 +0000 Subject: invoke user's standard mail client References: <1178266064.922925.125760@y80g2000hsf.googlegroups.com> Message-ID: In article <1178266064.922925.125760 at y80g2000hsf.googlegroups.com>, luc.saffre at gmail.com wrote: >Hello, > >the simplest way to launch the user's standard mail client from a >Python program is by creating a mailto: URL and launching the >webbrowser: > >def mailto_url(to=None,subject=None,body=None,cc=None): > """ > encodes the content as a mailto link as described on > http://www.faqs.org/rfcs/rfc2368.html > Examples partly taken from > http://selfhtml.teamone.de/html/verweise/email.htm > """ > url = "mailto:" + urllib.quote(to.strip(),"@,") > sep = "?" > if cc: > url+= sep + "cc=" + urllib.quote(cc,"@,") > sep = "&" > if subject: > url+= sep + "subject=" + urllib.quote(subject,"") > sep = "&" > if body: > # Also note that line breaks in the body of a message MUST be > # encoded with "%0D%0A". (RFC 2368) > body="\r\n".join(body.splitlines()) > url+= sep + "body=" + urllib.quote(body,"") > sep = "&" > return url > >import webbrowser >url = mailto_url(...) >webbrowser.open(url,new=1) > >(Excerpt from >http://svn.berlios.de/wsvn/lino/trunk/src/lino/tools/mail.py?op=file&rev=0&sc=0) > >But this method is limited: you cannot specify a file to be attached >to the mail. And I guess that there would be problems if the body text >is too complex. > >Does somebody know about a better method? >It should be possible at least on Windows, since Acrobat Reader is >able to do it. . . . Portland is the best standardization of this problem we have under Linux. I'll address Windows in a subsequent follow-up. From duncan.booth at invalid.invalid Thu May 3 08:13:49 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 3 May 2007 12:13:49 GMT Subject: Microsoft's Dynamic Languages Runtime (DLR) References: <1178130161.688812.311720@n76g2000hsh.googlegroups.com> Message-ID: sturlamolden wrote: > I am curious to know how it performs in comparison to CPython and an > efficient compiled Lisp like CMUCL. Speed is a major problem with > CPython but not with .NET or CMUCL, so it will be interesting to see > how the DLR performs in comparison. It would be great to finally see a > Python that runs on steroids, but knowing M$ bloatware my expectations > are not too high. The video of Jim Hugunin's talk from MIX has a slide showing how many Pystones you get on some different versions of Python. Of course that is just one benchmark and not terribly relevant to any real applications, but if you do get a similar speedup in real code 'Python that runs on steroids' won't be far from the truth. The claimed figures were 50,000 Pystones for CPython 2.5, and 101,000 for the latest IronPython. (He didn't mention it, but I believe Psyco will outdo both of these.) From hlubenow2 at gmx.net Thu May 3 16:30:15 2007 From: hlubenow2 at gmx.net (hlubenow) Date: Thu, 03 May 2007 22:30:15 +0200 Subject: Using python with MySQL References: <1178048415.272711.261930@n59g2000hsh.googlegroups.com> Message-ID: hlubenow wrote: > There's even another approach: ... On the other hand you may be better off with the "mysql-python"-module. Anyway, here's a nice overview over the most commonly used MySQL-commands (The commands should speak for themselves, even if the explanations are in German): http://www.linux-club.de/ftopic49585.html H. From python at rcn.com Mon May 28 01:29:58 2007 From: python at rcn.com (Raymond Hettinger) Date: 27 May 2007 22:29:58 -0700 Subject: itertools.groupby In-Reply-To: <7x8xb939ut.fsf@ruckus.brouhaha.com> References: <1180295221.3163.9.camel@localhost.localdomain> <1180313441.598026.198230@d30g2000prg.googlegroups.com> <7x8xb939ut.fsf@ruckus.brouhaha.com> Message-ID: <1180330198.466144.197620@j4g2000prf.googlegroups.com> On May 27, 8:28 pm, Paul Rubin wrote: > I use the module all the time now and it is great. Thanks for the accolades and the great example. FWIW, I checked in a minor update to the docs: +++ python/trunk/Doc/lib/libitertools.tex Mon May 28 07:23:22 2007 @@ -138,6 +138,13 @@ identity function and returns the element unchanged. Generally, the iterable needs to already be sorted on the same key function. + The operation of \function{groupby()} is similar to the \code{uniq} filter + in \UNIX{}. It generates a break or new group every time the value + of the key function changes (which is why it is usually necessary + to have sorted the data using the same key function). That behavior + differs from SQL's GROUP BY which aggregates common elements regardless + of their input order. + The returned group is itself an iterator that shares the underlying iterable with \function{groupby()}. Because the source is shared, when the \function{groupby} object is advanced, the previous group is no @@ -147,6 +154,7 @@ \begin{verbatim} groups = [] uniquekeys = [] + data = sorted(data, key=keyfunc) for k, g in groupby(data, keyfunc): groups.append(list(g)) # Store group iterator as a list uniquekeys.append(k) Raymond From apatheticagnostic at gmail.com Wed May 30 22:10:13 2007 From: apatheticagnostic at gmail.com (kaens) Date: Wed, 30 May 2007 22:10:13 -0400 Subject: Examples of high-quality python code? Message-ID: <163f0ce20705301910y11e2a1cdw17160b8d7f1ca1d6@mail.gmail.com> Hey everyone, I'm relatively new to python - I actually picked it up to see how quickly I could start building non-trivial apps with it. Needless to say, I was quite pleased. Anyhow, I'm looking to expand my understanding of python, and I feel that one of the best ways to do that is looking at other peoples code. Unfortunately, I don't feel like I grok the python mindset quite well enough to fully distinguish between awesome, average, and not-pythony code, so I was hoping some of the more experienced python people could point me to some (preferably FOSS) non-trivial apps written in python that are examples of great python code. I realize this may be a bit ambiguous - basically I don't want to go randomly downloading other people's source and end up assimilating techniques that aren't . . . well . . . pythonistic. So, who wants to hook me up? From gliquidsnake at hotmail.com Thu May 24 13:58:53 2007 From: gliquidsnake at hotmail.com (gliquidsnake at hotmail.com) Date: Thu, 24 May 2007 13:58:53 -0400 Subject: question about getch() Message-ID: Hey all, I'm having a problem with using msvcrt.getch() . What I want is some functionality like this: print 'blah blah blah, good_input to do blah blah blah, exit_key to exit' while input != exit_key: input = get_input_from_getch() if input == good_input: print input #do something if input == bad_input: #ask for new input if input == exit_key: pass so, if the user's input is good, the input is printed to the screen and the user is allowed to put in more input. if the user's input is bad, the input is not printed to the screen and python ignores the input. if the user presses a designated key then the program continues. for some reason, all I get when I try to implement getch() is python getting stuck in an infinite loop and printing "?" continuously. I tried using msvcrt.kbhit() to wait for a key to be pressed before continuing to getch() but it seems the program then skips the loop entirely. I guess I just don't really understand how to use getch(). =( -------------- next part -------------- An HTML attachment was scrubbed... URL: From whamil1 at entergy.com Thu May 10 09:01:36 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Thu, 10 May 2007 08:01:36 -0500 Subject: change of random state when pyc created?? Message-ID: <588D53831C701746A2DF46E365C018CE01D2CA93@LITEXETSP001.etrsouth.corp.entergy.com> > From: Alan Isaac > > I'm sure my first pass will be flawed, but here goes: > > http://docs.python.org/lib/typesmapping.html: > to footnote (3), add phrase "which may depend on the memory location of > the > keys" to get: > > Keys and values are listed in an arbitrary order, > which may depend on the memory location of the keys. > This order is non-random, varies across Python implementations, > and depends on the dictionary's history of insertions and deletions. > > http://docs.python.org/lib/types-set.html: append a new sentence to 2nd > paragraph > > Iteration over a set returns elements in an arbitrary order, > which may depend on the memory location of the elements. It's possible there are other factors that can affect this as well. A more general statement is probably more appropriate: "Keys and values are listed in an arbitrary order. This order is non-random, varies across Python implementations, and depends on the dictionary's history of insertions and deletions as well as factors outside the scope of the containing program." "Iteration over a set returns elements in an arbitrary order, which may depend on factors outside the scope of the containing program." --- -Bill Hamilton From horpner at yahoo.com Tue May 22 07:44:11 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 22 May 2007 11:44:11 GMT Subject: Installing Python in a path that contains a blank References: Message-ID: On 2007-05-22, Konrad Hinsen wrote: > On 21.05.2007, at 21:11, Stargaming wrote: > >> You could give /foo/bar\ baz/ham or "/foo/bar baz/ham" (either >> escaping >> the blanks or wrapping the path in quotation marks) a try. I can't >> verify it either, just guess from other terminals' behaviour. > > I tried both already, but neither one works. If I use a > backslash, it doesn't end up in the Makefile, and if I use > quotes, I get lots of error messages that I don't really want > to analyze. Try adding *more* backslashes. Sometimes, it's the only way. ;) -- Neil Cerutti There are two ways to argue with a woman, and neither of them work. --Carlos Boozer From john at datavoiceint.com Tue May 15 18:56:26 2007 From: john at datavoiceint.com (HMS Surprise) Date: 15 May 2007 15:56:26 -0700 Subject: Name of function caller In-Reply-To: <1179267214.735025.167470@l77g2000hsb.googlegroups.com> References: <1179266351.304587.182070@n59g2000hsh.googlegroups.com> <1179267214.735025.167470@l77g2000hsb.googlegroups.com> Message-ID: <1179269786.256165.151340@o5g2000hsb.googlegroups.com> On May 15, 5:13 pm, Paul McGuire wrote: > On May 15, 4:59 pm, HMS Surprise wrote: > > > Is there a way that a function may access the doc string or func_name > > of the caller? > > > Thanks, > > > jvh > > Yes. The inspect module allows you to look up the call stack for > information on the caller, the caller's caller, local vars, etc. > > -- Paul Thanks Paul. Running jython 2.2. No module named inspect or cInspect drat... From carsten at uniqsys.com Sat May 12 00:49:20 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 12 May 2007 00:49:20 -0400 Subject: help with Python C-API, tuple object In-Reply-To: <1178943066.289330.58690@w5g2000hsg.googlegroups.com> References: <1178943066.289330.58690@w5g2000hsg.googlegroups.com> Message-ID: <20070512043453.M48016@uniqsys.com> On 11 May 2007 21:11:06 -0700, fabian.conrad wrote > Hi, > sorry for the rather basic question but I've searched everywhere and > don't find an answer. > I want to call PyObject_CallObject from the Python C-API and pass a > tuple I've created from a C-array > > How can I pass the tuple as an object rather then having to declare > the python function with the number of arguments equal to the no of > elements in the tuple? The documentation at http://docs.python.org/api/object.html lists various Call flavors. The one you chose will unpack the tuple as if you called pFunc(*pArgs), which results in the undesired behavior of pFunc receiving three arguments. You want it to receive one argument that is the tuple pArgs. One (bad) way of achieving this would be to build another tuple of size one, stick pArgs into it, and pass that size-one tuple to PyObject_CallObject. A better way is to use PyObject_CallFunctionObjArgs. If I'm not mistaken, you'll want something like pValue = PyObject_CallFunctionObjArgs(pFunc, pArgs, NULL); Hope this helps, -- Carsten Haese http://informixdb.sourceforge.net From andy.terrel at gmail.com Thu May 3 22:39:50 2007 From: andy.terrel at gmail.com (Andy Terrel) Date: 3 May 2007 19:39:50 -0700 Subject: Decorating class member functions In-Reply-To: <1178245732.628599.251020@l77g2000hsb.googlegroups.com> References: <1178241696.641350.292210@n59g2000hsh.googlegroups.com> <1178244237.702552.201410@l77g2000hsb.googlegroups.com> <1178245732.628599.251020@l77g2000hsb.googlegroups.com> Message-ID: <1178246390.183766.166620@u30g2000hsc.googlegroups.com> not quite as elegant but here is a workaround... Thanks Virgil for taking some time to think about it. --- class Bugger (object): def __init__ (self, module): print "Entering __init__" self.module = module self.verb = 0 def instrument (module_name): def wrapper(f): def _wrap(*args,**kws): ret_val = f(*args,**kws) return ret_val return _wrap b = Bugger(module_name) if b.verb == 0: ret_val = wrapper else: ret_val = lambda x:x return ret_val class Stupid: def __init__(self): self.val = 1 @instrument("spam") def update(self): self.val += 1 s = Stupid() s.update() s.update() s.update() s.update() print s.val From siona at chiark.greenend.org.uk Tue May 22 08:01:20 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 22 May 2007 13:01:20 +0100 (BST) Subject: NEWBIE: Extending a For Statement. References: <1179749446.179064.222990@z28g2000prd.googlegroups.com> <1179756164.506426.116210@x18g2000prd.googlegroups.com> Message-ID: <4-v*KBlLr@news.chiark.greenend.org.uk> wrote: >mosscliffe: >> if key in xrange (60,69) or key == 3: >I keep seeing again and again code like this, mostly from people not >much expert of Python, but the PEP 260 shows the fast in was removed, >so it's O(n). If you're going to point that out, you should at least also mention the "correct" formulation: if 60 <= key < 69 or key == 3: And if anyone cares about performance: $ python -mtimeit -s 'x = 67' 'x in range(60, 69)' 1000000 loops, best of 3: 0.906 usec per loop $ python -mtimeit -s 'x = 67' 'x in xrange(60, 69)' 1000000 loops, best of 3: 0.744 usec per loop $ python -mtimeit -s 'x = 61' 'x in range(60, 69)' 1000000 loops, best of 3: 0.707 usec per loop $ python -mtimeit -s 'x = 61' 'x in xrange(60, 69)' 1000000 loops, best of 3: 0.471 usec per loop $ python -mtimeit -s 'x = 67' '60 <= x < 69' 10000000 loops, best of 3: 0.155 usec per loop -- \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 lyoshaM at gmail.com Wed May 23 15:19:09 2007 From: lyoshaM at gmail.com (Lyosha) Date: 23 May 2007 12:19:09 -0700 Subject: Inheriting from Python list object(type?) In-Reply-To: <1179947267.368622.92350@m36g2000hse.googlegroups.com> Message-ID: <1179947949.769537.91920@r3g2000prh.googlegroups.com> On May 23, 12:07 pm, Mangabasi wrote: > On May 23, 1:43 pm, "Jerry Hill" wrote: > > > > > On 23 May 2007 11:31:56 -0700, Mangabasi wrote: > > > > When I modified this to: > > > > class Point(list): > > > def __init__(self,x,y): > > > super(Point, self).__init__([x, y]) > > > self.x = x > > > self.y = y > > > > It worked. > > > Are you sure? > > > >>> p = Point(10, 20) > > >>> p > > [10, 20] > > >>> p.x > > 10 > > >>> p.x = 15 > > >>> p > > [10, 20] > > >>> p[0] > > 10 > > >>> p.x > > 15 > > > That doesn't look like what you were asking for in the original post. > > I'm afraid I don't know anything about numpy arrays or what special > > attributes an object may need to be put into a numpy array though. > > > -- > > Jerry > > This is the winner: > > class Point(list): > def __init__(self, x, y, z = 1): > super(Point, self).__init__([x, y, z]) > self.x = x > self.y = y > self.z = z [...] http://docs.python.org/dev/whatsnew/node3.html announces named tuples in python2.6. This is not what you want since tuples are immutable, but you might get some inspiration from their implementation. Or maybe not. From gagsl-py2 at yahoo.com.ar Tue May 29 15:03:48 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 29 May 2007 16:03:48 -0300 Subject: Storing tracebacks References: <1180410412.643608.30050@q66g2000hsg.googlegroups.com> <1180446376.879439.55840@m36g2000hse.googlegroups.com> <1180457469.296553.291590@x35g2000prf.googlegroups.com> <1180462413.787936.125830@q66g2000hsg.googlegroups.com> Message-ID: En Tue, 29 May 2007 15:13:33 -0300, George Sakkis escribi?: > On May 29, 1:21 pm, "Gabriel Genellina" > wrote: >> A traceback contains a linked list of frames, each with its own globals >> and locals and lot of context info. >> I'm not sure that moving a traceback across processes has any sense; a >> textual representation should be enough, as t.b. are usually a debugging >> aid and not supposed to reach the final user. > > The final user in this case is another programmer that uses a library, > not some random guy using an application, so he certainly would be > interested in seeing the traceback. I agree that the traceback is > useful for debugging and the text representation would be enough if, > for example, it was stored as an attribute in the Exception object and > then used automatically by the runtime system (instead of calling > sys.exc_info()). Of course nobody stops me from sticking > traceback.format_tb() as an attribute in the Exception object and then > have the client access it explicitly, something like: > > try: r = job.result() > except Exception, ex: > print ex.traceback > > The problem with this is that it's not transparent any more. The > client must know that the originally raised object has been modified > (or wrapped), sys.exc_info() doesn't work as expected, etc. It's not a > show stopper by any means, but it would be convenient if there was a > standardized optional "traceback" attribute that the runtime looks for > and treats as the 3rd item of sys.exc_info() (otherwise it falls back > to the current behavior). Would this be a reasonable feature request ? Already requested - see PEP 344 and 3110 for changes on exception handling and tracebacks (in Python 3.0 at least; I'm unsure of the PEP344 status on the 2.X series) -- Gabriel Genellina From stefan.behnel-n05pAM at web.de Tue May 15 11:35:11 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 15 May 2007 17:35:11 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers In-Reply-To: References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <4649BC4C.10200@web.de> Message-ID: <4649D32F.4010209@web.de> Eric Brunel wrote: > On Tue, 15 May 2007 15:57:32 +0200, Stefan Behnel >> In-house developers are rather for this PEP as they see the advantage of >> expressing concepts in the way the "non-techies" talk about it. > > No: I *am* an "in-house" developer. The argument is not > public/open-source against private/industrial. As I said in some of my > earlier posts, any code can pass through many people in its life, people > not having the same language. I dare to say that starting a project > today in any other language than english is almost irresponsible: the > chances that it will get at least read by people not talking the same > language as the original coders are very close to 100%, even if it > always stays "private". Ok, so I'm an Open-Source guy who happens to work in-house. And I'm a supporter of PEP 3131. I admit that I was simplifying in my round-up. :) But I would say that "irresponsible" is a pretty self-centered word in this context. Can't you imagine that those who take the "irresponsible" decisions of working on (and starting) projects in "another language than English" are maybe as responsible as you are when you take the decision of starting a project in English, but in a different context? It all depends on the specific constraints of the project, i.e. environment, developer skills, domain, ... The more complex an application domain, the more important is clear and correct domain terminology. And software developers just don't have that. They know their own domain (software development with all those concepts, languages and keywords), but there is a reason why they develop software for those who know the complex professional domain in detail but do not know how to develop software. And it's a good idea to name things in a way that is consistent with those who know the professional domain. That's why keywords are taken from the domain of software development and identifiers are taken (mostly) from the application domain. And that's why I support PEP 3131. Stefan From see_below_no_spam at yahoo.es Fri May 18 12:42:06 2007 From: see_below_no_spam at yahoo.es (Javier Bezos) Date: Fri, 18 May 2007 18:42:06 +0200 Subject: PEP 3131: Supporting Non-ASCII Identifiers References: <46473267$0$31532$9b622d9e@news.freenet.de> <1179236673.893122.28800@w5g2000hsg.googlegroups.com> <464C5382.6080403@v.loewis.de> <1179423799.254286.294930@w5g2000hsg.googlegroups.com> <1179503525.018943.95740@u30g2000hsc.googlegroups.com> Message-ID: "Istvan Albert" escribi?: > How about debugging this (I wonder will it even make it through?) : > > class 6??????? > 6?? = 0 > 6????? ?? ?=10 This question is more or less what a Korean who doesn't speak English would ask if he had to debug a program written in English. > (I don't know what it means, just copied over some words > from a japanese news site, A Japanese speaking Korean, it seems. :-) Javier ------------------------------------------ http://www.texytipografia.com